| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256 |
- <?php
- namespace app\admin\controller\qingdong\customer;
- use addons\qingdong\model\BusinessProduct;
- use addons\qingdong\model\ContactsOther;
- use addons\qingdong\model\ContractProduct;
- use addons\qingdong\model\CustomerOther;
- use addons\qingdong\model\ExamineRecord;
- use addons\qingdong\model\File;
- use addons\qingdong\model\FormField;
- use addons\qingdong\model\ProductPart;
- use addons\qingdong\model\Product;
- use addons\qingdong\model\Ratio;
- use addons\qingdong\model\Receivables;
- use addons\qingdong\model\Staff;
- use addons\qingdong\model\WordTemplate;
- use app\admin\controller\qingdong\Base;
- use addons\qingdong\model\ContractOther;
- use addons\qingdong\model\Form;
- use addons\qingdong\model\Contacts;
- use addons\qingdong\model\Customer;
- use addons\qingdong\model\OperationLog;
- use addons\qingdong\model\Record;
- use addons\qingdong\model\ContractFile;
- use addons\qingdong\model\Flow;
- use addons\qingdong\model\Business;
- use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
- use PhpOffice\PhpSpreadsheet\Reader\Csv;
- use PhpOffice\PhpSpreadsheet\Reader\Xls;
- use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
- use PhpOffice\PhpSpreadsheet\RichText\RichText;
- use PhpOffice\PhpWord\Settings;
- use PhpOffice\PhpWord\TemplateProcessor;
- use think\Db;
- use think\Exception;
- /**
- * 合同管理
- * 操作文档:https://doc.fastadmin.net/qingdong
- * 软件介绍:https://www.fastadmin.net/store/qingdong.html
- * 售后微信:qingdong_crm
- */
- class Contract extends Base {
- protected $relationSearch = true;
- /**
- * @var \addons\qingdong\model\Contract
- */
- protected $model = null;
- public function _initialize() {
- parent::_initialize();
- $this->model = new \addons\qingdong\model\Contract;
- }
- /**
- * 查看
- */
- public function index() {
- //设置过滤方法
- $this->request->filter(['strip_tags', 'trim']);
- if ($this->request->isAjax()) {
- if ($this->request->request('keyField')) {
- return $this->selectpage();
- }
- //0:全部 1:我负责的 2:下属负责的 3:今日待跟进 4:今日已跟进 5:从未跟进的
- $type = input('type',0);
- list($where, $sort, $order, $offset, $limit) = $this->buildparams();
- switch($type){
- case 1:
- $staff = Staff::info();
- $wheres['owner_staff_id'] = $staff->id;
- break;
- case 2:
- $wheres['owner_staff_id'] = array('in',Staff::getLowerStaffId());
- break;
- case 3:
- $start = date('Y-m-d 00:00:00');
- $end = date('Y-m-d 23:59:59');
- $record = collection(Record::where(array('relation_type'=>3,'next_time'=>array(array('egt',$start),array('elt',$end))))->field("id,relation_id")->select())->toArray();
- $relationId = [];
- foreach($record as $k=>$v){
- $whereRe['id'] = array('gt',$v['id']);
- $whereRe['relation_id'] = $v['relation_id'];
- $recordData = Record::where($whereRe)->count();
- if($recordData == 0){
- $relationId[] = $v['relation_id'];
- }
- }
- $wheres['id'] = array('in',$relationId);
- $staff = Staff::info();
- $wheres['owner_staff_id'] = $staff->id;
- break;
- case 4:
- $start = date('Y-m-d 00:00:00');
- $end = date('Y-m-d 23:59:59');
- $record = collection(Record::where(array('relation_type'=>3,'next_time'=>array(array('egt',$start),array('elt',$end))))->field("id,relation_id")->select())->toArray();
- $relationId = [];
- foreach($record as $k=>$v){
- $whereRe['id'] = array('gt',$v['id']);
- $whereRe['relation_id'] = $v['relation_id'];
- $recordData = Record::where($whereRe)->count();
- if($recordData >=1){
- $relationId[] = $v['relation_id'];
- }
- }
- $wheres['id'] = array('in',$relationId);
- $staff = Staff::info();
- $wheres['owner_staff_id'] = $staff->id;
- break;
- case 5:
- $record = collection(Record::where(array('relation_type'=>3,'next_time'=>array('neq','')))->column('relation_id'))->toArray();
- $wheres['id'] = array('not in',$record);
- $staff = Staff::info();
- $wheres['owner_staff_id'] = $staff->id;
- break;
- default:
- $wheres['owner_staff_id'] = array('in',Staff::getMyStaffIds());
- break;
- }
- $ids=[];
- $group_id=input('group_id');
- $staff_id=input('staff_id');
- if ($group_id) {//角色组
- $ids = Staff::getGroupStaffIds($group_id);
- }
- if ($staff_id) {
- $ids = $staff_id;
- }
- if ($group_id || $staff_id) {
- $wheres['owner_staff_id'] = ['in', $ids];
- }
- $list = $this->model->where($where)
- ->where($wheres)
- ->with([
- 'customer',
- 'orderStaff',
- 'contacts'
- ])->order($sort, $order)->paginate($limit);
- $allmoney = $this->model->where($wheres)->where(array('check_status'=>2))->sum('money');
- $repayment_money = Receivables::where($wheres)->where(array('check_status'=>2))->sum('money'); //已回款
- $no_money = $allmoney - $repayment_money;
- if($no_money <= 0){
- $no_money = 0;
- }
- $result = array("total" => $list->total(), "rows" => $list->items(),'allmoney'=>$allmoney,'repayment_money'=>$repayment_money,'no_money'=>$no_money);
- return json($result);
- }
- $field = FormField::getFields(FormField::CONTRACT_TYPE);
- $this->assignconfig('fields', $field);
- return $this->view->fetch();
- }
- /**
- * 添加
- */
- public function add()
- {
- if ($this->request->isPost()) {
- $params = $this->request->post("row/a");
- if ($params) {
- $params = $this->preExcludeFields($params);
- // 表单验证
- if (($result = $this->qingdongValidate($params, 'Contract', 'create')) !== true) {
- $this->error($result);
- }
- $result = FormField::checkFields(FormField::CONTRACT_TYPE, $params);
- if ($result !== true) {
- $this->error($result);
- }
- $result = false;
- Db::startTrans();
- try {
- $params = Form::updateFormParams(Form::CONTRACT_TYPE, $params);
- if($params['product']){
- $params['product']=json_decode($params['product'],true);
- }
- $result = $this->model::createContract($params);
- Db::commit();
- } catch (Exception $e) {
- Db::rollback();
- $this->error($e->getMessage());
- }
- if ($result !== false) {
- $this->success();
- } else {
- $this->error(__('No rows were inserted'));
- }
- }
- $this->error(__('Parameter %s can not be empty', ''));
- }
- $flow= Flow::getsteplist(Flow::CONTRACT_STATUS);
- if (empty($flow)) {
- $this->error('无可用审批流,请联系管理员','qingdong/work/flow');
- }
- $customer_id = input('customer_id');
- if($customer_id){
- $business = Business::where(array('customer_id'=>$customer_id))->select();
- }else{
- $business = Business::getList();
- }
- $this->assign('flow',$flow);
- $this->assign('staff', Staff::getStaff());
- $this->assign('customers', Customer::getList());
- $this->assign('business', $business);
- $this->assign('customer_id', $customer_id);
- $this->assign('business_id', input('business_id'));
- $this->assign('staffs', Staff::allList());
- $this->assign('form_data', Form::getDataValue('contract'));
- $this->assign('ratio',Ratio::where(['status'=>1])->select());
- $this->assign('contractNum', 'C'.date('Ymd').rand(10000,99999));
- return $this->view->fetch();
- }
- /**
- * 修改合同
- */
- public function edit($ids = null) {
- $map['id'] = $ids;
- if ($this->request->isAjax()) {
- $params = $this->request->post('row/a');
- $params = $this->preExcludeFields($params);
- $row = $this->model::where(['id' => $ids, 'check_status' => ['in', [3, 4]]])->find();
- if (empty($row)) {
- $this->error('合同审核中或已审核通过无法修改');
- }
- // 表单验证
- if (($result = $this->qingdongValidate($params, 'Contract', 'create')) !== true) {
- $this->error($result);
- }
- $result = FormField::checkFields(FormField::CONTRACT_TYPE, $params,$ids);
- if ($result !== true) {
- $this->error($result);
- }
- Db::startTrans();
- try {
- $params = Form::updateFormParams(Form::CONTRACT_TYPE, $params);
- $params['id']=$ids;
- $params['owner_staff_id'] = $row['owner_staff_id'];
- if($params['product']){
- $params['product']=json_decode($params['product'],true);
- }
- $result = $this->model::updateContract($params);
- Db::commit();
- } catch (Exception $e) {
- Db::rollback();
- $this->error($e->getMessage());
- }
- $this->success('修改成功');
- }
- $row = $this->model->where($map)->with(['customer','contacts','business'])->find();
- if(empty($row)){
- $this->error('信息不存在');
- }
- $row = $row->toArray();
- $row = ContractOther::getOther($row);
- $product=ContractProduct::where(['contract_id'=>$ids])->with(['productinfo'])->select();
- foreach ($product as $k=>$v){
- if($v['productinfo']){
- $v['product_name']=$v['productinfo']['name'];
- $v['cost_price']=$v['productinfo']['cost_price'];
- $v['type']=$v['productinfo']['type'];
- if($v['productinfo']['goods']){
- $v['goods_name']=$v['productinfo']['goods']['name'];
- }
- }
- $product[$k]=$v;
- }
- $row['product']=json_encode($product);
- $row['ratios']=json_decode($row['ratios'],true);
- $flow= Flow::getsteplist(Flow::CONTRACT_STATUS);
- if (empty($flow)) {
- $this->error('无可用审批流,请联系管理员','qingdong/work/flow');
- }
- $this->assign('flow',$flow);
- $this->view->assign("row", $row);
- $this->assign('customers', Customer::getList());
- $this->assign('business', Business::getList());
- $this->assign('staffs', Staff::getList());
- $this->assign('staff', Staff::getStaff());
- $this->assign('ratio',Ratio::where(['status'=>1])->select());
- $this->assign('form_data', Form::getDataValue('contract',$row));
- $this->assign('contacts', Contacts::where(['customer_id'=>$row['customer_id']])->field('id,name')->select());
- return $this->view->fetch();
- }
- /**
- * 获取附件记录
- */
- public function get_file($ids = null) {
- list($where, $sort, $order, $offset, $limit) = $this->buildparams();
- $list = ContractFile::where(['contract_id' => $ids])->with(['file'])->field('file_id')->paginate($limit);
- $result = array("total" => $list->total(), "rows" => $list->items());
- return json($result);
- }
- /**
- * 合同详情
- */
- public function detail($ids = null) {
- $row = $this->model->where(['id' => $ids])->with([
- 'customer',
- 'contacts',
- 'orderStaff',
- 'ownerStaff',
- 'business'
- ])->find();
- if (empty($row)) {
- $this->error(__('No Results were found'));
- }
- $row=$row->toArray();
- $row=ContractOther::getOther($row);
- $row['ratios'] = json_decode($row['ratios'], true);
- if ($row['ratios']) {
- foreach ($row['ratios'] as $k => $v) {
- $v['staff'] = Staff::where(['id' => $v['staff_id']])->field('id,name,img,post')->find()->toArray();
- $v['money'] = $row['money'] * ($v['ratio'] / 100);
- $row['ratios'][$k] = $v;
- }
- }
- $row['repayment_money'] = Receivables::where(['contract_id'=>$ids])->sum('money'); //已回款
- $row['no_money'] = $row['money'] -$row['repayment_money'];
- if($row['no_money'] <= 0){
- $row['no_money'] = 0;
- }
- $this->assign('examine_record',ExamineRecord::getList(ExamineRecord::CONTRACT_TYPE,$ids));
- $this->assign('flow',Flow::getstepdetail(Flow::CONTRACT_STATUS, $ids));
- //跟进记录
- $this->assign('records', Record::getList(Record::CONTRACT_TYPE, $ids));
- //操作记录
- $log=OperationLog::getList(OperationLog::CONTRACT_TYPE, $ids);
- $this->assign('operation_log',$log);
- $this->assign('row', $row);
- $this->assign('ids', $ids);
- $this->assign('form_data', Form::getDataValue('contract',$row));
- $this->assignconfig("idinfo", ['id' => $ids]);
- return $this->view->fetch();
- }
- /**
- * 获取联系人select
- */
- public function get_contacts_list(){
- $pageSize = input('pageSize');
- $pageNumber = input('pageNumber');
- $where = [];
- if ($keyValue = $this->request->request("keyValue")) {
- $where['id'] = ['in',$keyValue];
- }
- $ids=input('ids');
- $name = input('name');
- if(!empty($name)){
- $where['name'] = ['like','%'.$name.'%'];
- }
- $staff = Contacts::where($where)->where(['customer_id'=>$ids])
- ->field('id,name')->order('id desc')->paginate($pageSize, false, ['page' => $pageNumber]);
- return json(['list' => $staff->items(), 'total' => $staff->total()]);
- }
- /**
- * 获取产品明细
- */
- public function get_contract_product(){
- $contract_id=input('contract_id',0,'intval');
- if(empty($contract_id)){
- $this->error('参数不能为空');
- }
- $products=ContractProduct::where(['contract_id'=>$contract_id])
- ->with(['productinfo'])->select();
- foreach($products as $k=>$v){
- if(!$v['productinfo']['id']){
- unset($products[$k]);
- }
- }
- return json(['rows' =>$products, 'total' => count($products)]);
- }
- /**
- * 获取回款计划
- */
- public function get_receivables_plan($ids = null) {
- list($where, $sort, $order, $offset, $limit) = $this->buildparams();
- $list = \addons\qingdong\model\ReceivablesPlan::where([
- 'contract_id' => $ids
- ])->with(['customer'])->paginate($limit);
- $result = array("total" => $list->total(), "rows" => $list->items());
- return json($result);
- }
- /**
- * 获取回款记录
- */
- public function get_receivables($ids = null) {
- list($where, $sort, $order, $offset, $limit) = $this->buildparams();
- $list = \addons\qingdong\model\Receivables::where([
- 'contract_id' => $ids
- ])->with(['customer','ownerStaff'])->paginate($limit);
- $result = array("total" => $list->total(), "rows" => $list->items());
- return json($result);
- }
- /**
- * 获取商机关联产品
- */
- public function get_business_product(){
- $business_id=input('business_id');
- if(empty($business_id)){
- $this->error('参数不能为空');
- }
- $business=BusinessProduct::where(['business_id'=>$business_id])->with(['productinfo'])->select();
- $this->success('请求成功','',$business);
- }
- /**
- * 获取产品
- */
- public function get_product()
- {
- $where = [];
- if ($keyValue = $this->request->request("keyValue")) {
- $where['id'] = $keyValue;
- }
- $name = input('name');
- if(!empty($name)){
- $where['name'] = ['like','%'.$name.'%'];
- }
- $countrys = Product::where($where)->field('id,name')->order('id desc')->select();
- return json(['list' => $countrys, 'total' => count($countrys)]);
- }
- /**
- * 获取产品配置
- */
- public function get_product_part()
- {
- $where = [];
- if ($keyValue = $this->request->request("keyValue")) {
- $where['id'] = $keyValue;
- }
- $name = input('name');
- if(!empty($name)){
- $where['name'] = ['like','%'.$name.'%'];
- }
- $countrys = ProductPart::where($where)->field('id,name')->order('id desc')->select();
- return json(['list' => $countrys, 'total' => count($countrys)]);
- }
- /**
- * 获取产品价格
- */
- public function get_product_price()
- {
- $id = input('id', 0);
- $price = Product::where(['id' => $id])->value('price') ?? 0;
- $this->success('请求成功', '', ['price' => $price]);
- }
- /**
- * 获取审批人列表
- */
- public function getstaff(){
- $pageSize = input('pageSize');
- $pageNumber = input('pageNumber');
- $where = [];
- if ($keyValue = $this->request->request("keyValue")) {
- $where['id'] = ['in',$keyValue];
- }
- $name = input('name');
- if(!empty($name)){
- $where['name'] = ['like','%'.$name.'%'];
- }
- $staff = Staff::where($where)->where(['id'=>['neq',$this->_staff->id]])->field('id,name')->order('id desc')->paginate($pageSize, false, ['page' => $pageNumber]);
- return json(['list' => $staff->items(), 'total' => $staff->total()]);
- }
- /**
- * 删除
- */
- public function del($ids = "") {
- if (!$this->request->isPost()) {
- $this->error(__("Invalid parameters"));
- }
- $map['id'] = array('in', $ids);
- $result = $this->model->destroy($map);
- if (!$result) {
- $this->error('删除失败');
- }
- $this->success('删除成功');
- }
- /**
- * 导入合同
- * @return string|void
- */
- public function import()
- {
- set_time_limit(0);
- if ($this->request->isPost()) {
- $file = $this->request->request('file');
- if (!$file) {
- $this->error(__('Parameter %s can not be empty', 'file'));
- }
- $filePath = ROOT_PATH . 'public' . $file;
- if (!is_file($filePath)) {
- $this->error(__('No results were found'));
- }
- //实例化reader
- $ext = pathinfo($filePath, PATHINFO_EXTENSION);
- if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
- $this->error(__('Unknown data format'));
- }
- if ($ext === 'csv') {
- $file = fopen($filePath, 'r');
- $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
- $fp = fopen($filePath, "w");
- $n = 0;
- while ($line = fgets($file)) {
- $line = rtrim($line, "\n\r\0");
- $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
- if ($encoding != 'utf-8') {
- $line = mb_convert_encoding($line, 'utf-8', $encoding);
- }
- if ($n == 0 || preg_match('/^".*"$/', $line)) {
- fwrite($fp, $line . "\n");
- } else {
- fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
- }
- $n++;
- }
- fclose($file) || fclose($fp);
- $reader = new Csv();
- } elseif ($ext === 'xls') {
- $reader = new Xls();
- } else {
- $reader = new Xlsx();
- }
- if (!$PHPExcel = $reader->load($filePath)) {
- $this->error(__('Unknown data format'));
- }
- $currentSheet = $PHPExcel->getSheet(0); //读取文件中的第一个工作表
- $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
- $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
- $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
- //开始读取数据
- $fields = [];
- for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
- for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
- $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
- $fields[$currentRow][] = $val;
- if ($val instanceof RichText) {//富文本转换字符串
- $val = $val->__toString();
- }
- $values[] = is_null($val) ? NULL : trim($val);
- }
- }
- if (!isset($fields[1])) {
- $this->error('导入文件第一行没有数据');
- }
- $lastid = $this->model->withTrashed()->order('id desc')->value('id');
- $lastid = $lastid + 5;//防止重复
- $contractRow = [];
- $errorInfo = [];
- $fieldnames = FormField::where(['types' => FormField::CONTRACT_TYPE])->column('field', 'name');
- if(!$fieldnames){
- $this->error('请在系统管理->字段管理中保存合同管理表单生成合同导入字段');
- }
- $customerNames=Customer::where([])->column('id,owner_staff_id','name');
- $contacts = Contacts::where([])->field('id,name,customer_id')->select();
- $contacts = collection($contacts)->toArray();
- $contactsNames = [];
- foreach ($contacts as $v) {
- $contactsNames[$v['customer_id']][$v['name']] = $v;
- }
- $businessNames=Business::where([])->column('id','name');
- $staffNames=Staff::where([])->column('id','name');
- $fn = [];
- $nums=$this->model->where([])->column('num');
- for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
- $values = [];
- for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
- $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
- $values[] = is_null($val) ? '' : $val;
- }
- foreach ($values as $l) {
- $fn[] = $fieldnames[$l] ?? '';
- }
- }
- for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
- $values = [];
- for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
- $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
- if ($val instanceof RichText) {//富文本转换字符串
- $val = $val->__toString();
- }
- $values[] = is_null($val) ? NULL : trim($val);
- }
- $lastid++;
- $addContract = ['id' => $lastid];
- $customer=isset($customerNames[$values[0]])?$customerNames[$values[0]]:0;
- if(empty($customer)){
- $errorInfo[] = "第{$currentRow}行,客户名称不存在;";
- continue;
- }
- $addContract['customer_id']=$customer['id'];
- $addContract['owner_staff_id']=$customer['owner_staff_id'];
- $addContract['create_staff_id']=$customer['owner_staff_id'];
- $contacts = isset($contactsNames[$addContract['customer_id']])?(isset($contactsNames[$addContract['customer_id']][$values[1]]) ? $contactsNames[$addContract['customer_id']][$values[1]] : []):[];
- if (!empty($values[1]) && empty($contacts)) {
- $errorInfo[] = "第{$currentRow}行,客户签约人名称不存在;";
- continue;
- }
- $addContract['contacts_id']=$contacts['id']??0;
- $business=isset($businessNames[$values[2]])?$businessNames[$values[2]]:[];
- if (!empty($values[2]) && empty($business)) {
- $errorInfo[] = "第{$currentRow}行,商机名称不存在;";
- continue;
- }
- $addContract['business_id']=$business['id']??0;
- $orderstaff=isset($staffNames[$values[3]])?$staffNames[$values[3]]:[];
- if (!empty($values[3]) && empty($orderstaff)) {
- $errorInfo[] = "第{$currentRow}行,商机名称不存在;";
- continue;
- }
- $addContract['order_staff_id']=$orderstaff['id']??0;
- foreach ($values as $kv => $value) {
- if (!isset($fn[$kv]) || empty($fn[$kv])) {
- continue;
- }
- $addContract[$fn[$kv]] = $value;
- }
- if (empty($addContract['num'])) {
- $errorInfo[] = "第{$currentRow}行,合同编号不能为空;";
- continue;
- }
- if (in_array($addContract['num'], $nums)) {
- $errorInfo[] = "第{$currentRow}行,合同编号`{$addContract['num']}`已存在;";
- continue;
- }
- if (empty($addContract['name'])) {
- $errorInfo[] = "第{$currentRow}行,合同名称不能为空;";
- continue;
- }
- $contractRow[] = $addContract;
- }
- if (!empty($errorInfo)) {
- $this->error(implode(',', $errorInfo));
- }
- Db::startTrans();
- try {
- $this->model::importContract($contractRow);
- Db::commit();
- } catch (Exception $e) {
- Db::rollback();
- $this->error($e->getMessage());
- }
- $this->success('导入成功');
- }
- $this->assign('staffs', Staff::getList());
- return $this->view->fetch();
- }
- /**
- * 模板
- */
- public function template()
- {
- $title = [
- '客户名称',
- '客户签约人',
- '商机名称',
- '公司签约人',
- ];
- $contractData = Form::getDataValue(Form::CONTRACT_TYPE);
- foreach ($contractData as $val) {
- $title[] = $val['config']['label'];
- }
- $file = export_excel($title, [], '合同');
- header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
- header('Content-Disposition: attachment;filename=' . $file['fileName']);
- header('Cache-Control: max-age=0');
- $obj = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
- // 以下内容是excel文件的信息描述信息
- $obj->getProperties()->setTitle('导出文件'); //设置标题
- $obj->setActiveSheetIndex(0);
- $obj->getActiveSheet()->setTitle('导出文件');
- /* 循环读取每个单元格的数据 */
- $a = 'A';
- $currentSheet = $obj->getActiveSheet();
- foreach ($title as $key => $value) {
- //读取工作表1
- // 设置第一行加粗
- $obj->getActiveSheet()->getStyle($a . '1')->getFont()->setBold(true);
- //这里是设置单元格的内容
- $currentSheet->getCell($a . '1')->setValue($value);
- $a++;
- }
- $PHPWriter = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($obj);
- $PHPWriter->save('php://output');
- }
- /**
- * 导出信息
- */
- public function export()
- {
- $this->request->filter(['strip_tags', 'trim']);
- $ids = input('ids');
- $isall = input('isall');
- $wheres = array();
- //导出其中几条
- if (isset($ids)) {
- $wheres['id'] = array('in', $ids);
- }
- //导出全部
- if (isset($isall)) {
- if ($isall == 3) {
- unset($wheres['id']);
- }
- }
- //0:全部 1:我负责的 2:下属负责的 3:今日待跟进 4:今日已跟进 5:从未跟进的
- $type = input('type',0);
- list($where, $sort, $order, $offset, $limit) = $this->buildparams();
- switch($type){
- case 1:
- $staff = Staff::info();
- $wheres['owner_staff_id'] = $staff->id;
- break;
- case 2:
- $wheres['owner_staff_id'] = array('in',Staff::getLowerStaffId());
- break;
- case 3:
- $start = date('Y-m-d 00:00:00');
- $end = date('Y-m-d 23:59:59');
- $record = collection(Record::where(array('relation_type'=>3,'next_time'=>array(array('egt',$start),array('elt',$end))))->field("id,relation_id")->select())->toArray();
- $relationId = [];
- foreach($record as $k=>$v){
- $whereRe['id'] = array('gt',$v['id']);
- $whereRe['relation_id'] = $v['relation_id'];
- $recordData = Record::where($whereRe)->count();
- if($recordData == 0){
- $relationId[] = $v['relation_id'];
- }
- }
- $wheres['id'] = array('in',$relationId);
- $staff = Staff::info();
- $wheres['owner_staff_id'] = $staff->id;
- break;
- case 4:
- $start = date('Y-m-d 00:00:00');
- $end = date('Y-m-d 23:59:59');
- $record = collection(Record::where(array('relation_type'=>3,'next_time'=>array(array('egt',$start),array('elt',$end))))->field("id,relation_id")->select())->toArray();
- $relationId = [];
- foreach($record as $k=>$v){
- $whereRe['id'] = array('gt',$v['id']);
- $whereRe['relation_id'] = $v['relation_id'];
- $recordData = Record::where($whereRe)->count();
- if($recordData >=1){
- $relationId[] = $v['relation_id'];
- }
- }
- $wheres['id'] = array('in',$relationId);
- $staff = Staff::info();
- $wheres['owner_staff_id'] = $staff->id;
- break;
- case 5:
- $record = collection(Record::where(array('relation_type'=>3,'next_time'=>array('neq','')))->column('relation_id'))->toArray();
- $wheres['id'] = array('not in',$record);
- $staff = Staff::info();
- $wheres['owner_staff_id'] = $staff->id;
- break;
- default:
- $wheres['owner_staff_id'] = array('in',Staff::getMyStaffIds());
- break;
- }
- $list = $this->model->with([
- 'customer',
- 'orderStaff',
- 'contacts',
- 'ownerStaff','contractOther',
- ])->where($where)->where($wheres)->order($sort, $order)->select();
- $list = collection($list)->toArray();
- if (!$list) {
- $this->error('无导出数据');
- }
- $title = [
- '序号',
- '客户名称',
- '客户签约人',
- '公司签约人',
- '归属人',
- '创建时间',
- ];
- $dataValue = Form::getDataValue(Form::CONTRACT_TYPE);
- foreach ($dataValue as $val) {
- $title[] = $val['config']['label'];
- }
- foreach ($list as $k => $v) {
- if($v['contract_other']){//其他客户
- $other=$v['contract_other']['otherdata'];
- $other=json_decode($other,true);
- $v = array_merge($v, $other);
- }
- $field = array(
- $v['id'],
- $v['customer']['name'],
- $v['contacts']['name']??'',
- $v['order_staff']['name']??'',
- $v['owner_staff']['name']??'',
- $v['createtime'],
- );
- foreach ($dataValue as $val) {
- if ($val['component'] == 'uploadImage' || $val['component'] == 'uploadFile') {
- $field[] = $v[$val['id'] . '_str'] ?? '';
- } else {
- $field[] = ($v[$val['id']] ?? '');
- }
- }
- $data[] = $field;
- }
- $file = export_excel($title, $data, '合同');
- if ($file['filePath']) {
- $this->success('导出成功', '', $file);
- }
- $this->error('导出失败');
- }
- /**
- * 导入产品明细
- * @return string|void
- */
- public function import_product()
- {
- set_time_limit(0);
- if ($this->request->isPost()) {
- $file = $this->request->request('file');
- if (!$file) {
- $this->error(__('Parameter %s can not be empty', 'file'));
- }
- $filePath = ROOT_PATH . 'public' . $file;
- if (!is_file($filePath)) {
- $this->error(__('No results were found'));
- }
- //实例化reader
- $ext = pathinfo($filePath, PATHINFO_EXTENSION);
- if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
- $this->error(__('Unknown data format'));
- }
- if ($ext === 'csv') {
- $file = fopen($filePath, 'r');
- $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
- $fp = fopen($filePath, "w");
- $n = 0;
- while ($line = fgets($file)) {
- $line = rtrim($line, "\n\r\0");
- $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
- if ($encoding != 'utf-8') {
- $line = mb_convert_encoding($line, 'utf-8', $encoding);
- }
- if ($n == 0 || preg_match('/^".*"$/', $line)) {
- fwrite($fp, $line . "\n");
- } else {
- fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
- }
- $n++;
- }
- fclose($file) || fclose($fp);
- $reader = new Csv();
- } elseif ($ext === 'xls') {
- $reader = new Xls();
- } else {
- $reader = new Xlsx();
- }
- if (!$PHPExcel = $reader->load($filePath)) {
- $this->error(__('Unknown data format'));
- }
- $currentSheet = $PHPExcel->getSheet(0); //读取文件中的第一个工作表
- $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
- $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
- $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
- //开始读取数据
- $fields = [];
- for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
- for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
- $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
- $fields[$currentRow][] = $val;
- if ($val instanceof RichText) {//富文本转换字符串
- $val = $val->__toString();
- }
- $values[] = is_null($val) ? '' : trim($val);
- }
- }
- if (!isset($fields[1])) {
- $this->error('导入文件第一行没有数据');
- }
- $lastid = ContractProduct::order('id desc')->value('id');
- $lastid = $lastid + 5;//防止重复
- $contractProductRow = [];
- $errorInfo = [];
- $contractNum=$this->model::where([])->column('id,name','num');
- $productName=Product::where([])->column('id,price','name');
- $fn = [];
- for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
- $values = [];
- for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
- $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
- $values[] = is_null($val) ? '' : $val;
- }
- }
- for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
- $values = [];
- for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
- $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
- if ($val instanceof RichText) {//富文本转换字符串
- $val = $val->__toString();
- }
- $values[] = is_null($val) ? NULL : trim($val);
- }
- $lastid++;
- $addContractProduct = ['id' => $lastid];
- $contract = isset($contractNum[$values[0]]) ? $contractNum[$values[0]] : 0;
- if (empty($contract)) {
- $errorInfo[] = "第{$currentRow}行,合同编号不存在;";
- continue;
- }
- $product = isset($productName[$values[1]]) ? $productName[$values[1]] : 0;
- if (empty($product)) {
- $errorInfo[] = "第{$currentRow}行,产品名称不存在;";
- continue;
- }
- if (empty($values[2])) {
- $errorInfo[] = "第{$currentRow}行,产品数量不能为空;";
- continue;
- }
- if (empty($values[3])) {
- $errorInfo[] = "第{$currentRow}行,产品售价不能为空;";
- continue;
- }
- $addContractProduct['contract_id'] = $contract['id'];
- $addContractProduct['product_id'] = $product['id'];
- $addContractProduct['number'] = $values[2];
- $addContractProduct['price'] = $values[3];
- $contractProductRow[]=$addContractProduct;
- }
- if (!empty($errorInfo)) {
- $this->error(implode(',', $errorInfo));
- }
- Db::startTrans();
- try {
- ContractProduct::importProduct($contractProductRow);
- Db::commit();
- } catch (Exception $e) {
- Db::rollback();
- $this->error($e->getMessage());
- }
- $this->success('导入成功');
- }
- $this->assign('staffs', Staff::getList());
- return $this->view->fetch();
- }
- /**
- * 模板
- */
- public function template_product()
- {
- $title = [
- '合同编号',
- '商品名称',
- '数量',
- '售价',
- ];
- $file = export_excel($title, [], '产品明细');
- header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
- header('Content-Disposition: attachment;filename=' . $file['fileName']);
- header('Cache-Control: max-age=0');
- $obj = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
- // 以下内容是excel文件的信息描述信息
- $obj->getProperties()->setTitle('导出文件'); //设置标题
- $obj->setActiveSheetIndex(0);
- $obj->getActiveSheet()->setTitle('导出文件');
- /* 循环读取每个单元格的数据 */
- $a = 'A';
- $currentSheet = $obj->getActiveSheet();
- foreach ($title as $key => $value) {
- //读取工作表1
- // 设置第一行加粗
- $obj->getActiveSheet()->getStyle($a . '1')->getFont()->setBold(true);
- //这里是设置单元格的内容
- $currentSheet->getCell($a . '1')->setValue($value);
- $a++;
- }
- $PHPWriter = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($obj);
- $PHPWriter->save('php://output');
- }
- /**
- * 导出信息
- */
- public function export_product()
- {
- $ids = input('ids');
- $type = input('type');
- $wheres = array();
- //导出其中几条
- if (isset($ids)) {
- $wheres['contract_id'] = array('in', $ids);
- }
- //导出全部
- if (isset($type)) {
- if ($type == 3) {
- unset($wheres['contract_id']);
- }
- }
- $list=ContractProduct::where($wheres)->with(['contract','productinfo'])->select();
- $list = collection($list)->toArray();
- if (!$list) {
- $this->error('无导出数据');
- }
- $title = [
- '序号',
- '合同编号',
- '合同名称',
- '商品名称',
- '售价',
- '批发价',
- '产品',
- '规格',
- '数量',
- ];
- $data=[];
- foreach ($list as $k => $v) {
- $field = array(
- $v['id'],
- $v['contract']['num'],
- $v['contract']['name'],
- $v['productinfo']['name']??'',
- $v['price']??'',
- $v['productinfo']['cost_price']??'',
- $v['productinfo']['goods']['name']??'',
- $v['productinfo']['unit']??'',
- $v['number']??'',
- );
- $data[] = $field;
- }
- $file = export_excel($title, $data, '产品明细');
- if ($file['filePath']) {
- $this->success('导出成功', '', $file);
- }
- $this->error('导出失败');
- }
- /**
- * 导出word
- */
- public function words($ids = null)
- {
- if ($this->request->isPost()) {
- $file = input('file', '');
- $is_template=input('is_template',0);
- $template_name=input('template_name','');
- if (empty($file)) {
- $this->error('导出模板');
- }
- if($is_template == 1){
- if(empty($template_name)){
- $this->error('模板名称不能为空');
- }
- $create=[
- 'type'=>'contract',
- 'name'=>$template_name,
- 'url'=>$file
- ];
- $wordTemplateModel = new WordTemplate();
- $wordTemplateModel->save($create);
- }
- $tmp = new TemplateProcessor('.' . $file);
- Settings::setCompatibility(true);
- Settings::setOutputEscapingEnabled(true);
- $row = $this->model->where(['id'=>$ids])->with(['customer','contacts','business','orderStaff'])->find();
- $row = $row->toArray();
- $row = ContractOther::getOther($row);
- $form = Form::getDataValue(Form::CONTRACT_TYPE);
- $imgNames=[];
- foreach($form as $k=>$v){
- if($v['component'] == 'uploadImage'){
- $imgNames[]=$v['id'];
- }
- }
- foreach ($row as $key => $item) {
- if(in_array($key,$imgNames) && $item ){
- if(is_array($item)){
- foreach ($item as $it){
- $tmp->setImageValue($key,ltrim(parse_url($it['file_path'])['path'],'/'));
- }
- }else{
- $fileinfo = File::where(['id'=>['in',$item]])->field('id,name,file_path,save_name')->select();
- foreach ($fileinfo as $it){
- $tmp->setImageValue($key,ltrim(parse_url($it['file_path'])['path'],'/'));
- }
- }
- }else{
- if(is_array($item)){
- $tmp->setValue($key , '');//
- continue;
- }
- $tmp->setValue($key , $item);//
- }
- }
- $contractProduct=ContractProduct::where(['contract_id'=>$ids])
- ->with(['productinfo'])->select();
- $contractProduct=collection($contractProduct)->toArray();
- $c = count($contractProduct);//总行数
- // $tmp->cloneRow('product_name', $c);//复制行
- // for ($i = 0; $i < $c; $i++) {
- // $p=$contractProduct[$i];
- // $tmp->setValue("product_name#" . ($i + 1), $p['productinfo']['name'] ?? '');//名称
- // $tmp->setValue("product_unit#" . ($i + 1), $p['productinfo']['unit'] ?? '');//单位
- // $tmp->setValue("product_num#" . ($i + 1), $p['productinfo']['num'] ?? '');//编码
- // $tmp->setValue("product_type#" . ($i + 1), $p['productinfo']['type'] ?? '');//规格
- // $tmp->setValue("product_number#" . ($i + 1), $p['number']);//数量
- // $tmp->setValue("product_price#" . ($i + 1), $p['price']);//总价格
- // $tmp->setValue("product_total#" . ($i + 1), $p['price'] * $p['number']);//总价格
- // }
- $tmp->setValue('money_big', convertAmountToCn($row['money']));
- $tmp->setValue('customer_name', $row['customer']['name'] ?? '');
- $tmp->setValue('contacts_name', $row['contacts']['name'] ?? '');
- $tmp->setValue('business_name', $row['business']['name'] ?? '');
- $tmp->setValue('order_staff_name', $row['order_staff']['name'] ?? '');
- //end 配置
- $filename = $row['name'];
- $filepath = $filename . '.docx';
- $fileurl = './uploads/' . date('Ymd') . '/';
- if (!file_exists($fileurl)) {
- mkdir($fileurl);
- }
- $tmp->saveAs($fileurl . $filepath);//另存为
- $model = new File();
- $data = [
- 'types' => 'file',
- 'name' => $filepath,
- 'save_name' => $fileurl . $filepath,
- 'size' => filesize($fileurl . $filepath),
- 'file_path' => trim($fileurl, '.') . $filepath,
- ];
- $model->save($data);
- $lastid = $model->id;
- $file = cdnurl($model::getUrl($lastid), true);
- $this->success('成功', '', ['file' => $file, 'id' => $lastid, 'filename' => $filepath]);
- }
- $templates=WordTemplate::where(['type'=>'contract'])->select();
- $contract = Form::getDataValue(Form::CONTRACT_TYPE);
- $columns = array();
- $columns[] = ['key' => 'customer_name', 'name' => '客户名称'];
- $columns[] = ['key' => 'contacts_name', 'name' => '联系人名称'];
- $columns[] = ['key' => 'business_name', 'name' => '商机名称'];
- $columns[] = ['key' => 'order_staff_name', 'name' => '公司签约人名称'];
- $columns[] = ['key' => 'money_big', 'name' => '合同金额人民币大写'];
- foreach ($contract as $k => $v) {
- $columns[] = array(
- 'key' => $v['id'],
- 'name' => $v['config']['label'],
- );
- }
- $columns[] = ['key' => 'product_name', 'name' => '产品名称'];
- $columns[] = ['key' => 'product_unit', 'name' => '产品单位'];
- $columns[] = ['key' => 'product_num', 'name' => '产品编码'];
- $columns[] = ['key' => 'product_type', 'name' => '产品规格'];
- $columns[] = ['key' => 'product_number', 'name' => '产品数量'];
- $columns[] = ['key' => 'product_price', 'name' => '产品单价'];
- $columns[] = ['key' => 'product_total', 'name' => '产品合计'];
- $this->assign('column', $columns);
- $this->assign('templates', $templates);
- $this->assign('ids', $ids);
- return $this->view->fetch();
- }
- }
|