Contract.php 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299
  1. <?php
  2. namespace app\admin\controller\qingdong\customer;
  3. use addons\qingdong\model\BusinessProduct;
  4. use addons\qingdong\model\ContactsOther;
  5. use addons\qingdong\model\ContractProduct;
  6. use addons\qingdong\model\CustomerOther;
  7. use addons\qingdong\model\ExamineRecord;
  8. use addons\qingdong\model\File;
  9. use addons\qingdong\model\FormField;
  10. use addons\qingdong\model\ProductPart;
  11. use addons\qingdong\model\Product;
  12. use addons\qingdong\model\Ratio;
  13. use addons\qingdong\model\Receivables;
  14. use addons\qingdong\model\Staff;
  15. use addons\qingdong\model\WordTemplate;
  16. use app\admin\controller\qingdong\Base;
  17. use addons\qingdong\model\ContractOther;
  18. use addons\qingdong\model\Form;
  19. use addons\qingdong\model\Contacts;
  20. use addons\qingdong\model\Customer;
  21. use addons\qingdong\model\OperationLog;
  22. use addons\qingdong\model\Record;
  23. use addons\qingdong\model\ContractFile;
  24. use addons\qingdong\model\Flow;
  25. use addons\qingdong\model\Business;
  26. use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
  27. use PhpOffice\PhpSpreadsheet\Reader\Csv;
  28. use PhpOffice\PhpSpreadsheet\Reader\Xls;
  29. use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
  30. use PhpOffice\PhpSpreadsheet\RichText\RichText;
  31. use PhpOffice\PhpWord\Settings;
  32. use PhpOffice\PhpWord\TemplateProcessor;
  33. use think\Db;
  34. use think\Exception;
  35. /**
  36. * 合同管理
  37. * 操作文档:https://doc.fastadmin.net/qingdong
  38. * 软件介绍:https://www.fastadmin.net/store/qingdong.html
  39. * 售后微信:qingdong_crm
  40. */
  41. class Contract extends Base {
  42. protected $relationSearch = true;
  43. /**
  44. * @var \addons\qingdong\model\Contract
  45. */
  46. protected $model = null;
  47. public function _initialize() {
  48. parent::_initialize();
  49. $this->model = new \addons\qingdong\model\Contract;
  50. }
  51. /**
  52. * 查看
  53. */
  54. public function index() {
  55. //设置过滤方法
  56. $this->request->filter(['strip_tags', 'trim']);
  57. if ($this->request->isAjax()) {
  58. if ($this->request->request('keyField')) {
  59. return $this->selectpage();
  60. }
  61. //0:全部 1:我负责的 2:下属负责的 3:今日待跟进 4:今日已跟进 5:从未跟进的
  62. $type = input('type',0);
  63. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  64. switch($type){
  65. case 1:
  66. $staff = Staff::info();
  67. $wheres['owner_staff_id'] = $staff->id;
  68. break;
  69. case 2:
  70. $wheres['owner_staff_id'] = array('in',Staff::getLowerStaffId());
  71. break;
  72. case 3:
  73. $start = date('Y-m-d 00:00:00');
  74. $end = date('Y-m-d 23:59:59');
  75. $record = collection(Record::where(array('relation_type'=>3,'next_time'=>array(array('egt',$start),array('elt',$end))))->field("id,relation_id")->select())->toArray();
  76. $relationId = [];
  77. foreach($record as $k=>$v){
  78. $whereRe['id'] = array('gt',$v['id']);
  79. $whereRe['relation_id'] = $v['relation_id'];
  80. $recordData = Record::where($whereRe)->count();
  81. if($recordData == 0){
  82. $relationId[] = $v['relation_id'];
  83. }
  84. }
  85. $wheres['id'] = array('in',$relationId);
  86. $staff = Staff::info();
  87. $wheres['owner_staff_id'] = $staff->id;
  88. break;
  89. case 4:
  90. $start = date('Y-m-d 00:00:00');
  91. $end = date('Y-m-d 23:59:59');
  92. $record = collection(Record::where(array('relation_type'=>3,'next_time'=>array(array('egt',$start),array('elt',$end))))->field("id,relation_id")->select())->toArray();
  93. $relationId = [];
  94. foreach($record as $k=>$v){
  95. $whereRe['id'] = array('gt',$v['id']);
  96. $whereRe['relation_id'] = $v['relation_id'];
  97. $recordData = Record::where($whereRe)->count();
  98. if($recordData >=1){
  99. $relationId[] = $v['relation_id'];
  100. }
  101. }
  102. $wheres['id'] = array('in',$relationId);
  103. $staff = Staff::info();
  104. $wheres['owner_staff_id'] = $staff->id;
  105. break;
  106. case 5:
  107. $record = collection(Record::where(array('relation_type'=>3,'next_time'=>array('neq','')))->column('relation_id'))->toArray();
  108. $wheres['id'] = array('not in',$record);
  109. $staff = Staff::info();
  110. $wheres['owner_staff_id'] = $staff->id;
  111. break;
  112. default:
  113. $wheres['owner_staff_id'] = array('in',Staff::getMyStaffIds());
  114. break;
  115. }
  116. $staff = Staff::info();
  117. $ids=[];
  118. $group_id=input('group_id');
  119. $staff_id=input('staff_id');
  120. if ($group_id) {//角色组
  121. $ids = Staff::getGroupStaffIds($group_id);
  122. }
  123. if ($staff_id) {
  124. $ids = $staff_id;
  125. }
  126. if ($group_id || $staff_id) {
  127. $wheres['owner_staff_id'] = ['in', $ids];
  128. }
  129. $staff = Staff::info();
  130. $staffid = $staff->id;
  131. $s = "FIND_IN_SET(".$staffid.",order_staff_id)";
  132. $list = $this->model->where($where)
  133. ->where($s)
  134. ->with([
  135. 'customer',
  136. 'orderStaff',
  137. 'contacts'
  138. ])->order($sort, $order)->paginate($limit);
  139. $allmoney = $this->model->where($wheres)->where(array('check_status'=>2))->sum('money');
  140. $repayment_money = Receivables::where($wheres)->where(array('check_status'=>2))->sum('money'); //已回款
  141. $no_money = $allmoney - $repayment_money;
  142. if($no_money <= 0){
  143. $no_money = 0;
  144. }
  145. $result = array("total" => $list->total(), "rows" => $list->items(),'allmoney'=>$allmoney,'repayment_money'=>$repayment_money,'no_money'=>$no_money,
  146. 'role' => $staff->role);
  147. return json($result);
  148. }
  149. $field = FormField::getFields(FormField::CONTRACT_TYPE);
  150. $this->assignconfig('fields', $field);
  151. return $this->view->fetch();
  152. }
  153. /**
  154. * 添加
  155. */
  156. public function add()
  157. {
  158. if ($this->request->isPost()) {
  159. $params = $this->request->post("row/a");
  160. if ($params) {
  161. $params = $this->preExcludeFields($params);
  162. $nowsaff = Staff::info();
  163. $params['order_staff_id'] = $nowsaff->id;
  164. $params['flow_staff_ids'] = '1';
  165. if(!isset($params['money'])){
  166. $params['money'] = 0;
  167. }
  168. // 表单验证
  169. if (($result = $this->qingdongValidate($params, 'Contract', 'create')) !== true) {
  170. $this->error($result);
  171. }
  172. $result = FormField::checkFields(FormField::CONTRACT_TYPE, $params);
  173. if ($result !== true) {
  174. $this->error($result);
  175. }
  176. $result = false;
  177. Db::startTrans();
  178. try {
  179. $params = Form::updateFormParams(Form::CONTRACT_TYPE, $params);
  180. // if($params['product']){
  181. // $params['product']=json_decode($params['product'],true);
  182. // }
  183. $file_id = File::getId($params['files']);
  184. $params['main_vujfcz'] = $file_id;
  185. $result = $this->model::createContract($params);
  186. Db::commit();
  187. } catch (Exception $e) {
  188. Db::rollback();
  189. $this->error($e->getMessage());
  190. }
  191. if ($result !== false) {
  192. $this->success();
  193. } else {
  194. $this->error(__('No rows were inserted'));
  195. }
  196. }
  197. $this->error(__('Parameter %s can not be empty', ''));
  198. }
  199. $flow= Flow::getsteplist(Flow::CONTRACT_STATUS);
  200. if (empty($flow)) {
  201. $this->error('无可用审批流,请联系管理员','qingdong/work/flow');
  202. }
  203. $customer_id = input('customer_id');
  204. if($customer_id){
  205. $business = Business::where(array('customer_id'=>$customer_id))->select();
  206. }else{
  207. $business = Business::getList();
  208. }
  209. $this->assign('flow',$flow);
  210. $this->assign('staff', Staff::getStaff());
  211. $this->assign('customers', Customer::getList());
  212. $this->assign('business', $business);
  213. $this->assign('customer_id', $customer_id);
  214. $this->assign('business_id', input('business_id'));
  215. $this->assign('staffs', Staff::allList());
  216. $this->assign('form_data', Form::getDataValue('contract'));
  217. $this->assign('ratio',Ratio::where(['status'=>1])->select());
  218. $this->assign('contractNum', 'C'.date('Ymd').rand(10000,99999));
  219. return $this->view->fetch();
  220. }
  221. /**
  222. * 修改合同
  223. */
  224. public function edit($ids = null) {
  225. $map['id'] = $ids;
  226. if ($this->request->isAjax()) {
  227. $params = $this->request->post('row/a');
  228. $params = $this->preExcludeFields($params);
  229. $row = $this->model::where(['id' => $ids])->find();
  230. // if (empty($row)) {
  231. // $this->error('合同审核中或已审核通过无法修改');
  232. // }
  233. $params['flow_staff_ids'] = '1';
  234. if(!isset($params['money'])){
  235. $params['money'] = 0;
  236. }
  237. // 表单验证
  238. if (($result = $this->qingdongValidate($params, 'Contract', 'create')) !== true) {
  239. $this->error($result);
  240. }
  241. $result = FormField::checkFields(FormField::CONTRACT_TYPE, $params,$ids);
  242. if ($result !== true) {
  243. $this->error($result);
  244. }
  245. Db::startTrans();
  246. try {
  247. $params = Form::updateFormParams(Form::CONTRACT_TYPE, $params);
  248. $params['id']=$ids;
  249. $params['owner_staff_id'] = $row['owner_staff_id'];
  250. // if($params['product']){
  251. // $params['product']=json_decode($params['product'],true);
  252. // }
  253. $result = $this->model::updateContract($params);
  254. Db::commit();
  255. } catch (Exception $e) {
  256. Db::rollback();
  257. $this->error($e->getMessage());
  258. }
  259. $this->success('修改成功');
  260. }
  261. $row = $this->model->where($map)->with(['customer','contacts','business'])->find();
  262. if(empty($row)){
  263. $this->error('信息不存在');
  264. }
  265. $row = $row->toArray();
  266. $row = ContractOther::getOther($row);
  267. $product=ContractProduct::where(['contract_id'=>$ids])->with(['productinfo'])->select();
  268. foreach ($product as $k=>$v){
  269. if($v['productinfo']){
  270. $v['product_name']=$v['productinfo']['name'];
  271. $v['cost_price']=$v['productinfo']['cost_price'];
  272. $v['type']=$v['productinfo']['type'];
  273. if($v['productinfo']['goods']){
  274. $v['goods_name']=$v['productinfo']['goods']['name'];
  275. }
  276. }
  277. $product[$k]=$v;
  278. }
  279. $row['product']=json_encode($product);
  280. $row['ratios']=json_decode($row['ratios'],true);
  281. $flow= Flow::getsteplist(Flow::CONTRACT_STATUS);
  282. if (empty($flow)) {
  283. $this->error('无可用审批流,请联系管理员','qingdong/work/flow');
  284. }
  285. $this->assign('flow',$flow);
  286. $this->view->assign("row", $row);
  287. $this->assign('customers', Customer::getList());
  288. $this->assign('business', Business::getList());
  289. $this->assign('staffs', Staff::getList());
  290. $this->assign('staff', Staff::getStaff());
  291. $this->assign('ratio',Ratio::where(['status'=>1])->select());
  292. $this->assign('form_data', Form::getDataValue('contract',$row));
  293. $this->assign('contacts', Contacts::where(['customer_id'=>$row['customer_id']])->field('id,name')->select());
  294. return $this->view->fetch();
  295. }
  296. /**
  297. * 获取附件记录
  298. */
  299. public function get_file($ids = null) {
  300. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  301. $list = ContractFile::where(['contract_id' => $ids])->with(['file'])->field('file_id')->paginate($limit);
  302. $result = array("total" => $list->total(), "rows" => $list->items());
  303. return json($result);
  304. }
  305. /**
  306. * 合同详情
  307. */
  308. public function detail($ids = null) {
  309. $row = $this->model->where(['id' => $ids])->with([
  310. 'customer',
  311. 'contacts',
  312. 'orderStaff',
  313. 'ownerStaff',
  314. 'business'
  315. ])->find();
  316. if (empty($row)) {
  317. $this->error(__('No Results were found'));
  318. }
  319. $row=$row->toArray();
  320. $row=ContractOther::getOther($row);
  321. $row['ratios'] = json_decode($row['ratios'], true);
  322. if ($row['ratios']) {
  323. foreach ($row['ratios'] as $k => $v) {
  324. $v['staff'] = Staff::where(['id' => $v['staff_id']])->field('id,name,img,post')->find()->toArray();
  325. $v['money'] = $row['money'] * ($v['ratio'] / 100);
  326. $row['ratios'][$k] = $v;
  327. }
  328. }
  329. $staff = Staff::info();
  330. $row['repayment_money'] = Receivables::where(['contract_id'=>$ids])->sum('money'); //已回款
  331. $row['no_money'] = $row['money'] -$row['repayment_money'];
  332. if($row['no_money'] <= 0){
  333. $row['no_money'] = 0;
  334. }
  335. $filedcontect = Form::getDataValue('contract',$row);
  336. if($staff->role != 1 && $staff->role != 2){
  337. foreach ($filedcontect as $k=>$v){
  338. unset($filedcontect[2]);
  339. }
  340. $filedcontect = array_values($filedcontect);
  341. }
  342. //重新排序
  343. $this->assign('examine_record',ExamineRecord::getList(ExamineRecord::CONTRACT_TYPE,$ids));
  344. $this->assign('flow',Flow::getstepdetail(Flow::CONTRACT_STATUS, $ids));
  345. //跟进记录
  346. $this->assign('records', Record::getList(Record::CONTRACT_TYPE, $ids));
  347. //操作记录
  348. $log=OperationLog::getList(OperationLog::CONTRACT_TYPE, $ids);
  349. $this->assign('operation_log',$log);
  350. $this->assign('row', $row);
  351. $this->assign('role', $staff->role);
  352. $this->assign('ids', $ids);
  353. $this->assign('form_data',$filedcontect);
  354. $this->assignconfig("idinfo", ['id' => $ids]);
  355. return $this->view->fetch();
  356. }
  357. /**
  358. * 获取联系人select
  359. */
  360. public function get_contacts_list(){
  361. $pageSize = input('pageSize');
  362. $pageNumber = input('pageNumber');
  363. $where = [];
  364. if ($keyValue = $this->request->request("keyValue")) {
  365. $where['id'] = ['in',$keyValue];
  366. }
  367. $ids=input('ids');
  368. $name = input('name');
  369. if(!empty($name)){
  370. $where['name'] = ['like','%'.$name.'%'];
  371. }
  372. $staff = Contacts::where($where)->where(['customer_id'=>$ids])
  373. ->field('id,name')->order('id desc')->paginate($pageSize, false, ['page' => $pageNumber]);
  374. return json(['list' => $staff->items(), 'total' => $staff->total()]);
  375. }
  376. /**
  377. * 获取产品明细
  378. */
  379. public function get_contract_product(){
  380. $contract_id=input('contract_id',0,'intval');
  381. if(empty($contract_id)){
  382. $this->error('参数不能为空');
  383. }
  384. $products=ContractProduct::where(['contract_id'=>$contract_id])
  385. ->with(['productinfo'])->select();
  386. foreach($products as $k=>$v){
  387. if(!$v['productinfo']['id']){
  388. unset($products[$k]);
  389. }
  390. }
  391. return json(['rows' =>$products, 'total' => count($products)]);
  392. }
  393. /**
  394. * 获取回款计划
  395. */
  396. public function get_receivables_plan($ids = null) {
  397. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  398. $list = \addons\qingdong\model\ReceivablesPlan::where([
  399. 'contract_id' => $ids
  400. ])->with(['customer'])->paginate($limit);
  401. $result = array("total" => $list->total(), "rows" => $list->items());
  402. return json($result);
  403. }
  404. /**
  405. * 获取回款记录
  406. */
  407. public function get_receivables($ids = null) {
  408. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  409. $list = \addons\qingdong\model\Receivables::where([
  410. 'contract_id' => $ids
  411. ])->with(['customer','ownerStaff'])->paginate($limit);
  412. $result = array("total" => $list->total(), "rows" => $list->items());
  413. return json($result);
  414. }
  415. /**
  416. * 获取商机关联产品
  417. */
  418. public function get_business_product(){
  419. $business_id=input('business_id');
  420. if(empty($business_id)){
  421. $this->error('参数不能为空');
  422. }
  423. $business=BusinessProduct::where(['business_id'=>$business_id])->with(['productinfo'])->select();
  424. $this->success('请求成功','',$business);
  425. }
  426. /**
  427. * 获取产品
  428. */
  429. public function get_product()
  430. {
  431. $where = [];
  432. if ($keyValue = $this->request->request("keyValue")) {
  433. $where['id'] = $keyValue;
  434. }
  435. $name = input('name');
  436. if(!empty($name)){
  437. $where['name'] = ['like','%'.$name.'%'];
  438. }
  439. $countrys = Product::where($where)->field('id,name')->order('id desc')->select();
  440. return json(['list' => $countrys, 'total' => count($countrys)]);
  441. }
  442. /**
  443. * 获取产品配置
  444. */
  445. public function get_product_part()
  446. {
  447. $where = [];
  448. if ($keyValue = $this->request->request("keyValue")) {
  449. $where['id'] = $keyValue;
  450. }
  451. $name = input('name');
  452. if(!empty($name)){
  453. $where['name'] = ['like','%'.$name.'%'];
  454. }
  455. $countrys = ProductPart::where($where)->field('id,name')->order('id desc')->select();
  456. return json(['list' => $countrys, 'total' => count($countrys)]);
  457. }
  458. /**
  459. * 获取产品价格
  460. */
  461. public function get_product_price()
  462. {
  463. $id = input('id', 0);
  464. $price = Product::where(['id' => $id])->value('price') ?? 0;
  465. $this->success('请求成功', '', ['price' => $price]);
  466. }
  467. /**
  468. * 获取审批人列表
  469. */
  470. public function getstaff(){
  471. $pageSize = input('pageSize');
  472. $pageNumber = input('pageNumber');
  473. $where = [];
  474. if ($keyValue = $this->request->request("keyValue")) {
  475. $where['id'] = ['in',$keyValue];
  476. }
  477. $name = input('name');
  478. if(!empty($name)){
  479. $where['name'] = ['like','%'.$name.'%'];
  480. }
  481. $staff = Staff::where($where)->where(['id'=>['neq',$this->_staff->id]])->field('id,name')->order('id desc')->paginate($pageSize, false, ['page' => $pageNumber]);
  482. return json(['list' => $staff->items(), 'total' => $staff->total()]);
  483. }
  484. /**
  485. * 删除
  486. */
  487. public function del($ids = "") {
  488. if (!$this->request->isPost()) {
  489. $this->error(__("Invalid parameters"));
  490. }
  491. $map['id'] = array('in', $ids);
  492. $result = $this->model->destroy($map);
  493. if (!$result) {
  494. $this->error('删除失败');
  495. }
  496. $this->success('删除成功');
  497. }
  498. /**
  499. * 导入合同
  500. * @return string|void
  501. */
  502. public function import()
  503. {
  504. set_time_limit(0);
  505. if ($this->request->isPost()) {
  506. $file = $this->request->request('file');
  507. if (!$file) {
  508. $this->error(__('Parameter %s can not be empty', 'file'));
  509. }
  510. $filePath = ROOT_PATH . 'public' . $file;
  511. if (!is_file($filePath)) {
  512. $this->error(__('No results were found'));
  513. }
  514. //实例化reader
  515. $ext = pathinfo($filePath, PATHINFO_EXTENSION);
  516. if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
  517. $this->error(__('Unknown data format'));
  518. }
  519. if ($ext === 'csv') {
  520. $file = fopen($filePath, 'r');
  521. $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
  522. $fp = fopen($filePath, "w");
  523. $n = 0;
  524. while ($line = fgets($file)) {
  525. $line = rtrim($line, "\n\r\0");
  526. $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
  527. if ($encoding != 'utf-8') {
  528. $line = mb_convert_encoding($line, 'utf-8', $encoding);
  529. }
  530. if ($n == 0 || preg_match('/^".*"$/', $line)) {
  531. fwrite($fp, $line . "\n");
  532. } else {
  533. fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
  534. }
  535. $n++;
  536. }
  537. fclose($file) || fclose($fp);
  538. $reader = new Csv();
  539. } elseif ($ext === 'xls') {
  540. $reader = new Xls();
  541. } else {
  542. $reader = new Xlsx();
  543. }
  544. if (!$PHPExcel = $reader->load($filePath)) {
  545. $this->error(__('Unknown data format'));
  546. }
  547. $currentSheet = $PHPExcel->getSheet(0); //读取文件中的第一个工作表
  548. $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
  549. $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
  550. $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
  551. //开始读取数据
  552. $fields = [];
  553. for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
  554. for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
  555. $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  556. $fields[$currentRow][] = $val;
  557. if ($val instanceof RichText) {//富文本转换字符串
  558. $val = $val->__toString();
  559. }
  560. $values[] = is_null($val) ? NULL : trim($val);
  561. }
  562. }
  563. if (!isset($fields[1])) {
  564. $this->error('导入文件第一行没有数据');
  565. }
  566. $lastid = $this->model->withTrashed()->order('id desc')->value('id');
  567. $lastid = $lastid + 5;//防止重复
  568. $contractRow = [];
  569. $errorInfo = [];
  570. $fieldnames = FormField::where(['types' => FormField::CONTRACT_TYPE])->column('field', 'name');
  571. if(!$fieldnames){
  572. $this->error('请在系统管理->字段管理中保存合同管理表单生成合同导入字段');
  573. }
  574. $customerNames=Customer::where([])->column('id,owner_staff_id','name');
  575. $contacts = Contacts::where([])->field('id,name,customer_id')->select();
  576. $contacts = collection($contacts)->toArray();
  577. $contactsNames = [];
  578. foreach ($contacts as $v) {
  579. $contactsNames[$v['customer_id']][$v['name']] = $v;
  580. }
  581. $businessNames=Business::where([])->column('id','name');
  582. $staffNames=Staff::where([])->column('id','name');
  583. $fn = [];
  584. $nums=$this->model->where([])->column('num');
  585. for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
  586. $values = [];
  587. for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
  588. $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  589. $values[] = is_null($val) ? '' : $val;
  590. }
  591. foreach ($values as $l) {
  592. $fn[] = $fieldnames[$l] ?? '';
  593. }
  594. }
  595. for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
  596. $values = [];
  597. for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
  598. $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  599. if ($val instanceof RichText) {//富文本转换字符串
  600. $val = $val->__toString();
  601. }
  602. $values[] = is_null($val) ? NULL : trim($val);
  603. }
  604. $lastid++;
  605. $addContract = ['id' => $lastid];
  606. $customer=isset($customerNames[$values[0]])?$customerNames[$values[0]]:0;
  607. if(empty($customer)){
  608. $errorInfo[] = "第{$currentRow}行,客户名称不存在;";
  609. continue;
  610. }
  611. $addContract['customer_id']=$customer['id'];
  612. $addContract['owner_staff_id']=$customer['owner_staff_id'];
  613. $addContract['create_staff_id']=$customer['owner_staff_id'];
  614. $contacts = isset($contactsNames[$addContract['customer_id']])?(isset($contactsNames[$addContract['customer_id']][$values[1]]) ? $contactsNames[$addContract['customer_id']][$values[1]] : []):[];
  615. if (!empty($values[1]) && empty($contacts)) {
  616. $errorInfo[] = "第{$currentRow}行,客户签约人名称不存在;";
  617. continue;
  618. }
  619. $addContract['contacts_id']=$contacts['id']??0;
  620. $business=isset($businessNames[$values[2]])?$businessNames[$values[2]]:[];
  621. if (!empty($values[2]) && empty($business)) {
  622. $errorInfo[] = "第{$currentRow}行,商机名称不存在;";
  623. continue;
  624. }
  625. $addContract['business_id']=$business['id']??0;
  626. $orderstaff=isset($staffNames[$values[3]])?$staffNames[$values[3]]:[];
  627. if (!empty($values[3]) && empty($orderstaff)) {
  628. $errorInfo[] = "第{$currentRow}行,商机名称不存在;";
  629. continue;
  630. }
  631. $addContract['order_staff_id']=$orderstaff['id']??0;
  632. foreach ($values as $kv => $value) {
  633. if (!isset($fn[$kv]) || empty($fn[$kv])) {
  634. continue;
  635. }
  636. $addContract[$fn[$kv]] = $value;
  637. }
  638. if (empty($addContract['num'])) {
  639. $errorInfo[] = "第{$currentRow}行,合同编号不能为空;";
  640. continue;
  641. }
  642. if (in_array($addContract['num'], $nums)) {
  643. $errorInfo[] = "第{$currentRow}行,合同编号`{$addContract['num']}`已存在;";
  644. continue;
  645. }
  646. if (empty($addContract['name'])) {
  647. $errorInfo[] = "第{$currentRow}行,合同名称不能为空;";
  648. continue;
  649. }
  650. $contractRow[] = $addContract;
  651. }
  652. if (!empty($errorInfo)) {
  653. $this->error(implode(',', $errorInfo));
  654. }
  655. Db::startTrans();
  656. try {
  657. $this->model::importContract($contractRow);
  658. Db::commit();
  659. } catch (Exception $e) {
  660. Db::rollback();
  661. $this->error($e->getMessage());
  662. }
  663. $this->success('导入成功');
  664. }
  665. $this->assign('staffs', Staff::getList());
  666. return $this->view->fetch();
  667. }
  668. /**
  669. * 模板
  670. */
  671. public function template()
  672. {
  673. $title = [
  674. '客户名称',
  675. '客户签约人',
  676. '商机名称',
  677. '公司签约人',
  678. ];
  679. $contractData = Form::getDataValue(Form::CONTRACT_TYPE);
  680. foreach ($contractData as $val) {
  681. $title[] = $val['config']['label'];
  682. }
  683. $file = export_excel($title, [], '合同');
  684. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  685. header('Content-Disposition: attachment;filename=' . $file['fileName']);
  686. header('Cache-Control: max-age=0');
  687. $obj = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
  688. // 以下内容是excel文件的信息描述信息
  689. $obj->getProperties()->setTitle('导出文件'); //设置标题
  690. $obj->setActiveSheetIndex(0);
  691. $obj->getActiveSheet()->setTitle('导出文件');
  692. /* 循环读取每个单元格的数据 */
  693. $a = 'A';
  694. $currentSheet = $obj->getActiveSheet();
  695. foreach ($title as $key => $value) {
  696. //读取工作表1
  697. // 设置第一行加粗
  698. $obj->getActiveSheet()->getStyle($a . '1')->getFont()->setBold(true);
  699. //这里是设置单元格的内容
  700. $currentSheet->getCell($a . '1')->setValue($value);
  701. $a++;
  702. }
  703. $PHPWriter = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($obj);
  704. $PHPWriter->save('php://output');
  705. }
  706. /**
  707. * 导出信息
  708. */
  709. public function export()
  710. {
  711. $this->request->filter(['strip_tags', 'trim']);
  712. $ids = input('ids');
  713. $isall = input('isall');
  714. $wheres = array();
  715. //导出其中几条
  716. if (isset($ids)) {
  717. $wheres['id'] = array('in', $ids);
  718. }
  719. //导出全部
  720. if (isset($isall)) {
  721. if ($isall == 3) {
  722. unset($wheres['id']);
  723. }
  724. }
  725. //0:全部 1:我负责的 2:下属负责的 3:今日待跟进 4:今日已跟进 5:从未跟进的
  726. $type = input('type',0);
  727. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  728. switch($type){
  729. case 1:
  730. $staff = Staff::info();
  731. $wheres['owner_staff_id'] = $staff->id;
  732. break;
  733. case 2:
  734. $wheres['owner_staff_id'] = array('in',Staff::getLowerStaffId());
  735. break;
  736. case 3:
  737. $start = date('Y-m-d 00:00:00');
  738. $end = date('Y-m-d 23:59:59');
  739. $record = collection(Record::where(array('relation_type'=>3,'next_time'=>array(array('egt',$start),array('elt',$end))))->field("id,relation_id")->select())->toArray();
  740. $relationId = [];
  741. foreach($record as $k=>$v){
  742. $whereRe['id'] = array('gt',$v['id']);
  743. $whereRe['relation_id'] = $v['relation_id'];
  744. $recordData = Record::where($whereRe)->count();
  745. if($recordData == 0){
  746. $relationId[] = $v['relation_id'];
  747. }
  748. }
  749. $wheres['id'] = array('in',$relationId);
  750. $staff = Staff::info();
  751. $wheres['owner_staff_id'] = $staff->id;
  752. break;
  753. case 4:
  754. $start = date('Y-m-d 00:00:00');
  755. $end = date('Y-m-d 23:59:59');
  756. $record = collection(Record::where(array('relation_type'=>3,'next_time'=>array(array('egt',$start),array('elt',$end))))->field("id,relation_id")->select())->toArray();
  757. $relationId = [];
  758. foreach($record as $k=>$v){
  759. $whereRe['id'] = array('gt',$v['id']);
  760. $whereRe['relation_id'] = $v['relation_id'];
  761. $recordData = Record::where($whereRe)->count();
  762. if($recordData >=1){
  763. $relationId[] = $v['relation_id'];
  764. }
  765. }
  766. $wheres['id'] = array('in',$relationId);
  767. $staff = Staff::info();
  768. $wheres['owner_staff_id'] = $staff->id;
  769. break;
  770. case 5:
  771. $record = collection(Record::where(array('relation_type'=>3,'next_time'=>array('neq','')))->column('relation_id'))->toArray();
  772. $wheres['id'] = array('not in',$record);
  773. $staff = Staff::info();
  774. $wheres['owner_staff_id'] = $staff->id;
  775. break;
  776. default:
  777. $wheres['owner_staff_id'] = array('in',Staff::getMyStaffIds());
  778. break;
  779. }
  780. $list = $this->model->with([
  781. 'customer',
  782. 'orderStaff',
  783. 'contacts',
  784. 'ownerStaff','contractOther',
  785. ])->where($where)->where($wheres)->order($sort, $order)->select();
  786. $list = collection($list)->toArray();
  787. if (!$list) {
  788. $this->error('无导出数据');
  789. }
  790. $title = [
  791. '序号',
  792. '客户名称',
  793. '客户签约人',
  794. '公司签约人',
  795. '归属人',
  796. '创建时间',
  797. ];
  798. $dataValue = Form::getDataValue(Form::CONTRACT_TYPE);
  799. foreach ($dataValue as $val) {
  800. $title[] = $val['config']['label'];
  801. }
  802. foreach ($list as $k => $v) {
  803. if($v['contract_other']){//其他客户
  804. $other=$v['contract_other']['otherdata'];
  805. $other=json_decode($other,true);
  806. $v = array_merge($v, $other);
  807. }
  808. $field = array(
  809. $v['id'],
  810. $v['customer']['name'],
  811. $v['contacts']['name']??'',
  812. $v['order_staff']['name']??'',
  813. $v['owner_staff']['name']??'',
  814. $v['createtime'],
  815. );
  816. foreach ($dataValue as $val) {
  817. if ($val['component'] == 'uploadImage' || $val['component'] == 'uploadFile') {
  818. $field[] = $v[$val['id'] . '_str'] ?? '';
  819. } else {
  820. $field[] = ($v[$val['id']] ?? '');
  821. }
  822. }
  823. $data[] = $field;
  824. }
  825. $file = export_excel($title, $data, '合同');
  826. if ($file['filePath']) {
  827. $this->success('导出成功', '', $file);
  828. }
  829. $this->error('导出失败');
  830. }
  831. /**
  832. * 导入产品明细
  833. * @return string|void
  834. */
  835. public function import_product()
  836. {
  837. set_time_limit(0);
  838. if ($this->request->isPost()) {
  839. $file = $this->request->request('file');
  840. if (!$file) {
  841. $this->error(__('Parameter %s can not be empty', 'file'));
  842. }
  843. $filePath = ROOT_PATH . 'public' . $file;
  844. if (!is_file($filePath)) {
  845. $this->error(__('No results were found'));
  846. }
  847. //实例化reader
  848. $ext = pathinfo($filePath, PATHINFO_EXTENSION);
  849. if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
  850. $this->error(__('Unknown data format'));
  851. }
  852. if ($ext === 'csv') {
  853. $file = fopen($filePath, 'r');
  854. $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
  855. $fp = fopen($filePath, "w");
  856. $n = 0;
  857. while ($line = fgets($file)) {
  858. $line = rtrim($line, "\n\r\0");
  859. $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
  860. if ($encoding != 'utf-8') {
  861. $line = mb_convert_encoding($line, 'utf-8', $encoding);
  862. }
  863. if ($n == 0 || preg_match('/^".*"$/', $line)) {
  864. fwrite($fp, $line . "\n");
  865. } else {
  866. fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
  867. }
  868. $n++;
  869. }
  870. fclose($file) || fclose($fp);
  871. $reader = new Csv();
  872. } elseif ($ext === 'xls') {
  873. $reader = new Xls();
  874. } else {
  875. $reader = new Xlsx();
  876. }
  877. if (!$PHPExcel = $reader->load($filePath)) {
  878. $this->error(__('Unknown data format'));
  879. }
  880. $currentSheet = $PHPExcel->getSheet(0); //读取文件中的第一个工作表
  881. $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
  882. $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
  883. $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
  884. //开始读取数据
  885. $fields = [];
  886. for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
  887. for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
  888. $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  889. $fields[$currentRow][] = $val;
  890. if ($val instanceof RichText) {//富文本转换字符串
  891. $val = $val->__toString();
  892. }
  893. $values[] = is_null($val) ? '' : trim($val);
  894. }
  895. }
  896. if (!isset($fields[1])) {
  897. $this->error('导入文件第一行没有数据');
  898. }
  899. $lastid = ContractProduct::order('id desc')->value('id');
  900. $lastid = $lastid + 5;//防止重复
  901. $contractProductRow = [];
  902. $errorInfo = [];
  903. $contractNum=$this->model::where([])->column('id,name','num');
  904. $productName=Product::where([])->column('id,price','name');
  905. $fn = [];
  906. for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
  907. $values = [];
  908. for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
  909. $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  910. $values[] = is_null($val) ? '' : $val;
  911. }
  912. }
  913. for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
  914. $values = [];
  915. for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
  916. $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  917. if ($val instanceof RichText) {//富文本转换字符串
  918. $val = $val->__toString();
  919. }
  920. $values[] = is_null($val) ? NULL : trim($val);
  921. }
  922. $lastid++;
  923. $addContractProduct = ['id' => $lastid];
  924. $contract = isset($contractNum[$values[0]]) ? $contractNum[$values[0]] : 0;
  925. if (empty($contract)) {
  926. $errorInfo[] = "第{$currentRow}行,合同编号不存在;";
  927. continue;
  928. }
  929. $product = isset($productName[$values[1]]) ? $productName[$values[1]] : 0;
  930. if (empty($product)) {
  931. $errorInfo[] = "第{$currentRow}行,产品名称不存在;";
  932. continue;
  933. }
  934. if (empty($values[2])) {
  935. $errorInfo[] = "第{$currentRow}行,产品数量不能为空;";
  936. continue;
  937. }
  938. if (empty($values[3])) {
  939. $errorInfo[] = "第{$currentRow}行,产品售价不能为空;";
  940. continue;
  941. }
  942. $addContractProduct['contract_id'] = $contract['id'];
  943. $addContractProduct['product_id'] = $product['id'];
  944. $addContractProduct['number'] = $values[2];
  945. $addContractProduct['price'] = $values[3];
  946. $contractProductRow[]=$addContractProduct;
  947. }
  948. if (!empty($errorInfo)) {
  949. $this->error(implode(',', $errorInfo));
  950. }
  951. Db::startTrans();
  952. try {
  953. ContractProduct::importProduct($contractProductRow);
  954. Db::commit();
  955. } catch (Exception $e) {
  956. Db::rollback();
  957. $this->error($e->getMessage());
  958. }
  959. $this->success('导入成功');
  960. }
  961. $this->assign('staffs', Staff::getList());
  962. return $this->view->fetch();
  963. }
  964. /**
  965. * 模板
  966. */
  967. public function template_product()
  968. {
  969. $title = [
  970. '合同编号',
  971. '商品名称',
  972. '数量',
  973. '售价',
  974. ];
  975. $file = export_excel($title, [], '产品明细');
  976. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  977. header('Content-Disposition: attachment;filename=' . $file['fileName']);
  978. header('Cache-Control: max-age=0');
  979. $obj = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
  980. // 以下内容是excel文件的信息描述信息
  981. $obj->getProperties()->setTitle('导出文件'); //设置标题
  982. $obj->setActiveSheetIndex(0);
  983. $obj->getActiveSheet()->setTitle('导出文件');
  984. /* 循环读取每个单元格的数据 */
  985. $a = 'A';
  986. $currentSheet = $obj->getActiveSheet();
  987. foreach ($title as $key => $value) {
  988. //读取工作表1
  989. // 设置第一行加粗
  990. $obj->getActiveSheet()->getStyle($a . '1')->getFont()->setBold(true);
  991. //这里是设置单元格的内容
  992. $currentSheet->getCell($a . '1')->setValue($value);
  993. $a++;
  994. }
  995. $PHPWriter = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($obj);
  996. $PHPWriter->save('php://output');
  997. }
  998. /**
  999. * 导出信息
  1000. */
  1001. public function export_product()
  1002. {
  1003. $ids = input('ids');
  1004. $type = input('type');
  1005. $wheres = array();
  1006. //导出其中几条
  1007. if (isset($ids)) {
  1008. $wheres['contract_id'] = array('in', $ids);
  1009. }
  1010. //导出全部
  1011. if (isset($type)) {
  1012. if ($type == 3) {
  1013. unset($wheres['contract_id']);
  1014. }
  1015. }
  1016. $list=ContractProduct::where($wheres)->with(['contract','productinfo'])->select();
  1017. $list = collection($list)->toArray();
  1018. if (!$list) {
  1019. $this->error('无导出数据');
  1020. }
  1021. $title = [
  1022. '序号',
  1023. '合同编号',
  1024. '合同名称',
  1025. '商品名称',
  1026. '售价',
  1027. '批发价',
  1028. '产品',
  1029. '规格',
  1030. '数量',
  1031. ];
  1032. $data=[];
  1033. foreach ($list as $k => $v) {
  1034. $field = array(
  1035. $v['id'],
  1036. $v['contract']['num'],
  1037. $v['contract']['name'],
  1038. $v['productinfo']['name']??'',
  1039. $v['price']??'',
  1040. $v['productinfo']['cost_price']??'',
  1041. $v['productinfo']['goods']['name']??'',
  1042. $v['productinfo']['unit']??'',
  1043. $v['number']??'',
  1044. );
  1045. $data[] = $field;
  1046. }
  1047. $file = export_excel($title, $data, '产品明细');
  1048. if ($file['filePath']) {
  1049. $this->success('导出成功', '', $file);
  1050. }
  1051. $this->error('导出失败');
  1052. }
  1053. /**
  1054. * 导出word
  1055. */
  1056. public function words($ids = null)
  1057. {
  1058. if ($this->request->isPost()) {
  1059. $file = input('file', '');
  1060. $is_template=input('is_template',0);
  1061. $template_name=input('template_name','');
  1062. if (empty($file)) {
  1063. $this->error('导出模板');
  1064. }
  1065. if($is_template == 1){
  1066. if(empty($template_name)){
  1067. $this->error('模板名称不能为空');
  1068. }
  1069. $create=[
  1070. 'type'=>'contract',
  1071. 'name'=>$template_name,
  1072. 'url'=>$file
  1073. ];
  1074. $wordTemplateModel = new WordTemplate();
  1075. $wordTemplateModel->save($create);
  1076. }
  1077. $tmp = new TemplateProcessor('.' . $file);
  1078. Settings::setCompatibility(true);
  1079. Settings::setOutputEscapingEnabled(true);
  1080. $row = $this->model->where(['id'=>$ids])->with(['customer','contacts','business','orderStaff'])->find();
  1081. $row = $row->toArray();
  1082. $row = ContractOther::getOther($row);
  1083. $form = Form::getDataValue(Form::CONTRACT_TYPE);
  1084. $imgNames=[];
  1085. foreach($form as $k=>$v){
  1086. if($v['component'] == 'uploadImage'){
  1087. $imgNames[]=$v['id'];
  1088. }
  1089. }
  1090. foreach ($row as $key => $item) {
  1091. if(in_array($key,$imgNames) && $item ){
  1092. if(is_array($item)){
  1093. foreach ($item as $it){
  1094. $tmp->setImageValue($key,ltrim(parse_url($it['file_path'])['path'],'/'));
  1095. }
  1096. }else{
  1097. $fileinfo = File::where(['id'=>['in',$item]])->field('id,name,file_path,save_name')->select();
  1098. foreach ($fileinfo as $it){
  1099. $tmp->setImageValue($key,ltrim(parse_url($it['file_path'])['path'],'/'));
  1100. }
  1101. }
  1102. }else{
  1103. if(is_array($item)){
  1104. $tmp->setValue($key , '');//
  1105. continue;
  1106. }
  1107. $tmp->setValue($key , $item);//
  1108. }
  1109. }
  1110. $contractProduct=ContractProduct::where(['contract_id'=>$ids])
  1111. ->with(['productinfo'])->select();
  1112. $contractProduct=collection($contractProduct)->toArray();
  1113. $c = count($contractProduct);//总行数
  1114. // $tmp->cloneRow('product_name', $c);//复制行
  1115. // for ($i = 0; $i < $c; $i++) {
  1116. // $p=$contractProduct[$i];
  1117. // $tmp->setValue("product_name#" . ($i + 1), $p['productinfo']['name'] ?? '');//名称
  1118. // $tmp->setValue("product_unit#" . ($i + 1), $p['productinfo']['unit'] ?? '');//单位
  1119. // $tmp->setValue("product_num#" . ($i + 1), $p['productinfo']['num'] ?? '');//编码
  1120. // $tmp->setValue("product_type#" . ($i + 1), $p['productinfo']['type'] ?? '');//规格
  1121. // $tmp->setValue("product_number#" . ($i + 1), $p['number']);//数量
  1122. // $tmp->setValue("product_price#" . ($i + 1), $p['price']);//总价格
  1123. // $tmp->setValue("product_total#" . ($i + 1), $p['price'] * $p['number']);//总价格
  1124. // }
  1125. $tmp->setValue('money_big', convertAmountToCn($row['money']));
  1126. $tmp->setValue('customer_name', $row['customer']['name'] ?? '');
  1127. $tmp->setValue('contacts_name', $row['contacts']['name'] ?? '');
  1128. $tmp->setValue('business_name', $row['business']['name'] ?? '');
  1129. $tmp->setValue('order_staff_name', $row['order_staff']['name'] ?? '');
  1130. //end 配置
  1131. $filename = $row['name'];
  1132. $filepath = $filename . '.docx';
  1133. $fileurl = './uploads/' . date('Ymd') . '/';
  1134. if (!file_exists($fileurl)) {
  1135. mkdir($fileurl);
  1136. }
  1137. $tmp->saveAs($fileurl . $filepath);//另存为
  1138. $model = new File();
  1139. $data = [
  1140. 'types' => 'file',
  1141. 'name' => $filepath,
  1142. 'save_name' => $fileurl . $filepath,
  1143. 'size' => filesize($fileurl . $filepath),
  1144. 'file_path' => trim($fileurl, '.') . $filepath,
  1145. ];
  1146. $model->save($data);
  1147. $lastid = $model->id;
  1148. $file = cdnurl($model::getUrl($lastid), true);
  1149. $this->success('成功', '', ['file' => $file, 'id' => $lastid, 'filename' => $filepath]);
  1150. }
  1151. $templates=WordTemplate::where(['type'=>'contract'])->select();
  1152. $contract = Form::getDataValue(Form::CONTRACT_TYPE);
  1153. $columns = array();
  1154. $columns[] = ['key' => 'customer_name', 'name' => '客户名称'];
  1155. $columns[] = ['key' => 'contacts_name', 'name' => '联系人名称'];
  1156. $columns[] = ['key' => 'business_name', 'name' => '商机名称'];
  1157. $columns[] = ['key' => 'order_staff_name', 'name' => '公司签约人名称'];
  1158. $columns[] = ['key' => 'money_big', 'name' => '合同金额人民币大写'];
  1159. foreach ($contract as $k => $v) {
  1160. $columns[] = array(
  1161. 'key' => $v['id'],
  1162. 'name' => $v['config']['label'],
  1163. );
  1164. }
  1165. $columns[] = ['key' => 'product_name', 'name' => '产品名称'];
  1166. $columns[] = ['key' => 'product_unit', 'name' => '产品单位'];
  1167. $columns[] = ['key' => 'product_num', 'name' => '产品编码'];
  1168. $columns[] = ['key' => 'product_type', 'name' => '产品规格'];
  1169. $columns[] = ['key' => 'product_number', 'name' => '产品数量'];
  1170. $columns[] = ['key' => 'product_price', 'name' => '产品单价'];
  1171. $columns[] = ['key' => 'product_total', 'name' => '产品合计'];
  1172. $this->assign('column', $columns);
  1173. $this->assign('templates', $templates);
  1174. $this->assign('ids', $ids);
  1175. return $this->view->fetch();
  1176. }
  1177. }