| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323 |
- <?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;
- }
- $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(!isset($params['money'])){
- $params['money'] = 0;
- }
- // 表单验证
- 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);
- // }
- $file_id = File::getId($params['files']);
- $params['main_vujfcz'] = $file_id;
- $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:
- if(empty($wheres)){
- $wheres['owner_staff_id'] = array('in',Staff::getMyStaffIds());
- }
- break;
- }
- unset($wheres['owner_staff_id']);
- $list = $this->model->with([
- 'CustomerInfo',
- 'orderStaff',
- 'contacts',
- 'ownerStaff','contractOther',
- ])->where($where)->where($wheres)->order($sort, $order)->select();
- $list = collection($list)->toArray();
- // dump($list);die;
- 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);
- }
- $customer_name = Db::name('qingdong_customer')->where('id', $v['customer_id'])->value('name');
- $contacts_name = Db::name('qingdong_contacts')->where('id', $v['contacts_id'])->value('name');
- $contacts_name = Db::name('qingdong_contacts')->where('id', $v['contacts_id'])->value('name');
- $owner_staffs_list = Db::name('qingdong_staff')->where( 'id in ('.$v['owner_staff_id'].")")->field('name')->select();
- $owner_staffs_arr = array_column($owner_staffs_list,'name');
- $owner_staffs_str = implode('/',$owner_staffs_arr);
- $field = array(
- $v['id'],
- $customer_name,
- $contacts_name,
- $v['order_staff']['name']??'',
- $owner_staffs_str,
- date('Y-m-d H:i:s',$v['createtime']),
- );
- // $field = array(
- // $v['id'],
- // $v['customer']['name'],
- // $v['contacts']['name']??'',
- // $v['order_staff']['name']??'',
- // $v['owner_staff']['name']??'',
- // date('Y-m-d H:i:s',$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();
- }
- }
|