Contract.php 48 KB

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