1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723 |
- <?php
- namespace app\admin\controller\qingdongams\customer;
- use addons\qingdongams\model\Receivables;
- use addons\qingdongams\model\BusinessProduct;
- use addons\qingdongams\model\ContactsOther;
- use addons\qingdongams\model\ContractProduct;
- use addons\qingdongams\model\Quote;
- use addons\qingdongams\model\ExamineRecord;
- use addons\qingdongams\model\File;
- use addons\qingdongams\model\FormField;
- use addons\qingdongams\model\ProductPart;
- use addons\qingdongams\model\Product;
- use addons\qingdongams\model\QuoteProduct;
- use addons\qingdongams\model\Ratio;
- use addons\qingdongams\model\Staff;
- use addons\qingdongams\model\WordTemplate;
- use app\admin\controller\qingdongams\Base;
- use addons\qingdongams\model\ContractOther;
- use addons\qingdongams\model\Form;
- use addons\qingdongams\model\Contacts;
- use addons\qingdongams\model\Customer;
- use addons\qingdongams\model\OperationLog;
- use addons\qingdongams\model\Record;
- use addons\qingdongams\model\ContractFile;
- use addons\qingdongams\model\Flow;
- use addons\qingdongams\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 addons\qingdongams\model\Contract as ContractModel;
- use addons\qingdongams\model\Message;
- use think\Db;
- use think\Exception;
- /**
- * 合同管理
- * @desc 操作文档:https://doc.fastadmin.net/qingdongams
- * @desc 软件介绍:https://www.fastadmin.net/store/qingdongams.html
- * @desc 售后微信:qingdong_crm
- */
- class Contract extends Base {
- protected $relationSearch = true;
- /**
- * @var \addons\qingdongams\model\Contract
- */
- protected $model = null;
- protected $Equipmentdevice = null;
- protected $noNeedRight = ['index1'];
- protected $noNeedLogin = ['index1'];
- public function _initialize() {
- parent::_initialize();
- $this->model = new \addons\qingdongams\model\Contract;
- $this->Equipmentdevice = new \app\admin\model\qingdongams\customer\Equipmentdevice;
- }
- /**
- * 查看
- */
- public function index() {
- //设置过滤方法
- $this->request->filter(['strip_tags', 'trim']);
- if ($this->request->isAjax()) {
- if ($this->request->request('keyField')) {
- return $this->selectpage();
- }
- //0:全部 1:我负责的 2:下属负责的 3:今日待跟进 4:今日已跟进 5:从未跟进的
- $type = input('type',0);
- list($where, $sort, $order, $offset, $limit) = $this->buildparams();
- switch($type){
- case 1:
- $staff = Staff::info();
- $wheres['owner_staff_id'] = $staff->id;
- break;
- case 2:
- $wheres['owner_staff_id'] = array('in',Staff::getLowerStaffId());
- break;
- case 3:
- $start = date('Y-m-d 00:00:00');
- $end = date('Y-m-d 23:59:59');
- $record = collection(Record::where(array('relation_type'=>3,'next_time'=>array(array('egt',$start),array('elt',$end))))->field("id,relation_id")->select())->toArray();
- $relationId = [];
- foreach($record as $k=>$v){
- $whereRe['id'] = array('gt',$v['id']);
- $whereRe['relation_id'] = $v['relation_id'];
- $recordData = Record::where($whereRe)->count();
- if($recordData == 0){
- $relationId[] = $v['relation_id'];
- }
- }
- $wheres['id'] = array('in',$relationId);
- $staff = Staff::info();
- $wheres['owner_staff_id'] = $staff->id;
- break;
- case 4:
- $start = date('Y-m-d 00:00:00');
- $end = date('Y-m-d 23:59:59');
- $record = collection(Record::where(array('relation_type'=>3,'next_time'=>array(array('egt',$start),array('elt',$end))))->field("id,relation_id")->select())->toArray();
- $relationId = [];
- foreach($record as $k=>$v){
- $whereRe['id'] = array('gt',$v['id']);
- $whereRe['relation_id'] = $v['relation_id'];
- $recordData = Record::where($whereRe)->count();
- if($recordData >=1){
- $relationId[] = $v['relation_id'];
- }
- }
- $wheres['id'] = array('in',$relationId);
- $staff = Staff::info();
- $wheres['owner_staff_id'] = $staff->id;
- break;
- case 5:
- $record = collection(Record::where(array('relation_type'=>3,'next_time'=>array('neq','')))->column('relation_id'))->toArray();
- $wheres['id'] = array('not in',$record);
- $staff = Staff::info();
- $wheres['owner_staff_id'] = $staff->id;
- break;
- default:
- $wheres['owner_staff_id'] = array('in',Staff::getMyStaffIds());
- break;
- }
- $ids=[];
- $group_id=input('group_id');
- $staff_id=input('staff_id');
- if ($group_id) {//角色组
- $ids = Staff::getGroupStaffIds($group_id);
- }
- if ($staff_id) {
- $ids = $staff_id;
- }
- if ($group_id || $staff_id) {
- $wheres['owner_staff_id'] = ['in', $ids];
- }
- $list = $this->model->where($where)
- ->where($wheres)
- ->with([
- 'customer',
- 'orderStaff',
- 'contacts',
- 'receivables',
- 'invoice'
- ])->order($sort, $order)->paginate($limit);
- $result = array("total" => $list->total(), "rows" => $list->items());
- return json($result);
- }
- $field = FormField::getFields(FormField::CONTRACT_TYPE);
- $this->assignconfig('fields', $field);
- return $this->view->fetch();
- }
- public function index1() {
- //设置过滤方法
- $this->request->filter(['strip_tags', 'trim']);
- if ($this->request->isAjax()) {
- if ($this->request->request('keyField')) {
- return $this->selectpage();
- }
- //0:全部 1:我负责的 2:下属负责的 3:今日待跟进 4:今日已跟进 5:从未跟进的
- $type = input('type',0);
- list($where, $sort, $order, $offset, $limit) = $this->buildparams();
- switch($type){
- case 1:
- $staff = Staff::info();
- $wheres['owner_staff_id'] = $staff->id;
- break;
- case 2:
- $wheres['owner_staff_id'] = array('in',Staff::getLowerStaffId());
- break;
- case 3:
- $start = date('Y-m-d 00:00:00');
- $end = date('Y-m-d 23:59:59');
- $record = collection(Record::where(array('relation_type'=>3,'next_time'=>array(array('egt',$start),array('elt',$end))))->field("id,relation_id")->select())->toArray();
- $relationId = [];
- foreach($record as $k=>$v){
- $whereRe['id'] = array('gt',$v['id']);
- $whereRe['relation_id'] = $v['relation_id'];
- $recordData = Record::where($whereRe)->count();
- if($recordData == 0){
- $relationId[] = $v['relation_id'];
- }
- }
- $wheres['id'] = array('in',$relationId);
- $staff = Staff::info();
- $wheres['owner_staff_id'] = $staff->id;
- break;
- case 4:
- $start = date('Y-m-d 00:00:00');
- $end = date('Y-m-d 23:59:59');
- $record = collection(Record::where(array('relation_type'=>3,'next_time'=>array(array('egt',$start),array('elt',$end))))->field("id,relation_id")->select())->toArray();
- $relationId = [];
- foreach($record as $k=>$v){
- $whereRe['id'] = array('gt',$v['id']);
- $whereRe['relation_id'] = $v['relation_id'];
- $recordData = Record::where($whereRe)->count();
- if($recordData >=1){
- $relationId[] = $v['relation_id'];
- }
- }
- $wheres['id'] = array('in',$relationId);
- $staff = Staff::info();
- $wheres['owner_staff_id'] = $staff->id;
- break;
- case 5:
- $record = collection(Record::where(array('relation_type'=>3,'next_time'=>array('neq','')))->column('relation_id'))->toArray();
- $wheres['id'] = array('not in',$record);
- $staff = Staff::info();
- $wheres['owner_staff_id'] = $staff->id;
- break;
- default:
- $wheres['owner_staff_id'] = array('in',Staff::getMyStaffIds());
- break;
- }
- $ids=[];
- $group_id=input('group_id');
- $staff_id=input('staff_id');
- if ($group_id) {//角色组
- $ids = Staff::getGroupStaffIds($group_id);
- }
- if ($staff_id) {
- $ids = $staff_id;
- }
- if ($group_id || $staff_id) {
- $wheres['owner_staff_id'] = ['in', $ids];
- }
- $list = $this->model->where($where)
- ->where($wheres)
- ->with([
- 'customer',
- 'orderStaff',
- 'contacts',
- 'receivables',
- 'invoice'
- ])->order($sort, $order)->paginate(5);
- $result = array("total" => $list->total(), "rows" => $list->items());
- return json($result);
- }
- $field = FormField::getFields(FormField::CONTRACT_TYPE);
- $this->assignconfig('fields', $field);
- return $this->view->fetch();
- }
- /**
- * 添加
- */
- public function add()
- {
- if ($this->request->isPost()) {
- $params = $this->request->post("row/a");
- if ($params) {
- $params = $this->preExcludeFields($params);
- // 表单验证
- if (($result = $this->qingdongamsValidate($params, 'Contract', 'create')) !== true) {
- $this->error($result);
- }
- $result = FormField::checkFields(FormField::CONTRACT_TYPE, $params);
- if ($result !== true) {
- $this->error($result);
- }
- if(isset($params['flow_staff_ids'])){
- if(!$params['flow_staff_ids']){
- $this->error('请选择审批人');
- }
- }
- $result = false;
- Db::startTrans();
- try {
- $params = Form::updateFormParams(Form::CONTRACT_TYPE, $params);
- $res=true;
- if ($params['start_time'] && $params['end_time']) {
- if (strtotime($params['start_time']) >= strtotime($params['end_time'])) {
- $this->error('生效时间不能大于等于结束时间');
- }
- }
- if($params['product']){
- $params['product']=json_decode($params['product'],true);
- }
- $result = $this->model::createContract($params);
- if($params['device_ids']){
- $exp=explode(",",$params['device_ids']);
- if(count($exp)>0){
- foreach($exp as $key=>$val){
- //查询设备信息
- $info= $this->Equipmentdevice->where(array('id'=>$val))->find();
- if(!$info){
- $this->error("设备信息不存在");
- }
- //更新当前设备绑定信息
- //$result 合同id
- //customer_id 客户id
- $res=$this->Equipmentdevice->where(array('id'=>$val))->update(array('status'=>1,'customer_id'=>$params['customer_id'],'contract_id'=>$result));
- if($res){
- $res=true;
- }else{
- $res=false;
- }
- }
- }
- }
- if($res && $result){
- Db::commit();
- }else{
- Db::rollback();
- $this->error("创建失败");
- }
-
- } 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('无可用审批流,请联系管理员');
- }
- $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('customer', Customer::get($customer_id));
- $this->assign('business_id', input('business_id'));
- $this->assign('staffs', Staff::allList());
- $this->assign('form_data', Form::getDataValue('contract'));
- $this->assign('ratio',Ratio::where(['status'=>1])->select());
- $this->assign('contractNum', 'C'.date('Ymd').rand(10000,99999));
- return $this->view->fetch();
- }
- /**
- * 修改合同
- */
- public function edit($ids = null) {
- $map['id'] = $ids;
- if ($this->request->isAjax()) {
- $params = $this->request->post('row/a');
- $params = $this->preExcludeFields($params);
- $row = $this->model::where(['id' => $ids, 'check_status' => ['in', [3, 4]]])->find();
- if (empty($row)) {
- $this->error('合同审核中或已审核通过无法修改');
- }
- // 表单验证
- if (($result = $this->qingdongamsValidate($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('无可用审批流,请联系管理员');
- }
- $this->assign('flow',$flow);
- $this->view->assign("row", $row);
- $this->assign('customers', Customer::getList());
- $this->assign('business', Business::getList());
- $this->assign('staffs', Staff::getList());
- $this->assign('staff', Staff::getStaff());
- $this->assign('ratio',Ratio::where(['status'=>1])->select());
- $this->assign('form_data', Form::getDataValue('contract',$row));
- $this->assign('contacts', Contacts::where(['customer_id'=>$row['customer_id']])->field('id,name')->select());
- return $this->view->fetch();
- }
- /**
- * 获取附件记录
- */
- public function get_file($ids = null) {
- list($where, $sort, $order, $offset, $limit) = $this->buildparams();
- $list = ContractFile::where(['contract_id' => $ids])->with(['file'])->field('file_id')->paginate($limit);
- $result = array("total" => $list->total(), "rows" => $list->items());
- return json($result);
- }
- /**
- * 合同详情
- */
- public function detail($ids = null) {
- $row = $this->model->where(['id' => $ids])->with([
- 'customer',
- 'contacts',
- 'orderStaff',
- 'ownerStaff',
- 'business'
- ])->find();
- if (empty($row)) {
- $this->error(__('No Results were found'));
- }
- $row=$row->toArray();
- $row=ContractOther::getOther($row);
- $row['ratios'] = json_decode($row['ratios'], true);
- if ($row['ratios']) {
- foreach ($row['ratios'] as $k => $v) {
- $v['staff'] = Staff::where(['id' => $v['staff_id']])->field('id,name,img,post')->find()->toArray();
- $v['money'] = $row['money'] * ($v['ratio'] / 100);
- $row['ratios'][$k] = $v;
- }
- }
- $row['repayment_money'] = Receivables::where(['contract_id'=>$ids])->sum('money'); //已回款
- $row['no_money'] = $row['money'] -$row['repayment_money'];
- if($row['no_money'] <= 0){
- $row['no_money'] = 0;
- }
- $this->assign('examine_record',ExamineRecord::getList(ExamineRecord::CONTRACT_TYPE,$ids));
- $this->assign('flow',Flow::getstepdetail(Flow::CONTRACT_STATUS, $ids));
- //跟进记录
- $this->assign('records', Record::getList(Record::CONTRACT_TYPE, $ids));
- //操作记录
- $log=OperationLog::getList(OperationLog::CONTRACT_TYPE, $ids);
- //标记通知已读
- Message::setRead(Message::CONTRACT_TYPE, $ids, $this->_staff->id);
- $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('参数不能为空');
- }
- $list=$this->Equipmentdevice->where(array('contract_id'=>$contract_id))->select();
- return json(['rows' =>$list, 'total' => count($list)]);
- }
- /**
- * 获取产品明细
- */
- // 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\qingdongams\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\qingdongams\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);
- // 修改绑定设备的设备状态
- \app\admin\model\qingdongams\customer\Equipmentdevice::updateStatus($ids);
- // 更新合同表时间
- $contract = \addons\qingdongams\model\Contract::where(['id' => $ids])->find();
- $contract->updatetime = time();
- $contract->save();
- $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 quote_change()
- {
- $quote_id = input('quote_id');
- if ($this->request->isPost()) {
- $params = $this->request->post("row/a");
- if ($params) {
- $params = $this->preExcludeFields($params);
- // 表单验证
- if (($result = $this->qingdongamsValidate($params, 'Contract', 'create')) !== true) {
- $this->error($result);
- }
- $result = FormField::checkFields(FormField::CONTRACT_TYPE, $params);
- if ($result !== true) {
- $this->error($result);
- }
- $result = false;
- Db::startTrans();
- try {
- $params = Form::updateFormParams(Form::CONTRACT_TYPE, $params);
- if ($params['product']) {
- $params['product'] = json_decode($params['product'], true);
- }
- $result = $this->model::createContract($params);
- Db::commit();
- } catch (Exception $e) {
- Db::rollback();
- $this->error($e->getMessage());
- }
- if ($result !== false) {
- $this->success();
- } else {
- $this->error(__('No rows were inserted'));
- }
- }
- $this->error(__('Parameter %s can not be empty', ''));
- }
- $flow = Flow::getsteplist(Flow::CONTRACT_STATUS);
- if (empty($flow)) {
- $this->error('无可用审批流,请联系管理员');
- }
- $customer_id = input('customer_id');
- if ($customer_id) {
- $business = Business::where(array('customer_id' => $customer_id))->select();
- } else {
- $business = Business::getList();
- }
- $quote = Quote::where(['id' => $quote_id])->with(['customer','contacts'])->find();
- $product=QuoteProduct::where(['quote_id'=>$quote['id']])->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;
- }
- $quote['product']=json_encode($product);
- $quote['num']=getItemNumber('contract');
- $quote['money']=$quote['quote_amount'];
- $this->assign('row', $quote);
- $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());
- return $this->view->fetch();
- }
- /**下载合同
- */
- public function download_quote($id = null)
- {
- $contract = ContractModel::where(['id' => $id])->with(['customer', 'contacts','orderStaff',])->find();
- if (empty($contract)) {
- $this->error('不能为空');
- }
- $contract = $contract->toArray();
- $contractProduct = ContractProduct::where(['contract_id' => $id])->with(['product'])->select();
- $tmp = new TemplateProcessor('assets/addons/qingdongams/phpword/contract.docx');
- \PhpOffice\PhpWord\Settings::setCompatibility(true);
- \PhpOffice\PhpWord\Settings::setOutputEscapingEnabled(true);
- $tmp->setValue('number', $contract['num']);//合同编号
- $tmp->setValue('name', $contract['customer']['name']);//乙方
- $tmp->setValue('signing_time', date('Y年m月d日', strtotime($contract['order_date'])));//签订时间
- $tmp->setValue('signed_at', $contract['signed_at']);//签订地点
- $tmp->setValue('order_name', $contract['order_staff']['name']);
- $tmp->setValue('order_mobile', $contract['order_staff']['mobile']);
- $rows = count($contractProduct);//总行数
- $tmp->cloneRow('one', $rows);//复制行
- for ($i = 0; $i < $rows; $i++) {
- $tmp->setValue("one#" . ($i + 1), $contractProduct[$i]['name'] ?? '');//名称
- $tmp->setValue("two#" . ($i + 1), $contractProduct[$i]['num'] ?? '');//型号
- $tmp->setValue("three#" . ($i + 1), $contractProduct[$i]['number'] ?? '');//数量
- $tmp->setValue("four#" . ($i + 1), $contractProduct[$i]['price'] ?? '');//总价格
- }
- //start 配置
- $configs = [];
- $tmp->setValue("discount_rate", $contract['discount_rate']);//金额
- $tmp->setValue("price", $contract['money']);//金额
- $tmp->setValue("price_big", convertAmountToCn($contract['money'] ?? 0));//汉字金额
- $tmp->setValue("remarks", $contract['remarks']);//备注
- $tmp->setValue("payment", $contract['payment']);//支付方式
- $tmp->setValue("be_overdue", $contract['be_overdue']);//到期条款
- $tmp->setValue("delivery_time", $contract['delivery_time']);//
- $tmp->setValue("account", $contract['collection_account']);//
- $tmp->setValue("account_name", $contract['collection_deposit']);//
- $tmp->setValue("bank_name", $contract['collection_name']);//
- $tmp->setValue("effective", $contract['effective']);//
- $tmp->setValue("guarantee", $contract['guarantee']);//
- $tmp->setValue("address", $contract['customer']['address']);//
- $tmp->setValue("legal", $contract['legal']);//
- $tmp->setValue("entrust", $contract['entrust']);//
- $tmp->setValue("handler", $contract['handler']);//
- $tmp->setValue("mobile", $contract['mobile']);//
- $tmp->setValue("fax", $contract['fax']);//
- $tmp->setValue("deposit", $contract['deposit']);//
- $tmp->setValue("y_account", $contract['account']);//
- //end 配置
- $filename = $contract['customer']['name'] . $contract['num'] . '.docx';
- $fileurl = './uploads/' . date('Ymd') . '/';
- if (!file_exists($fileurl)) {
- mkdir($fileurl);
- }
- $tmp->saveAs($fileurl . $filename);//另存为
- $model = new File();
- $data = [
- 'types' => 'file',
- 'name' => $filename,
- 'save_name' => $fileurl . $filename,
- 'size' => filesize($fileurl . $filename),
- 'file_path' => trim($fileurl, '.') . $filename,
- ];
- $model->save($data);
- $lastid = $model->getLastInsID();
- $file = cdnurl($model::getUrl($lastid), true);
- $this->success('成功', '', ['file' => $file, 'id' => $lastid, 'filename' => $filename]);
- }
- /**
- * 添加收货地址
- */
- public function address($ids = null)
- {
- if ($this->request->isAjax()) {
- $params = $this->request->post('row/a');
- $row = ContractModel::where(['id' => $ids])->find();
- if (empty($row)) {
- $this->error('合同信息不存在');
- }
- $params['id'] = $ids;
- Db::startTrans();
- try {
- ContractModel::updateContractAddress($params);
- // 更新合同表时间
- $contract = \addons\qingdongams\model\Contract::where(['id' => $ids])->find();
- $contract->updatetime = time();
- $contract->save();
- Db::commit();
- } catch (Exception $e) {
- Db::rollback();
- $this->error($e->getMessage());
- }
- $this->success('添加收货地址信息成功');
- }
- $row = $this->model->where(['id' => $ids])->find();
- $this->view->assign("row", $row);
- $this->view->assign("id", $ids);
- return $this->view->fetch();
- }
- /**
- * 发票物流
- */
- public function invoice_contract($ids = null)
- {
- if ($this->request->isAjax()) {
- $params = $this->request->post('row/a');
- $row = ContractModel::where(['id' => $ids])->find();
- if (empty($row)) {
- $this->error('合同信息不存在');
- }
- $params['id'] = $ids;
- Db::startTrans();
- try {
- $params['invoice_file_ids'] = File::getId($params['invoice_file_ids']);
- ContractModel::invoiceContract($params);
- // 更新合同表时间
- $contract = \addons\qingdongams\model\Contract::where(['id' => $ids])->find();
- $contract->updatetime = time();
- $contract->save();
- Db::commit();
- } catch (Exception $e) {
- Db::rollback();
- $this->error($e->getMessage());
- }
- $this->success('添加收货地址信息成功');
- }
- $row = $this->model->where(['id' => $ids])->find()->toArray();
- $row['invoice_file_ids'] = implode(',', $row['invoice_file_ids']);
- $this->view->assign("row", $row);
- $this->view->assign("id", $ids);
- return $this->view->fetch();
- }
- /**
- * 发票回执单
- */
- public function receipt_contract($ids = null)
- {
- if ($this->request->isAjax()) {
- $params = $this->request->post('row/a');
- if (empty($params['receipt_file_ids'])) {
- $this->error('回执单不能为空');
- }
- if (empty($params['receipt_date'])) {
- $this->error('回执时间不能为空');
- }
- Db::startTrans();
- try {
- $params['id'] = $ids;
- $params['receipt_file_ids'] = File::getId($params['receipt_file_ids']);
- ContractModel::receiptContract($params);
- // 更新合同表时间
- $contract = \addons\qingdongams\model\Contract::where(['id' => $ids])->find();
- $contract->updatetime = time();
- $contract->save();
- Db::commit();
- } catch (Exception $e) {
- Db::rollback();
- $this->error($e->getMessage());
- }
- $this->success('回执成功');
- }
- $row = $this->model->where(['id' => $ids])->find()->toArray();
- $row['receipt_file_ids'] = implode(',', $row['receipt_file_ids']);
- $this->view->assign("row", $row);
- $this->view->assign("id", $ids);
- return $this->view->fetch();
- }
- /**
- * 终止合同
- */
- public function revoke_contract()
- {
- $id = input('id');
- $model = new ContractModel();
- $row = $model->get($id);
- if (empty($row)) {
- $this->error('信息不存在');
- }
- $files = $model->where(['id' => $id])->update(['contract_status' => 2, 'check_status' => 9]);
- // 修改绑定设备的设备状态
- \app\admin\model\qingdongams\customer\Equipmentdevice::updateStatus($id);
- OperationLog::createLog(OperationLog::CONTRACT_TYPE, $id, '终止合同');
- $this->success('操作成功', $files);
- }
- }
|