request->action()); $noNeedLoginActions = ['getcontractgoods', 'object_array', 'tmrxyo', 'billselectpage', 'flow', 'get_contract_offer_id', 'get_quotation_id_from_offer', 'search_contracts', 'get_contract_detail', 'get_offer_business_hint']; if (in_array($action, $noNeedLoginActions)) { // 只初始化模型,跳过可能导致错误的操作 $this->model = new \addons\qingdong\model\Contract; return; } } catch (\Exception $e) { // 如果获取 action 失败,继续执行 } 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]; } ////审批流完成将合同状态改为通过审核 // halt($where); $list = $this->model ->where($where) ->where($wheres) ->with([ 'customer', 'orderStaff', 'contacts' ]) ->order('id desc') ->paginate($limit); $aa_list = $this->model->where('check_status',0)->field('id,bill_id,name,check_status')->select(); foreach ($aa_list as $v){ $status = Db::name('bywnpk')->where('ats_bywnpk.id',$v['bill_id'])->value('status'); if($status == 2){ $this->model->where('id',$v['id'])->update(['check_status'=>2]); } } $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 index2(){ $this->request->filter(['strip_tags', 'trim']); if ($this->request->isAjax()) { if ($this->request->request('keyField')) { return $this->selectpage2(1); } } } public function getContractGoods(){ $param = $this->request->param(); if(isset($param['ids']) && !empty($param['ids'])){ $find = (new \addons\antis\model\Contract())->where('id',$param['ids'])->find(); $data = (new Amodela())->where('id',$find['offer_id'])->find(); if($data){ $goodsModel = new Goods(); $json = json_decode($data['json']); $json = $this->object_array($json); if($json){ $this->success('','',$json); } } } $this->success('','',''); } //合同出仓 public function tmrxyo($ids = null){ if ($this->request->isPost()) { $params = $this->request->post("row/a"); $row = $this->model->get($ids); $stockModel = new GoodsStock(); //组合商品 if(!empty($params['goods_id'])){ $goods_array = []; $goods_array2 = []; for($i = 0 ; $i < count($params['goods_id']); $i++) { //商品数量大于0才进行出仓 if($params['nums'][$i] > 0){ $find = $stockModel->where('goods_id',$params['goods_id'][$i])->where('stores_id','1')->sum('stock'); //分成都和深圳仓库 if($find > 0){ $goods_array[]=[ 'goods_id'=>$params['goods_id'][$i], 'nums'=>$params['nums'][$i], 'unitPrice'=>$params['unitPrice'][$i], ]; }else{ $goods_array2[]=[ 'goods_id'=>$params['goods_id'][$i], 'nums'=>$params['nums'][$i], 'unitPrice'=>$params['unitPrice'][$i], ]; } } } }else{ $this->error('该合同没有商品!'); } $goodsModel = new Goods(); Db::startTrans(); try { if(!empty($goods_array)){ //添加出仓审批流程 $tmrxyo_data = [ 'initiator_id'=>$this->auth->id, 'status'=>1, 'type'=>'1', 'contract_id'=>$row['id'], ]; $tmrxyoModel = new \app\admin\model\fastflow\bill\Tmrxyo(); $tmrxyoModel->save($tmrxyo_data); $id = $tmrxyoModel->id; $api = new api(new CustomMessage(), (new Run)); $data4 = [ 'bill'=>'ats_tmrxyo', 'bill_id'=>$id, 'ebill_id'=>'', 'flow_id'=>35, 'checkcontent'=>'', 'file_name'=>'', 'file'=>'', 'carbon_scope'=>1, 'carbon_receiver'=>'', 'carbon_range'=>1, ]; $api->startFlow($data4); //判断当前的出仓数量加上该合同之前的出仓数量是否大于合同的该商品数量 $amodelGoods = new AmodelGoods(); $offer_id= (new \app\admin\model\qingdong\Contract())->where('id',$row['id'])->value('offer_id'); //$price = []; if($offer_id){ $data = (new Amodela())->where('id',$offer_id)->find(); $json = $this->object_array(json_decode($data['json'])); $inster_data = []; foreach ($goods_array as $v){ $inster_data[]=[ 'amodela_id'=>$offer_id, 'tmrxyo_id'=>$id, 'goods_id'=>$v['goods_id'], 'nums'=>$v['nums'], 'unitPrice'=>$v['unitPrice'], 'status'=>1, 'createtime'=>time() ]; $qty = $amodelGoods->where('goods_id',$v['goods_id'])->where('amodela_id',$offer_id)->where('unitPrice',$v['unitPrice'])->count('nums'); $qty = $v['nums'] + $qty; foreach ($json as $item){ //$price[$item['productID']] = $item['unitPrice']; if($item['productID'] == $v['goods_id'] && $item['unitPrice'] == $v['unitPrice']){ if($qty > $item['qty']){ $msg = $item['productName'].'已超出该报价单数量'; throw new Exception($msg); } } } } }else{ throw new Exception('查询不到该合同'); } //添加进销存客户数据 //进销存客户数据 $time = time(); $customer_data = (new Customer())->where('id',$row['customer_id'])->find(); $customer_res = (new Customers())->where('customer_id',$customer_data['id'])->find(); if(!$customer_res){ $codel = (new Customers())->order('id desc')->find(); $code = $this->incrementNumberInString($codel->customer_code); $customers_data = [ 'customertype_id'=>1, 'customerlevel_id'=>1, 'customer_code'=>$code, 'customer_name'=>$customer_data['name'], 'account_time'=>false, 'receive_account'=>'', 'opening_prepayment'=>'', 'identification'=>'', 'deposit_bank'=>'', 'bank_number'=>'', 'staff_member_id'=>'', 'note'=>'', 'need_receive_account'=>0, 'connet_name'=>$customer_data['name'], 'customer_mobile'=>$customer_data['mobile'], 'customer_phone'=>$customer_data['mobile'], 'qq_wx_email'=>'', 'getgoods_address'=>$customer_data['address']??'无', 'createtime'=>$time, 'updatetime'=>$time, 'customer_id'=> $row['customer_id'], ]; $receiving_address = $customer_data['address']; $sid = Db::name('kuerp_customers')->insertGetId($customers_data); Db::name('kuerp_sales_payment_log')->insert([ 'customers_id' => $sid, 'business_type' => 5, 'bill_time' => $customers_data['account_time'], 'bill_code' => $customers_data['customer_code'], 'give_money' => $customers_data['need_receive_account'], ]); $customers_user[] = [ 'first_connect_name'=>$customer_data['name'], 'first_connect_mobile'=>$customer_data['mobile'], 'first_connect_phone'=>$customer_data['mobile'], 'qq_wx_email'=>'', 'connect_address'=>$customer_data['address']??'无', 'is_first'=>1, 'createtime'=>$time, 'updatetime'=>$time, 'customers_code'=>$code, 'sid'=>$sid, ]; Db::name('kuerp_customers_user')->insertAll($customers_user); }else{ //$customer_res = (new Customers())->where('customer_id',$customer_data['id'])->find(); $sid = $customer_res['id']; $receiving_address = $customer_res['getgoods_address']; } //销货单 $s_number = 0; $all_money = 0; $purchase_code = 'XHD1'.date('YmdHis'); foreach ($inster_data as $item){ $s_number += $item['nums']; $all_money += $item['unitPrice'] * $item['nums']; } foreach ($inster_data as $item){ $goods_allmoney = $item['unitPrice'] * $item['nums']; $rres = $goodsModel->where('id',$item['goods_id'])->find(); $sales_info_data[] = [ 'purchase_code'=>$purchase_code, 'purchase_type'=>'1', 'purchase_time'=>$time, 'customers_id'=>$sid, 'sale_user'=>1, 'receiving_address'=>$receiving_address, 'goods_code'=>$rres['goods_code'], 'goods_note'=>$rres['goods_name'], 'goods_unit'=>$rres['unit_id'], 'stores_id'=>1, 'allow_stock'=>$rres['inventory'], 'order_info_id'=>0, 'number'=>$item['nums'], 'default_unit'=>$rres['unit_id'], 'basic_nmber'=> $item['nums'], 'unit_price'=>$item['unitPrice'], 'cost_price'=>0, 'dis_money'=>0, 'all_money'=>$goods_allmoney, 'remark'=>'', 'goods_attr'=>0, 'tax_included'=>$item['unitPrice'], 'tax_rate'=>0, 'tax_money'=>'', 'money_tax_price'=>$goods_allmoney, 'batch_id'=>'', 'batch_name'=>'', 'manufacture'=>false, 'guarantee'=>'0', 'validity'=>false, 'preferential_rate'=>0, 'preferential_money'=>0, 'real_money'=>$all_money, 'purchase_money'=>0, 'preparation_id'=>$this->auth->id, 'operation_id'=>$this->auth->id, 'pay_status'=>'0', 'pay_money'=>0, 'account'=>0, 'createtime'=>$time, 'updatetime'=>$time, 'purchase_order_id'=>'', 'period'=>null, 'serial_code'=>[], 'goods_batch_info'=>[], 'user_order_info_id'=>[], ]; } $sales_data = [ 'purchase_code'=>$purchase_code, 'purchase_type'=>'1', 'purchase_time'=>$time, 'customers_id'=>$sid, 'sale_user'=>1, 'receiving_address'=>$receiving_address, 'customers_money'=>0, 'number'=>$s_number, 'all_money'=>$all_money, 'tax_money'=>0, 'money_tax_price'=>$all_money, 'preferential_rate'=>0, 'preferential_money'=>0, 'real_money'=>$all_money, 'note'=>'', 'preparation_id'=>$this->auth->id, 'operation_id'=>$this->auth->id, 'arrears'=>$all_money, 'all_arrears'=>$all_money, 'purchase_order_id'=>'', 'pay_status'=>0, 'pay_money'=>0, 'account'=>0, 'cost_data'=>'', 'createtime'=>$time, 'updatetime'=>$time, 'tmrxyo_id'=>$id, 'see_stastus'=>0 ]; $GoodsSalesMOdel = new \app\admin\model\kuerp\GoodsSales; $goodsSales_id = $GoodsSalesMOdel->insertGetId($sales_data); Db::name('kuerp_goods_sales_info')->where(['purchase_code'=>$sales_data['purchase_code']])->delete(); //销货单其他表 foreach ($sales_info_data as $data_k=>$data_v){ $goods_serial = $data_v['serial_code']; unset($data_v['serial_code']); $goods_batch_info = $data_v['goods_batch_info']; unset($data_v['goods_batch_info']); $user_order_info_id = $data_v['user_order_info_id'];unset($data_v['user_order_info_id']); $purchase_id = Db::name('kuerp_goods_sales_info')->insertGetId($data_v); if(!empty($user_order_info_id) && !empty($params['order_id'])){ //订货单详情关联表 Db::name('kuerp_user_ordersaleinfo')->insert([ 'sales_id' => $goodsSales_id, 'orderinfo_id' => $user_order_info_id, 'salesinfo_id' => $purchase_id, ]); } //批次 if($goods_batch_info){ //商品销售批次详情表 $goods_batch_info['purchase_info_id'] = $purchase_id; Db::name('kuerp_goods_batch_sale_info')->insert($goods_batch_info); } if(!empty($goods_serial)){ //商品序列号 Db::name('kuerp_goods_serial')->where(['serial'=>['in',$goods_serial]])->update([ 'status'=>'3', 'sale_id' => $purchase_id, 'sale_code' => $data_v['purchase_code'] ]); } if(!empty($data_v['order_info_id'])){ //销售订单关联 Db::name('kuerp_goods_saleord_info')->insert([ 'order_id'=>$data_v['order_info_id'], 'purchase_id'=>$purchase_id, 'number'=>$data_v['number'], 'money'=>$data_v['pay_money'], 'all_money'=>$data_v['all_money'], 'tax_rate'=>$data_v['tax_rate'], 'tax_money'=>$data_v['tax_money'], 'money_tax_price'=>$data_v['money_tax_price'] ]); } } foreach ($inster_data as &$item){ $item['sales_id'] = $goodsSales_id; } $amodelGoods->insertAll($inster_data); } if(!empty($goods_array2)){ //添加出仓审批流程 $tmrxyo_data = [ 'initiator_id'=>$this->auth->id, 'status'=>1, 'type'=>'2', 'contract_id'=>$row['id'], ]; $tmrxyoModel = new \app\admin\model\fastflow\bill\Tmrxyo(); $tmrxyoModel->save($tmrxyo_data); $id = $tmrxyoModel->id; $api = new api(new CustomMessage(), (new Run)); $data4 = [ 'bill'=>'ats_tmrxyo', 'bill_id'=>$id, 'ebill_id'=>'', 'flow_id'=>35, 'checkcontent'=>'', 'file_name'=>'', 'file'=>'', 'carbon_scope'=>1, 'carbon_receiver'=>'', 'carbon_range'=>1, ]; $api->startFlow($data4); //判断当前的出仓数量加上该合同之前的出仓数量是否大于合同的该商品数量 $amodelGoods = new AmodelGoods(); $offer_id= (new \app\admin\model\qingdong\Contract())->where('id',$row['id'])->value('offer_id'); //$price = []; if($offer_id){ $data = (new Amodela())->where('id',$offer_id)->find(); $json = $this->object_array(json_decode($data['json'])); $inster_data2 = []; foreach ($goods_array2 as $v){ $inster_data2[]=[ 'amodela_id'=>$offer_id, 'tmrxyo_id'=>$id, 'goods_id'=>$v['goods_id'], 'nums'=>$v['nums'], 'unitPrice'=>$v['unitPrice'], 'status'=>1, 'createtime'=>time() ]; $qty = $amodelGoods->where('goods_id',$v['goods_id'])->where('amodela_id',$offer_id)->where('unitPrice',$v['unitPrice'])->count('nums'); $qty = $v['nums'] + $qty; foreach ($json as $item){ if($item['productID'] == $v['goods_id'] && $item['unitPrice'] == $v['unitPrice']){ if($qty > $item['qty']){ $msg = $item['productName'].'已超出该报价单数量'; throw new Exception($msg); } } } } }else{ throw new Exception('查询不到该合同'); } //添加进销存客户数据 //进销存客户数据 $time = time(); $customer_data = (new Customer())->where('id',$row['customer_id'])->find(); $customer_res = (new Customers())->where('customer_id',$customer_data['id'])->find(); if(!$customer_res){ $codel = (new Customers())->order('id desc')->find(); $code = $this->incrementNumberInString($codel->customer_code); $customers_data = [ 'customertype_id'=>1, 'customerlevel_id'=>1, 'customer_code'=>$code, 'customer_name'=>$customer_data['name'], 'account_time'=>false, 'receive_account'=>'', 'opening_prepayment'=>'', 'identification'=>'', 'deposit_bank'=>'', 'bank_number'=>'', 'staff_member_id'=>'', 'note'=>'', 'need_receive_account'=>0, 'connet_name'=>$customer_data['name'], 'customer_mobile'=>$customer_data['mobile'], 'customer_phone'=>$customer_data['mobile'], 'qq_wx_email'=>'', 'getgoods_address'=>$customer_data['address']??'无', 'createtime'=>$time, 'updatetime'=>$time, 'customer_id'=> $row['customer_id'], ]; $receiving_address = $customer_data['address']; $sid = Db::name('kuerp_customers')->insertGetId($customers_data); Db::name('kuerp_sales_payment_log')->insert([ 'customers_id' => $sid, 'business_type' => 5, 'bill_time' => $customers_data['account_time'], 'bill_code' => $customers_data['customer_code'], 'give_money' => $customers_data['need_receive_account'], ]); $customers_user[] = [ 'first_connect_name'=>$customer_data['name'], 'first_connect_mobile'=>$customer_data['mobile'], 'first_connect_phone'=>$customer_data['mobile'], 'qq_wx_email'=>'', 'connect_address'=>$customer_data['address']??'无', 'is_first'=>1, 'createtime'=>$time, 'updatetime'=>$time, 'customers_code'=>$code, 'sid'=>$sid, ]; Db::name('kuerp_customers_user')->insertAll($customers_user); }else{ $sid = $customer_res['id']; $receiving_address = $customer_res['getgoods_address']; } //销货单 $s_number = 0; $all_money = 0; $purchase_code = 'XHD2'.date('YmdHis'); foreach ($inster_data2 as $item){ $s_number += $item['nums']; $all_money += $item['unitPrice'] * $item['nums']; } foreach ($inster_data2 as $item){ $goods_allmoney = $item['unitPrice'] * $item['nums']; $rres = $goodsModel->where('id',$item['goods_id'])->find(); $sales_info_data2[] = [ 'purchase_code'=>$purchase_code, 'purchase_type'=>'1', 'purchase_time'=>$time, 'customers_id'=>$sid, 'sale_user'=>1, 'receiving_address'=>$receiving_address, 'goods_code'=>$rres['goods_code'], 'goods_note'=>$rres['goods_name'], 'goods_unit'=>$rres['unit_id'], 'stores_id'=>1, 'allow_stock'=>$rres['inventory'], 'order_info_id'=>0, 'number'=>$item['nums'], 'default_unit'=>$rres['unit_id'], 'basic_nmber'=> $item['nums'], 'unit_price'=>$item['unitPrice'], 'cost_price'=>0, 'dis_money'=>0, 'all_money'=>$goods_allmoney, 'remark'=>'', 'goods_attr'=>0, 'tax_included'=>$item['unitPrice'], 'tax_rate'=>0, 'tax_money'=>'', 'money_tax_price'=>$goods_allmoney, 'batch_id'=>'', 'batch_name'=>'', 'manufacture'=>false, 'guarantee'=>'0', 'validity'=>false, 'preferential_rate'=>0, 'preferential_money'=>0, 'real_money'=>$all_money, 'purchase_money'=>0, 'preparation_id'=>$this->auth->id, 'operation_id'=>$this->auth->id, 'pay_status'=>'0', 'pay_money'=>0, 'account'=>0, 'createtime'=>$time, 'updatetime'=>$time, 'purchase_order_id'=>'', 'period'=>null, 'serial_code'=>[], 'goods_batch_info'=>[], 'user_order_info_id'=>[], ]; } $sales_data = [ 'purchase_code'=>$purchase_code, 'purchase_type'=>'1', 'purchase_time'=>$time, 'customers_id'=>$sid, 'sale_user'=>1, 'receiving_address'=>$receiving_address, 'customers_money'=>0, 'number'=>$s_number, 'all_money'=>$all_money, 'tax_money'=>0, 'money_tax_price'=>$all_money, 'preferential_rate'=>0, 'preferential_money'=>0, 'real_money'=>$all_money, 'note'=>'', 'preparation_id'=>$this->auth->id, 'operation_id'=>$this->auth->id, 'arrears'=>$all_money, 'all_arrears'=>$all_money, 'purchase_order_id'=>'', 'pay_status'=>0, 'pay_money'=>0, 'account'=>0, 'cost_data'=>'', 'createtime'=>$time, 'updatetime'=>$time, 'tmrxyo_id'=>$id, 'see_stastus'=>0 ]; $GoodsSalesMOdel = new \app\admin\model\kuerp\GoodsSales; $goodsSales_id = $GoodsSalesMOdel->insertGetId($sales_data); Db::name('kuerp_goods_sales_info')->where(['purchase_code'=>$sales_data['purchase_code']])->delete(); //销货单其他表 foreach ($sales_info_data2 as $data_k=>$data_v){ $goods_serial = $data_v['serial_code']; unset($data_v['serial_code']); $goods_batch_info = $data_v['goods_batch_info']; unset($data_v['goods_batch_info']); $user_order_info_id = $data_v['user_order_info_id'];unset($data_v['user_order_info_id']); $purchase_id = Db::name('kuerp_goods_sales_info')->insertGetId($data_v); if(!empty($user_order_info_id) && !empty($params['order_id'])){ //订货单详情关联表 Db::name('kuerp_user_ordersaleinfo')->insert([ 'sales_id' => $goodsSales_id, 'orderinfo_id' => $user_order_info_id, 'salesinfo_id' => $purchase_id, ]); } //批次 if($goods_batch_info){ //商品销售批次详情表 $goods_batch_info['purchase_info_id'] = $purchase_id; Db::name('kuerp_goods_batch_sale_info')->insert($goods_batch_info); } if(!empty($goods_serial)){ //商品序列号 Db::name('kuerp_goods_serial')->where(['serial'=>['in',$goods_serial]])->update([ 'status'=>'3', 'sale_id' => $purchase_id, 'sale_code' => $data_v['purchase_code'] ]); } if(!empty($data_v['order_info_id'])){ //销售订单关联 Db::name('kuerp_goods_saleord_info')->insert([ 'order_id'=>$data_v['order_info_id'], 'purchase_id'=>$purchase_id, 'number'=>$data_v['number'], 'money'=>$data_v['pay_money'], 'all_money'=>$data_v['all_money'], 'tax_rate'=>$data_v['tax_rate'], 'tax_money'=>$data_v['tax_money'], 'money_tax_price'=>$data_v['money_tax_price'] ]); } } foreach ($inster_data2 as &$item){ $item['sales_id'] = $goodsSales_id; } $amodelGoods->insertAll($inster_data2); } Db::commit(); } catch (ValidateException $e) { Db::rollback(); $this->error($e->getMessage()); } catch (PDOException $e) { Db::rollback(); $this->error($e->getMessage()); } catch (Exception $e) { Db::rollback(); $this->error($e->getMessage()); } $this->success(); } $find = (new \addons\antis\model\Contract())->where('id',$ids)->find(); $data = (new Amodela())->where('id',$find['offer_id'])->find(); if($data){ $json = json_decode($data['json']); $json = $this->object_array($json); } $amodelGoods = new AmodelGoods(); foreach ($json as &$item){ $count = $amodelGoods->where('amodela_id',$find['offer_id'])->where('goods_id',$item['productID'])->count('nums')??0; $item['surplus'] = $item['qty'] - $count; } //halt($json); $this->assign('row', $json); return $this->view->fetch('tmrxyo'); } public function incrementNumberInString($input) { // 使用正则表达式匹配前面是大写英文,后面是数字的部分 preg_match('/([A-Z]+)(\d+)/', $input, $matches); $letters = $matches[1]; $number = (int)$matches[2]; // 将数字加1 $newNumber = $number + 1; $result = str_pad($newNumber, 3, '0', STR_PAD_LEFT); // 重新组合 return $letters . $result; } /** * 添加 */ public function add() { if ($this->request->isPost()) { $params = $this->request->post("row/a"); if ($params) { $params = $this->preExcludeFields($params); $result = FormField::checkFields(FormField::CONTRACT_TYPE, $params); if ($result !== true) { $this->error($result); } $result = false; Db::startTrans(); try { //halt($params); $params = Form::updateFormParams(Form::CONTRACT_TYPE, $params); //halt($params); $result = $this->model::createContract($params); Db::commit(); } catch (Exception $e) { Db::rollback(); $this->error($e->getMessage()); } if ($result !== false) { //$this->success('','admin\fastflow/flow/run/start?bill=ats_xtuqll&bill_id='.$result); //$this->redirect('admin\fastflow/flow/run/start?bill=ats_xtuqll&bill_id='.$result); // $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('无可用审批流,请联系管理员','antis/work/flow'); //} $customer_id = input('customer_id'); if($customer_id){ $business = Business::where(array('customer_id'=>$customer_id))->select(); }else{ $business = Business::getList(); } $bus_ids = (new \app\admin\model\qingdong\Business())->where('create_staff_id',$this->auth->id)->column('id'); $bill_ids = (new Czgprz())->where('status',2)->column('id'); $bill = (new Amodela())->where('business_id','in',$bus_ids)->where('bill_id','in',$bill_ids)->field('id,name')->select(); $staff = Staff::info(); //halt($customer_id); $mainbody = (new Mainbody())->select(); $this->assign('mainbody',$mainbody); $this->assign('flow',$flow); $this->assign('bill', $bill); $this->assign('staff', Staff::getStaff()); $this->assign('customers', Customer::getList()); $this->assign('business', $business); $this->assign('businesss', Business::get(input('business_id'))); $this->assign('customer', Customer::get($customer_id)); $this->assign('customer_id', $customer_id); $this->assign('business_id', input('business_id')); $this->assign('staffs', Staff::allList()); $this->assign('order_staff_id',$staff->id); $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 Billselectpage(){ $param = $this->request->param(); // ids = 项目 business_id;未选项目时可传 customer_id,列出该客户下所有项目的报价单(含用友关联的 amodel_a) $businessIds = []; if (!empty($param['ids'])) { $businessIds = [intval($param['ids'])]; } elseif (!empty($param['customer_id'])) { $businessIds = Business::where('customer_id', intval($param['customer_id']))->column('id'); } if (empty($businessIds)) { return json(array("total" => 0, "rows" => [])); } $amodel = (new Amodela())->field('id,bill_id,name')->select(); $arr = []; foreach ($amodel as $v){ // 判断是否是用友集成的报价单(通过 name 字段中包含 quotation_ 标记) $isYongyouQuotation = false; if (isset($v['name']) && strpos($v['name'], '(quotation_') !== false) { $isYongyouQuotation = true; } if($isYongyouQuotation){ // 用友集成的报价单,直接包含(bill_id 可能为 0 或 null) $arr[] = $v['id']; } elseif($v['bill_id'] != '0' && $v['bill_id'] != null){ // PHP项目的报价单,需要检查状态 $status = (new Czgprz())->where('id' ,$v['bill_id'] )->where('status',2)->value('status'); if($status == 2){ $arr[] = $v['id']; } }else{ // bill_id 为 0 或 null 但不是用友集成的,可能是其他类型,也包含 $arr[] = $v['id']; } } // 根据 business_id 筛选,只返回与当前项目关联的报价单 // 支持模糊搜索(通过 name 字段) $searchName = $param['name'] ?? ''; $pageNumber = isset($param['pageNumber']) ? intval($param['pageNumber']) : 1; $pageSize = isset($param['pageSize']) ? intval($param['pageSize']) : 10; // 确保至少显示10条 if ($pageNumber == 1 && $pageSize < 10) { $pageSize = 10; } $model = (new Amodela()) ->where('business_id', 'in', $businessIds) ->where('id', 'in', $arr); if (!empty($searchName)) { $model->where('name', 'LIKE', '%' . $searchName . '%'); } $count = $model->count(); $list = (new Amodela()) ->where('business_id', 'in', $businessIds) ->where('id', 'in', $arr); if (!empty($searchName)) { $list->where('name', 'LIKE', '%' . $searchName . '%'); } $list = $list->order('createtime', 'desc') // 按创建时间倒序排列 ->page($pageNumber, $pageSize) ->select(); $result = array("total" => $count, "rows" => $list); return json($result); } /** * 获取报价单金额(通过调用用友集成API) */ public function getQuotationAmount() { $this->applyCrmJsonCorsHeaders(); $amodel_a_id = input('amodel_a_id/d', 0); if (!$amodel_a_id) { return json(['code' => 0, 'msg' => '参数错误', 'data' => null]); } $amodel = (new \addons\qingdong\model\Amodela())->where('id', $amodel_a_id)->find(); if (!$amodel) { return json(['code' => 0, 'msg' => '报价单记录不存在', 'data' => null]); } // 从 name 中解析 quotation_id $name = $amodel['name'] ?? ''; if (!preg_match('/\(quotation_(\d+)\)/', $name, $matches)) { return json(['code' => 0, 'msg' => '未找到用友报价单ID', 'data' => null]); } $quotation_id = $matches[1]; // 调用用友集成API获取报价单详情 $apiUrl = 'http://localhost:5002/api/Yongyou/Actions/GetQuotation/' . $quotation_id; $response = @file_get_contents($apiUrl); if ($response === false) { return json(['code' => 0, 'msg' => '获取报价单信息失败', 'data' => null]); } $data = json_decode($response, true); if (!$data || !isset($data['data'])) { return json(['code' => 0, 'msg' => '解析报价单数据失败', 'data' => null]); } $quotationData = $data['data']; return json([ 'code' => 1, 'msg' => '获取成功', 'data' => [ 'totalAmount' => $quotationData['totalAmount'] ?? 0, 'totalAmountInWords' => $quotationData['totalAmountInWords'] ?? '' ] ]); } /** * Vue 开发 (:5001) 直连 CRM PHP (:8000) 时的 CORS 与 OPTIONS。 */ protected function applyCrmJsonCorsHeaders() { header('Content-Type: application/json; charset=utf-8'); if (isset($_SERVER['HTTP_ORIGIN'])) { header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']); header('Access-Control-Allow-Credentials: true'); header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS'); header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With'); } if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; } } /** * 获取合同的报价单ID(offer_id) */ public function get_contract_offer_id() { $this->applyCrmJsonCorsHeaders(); $ids = input('ids'); if (empty($ids)) { return json(['code' => 0, 'msg' => '合同ID不能为空', 'data' => null]); } $contract = $this->model->where('id', $ids)->find(); if (!$contract) { return json(['code' => 0, 'msg' => '合同不存在', 'data' => null]); } return json([ 'code' => 1, 'msg' => '获取成功', 'data' => [ 'offer_id' => $contract->offer_id ] ]); } /** * 获取合同详情(包括合同编号) */ public function get_contract_detail() { $this->applyCrmJsonCorsHeaders(); $ids = input('ids'); if (empty($ids)) { return json(['code' => 0, 'msg' => '合同ID不能为空', 'data' => null]); } $contract = $this->model->where('id', $ids)->with(['business'])->find(); if (!$contract) { return json(['code' => 0, 'msg' => '合同不存在', 'data' => null]); } $businessName = $this->resolveContractBusinessDisplayName($contract); return json([ 'code' => 1, 'msg' => '获取成功', 'data' => [ 'id' => $contract->id, 'num' => $contract->num, 'name' => $contract->name, 'offer_id' => $contract->offer_id, 'business_id' => $contract->business_id, 'business_name' => $businessName ] ]); } /** * 解析合同对应的「项目名称」:优先 CRM 商机名称;合同未绑商机时从关联报价单 amodel_a.business_name 读取(与 save_quotation_link 写入一致)。 * @param \addons\qingdong\model\Contract $contract */ protected function resolveContractBusinessDisplayName($contract) { try { if ($contract->business && !empty($contract->business->name)) { return trim((string)$contract->business->name); } $bid = isset($contract->business_id) ? $contract->business_id : null; if (!empty($bid)) { $n = \addons\qingdong\model\Business::where('id', $bid)->value('name'); if ($n !== null && $n !== '') { return trim((string)$n); } } $oid = isset($contract->offer_id) ? $contract->offer_id : null; if (!empty($oid)) { $amodelRow = (new Amodela())->where('id', $oid)->find(); $hint = $this->resolveBusinessHintFromAmodelRow($amodelRow); if (($hint['business_name'] ?? '') !== '') { return $hint['business_name']; } } } catch (\Throwable $e) { \think\Log::write('resolveContractBusinessDisplayName: ' . $e->getMessage(), 'warning'); } return ''; } /** * amodel_a 一行上的商机显示名(business_name 或关联 qingdong_business.name)。 * * @param object|null $amodelRow * @return array{business_name: string, business_id: mixed|null} */ protected function resolveBusinessHintFromAmodelRow($amodelRow) { if (!$amodelRow) { return ['business_name' => '', 'business_id' => null]; } try { $bizName = trim((string)($amodelRow->business_name ?? '')); $abid = isset($amodelRow->business_id) ? $amodelRow->business_id : null; if ($bizName === '' && !empty($abid)) { $n = \addons\qingdong\model\Business::where('id', $abid)->value('name'); if ($n !== null && $n !== '') { $bizName = trim((string)$n); } } return ['business_name' => $bizName, 'business_id' => $abid]; } catch (\Throwable $e) { \think\Log::write('resolveBusinessHintFromAmodelRow: ' . $e->getMessage(), 'warning'); } return ['business_name' => '', 'business_id' => null]; } /** * 关联报价单行(amodel_a)上的商机摘要:销售订单表头「项目名称」兜底; * 兼容 get_contract_detail 仅返回旧字段(仅有 offer_id)时仍能带出商机名称。 */ public function get_offer_business_hint() { $this->applyCrmJsonCorsHeaders(); $offer_id = input('offer_id'); if ($offer_id === null || $offer_id === '') { return json(['code' => 0, 'msg' => '报价单关联ID(offer_id)不能为空', 'data' => null]); } try { $amodelRow = (new Amodela())->where('id', $offer_id)->find(); if (!$amodelRow) { return json(['code' => 0, 'msg' => '报价单行不存在', 'data' => null]); } $hint = $this->resolveBusinessHintFromAmodelRow($amodelRow); return json([ 'code' => 1, 'msg' => '获取成功', 'data' => [ 'business_name' => $hint['business_name'], 'business_id' => $hint['business_id'], ], ]); } catch (\Throwable $e) { \think\Log::write('get_offer_business_hint: ' . $e->getMessage(), 'error'); return json(['code' => 0, 'msg' => $e->getMessage(), 'data' => null]); } } /** * 从 offer_id(amodel_a表的ID)获取用友集成的报价单ID * 如果报价单是用友集成的,name字段包含 (quotation_数字),提取其中的 quotation_id * 同时返回 amodel_a 上的商机摘要(业务上作为销售订单「项目名称」),无需单独调 get_offer_business_hint(线上已存在本接口)。 */ public function get_quotation_id_from_offer() { $this->applyCrmJsonCorsHeaders(); $offer_id = input('offer_id'); if (empty($offer_id)) { return json(['code' => 0, 'msg' => '报价单ID不能为空', 'data' => null]); } $amodela = (new Amodela())->where('id', $offer_id)->find(); if (!$amodela) { return json(['code' => 0, 'msg' => '报价单不存在', 'data' => null]); } $offerBizHint = $this->resolveBusinessHintFromAmodelRow($amodela); $quotationId = null; // 判断是否是用友集成的报价单(通过 name 字段中包含 quotation_ 标记) if (isset($amodela->name) && strpos($amodela->name, '(quotation_') !== false) { // 提取 quotation_id if (preg_match('/\(quotation_(\d+)\)/', $amodela->name, $matches)) { $quotationId = $matches[1]; } } return json([ 'code' => 1, 'msg' => '获取成功', 'data' => [ 'quotation_id' => $quotationId, 'is_yongyou' => !empty($quotationId), 'offer_id' => $offer_id, 'business_name' => $offerBizHint['business_name'], 'business_id' => $offerBizHint['business_id'], ] ]); } /** * 搜索合同列表(用于下拉框选择,无需认证) */ public function search_contracts() { // 立即设置响应头为 JSON,避免 ThinkPHP 输出 HTML 错误页面 header('Content-Type: application/json; charset=utf-8'); // 处理 CORS 跨域请求 if (isset($_SERVER['HTTP_ORIGIN'])) { header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']); header('Access-Control-Allow-Credentials: true'); header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS'); header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With'); } // 处理 OPTIONS 预检请求 if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') { http_response_code(200); exit; } // 使用 ob_start 捕获所有输出,确保只返回 JSON ob_start(); try { // 确保模型已初始化 if (!$this->model) { $this->model = new \addons\qingdong\model\Contract; } $name = input('name', ''); $num = input('num', ''); // 支持按合同编号搜索 $pageNumber = input('pageNumber', 1); $pageSize = input('pageSize', 20); $where = []; if (!empty($name)) { $where['name'] = ['like', '%' . $name . '%']; } // 如果提供了合同编号,优先按合同编号精确匹配 if (!empty($num)) { $where['num'] = $num; } // 查询所有状态的合同(包括待审核、已审核通过等),以便在销售订单中可以选择 // 不再限制 check_status,让用户可以选择任意状态的合同 $list = $this->model ->where($where) ->with(['customer', 'business']) ->order('id desc') ->page($pageNumber, $pageSize) ->select(); $count = $this->model->where($where)->count(); // 格式化返回数据 $rows = []; foreach ($list as $contract) { $bizDisplay = $this->resolveContractBusinessDisplayName($contract); $bid = isset($contract->business_id) ? $contract->business_id : null; $rows[] = [ 'id' => $contract->id, 'name' => $contract->name, 'num' => $contract->num, 'customer' => $contract->customer ? [ 'id' => $contract->customer->id, 'name' => $contract->customer->name ] : null, 'business' => ($bizDisplay !== '') ? [ 'id' => $bid, 'name' => $bizDisplay ] : null, 'business_name' => $bizDisplay, 'offer_id' => $contract->offer_id, 'money' => $contract->money ]; } ob_clean(); echo json_encode([ 'total' => $count, 'rows' => $rows ], JSON_UNESCAPED_UNICODE); exit; } catch (\Exception $e) { \think\Log::write('search_contracts 异常: ' . $e->getMessage() . ' | 文件: ' . $e->getFile() . ' | 行号: ' . $e->getLine(), 'error'); ob_clean(); header('Content-Type: application/json; charset=utf-8'); http_response_code(200); echo json_encode([ 'total' => 0, 'rows' => [], 'error' => '查询合同失败:' . $e->getMessage() ], JSON_UNESCAPED_UNICODE); exit; } catch (\Throwable $e) { \think\Log::write('search_contracts 致命错误: ' . $e->getMessage() . ' | 文件: ' . $e->getFile() . ' | 行号: ' . $e->getLine(), 'error'); ob_clean(); header('Content-Type: application/json; charset=utf-8'); http_response_code(200); echo json_encode([ 'total' => 0, 'rows' => [], 'error' => '查询合同失败:' . $e->getMessage() ], JSON_UNESCAPED_UNICODE); exit; } finally { // 清理输出缓冲区 if (ob_get_level() > 0) { ob_end_flush(); } } } /** * 修改合同 */ 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('无可用审批流,请联系管理员','antis/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 get_file($ids = null) { list($where, $sort, $order, $offset, $limit) = $this->buildparams(); $list = Invoice::where(['contract_id' => $ids])->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; } // 关联报价单(amodel_a.offer_id):用于详情页展示,逻辑与 get_quotation_id_from_offer / get_business_bill 一致 $quotation_info = [ 'has_offer' => false, 'offer_id' => null, 'offer_name' => '', 'offer_name_display' => '', 'is_yongyou' => false, 'quotation_id' => null, 'view_url' => '', ]; if (!empty($row['offer_id'])) { $amodela = (new Amodela())->where('id', $row['offer_id'])->find(); if ($amodela) { $amodelaArr = $amodela->toArray(); $name = isset($amodelaArr['name']) ? (string)$amodelaArr['name'] : ''; $quotation_info['has_offer'] = true; $quotation_info['offer_id'] = $amodelaArr['id']; $quotation_info['offer_name'] = $name; $display = preg_replace('/\s*\(quotation_\d+\)\s*$/u', '', $name); $quotation_info['offer_name_display'] = trim($display) !== '' ? trim($display) : $name; if ($name !== '' && strpos($name, '(quotation_') !== false && preg_match('/\(quotation_(\d+)\)/', $name, $matches)) { $quotation_info['is_yongyou'] = true; $quotation_info['quotation_id'] = $matches[1]; $quotation_info['view_url'] = get_yongyou_integration_full_url('quotation', ['id' => $matches[1], 'mode' => 'view']); } } } $this->assign('quotation_info', $quotation_info); $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\antis\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\antis\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(); } public function flow(){ $params = $this->request->param(); $url = request()->domain() . '/addons/qingdong/bill/detail'; $headers = [ 'Content-Type' => 'application/json' ]; $bodys = json_encode([ "bill"=>"ats_bywnpk", "bill_id"=>$params['bill_id'], ]); $client = new Client(); $request = new Request('POST', $url, $headers, $bodys); $res = $client->sendAsync($request)->wait(); $file = $res->getBody()->getContents(); $data = json_decode($file)->data; $lclist = []; $c1 = []; $nodes_data2 = $this->object_array($data->nodes_data2); if (empty($nodes_data2)) { }else{ $logs = array_reverse($this->object_array($data->logs)); if (end($logs)['step_name'] == '结束') { $lclist = $logs; } else { if (count($logs) <= count($nodes_data2)) { $c1[] = $logs[0]; foreach ($nodes_data2 as $n => $node) { $cq = null; $nodes_data2[$n]['type'] = '2'; foreach ($logs as $i => $log) { if ($node['name'] == $log['step_name']) { $cq = $i; break; } } if (!is_null($cq)) { $c1[] = $logs[$cq]; } else { $c1[] = $nodes_data2[$n]; } } } else { $c1 = $logs; } $lclist = $c1; } } // halt($lclist); $lclist = $this->object_array($lclist); $this->assign('row', $lclist); return $this->view->fetch('flow'); } }