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; } $staff = Staff::info(); $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]; } $staff = Staff::info(); $staffid = $staff->id; $s = "FIND_IN_SET(".$staffid.",order_staff_id)"; $list = $this->model->where($where) ->where($s) ->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, 'role' => $staff->role); 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); $nowsaff = Staff::info(); $params['order_staff_id'] = $nowsaff->id; $params['flow_staff_ids'] = '1'; // 表单验证 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])->find(); // if (empty($row)) { // $this->error('合同审核中或已审核通过无法修改'); // } $params['flow_staff_ids'] = '1'; if(!isset($params['money'])){ $params['money'] = 0; } // 表单验证 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; } } $staff = Staff::info(); $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; } $filedcontect = Form::getDataValue('contract',$row); if($staff->role != 1 && $staff->role != 2){ foreach ($filedcontect as $k=>$v){ unset($filedcontect[2]); } $filedcontect = array_values($filedcontect); } //重新排序 $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('role', $staff->role); $this->assign('ids', $ids); $this->assign('form_data',$filedcontect); $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(); } }