Business.php 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031
  1. <?php
  2. namespace app\admin\controller\qingdongams\customer;
  3. use addons\qingdongams\model\BusinessStatus;
  4. use addons\qingdongams\model\Customer;
  5. use addons\qingdongams\model\Field;
  6. use addons\qingdongams\model\File;
  7. use addons\qingdongams\model\BusinessProduct;
  8. use addons\qingdongams\model\FormField;
  9. use addons\qingdongams\model\Product;
  10. use addons\qingdongams\model\Staff;
  11. use app\admin\controller\qingdongams\Base;
  12. use addons\qingdongams\model\BusinessOther;
  13. use addons\qingdongams\model\Form;
  14. use addons\qingdongams\model\Contract;
  15. use addons\qingdongams\model\Record;
  16. use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
  17. use PhpOffice\PhpSpreadsheet\Reader\Csv;
  18. use PhpOffice\PhpSpreadsheet\Reader\Xls;
  19. use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
  20. use PhpOffice\PhpSpreadsheet\RichText\RichText;
  21. use think\Db;
  22. use think\Exception;
  23. /**
  24. * 商机管理
  25. * @icon fa fa-handshake-o
  26. */
  27. class Business extends Base
  28. {
  29. protected $relationSearch = true;
  30. /**
  31. * @var \addons\qingdongams\model\Business
  32. */
  33. protected $model = null;
  34. public function _initialize()
  35. {
  36. parent::_initialize();
  37. $this->model = new \addons\qingdongams\model\Business;
  38. }
  39. /**
  40. * 查看
  41. */
  42. public function index()
  43. {
  44. //设置过滤方法
  45. $this->request->filter(['strip_tags', 'trim']);
  46. if ($this->request->isAjax()) {
  47. if ($this->request->request('keyField')) {
  48. return $this->selectpage();
  49. }
  50. //0:全部 1:我负责的 2:下属负责的 3:今日待跟进 4:今日已跟进 5:从未跟进的
  51. $type = input('type', 0);
  52. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  53. switch ($type) {
  54. case 1:
  55. $staff = Staff::info();
  56. $wheres['owner_staff_id'] = $staff->id;
  57. break;
  58. case 2:
  59. $wheres['owner_staff_id'] = array('in', Staff::getLowerStaffId());
  60. break;
  61. case 3:
  62. $start = date('Y-m-d 00:00:00');
  63. $end = date('Y-m-d 23:59:59');
  64. $record = collection(Record::where(array('relation_type' => 5, 'next_time' => array(array('egt', $start), array('elt', $end))))->field("id,relation_id")->select())->toArray();
  65. $relationId = [];
  66. foreach ($record as $k => $v) {
  67. $whereRe['id'] = array('gt', $v['id']);
  68. $whereRe['relation_id'] = $v['relation_id'];
  69. $recordData = Record::where($whereRe)->count();
  70. if ($recordData == 0) {
  71. $relationId[] = $v['relation_id'];
  72. }
  73. }
  74. $wheres['id'] = array('in', $relationId);
  75. $staff = Staff::info();
  76. $wheres['owner_staff_id'] = $staff->id;
  77. break;
  78. case 4:
  79. $start = date('Y-m-d 00:00:00');
  80. $end = date('Y-m-d 23:59:59');
  81. $record = collection(Record::where(array('relation_type' => 5, 'next_time' => array(array('egt', $start), array('elt', $end))))->field("id,relation_id")->select())->toArray();
  82. $relationId = [];
  83. foreach ($record as $k => $v) {
  84. $whereRe['id'] = array('gt', $v['id']);
  85. $whereRe['relation_id'] = $v['relation_id'];
  86. $recordData = Record::where($whereRe)->count();
  87. if ($recordData >= 1) {
  88. $relationId[] = $v['relation_id'];
  89. }
  90. }
  91. $wheres['id'] = array('in', $relationId);
  92. $staff = Staff::info();
  93. $wheres['owner_staff_id'] = $staff->id;
  94. break;
  95. case 5:
  96. $record = collection(Record::where(array('relation_type' => 5, 'next_time' => array('neq', '')))->column('relation_id'))->toArray();
  97. $wheres['id'] = array('not in', $record);
  98. $staff = Staff::info();
  99. $wheres['owner_staff_id'] = $staff->id;
  100. break;
  101. default:
  102. $wheres['owner_staff_id'] = array('in', Staff::getMyStaffIds());
  103. break;
  104. }
  105. $ids = [];
  106. $group_id = input('group_id');
  107. $staff_id = input('staff_id');
  108. if ($group_id) {//角色组
  109. $ids = Staff::getGroupStaffIds($group_id);
  110. }
  111. if ($staff_id) {
  112. $ids = $staff_id;
  113. }
  114. if ($group_id || $staff_id) {
  115. $wheres['owner_staff_id'] = ['in', $ids];
  116. }
  117. $list = $this->model->where($where)
  118. ->where($wheres)
  119. ->with([
  120. 'customer',
  121. 'ownerStaff',
  122. 'product'
  123. ])->order($sort, $order)->paginate($limit);
  124. foreach ($list as $k => $v) {
  125. $types = BusinessStatus::where(array('business_id' => $v['id']))->order('id desc')->value('type');
  126. $list[$k]['type'] = $types ? (int)$types : 0;
  127. }
  128. $result = array("total" => $list->total(), "rows" => $list->items());
  129. return json($result);
  130. }
  131. $field = FormField::getFields(FormField::BUSINESS_TYPE);
  132. $this->assignconfig('fields', $field);
  133. return $this->view->fetch();
  134. }
  135. /**
  136. * 添加
  137. */
  138. public function add()
  139. {
  140. if ($this->request->isPost()) {
  141. $params = $this->request->post("row/a");
  142. if ($params) {
  143. $params = $this->preExcludeFields($params);
  144. $result = FormField::checkFields(FormField::BUSINESS_TYPE, $params);
  145. if ($result !== true) {
  146. $this->error($result);
  147. }
  148. $result = false;
  149. Db::startTrans();
  150. try {
  151. $params = Form::updateFormParams(Form::BUSINESS_TYPE, $params);
  152. if ($params['product']) {
  153. $params['product'] = json_decode($params['product'], true);
  154. }
  155. $result = $this->model::createBusiness($params);
  156. Db::commit();
  157. } catch (Exception $e) {
  158. Db::rollback();
  159. $this->error($e->getMessage());
  160. }
  161. if ($result !== false) {
  162. $this->success();
  163. } else {
  164. $this->error(__('No rows were inserted'));
  165. }
  166. }
  167. $this->error(__('Parameter %s can not be empty', ''));
  168. }
  169. $customer_id = input('customer_id');
  170. $this->assign('customer_id', $customer_id);
  171. $this->assign('customer', Customer::get($customer_id));
  172. $this->assign('staffs', Staff::allList());
  173. $this->assign('form_data', Form::getDataValue('business'));
  174. return $this->view->fetch();
  175. }
  176. /**
  177. * 修改
  178. */
  179. public function edit($ids = null)
  180. {
  181. $map['id'] = $ids;
  182. if ($this->request->isAjax()) {
  183. $params = $this->request->post('row/a');
  184. $params = $this->preExcludeFields($params);
  185. $result = FormField::checkFields(FormField::BUSINESS_TYPE, $params, $ids);
  186. if ($result !== true) {
  187. $this->error($result);
  188. }
  189. Db::startTrans();
  190. try {
  191. $params = Form::updateFormParams(Form::BUSINESS_TYPE, $params);
  192. $params['id'] = $ids;
  193. $result = $this->model::updateBusiness($params);
  194. Db::commit();
  195. } catch (Exception $e) {
  196. Db::rollback();
  197. $this->error($e->getMessage());
  198. }
  199. if ($result !== false) {
  200. $this->success();
  201. } else {
  202. $this->error(__('No rows were inserted'));
  203. }
  204. }
  205. $row = $this->model->where($map)->with(['customer'])->find();
  206. $product = BusinessProduct::where(['business_id' => $ids])->with(['productinfo'])->select();
  207. foreach ($product as $k => $v) {
  208. if ($v['productinfo']) {
  209. $v['product_name'] = $v['productinfo']['name'];
  210. $v['cost_price'] = $v['productinfo']['cost_price'];
  211. $v['type'] = $v['productinfo']['type'];
  212. if ($v['productinfo']['goods']) {
  213. $v['goods_name'] = $v['productinfo']['goods']['name'];
  214. }
  215. }
  216. $product[$k] = $v;
  217. }
  218. $row['product'] = json_encode($product);
  219. $row = $row->toArray();
  220. $row = BusinessOther::getOther($row);
  221. $this->view->assign("row", $row);
  222. $this->assign('customers', Customer::getList());
  223. $this->assign('form_data', Form::getDataValue('business', $row));
  224. return $this->view->fetch();
  225. }
  226. /**
  227. * 详情
  228. */
  229. public function detail($ids = null)
  230. {
  231. $row = $this->model->where(['id' => $ids])->with([
  232. 'customer',
  233. 'ownerStaff'
  234. ])->find();
  235. if (empty($row)) {
  236. $this->error(__('No Results were found'));
  237. }
  238. $row = $row->toArray();
  239. $row = BusinessOther::getOther($row);
  240. //跟进记录
  241. $this->assign('records', Record::getList(Record::CONTRACT_TYPE, $ids));
  242. $type = BusinessStatus::where(array('business_id' => $ids))->order('id desc')->value('type');
  243. $row['type'] = $type ? (int)$type : 0;
  244. $this->assign('row', $row);
  245. $this->assign('ids', $ids);
  246. $this->assign('form_data', Form::getDataValue('business', $row));
  247. $this->assignconfig("idinfo", ['id' => $ids]);
  248. return $this->view->fetch();
  249. }
  250. /**
  251. * 添加跟进
  252. */
  253. public function record($ids = null)
  254. {
  255. if ($this->request->isPost()) {
  256. $params = $this->request->post('row/a');
  257. $params['relation_type'] = 5;
  258. $params['relation_id'] = $ids;
  259. if (!empty($params['files'])) {
  260. $params['files'] = File::getId($params['files']);
  261. }
  262. $reminds_id = $this->request->post('reminds_id/a');
  263. $params['reminds_id']='';
  264. if($reminds_id){
  265. $params['reminds_id'] = implode(',',$reminds_id);
  266. }
  267. Db::startTrans();
  268. try {
  269. $result = Record::createRecord($params);
  270. Db::commit();
  271. } catch (Exception $e) {
  272. Db::rollback();
  273. $this->error($e->getMessage());
  274. }
  275. if ($result) {
  276. $this->success('创建跟进记录成功');
  277. }
  278. $this->error('创建失败');
  279. }
  280. $staff = Staff::where(['status'=>1])->column('name', 'id');
  281. $follow = Field::getField('商机阶段');
  282. $this->assign('follow', $follow);
  283. $this->assign('ids', $ids);
  284. $this->assign('staff', $staff);
  285. return $this->view->fetch();
  286. }
  287. /**
  288. * 批量转移商机
  289. */
  290. public function batch_change($ids = null)
  291. {
  292. $ids = json_decode($ids, true);
  293. $ids = $this->model->where([
  294. 'id' => ['in', $ids]
  295. ])->column('id');
  296. if (empty($ids)) {
  297. $this->error(__('No Results were found'));
  298. }
  299. if ($this->request->isPost()) {
  300. $params = $this->request->post("row/a");
  301. if ($params) {
  302. $params = $this->preExcludeFields($params);
  303. $result = false;
  304. Db::startTrans();
  305. try {
  306. $result = $this->model::batchTransfer($ids, $params['owner_staff_id']);
  307. Db::commit();
  308. } catch (Exception $e) {
  309. Db::rollback();
  310. $this->error($e->getMessage());
  311. }
  312. if ($result !== false) {
  313. $this->success();
  314. } else {
  315. $this->error(__('No rows were inserted'));
  316. }
  317. }
  318. $this->error(__('Parameter %s can not be empty', ''));
  319. }
  320. $staffs = Staff::getList();
  321. $this->assign('staffs', $staffs);
  322. $this->assign('ids', json_encode($ids));
  323. return $this->view->fetch();
  324. }
  325. /**
  326. * 产品信息
  327. */
  328. public function product()
  329. {
  330. $this->request->filter(['strip_tags']);
  331. if ($this->request->isAjax()) {
  332. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  333. $business_id = input('business_id');
  334. $wheres['business_product.business_id'] = $business_id;
  335. $list = BusinessProduct::where($where)->where($wheres)->with(['product'])->order($sort, $order)->paginate($limit);
  336. foreach ($list as $k => $v) {
  337. if (!$v['product']['id']) {
  338. unset($list[$k]);
  339. }
  340. }
  341. $row = $list->items();
  342. $result = array("total" => $list->total(), "rows" => $row);
  343. return json($result);
  344. }
  345. return $this->view->fetch();
  346. }
  347. /**
  348. * 获取相关合同
  349. */
  350. public function get_contract()
  351. {
  352. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  353. $business_id = input('business_id');
  354. $wheres['business_id'] = $business_id;
  355. $list = Contract::where([
  356. 'business_id' => $business_id,
  357. ])->with('customer')->paginate($limit);
  358. $result = array("total" => $list->total(), "rows" => $list->items());
  359. return json($result);
  360. }
  361. /**
  362. * 删除商机
  363. */
  364. public function delete($ids = null)
  365. {
  366. if (!$ids) {
  367. $this->error('参数不正确');
  368. }
  369. $data = $this->model->where([
  370. 'id' => $ids
  371. ])->column('id');
  372. if (empty($data)) {
  373. $this->error('商机不存在');
  374. }
  375. $result = $this->model->where(array('id' => $ids))->update(array('updatetime' => time(), 'deletetime' => time()));
  376. if (!$result) {
  377. $this->error('删除失败');
  378. }
  379. $this->success('删除成功');
  380. }
  381. /**
  382. * 推进商机
  383. */
  384. public function batch_status($ids = null)
  385. {
  386. $ids = $this->model->where([
  387. 'id' => $ids
  388. ])->value('id');
  389. if (empty($ids)) {
  390. $this->error('商机不存在');
  391. }
  392. if ($this->request->isPost()) {
  393. $params = $this->request->post("row/a");
  394. if ($params) {
  395. $params = $this->preExcludeFields($params);
  396. if (!empty($params['file'])) {
  397. $params['file'] = File::getId($params['file']);
  398. }
  399. $result = false;
  400. Db::startTrans();
  401. try {
  402. $params['id'] = $ids;
  403. $result = $this->model::batchStatus($params);
  404. Db::commit();
  405. } catch (Exception $e) {
  406. Db::rollback();
  407. $this->error($e->getMessage());
  408. }
  409. if ($result !== false) {
  410. $this->success();
  411. } else {
  412. $this->error('推进失败');
  413. }
  414. }
  415. $this->error('推进失败');
  416. }
  417. return $this->view->fetch();
  418. }
  419. /**
  420. * 获取推进商机
  421. */
  422. public function get_business_status()
  423. {
  424. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  425. $business_id = input('business_id');
  426. $wheres['business_id'] = $business_id;
  427. $list = BusinessStatus::where([
  428. 'business_id' => $business_id,
  429. ])->order('id desc')->paginate($limit);
  430. foreach ($list as $k => $v) {
  431. if ($v['file']) {
  432. $list[$k]['file'] = File::where(array('id' => ['in', $v['file']]))->select();
  433. }
  434. }
  435. $result = array("total" => $list->total(), "rows" => $list->items());
  436. return json($result);
  437. }
  438. /**
  439. * 导入客户
  440. * @return string|void
  441. */
  442. public function import()
  443. {
  444. set_time_limit(0);
  445. if ($this->request->isPost()) {
  446. $file = $this->request->request('file');
  447. $staff_id = $this->request->request('staff_id', 0);
  448. if (!$file) {
  449. $this->error(__('Parameter %s can not be empty', 'file'));
  450. }
  451. $filePath = ROOT_PATH . 'public' . $file;
  452. if (!is_file($filePath)) {
  453. $this->error(__('No results were found'));
  454. }
  455. //实例化reader
  456. $ext = pathinfo($filePath, PATHINFO_EXTENSION);
  457. if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
  458. $this->error(__('Unknown data format'));
  459. }
  460. if ($ext === 'csv') {
  461. $file = fopen($filePath, 'r');
  462. $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
  463. $fp = fopen($filePath, "w");
  464. $n = 0;
  465. while ($line = fgets($file)) {
  466. $line = rtrim($line, "\n\r\0");
  467. $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
  468. if ($encoding != 'utf-8') {
  469. $line = mb_convert_encoding($line, 'utf-8', $encoding);
  470. }
  471. if ($n == 0 || preg_match('/^".*"$/', $line)) {
  472. fwrite($fp, $line . "\n");
  473. } else {
  474. fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
  475. }
  476. $n++;
  477. }
  478. fclose($file) || fclose($fp);
  479. $reader = new Csv();
  480. } elseif ($ext === 'xls') {
  481. $reader = new Xls();
  482. } else {
  483. $reader = new Xlsx();
  484. }
  485. if (!$PHPExcel = $reader->load($filePath)) {
  486. $this->error(__('Unknown data format'));
  487. }
  488. $currentSheet = $PHPExcel->getSheet(0); //读取文件中的第一个工作表
  489. $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
  490. $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
  491. $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
  492. //开始读取数据
  493. $fields = [];
  494. for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
  495. for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
  496. $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  497. $fields[$currentRow][] = $val;
  498. if ($val instanceof RichText) {//富文本转换字符串
  499. $val = $val->__toString();
  500. }
  501. $values[] = is_null($val) ? '' : trim($val);
  502. }
  503. }
  504. if (!isset($fields[1])) {
  505. $this->error('导入文件第一行没有数据');
  506. }
  507. $lastid = $this->model->order('id desc')->value('id');
  508. $lastid = $lastid + 5;//防止重复
  509. $customerRow = [];
  510. $errorInfo = [];
  511. $customerNames = Customer::where([])->column('id,owner_staff_id', 'name');
  512. $fieldnames = FormField::where(['types' => FormField::BUSINESS_TYPE])->column('field', 'name');
  513. $fn = [];
  514. for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
  515. $values = [];
  516. for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
  517. $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  518. $values[] = is_null($val) ? '' : $val;
  519. }
  520. foreach ($values as $l) {
  521. $fn[] = $fieldnames[$l] ?? '';
  522. }
  523. }
  524. for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
  525. $values = [];
  526. for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
  527. $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  528. if ($val instanceof RichText) {//富文本转换字符串
  529. $val = $val->__toString();
  530. }
  531. $values[] = is_null($val) ? NULL : trim($val);
  532. }
  533. $lastid++;
  534. $addBusiness = ['id' => $lastid];
  535. $customer = isset($customerNames[$values[0]]) ? $customerNames[$values[0]] : 0;
  536. if (empty($customer)) {
  537. $errorInfo[] = "第{$currentRow}行,客户名称不存在;";
  538. continue;
  539. }
  540. $addBusiness['customer_id'] = $customer['id'];
  541. $addBusiness['owner_staff_id'] = $customer['owner_staff_id'];
  542. foreach ($values as $kv => $value) {
  543. if (!isset($fn[$kv]) || empty($fn[$kv])) {
  544. continue;
  545. }
  546. $addBusiness[$fn[$kv]] = $value;
  547. }
  548. if (empty($addBusiness['name'])) {
  549. $errorInfo[] = "第{$currentRow}行,商机名称不能为空;";
  550. continue;
  551. }
  552. $customerRow[] = $addBusiness;
  553. }
  554. if (!empty($errorInfo)) {
  555. $this->error(implode(',', $errorInfo));
  556. }
  557. Db::startTrans();
  558. try {
  559. $this->model::importBusiness($customerRow);
  560. Db::commit();
  561. } catch (Exception $e) {
  562. Db::rollback();
  563. $this->error($e->getMessage());
  564. }
  565. $this->success('导入成功');
  566. }
  567. $this->assign('staffs', Staff::getList());
  568. return $this->view->fetch();
  569. }
  570. /**
  571. * 模板
  572. */
  573. public function template()
  574. {
  575. $title = ['客户名称'];
  576. $dataValue = Form::getDataValue(Form::BUSINESS_TYPE);
  577. foreach ($dataValue as $val) {
  578. $title[] = $val['config']['label'];
  579. }
  580. $file = export_excel($title, [], '商机');
  581. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  582. header('Content-Disposition: attachment;filename=' . $file['fileName']);
  583. header('Cache-Control: max-age=0');
  584. $obj = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
  585. // 以下内容是excel文件的信息描述信息
  586. $obj->getProperties()->setTitle('导出文件'); //设置标题
  587. $obj->setActiveSheetIndex(0);
  588. $obj->getActiveSheet()->setTitle('导出文件');
  589. /* 循环读取每个单元格的数据 */
  590. $a = 'A';
  591. $currentSheet = $obj->getActiveSheet();
  592. foreach ($title as $key => $value) {
  593. //读取工作表1
  594. // 设置第一行加粗
  595. $obj->getActiveSheet()->getStyle($a . '1')->getFont()->setBold(true);
  596. //这里是设置单元格的内容
  597. $currentSheet->getCell($a . '1')->setValue($value);
  598. $a++;
  599. }
  600. $PHPWriter = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($obj);
  601. $PHPWriter->save('php://output');
  602. }
  603. /**
  604. * 导出信息
  605. */
  606. public function export()
  607. {
  608. $this->request->filter(['strip_tags', 'trim']);
  609. $ids = input('ids');
  610. $isall = input('isall', 1);
  611. $wheres = array();
  612. //导出其中几条
  613. if (isset($ids) && $ids) {
  614. $wheres['id'] = array('in', $ids);
  615. }
  616. //导出全部
  617. if ($isall == 3) {
  618. unset($wheres['id']);
  619. }
  620. //0:全部 1:我负责的 2:下属负责的 3:今日待跟进 4:今日已跟进 5:从未跟进的
  621. $type = input('type', 0);
  622. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  623. $staff = Staff::info();
  624. $staff_id = $staff->id;
  625. switch ($type) {
  626. case 1:
  627. $wheres['owner_staff_id'] = $staff_id;
  628. break;
  629. case 2:
  630. $wheres['owner_staff_id'] = array('in', Staff::getLowerStaffId());
  631. break;
  632. case 3:
  633. $start = date('Y-m-d 00:00:00');
  634. $end = date('Y-m-d 23:59:59');
  635. $record = collection(Record::where(array('relation_type' => 5, 'next_time' => array(array('egt', $start), array('elt', $end))))->field("id,relation_id")->select())->toArray();
  636. $relationId = [];
  637. foreach ($record as $k => $v) {
  638. $whereRe['id'] = array('gt', $v['id']);
  639. $whereRe['relation_id'] = $v['relation_id'];
  640. $recordData = Record::where($whereRe)->count();
  641. if ($recordData == 0) {
  642. $relationId[] = $v['relation_id'];
  643. }
  644. }
  645. $wheres['id'] = array('in', $relationId);
  646. $staff = Staff::info();
  647. $wheres['owner_staff_id'] = $staff->id;
  648. break;
  649. case 4:
  650. $start = date('Y-m-d 00:00:00');
  651. $end = date('Y-m-d 23:59:59');
  652. $record = collection(Record::where(array('relation_type' => 5, 'next_time' => array(array('egt', $start), array('elt', $end))))->field("id,relation_id")->select())->toArray();
  653. $relationId = [];
  654. foreach ($record as $k => $v) {
  655. $whereRe['id'] = array('gt', $v['id']);
  656. $whereRe['relation_id'] = $v['relation_id'];
  657. $recordData = Record::where($whereRe)->count();
  658. if ($recordData >= 1) {
  659. $relationId[] = $v['relation_id'];
  660. }
  661. }
  662. $wheres['id'] = array('in', $relationId);
  663. $staff = Staff::info();
  664. $wheres['owner_staff_id'] = $staff->id;
  665. break;
  666. case 5:
  667. $record = collection(Record::where(array('relation_type' => 5, 'next_time' => array('neq', '')))->column('relation_id'))->toArray();
  668. $wheres['id'] = array('not in', $record);
  669. $staff = Staff::info();
  670. $wheres['owner_staff_id'] = $staff->id;
  671. break;
  672. default:
  673. $wheres['owner_staff_id'] = array('in', Staff::getMyStaffIds());
  674. break;
  675. }
  676. $list = $this->model->with([
  677. 'ownerStaff', 'businessOther', 'customer'
  678. ])->where($where)->where($wheres)->order($sort, $order)->select();
  679. $list = collection($list)->toArray();
  680. if (!$list) {
  681. $this->error('无导出数据');
  682. }
  683. $title = [
  684. '序号',
  685. '客户名称',
  686. '负责人',
  687. '创建时间',
  688. '下次联系时间',
  689. ];
  690. $dataValue = Form::getDataValue(Form::BUSINESS_TYPE);
  691. foreach ($dataValue as $val) {
  692. $title[] = $val['config']['label'];
  693. }
  694. foreach ($list as $k => $v) {
  695. if ($v['business_other']) {//其他客户
  696. $other = $v['business_other']['otherdata'];
  697. $other = json_decode($other, true);
  698. $v = array_merge($v, $other);
  699. }
  700. $field = array(
  701. $v['id'],
  702. $v['customer']['name'],
  703. $v['owner_staff']['name'],
  704. date('Y-m-d H:i:s', $v['createtime']),
  705. $v['next_time'],
  706. );
  707. foreach ($dataValue as $val) {
  708. if ($val['component'] == 'uploadImage' || $val['component'] == 'uploadFile') {
  709. $field[] = $v[$val['id'] . '_str'] ?? '';
  710. } else {
  711. $field[] = ($v[$val['id']] ?? '');
  712. }
  713. }
  714. $data[] = $field;
  715. }
  716. $file = export_excel($title, $data, '商机');
  717. if ($file['filePath']) {
  718. $this->success('导出成功', '', $file);
  719. }
  720. $this->error('导出失败');
  721. }
  722. /**
  723. * 导入产品明细
  724. * @return string|void
  725. */
  726. public function import_product()
  727. {
  728. set_time_limit(0);
  729. if ($this->request->isPost()) {
  730. $file = $this->request->request('file');
  731. if (!$file) {
  732. $this->error(__('Parameter %s can not be empty', 'file'));
  733. }
  734. $filePath = ROOT_PATH . 'public' . $file;
  735. if (!is_file($filePath)) {
  736. $this->error(__('No results were found'));
  737. }
  738. //实例化reader
  739. $ext = pathinfo($filePath, PATHINFO_EXTENSION);
  740. if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
  741. $this->error(__('Unknown data format'));
  742. }
  743. if ($ext === 'csv') {
  744. $file = fopen($filePath, 'r');
  745. $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
  746. $fp = fopen($filePath, "w");
  747. $n = 0;
  748. while ($line = fgets($file)) {
  749. $line = rtrim($line, "\n\r\0");
  750. $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
  751. if ($encoding != 'utf-8') {
  752. $line = mb_convert_encoding($line, 'utf-8', $encoding);
  753. }
  754. if ($n == 0 || preg_match('/^".*"$/', $line)) {
  755. fwrite($fp, $line . "\n");
  756. } else {
  757. fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
  758. }
  759. $n++;
  760. }
  761. fclose($file) || fclose($fp);
  762. $reader = new Csv();
  763. } elseif ($ext === 'xls') {
  764. $reader = new Xls();
  765. } else {
  766. $reader = new Xlsx();
  767. }
  768. if (!$PHPExcel = $reader->load($filePath)) {
  769. $this->error(__('Unknown data format'));
  770. }
  771. $currentSheet = $PHPExcel->getSheet(0); //读取文件中的第一个工作表
  772. $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
  773. $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
  774. $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
  775. //开始读取数据
  776. $fields = [];
  777. for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
  778. for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
  779. $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  780. $fields[$currentRow][] = $val;
  781. if ($val instanceof RichText) {//富文本转换字符串
  782. $val = $val->__toString();
  783. }
  784. $values[] = is_null($val) ? '' : trim($val);
  785. }
  786. }
  787. if (!isset($fields[1])) {
  788. $this->error('导入文件第一行没有数据');
  789. }
  790. $lastid = BusinessProduct::order('id desc')->value('id');
  791. $lastid = $lastid + 5;//防止重复
  792. $businessProductRow = [];
  793. $errorInfo = [];
  794. $businessName = $this->model::where([])->column('id,name,money', 'name');
  795. $productName = Product::where([])->column('id,price', 'name');
  796. for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
  797. $values = [];
  798. for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
  799. $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  800. $values[] = is_null($val) ? '' : $val;
  801. }
  802. }
  803. for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
  804. $values = [];
  805. for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
  806. $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  807. if ($val instanceof RichText) {//富文本转换字符串
  808. $val = $val->__toString();
  809. }
  810. $values[] = is_null($val) ? NULL : trim($val);
  811. }
  812. $lastid++;
  813. $addContractProduct = ['id' => $lastid];
  814. $business = isset($businessName[$values[0]]) ? $businessName[$values[0]] : 0;
  815. if (empty($business)) {
  816. $errorInfo[] = "第{$currentRow}行,商机名称不存在;";
  817. continue;
  818. }
  819. $product = isset($productName[$values[1]]) ? $productName[$values[1]] : 0;
  820. if (empty($product)) {
  821. $errorInfo[] = "第{$currentRow}行,产品名称不存在;";
  822. continue;
  823. }
  824. if (empty($values[2])) {
  825. $errorInfo[] = "第{$currentRow}行,产品数量不能为空;";
  826. continue;
  827. }
  828. if (empty($values[3])) {
  829. $errorInfo[] = "第{$currentRow}行,产品售价不能为空;";
  830. continue;
  831. }
  832. $addContractProduct['business_id'] = $business['id'];
  833. $addContractProduct['product_id'] = $product['id'];
  834. $addContractProduct['number'] = $values[2];
  835. $addContractProduct['price'] = $values[3];
  836. $businessProductRow[] = $addContractProduct;
  837. }
  838. if (!empty($errorInfo)) {
  839. $this->error(implode(',', $errorInfo));
  840. }
  841. Db::startTrans();
  842. try {
  843. BusinessProduct::importProduct($businessProductRow);
  844. Db::commit();
  845. } catch (Exception $e) {
  846. Db::rollback();
  847. $this->error($e->getMessage());
  848. }
  849. $this->success('导入成功');
  850. }
  851. $this->assign('staffs', Staff::getList());
  852. return $this->view->fetch();
  853. }
  854. /**
  855. * 模板
  856. */
  857. public function template_product()
  858. {
  859. $title = [
  860. '商机名称',
  861. '商品名称',
  862. '数量',
  863. '售价',
  864. ];
  865. $file = export_excel($title, [], '产品明细');
  866. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  867. header('Content-Disposition: attachment;filename=' . $file['fileName']);
  868. header('Cache-Control: max-age=0');
  869. $obj = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
  870. // 以下内容是excel文件的信息描述信息
  871. $obj->getProperties()->setTitle('导出文件'); //设置标题
  872. $obj->setActiveSheetIndex(0);
  873. $obj->getActiveSheet()->setTitle('导出文件');
  874. /* 循环读取每个单元格的数据 */
  875. $a = 'A';
  876. $currentSheet = $obj->getActiveSheet();
  877. foreach ($title as $key => $value) {
  878. //读取工作表1
  879. // 设置第一行加粗
  880. $obj->getActiveSheet()->getStyle($a . '1')->getFont()->setBold(true);
  881. //这里是设置单元格的内容
  882. $currentSheet->getCell($a . '1')->setValue($value);
  883. $a++;
  884. }
  885. $PHPWriter = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($obj);
  886. $PHPWriter->save('php://output');
  887. }
  888. /**
  889. * 导出信息
  890. */
  891. public function export_product()
  892. {
  893. $this->request->filter(['strip_tags', 'trim']);
  894. $ids = input('ids');
  895. $type = input('type');
  896. $wheres = array();
  897. //导出其中几条
  898. if (isset($ids)) {
  899. $wheres['business_id'] = array('in', $ids);
  900. }
  901. //导出全部
  902. if (isset($type)) {
  903. if ($type == 3) {
  904. unset($wheres['business_id']);
  905. }
  906. }
  907. $list = BusinessProduct::where($wheres)->with(['business', 'productinfo'])->select();
  908. $list = collection($list)->toArray();
  909. if (!$list) {
  910. $this->error('无导出数据');
  911. }
  912. $title = [
  913. '序号',
  914. '商机名称',
  915. '商品名称',
  916. '售价',
  917. '批发价',
  918. '产品',
  919. '规格',
  920. '数量',
  921. ];
  922. foreach ($list as $k => $v) {
  923. $field = array(
  924. $v['id'],
  925. $v['business']['name'],
  926. $v['productinfo']['name'] ?? '',
  927. $v['price'] ?? '',
  928. $v['productinfo']['cost_price'] ?? '',
  929. $v['productinfo']['goods']['name'] ?? '',
  930. $v['productinfo']['unit'] ?? '',
  931. $v['number'] ?? '',
  932. );
  933. $data[] = $field;
  934. }
  935. $file = export_excel($title, $data, '产品明细');
  936. if ($file['filePath']) {
  937. $this->success('导出成功', '', $file);
  938. }
  939. $this->error('导出失败');
  940. }
  941. }