Customer.php 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594
  1. <?php
  2. namespace app\admin\controller\qingdongams\customer;
  3. use addons\qingdongams\model\AdminConfig;
  4. use addons\qingdongams\model\BusinessStatus;
  5. use addons\qingdongams\model\ContactsOther;
  6. use addons\qingdongams\model\Field;
  7. use fast\Random;
  8. use addons\qingdongams\model\FormField;
  9. use addons\qingdongams\model\Message;
  10. use addons\qingdongams\model\Remind;
  11. use addons\qingdongams\model\Seastype;
  12. use addons\qingdongams\model\WordTemplate;
  13. use app\admin\controller\qingdongams\Base;
  14. use addons\qingdongams\model\CustomerOther;
  15. use addons\qingdongams\model\Form;
  16. use addons\qingdongams\model\Record;
  17. use addons\qingdongams\model\Staff;
  18. use addons\qingdongams\model\Consume;
  19. use addons\qingdongams\model\Contacts;
  20. use addons\qingdongams\model\Contract;
  21. use addons\qingdongams\model\Receivables;
  22. use addons\qingdongams\model\ReceivablesPlan;
  23. use addons\qingdongams\model\CustomerFile;
  24. use addons\qingdongams\model\StaffSignIn;
  25. use addons\qingdongams\model\File;
  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 addons\qingdongams\model\Business;
  32. use PhpOffice\PhpWord\TemplateProcessor;
  33. use PhpOffice\PhpWord\Settings;
  34. use think\Db;
  35. use think\Exception;
  36. /**
  37. * 客户管理
  38. * @desc 操作文档:https://doc.fastadmin.net/qingdongams
  39. * @desc 软件介绍:https://www.fastadmin.net/store/qingdongams.html
  40. * @desc 售后微信:qingdong_crm
  41. */
  42. class Customer extends Base
  43. {
  44. protected $relationSearch = true;
  45. protected $searchFields = 'id,name';
  46. /**
  47. * @var \addons\qingdongams\model\Customer
  48. */
  49. protected $model = null;
  50. protected $Person = null;
  51. public function _initialize()
  52. {
  53. parent::_initialize();
  54. $this->model = new \addons\qingdongams\model\Customer;
  55. $this->Person = new \addons\qingdongams\model\Person();
  56. }
  57. /**
  58. * 查看
  59. */
  60. public function index()
  61. {
  62. //设置过滤方法
  63. $this->request->filter(['strip_tags', 'trim']);
  64. if ($this->request->isAjax()) {
  65. if ($this->request->request('keyField')) {
  66. return $this->selectpage();
  67. }
  68. //0:全部 1:我负责的 2:下属负责的 3:今日待跟进 4:今日已跟进 5:从未跟进的
  69. $type = input('type', 0);
  70. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  71. $staff = Staff::info();
  72. $staff_id = $staff->id;
  73. switch ($type) {
  74. case 1://我负责
  75. $wheres['owner_staff_id'] = $staff_id;
  76. break;
  77. case 2://下属负责
  78. $wheres['owner_staff_id'] = array('in', Staff::getLowerStaffId());
  79. break;
  80. case 3:
  81. $start = date('Y-m-d 00:00:00');
  82. $end = date('Y-m-d 23:59:59');
  83. $record = collection(Record::where(array('relation_type' => 1, 'next_time' => array(array('egt', $start), array('elt', $end))))->field("id,relation_id")->select())->toArray();
  84. $relationId = [];
  85. foreach ($record as $k => $v) {
  86. $whereRe['id'] = array('gt', $v['id']);
  87. $whereRe['relation_id'] = $v['relation_id'];
  88. $recordData = Record::where($whereRe)->count();
  89. if ($recordData == 0) {
  90. $relationId[] = $v['relation_id'];
  91. }
  92. }
  93. $wheres['id'] = array('in', $relationId);
  94. $staff = Staff::info();
  95. $wheres['owner_staff_id'] = $staff->id;
  96. break;
  97. case 4:
  98. $start = date('Y-m-d 00:00:00');
  99. $end = date('Y-m-d 23:59:59');
  100. $record = collection(Record::where(array('relation_type' => 1, 'next_time' => array(array('egt', $start), array('elt', $end))))->field("id,relation_id")->select())->toArray();
  101. $relationId = [];
  102. foreach ($record as $k => $v) {
  103. $whereRe['id'] = array('gt', $v['id']);
  104. $whereRe['relation_id'] = $v['relation_id'];
  105. $recordData = Record::where($whereRe)->count();
  106. if ($recordData >= 1) {
  107. $relationId[] = $v['relation_id'];
  108. }
  109. }
  110. $wheres['id'] = array('in', $relationId);
  111. $staff = Staff::info();
  112. $wheres['owner_staff_id'] = $staff->id;
  113. break;
  114. case 5:
  115. $record = collection(Record::where(array('relation_type' => 1, 'next_time' => array('neq', '')))->column('relation_id'))->toArray();
  116. $wheres['id'] = array('not in', $record);
  117. $staff = Staff::info();
  118. $wheres['owner_staff_id'] = $staff->id;
  119. break;
  120. default:
  121. $wheres['owner_staff_id'] = array('in', Staff::getMyStaffIds());
  122. break;
  123. }
  124. $owner_staff_id = $wheres['owner_staff_id'];
  125. unset($wheres['owner_staff_id']);
  126. $list = $this->model->where($where)->with(['ownerStaff'])
  127. ->where($wheres)->where(function ($query) use ($staff_id, $owner_staff_id, $type) {
  128. if ($type == 0) {//全部
  129. $query->where(['ro_staff_id' => ['like', "%,{$staff_id},%"]])
  130. ->whereOr('rw_staff_id', 'like', "%,{$staff_id},%")
  131. ->whereOr(['owner_staff_id' => $owner_staff_id]);
  132. } else {
  133. $query->where(['owner_staff_id' => $owner_staff_id]);
  134. }
  135. })
  136. ->where('owner_staff_id != 0 and owner_staff_id is not null')
  137. ->order($sort, $order)->paginate($limit);
  138. $rows = $list->items();
  139. foreach ($rows as &$v) {
  140. $v['operation_team'] = 'read';
  141. if ($v['owner_staff_id'] == $this->_staff->id ||
  142. in_array($v['owner_staff_id'], Staff::getLowerStaffId()) ||
  143. in_array($this->_staff->id, explode(',', $v['rw_staff_id']))) {
  144. if (in_array($this->_staff->id, explode(',', $v['rw_staff_id']))) {
  145. $v['operation_team'] = 'update';//可修改客户不可操作其他
  146. }
  147. $v['operation'] = 'update';//修改权限
  148. } else {
  149. $v['operation'] = 'read';//只读权限
  150. }
  151. }
  152. $result = array("total" => $list->total(), "rows" => $list->items());
  153. return json($result);
  154. }
  155. $field = FormField::getFields(FormField::CUSTOMER_TYPE);
  156. $this->assignconfig('fields', $field);
  157. return $this->view->fetch();
  158. }
  159. /**
  160. * 添加
  161. */
  162. public function add()
  163. {
  164. if ($this->request->isPost()) {
  165. $params = $this->request->post("row/a");
  166. if ($params) {
  167. $params = $this->preExcludeFields($params);
  168. // 表单验证
  169. if (($result = $this->qingdongamsValidate($params, 'Customer', 'create')) !== true) {
  170. $this->error($result);
  171. }
  172. $result = FormField::checkFields(FormField::CUSTOMER_TYPE, $params);
  173. if ($result !== true) {
  174. $this->error($result);
  175. }
  176. $user = $this->Person->where(array('account' => $params['mobile']))->find();
  177. if ($user) {
  178. $this->error("手机号已存在,请更换手机号");
  179. }
  180. $result = false;
  181. Db::startTrans();
  182. try {
  183. $params = Form::updateFormParams(Form::CUSTOMER_TYPE, $params);
  184. $customerId = $this->model::createCustomer($params);
  185. if (isset($params['mobile']) && $params['mobile']) {
  186. $retC = array(
  187. 'customer_id' => $customerId,
  188. 'is_major' => 1,
  189. 'region' => 1,
  190. 'name' => $params['name'],
  191. 'mobile' => $params['mobile'],
  192. 'next_time' => date('Y-m-d H:i:s'),
  193. );
  194. Contacts::createContacts($retC);
  195. }
  196. //创建账号
  197. $data = [
  198. 'customer_id' => $customerId,
  199. 'nickname' => $params['name'],
  200. 'password' => $params['password'],
  201. 'email' => '',
  202. 'account' => $params['mobile']];
  203. $data['salt'] = Random::alnum();
  204. $data['password'] = md5(md5($data['password']) . $data['salt']);
  205. $this->Person->allowField(true)->save($data);
  206. Db::commit();
  207. } catch (Exception $e) {
  208. Db::rollback();
  209. $this->error($e->getMessage());
  210. }
  211. if ($customerId !== false) {
  212. $this->success();
  213. } else {
  214. $this->error(__('No rows were inserted'));
  215. }
  216. }
  217. $this->error(__('Parameter %s can not be empty', ''));
  218. }
  219. $this->assign('form_data', Form::getDataValue(Form::CUSTOMER_TYPE));
  220. $remind = Remind::where(['type' => Remind::CUSTOMER_TYPE])->find();
  221. $staff_ids = $remind['staff_ids'] ?? '';
  222. $this->assign('seastype', Seastype::where([])->column('name', 'id'));
  223. $this->assign('staff_ids', $staff_ids);
  224. $this->assign('staff', Staff::where([])->column('name', 'id'));
  225. return $this->view->fetch();
  226. }
  227. /**
  228. * 修改
  229. */
  230. public function edit($ids = null)
  231. {
  232. $row = $this->model->where([
  233. 'id' => $ids,
  234. ])->find();
  235. if (empty($row)) {
  236. $this->error(__('No Results were found'));
  237. }
  238. if (!in_array($row['owner_staff_id'], Staff::getMyStaffIds()) && $row['owner_staff_id'] != 0) {
  239. if (!in_array($this->_staff->id, explode(',', $row['rw_staff_id'])) &&
  240. !in_array($this->_staff->id, explode(',', $row['ro_staff_id']))) {//是否在团队内
  241. $this->error('权限不足');
  242. }
  243. }
  244. if ($this->request->isPost()) {
  245. $params = $this->request->post("row/a");
  246. if ($params) {
  247. $params = $this->preExcludeFields($params);
  248. // 表单验证
  249. if (($result = $this->qingdongamsValidate($params, 'Customer', 'create')) !== true) {
  250. $this->error($result);
  251. }
  252. $result = FormField::checkFields(FormField::CUSTOMER_TYPE, $params, $ids);
  253. if ($result !== true) {
  254. $this->error($result);
  255. }
  256. $result = false;
  257. Db::startTrans();
  258. try {
  259. $params = Form::updateFormParams(Form::CUSTOMER_TYPE, $params);
  260. $params['id'] = $ids;
  261. if (isset($params['password']) && $params['password']) {
  262. $data['salt'] = Random::alnum();
  263. $data['password'] = md5(md5($params['password']) . $data['salt']);
  264. $this->Person->where(array('customer_id' => $ids))->update($data);
  265. }
  266. unset($params['password']);
  267. $result = $this->model::updateCustomer($params);
  268. if (isset($params['mobile']) && $params['mobile']) {
  269. Contacts::where(array('customer_id' => $ids, 'is_major' => 1))->update(array('mobile' => $params['mobile'], 'updatetime' => time()));
  270. }
  271. Db::commit();
  272. } catch (Exception $e) {
  273. Db::rollback();
  274. $this->error($e->getMessage());
  275. }
  276. if ($result !== false) {
  277. $this->success();
  278. } else {
  279. $this->error(__('No rows were inserted'));
  280. }
  281. }
  282. $this->error(__('Parameter %s can not be empty', ''));
  283. }
  284. $row = $row->toArray();
  285. $other = CustomerOther::getOther($row);
  286. $row = array_merge($row, $other);
  287. $form = Form::getDataValue(Form::CUSTOMER_TYPE, $row);
  288. $this->assign('seastype', Seastype::where([])->column('name', 'id'));
  289. $this->assign('row', $row);
  290. $this->assign('form_data', $form);
  291. return $this->view->fetch();
  292. }
  293. /**
  294. * 搜索下拉列表
  295. */
  296. public function stafflist()
  297. {
  298. $data = ['searchlist' => Staff::getList()];
  299. $this->success('', null, $data);
  300. }
  301. /**
  302. * 转移客户
  303. */
  304. public function change($ids = null)
  305. {
  306. $row = $this->model->where([
  307. 'id' => $ids,
  308. ])->find();
  309. if (empty($row)) {
  310. $this->error(__('No Results were found'));
  311. }
  312. if (!in_array($row['owner_staff_id'], Staff::getMyStaffIds()) && $row['owner_staff_id'] != 0) {
  313. if (!in_array($this->_staff->id, explode(',', $row['rw_staff_id'])) &&
  314. !in_array($this->_staff->id, explode(',', $row['ro_staff_id']))) {//是否在团队内
  315. $this->error('权限不足');
  316. }
  317. }
  318. if ($this->request->isPost()) {
  319. $params = $this->request->post("row/a");
  320. if ($params) {
  321. $params = $this->preExcludeFields($params);
  322. $result = false;
  323. Db::startTrans();
  324. try {
  325. $result = $this->model::transfer($ids, $params['owner_staff_id']);
  326. Db::commit();
  327. } catch (Exception $e) {
  328. Db::rollback();
  329. $this->error($e->getMessage());
  330. }
  331. if ($result !== false) {
  332. $this->success();
  333. } else {
  334. $this->error(__('No rows were inserted'));
  335. }
  336. }
  337. $this->error(__('Parameter %s can not be empty', ''));
  338. }
  339. $staffs = Staff::getList();
  340. $this->assign('staffs', $staffs);
  341. $this->assign('row', $row);
  342. return $this->view->fetch();
  343. }
  344. /**
  345. * 批量转移客户
  346. */
  347. public function batch_change($ids = null)
  348. {
  349. $ids = json_decode($ids, true);
  350. $ids = $this->model->where([
  351. 'id' => ['in', $ids]
  352. ])->column('id');
  353. if (empty($ids)) {
  354. $this->error(__('No Results were found'));
  355. }
  356. if ($this->request->isPost()) {
  357. $params = $this->request->post("row/a");
  358. if ($params) {
  359. $params = $this->preExcludeFields($params);
  360. $result = false;
  361. Db::startTrans();
  362. try {
  363. $result = $this->model::batchTransfer($ids, $params['owner_staff_id']);
  364. Db::commit();
  365. } catch (Exception $e) {
  366. Db::rollback();
  367. $this->error($e->getMessage());
  368. }
  369. if ($result !== false) {
  370. $this->success();
  371. } else {
  372. $this->error(__('No rows were inserted'));
  373. }
  374. }
  375. $this->error(__('Parameter %s can not be empty', ''));
  376. }
  377. $staffs = Staff::getList();
  378. $this->assign('staffs', $staffs);
  379. $this->assign('ids', json_encode($ids));
  380. return $this->view->fetch();
  381. }
  382. /**
  383. * 客户详情
  384. */
  385. public function detail($ids = null)
  386. {
  387. $row = $this->model->with([
  388. 'create_staff',
  389. 'owner_staff',
  390. 'contractTotal',
  391. 'receivablesTotal',
  392. 'consumeTotal',
  393. 'workorderTotal'
  394. ])->where([
  395. 'id' => $ids,
  396. ])->find();
  397. if (empty($row)) {
  398. $this->error(__('No Results were found'));
  399. }
  400. if (!in_array($row['owner_staff_id'], Staff::getMyStaffIds()) && $row['owner_staff_id'] != 0) {
  401. if (!in_array($this->_staff->id, explode(',', $row['rw_staff_id'])) && !in_array($this->_staff->id, explode(',', $row['ro_staff_id']))) {//是否在团队内
  402. $this->error('权限不足');
  403. }
  404. }
  405. $row = $row->toArray();
  406. $other = CustomerOther::getOther($row);
  407. $row = array_merge($row, $other);
  408. $row['operation_team'] = 'read';
  409. if ($row['owner_staff_id'] == $this->_staff->id ||
  410. in_array($row['owner_staff_id'], Staff::getLowerStaffId()) ||
  411. in_array($this->_staff->id, explode(',', $row['rw_staff_id']))) {
  412. if (in_array($this->_staff->id, explode(',', $row['rw_staff_id']))) {
  413. $row['operation_team'] = 'update';//可修改客户不可操作其他
  414. }
  415. $row['operation'] = 'update';//修改权限
  416. } else {
  417. $row['operation'] = 'read';//只读权限
  418. }
  419. $form = Form::getDataValue(Form::CUSTOMER_TYPE, $row);
  420. foreach ($form as $ks => $vs) {
  421. //备注显示
  422. if ($vs['component'] == 'textarea' && ($vs['config']['label'] == '备注信息' || $vs['config']['label'] == '备注')) {
  423. $row[$vs['id']] = isset($row[$vs['id']]) ? $row[$vs['id']] : $row['remarks'];
  424. }
  425. }
  426. $row['c_money'] = isset($row['c_money']) ? $row['c_money'] : 0;
  427. $row['s_money'] = isset($row['s_money']) ? $row['s_money'] : 0;
  428. $row['w_money'] = isset($row['w_money']) ? $row['w_money'] : 0;
  429. $row['r_money'] = isset($row['r_money']) ? $row['r_money'] : 0;
  430. //标记通知已读
  431. Message::setRead(Message::CUSTOMER_TYPE, $ids, $this->_staff->id);
  432. $this->assign('records', Record::getList(Record::CUSTOMER_TYPE, $ids));
  433. $this->assign('form_data', $form);
  434. $this->assign('row', $row);
  435. $this->assign('ids', $ids);
  436. $this->assignconfig("idinfo", ['id' => $ids, 'operation' => $row['operation'], 'operation_team' => $row['operation_team']]);
  437. return $this->view->fetch();
  438. }
  439. /**
  440. * 获取相关联系人
  441. * @param null $ids
  442. * @return \think\response\Json
  443. */
  444. public function get_contacts($ids = null)
  445. {
  446. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  447. $list = Contacts::where(['customer_id' => $ids])->order('id desc')->paginate($limit);
  448. $result = array("total" => $list->total(), "rows" => $list->items());
  449. return json($result);
  450. }
  451. /**
  452. * 获取相关合同
  453. */
  454. public function get_contract($ids = null)
  455. {
  456. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  457. $list = Contract::where([
  458. 'customer_id' => $ids,
  459. ])->with('customer')->order('id desc')->paginate($limit);
  460. $result = array("total" => $list->total(), "rows" => $list->items());
  461. return json($result);
  462. }
  463. /**
  464. * 添加费用
  465. */
  466. public function add_consume($ids = null)
  467. {
  468. if ($this->request->isPost()) {
  469. $params = $this->request->post("row/a");
  470. if ($params) {
  471. // 表单验证
  472. if (($result = $this->qingdongamsValidate($params, 'Consume', 'create')) !== true) {
  473. $this->error($result);
  474. }
  475. Db::startTrans();
  476. try {
  477. $result = Consume::createConsume($params);
  478. Db::commit();
  479. } catch (Exception $e) {
  480. Db::rollback();
  481. $this->error($e->getMessage());
  482. }
  483. if ($result) {
  484. $this->success('添加费用成功');
  485. }
  486. }
  487. $this->error(__('Parameter %s can not be empty', ''));
  488. }
  489. $customer = $this->model->where(['id' => $ids])->find();
  490. $this->assign('staff', Staff::where([])->column('name', 'id'));
  491. $this->view->assign('customer', $customer);
  492. return $this->view->fetch();
  493. }
  494. /**
  495. * 获取费用
  496. */
  497. public function get_consume($ids = null)
  498. {
  499. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  500. $list = Consume::where([
  501. 'customer_id' => $ids,
  502. ])->with(['follow_staff', 'staff'])->order('id desc')->paginate($limit);
  503. $result = array("total" => $list->total(), "rows" => $list->items());
  504. return json($result);
  505. }
  506. /**
  507. * 获取团队成员
  508. * @param null $ids
  509. */
  510. public function getteam($ids = null)
  511. {
  512. $customer = $this->model::get($ids);
  513. if (empty($customer)) {
  514. $this->error('客户不存在');
  515. }
  516. $where = [];
  517. if ($keyValue = $this->request->request("keyValue")) {
  518. $where['id'] = ['eq', $keyValue];
  519. }
  520. if ($where) {
  521. $owner_staff = Staff::where($where)->find();
  522. $rw_staffs = [];
  523. $ro_staffs = [];
  524. } else {
  525. $owner_staff = Staff::where(['id' => $customer->owner_staff_id])->find();
  526. $rw_staffs = Staff::where(['id' => ['in', explode(',', $customer->rw_staff_id)]])->select();
  527. $ro_staffs = Staff::where(['id' => ['in', explode(',', $customer->ro_staff_id)]])->select();
  528. }
  529. $staffs = [];
  530. if ($owner_staff) {
  531. $staffs[] = [
  532. 'id' => $owner_staff->id,
  533. 'name' => $owner_staff->name,
  534. 'img' => $owner_staff->img,
  535. 'post' => $owner_staff->post,
  536. 'roles' => '负责人',
  537. 'is_edit' => '读写',
  538. 'customer_id' => $customer->id,
  539. ];
  540. }
  541. foreach ($rw_staffs as $v) {
  542. $staffs[] = [
  543. 'id' => $v->id,
  544. 'name' => $v->name,
  545. 'img' => $v->img,
  546. 'post' => $v->post,
  547. 'roles' => '普通员工',
  548. 'is_edit' => '读写',
  549. 'customer_id' => $customer->id,
  550. ];
  551. }
  552. foreach ($ro_staffs as $v) {
  553. $staffs[] = [
  554. 'id' => $v->id,
  555. 'name' => $v->name,
  556. 'img' => $v->img,
  557. 'post' => $v->post,
  558. 'roles' => '普通员工',
  559. 'is_edit' => '只读',
  560. 'customer_id' => $customer->id,
  561. ];
  562. }
  563. $result = array("total" => count($staffs), "rows" => $staffs);
  564. return json($result);
  565. }
  566. /**
  567. * 添加团队成员
  568. */
  569. public function addteam($ids = null)
  570. {
  571. $customer = \addons\qingdongams\model\Customer::get($ids);
  572. if (empty($customer)) {
  573. $this->error('客户不存在');
  574. }
  575. if ($this->request->isPost()) {
  576. $params = $this->request->post("row/a");
  577. $staff_ids = $params['staff_id'];
  578. if (empty($staff_ids)) {
  579. $this->error('员工不存在');
  580. }
  581. $staff_ids = explode(',', $staff_ids);
  582. foreach ($staff_ids as $k => $id) {
  583. if ($id == $customer->owner_staff_id) {
  584. unset($staff_ids[$k]);
  585. }
  586. }
  587. $ro_staff_id = explode(',', trim($customer->ro_staff_id, ','));
  588. $rw_staff_id = explode(',', trim($customer->rw_staff_id, ','));
  589. if ($params['rules'] == 1) {//读写
  590. $rw_staff_id = array_merge($rw_staff_id, $staff_ids);
  591. $rw_staff_id = array_unique($rw_staff_id);
  592. } else {
  593. $ro_staff_id = array_merge($ro_staff_id, $staff_ids);
  594. $ro_staff_id = array_unique($ro_staff_id);
  595. }
  596. $ro_staff_id = array_diff($ro_staff_id, $rw_staff_id);
  597. $rw_staff_id = implode(',', $rw_staff_id);
  598. $ro_staff_id = implode(',', $ro_staff_id);
  599. $result = $customer->save(['rw_staff_id' => ",{$rw_staff_id},",
  600. 'ro_staff_id' => ",{$ro_staff_id},"]);
  601. if ($result === false) {
  602. $this->error('修改失败');
  603. }
  604. $this->success('修改成功');
  605. }
  606. $owner_staff = Staff::where(['id' => $customer->owner_staff_id])->find();
  607. $rw_staffs = Staff::where(['id' => ['in', explode(',', $customer->rw_staff_id)]])->select();
  608. $ro_staffs = Staff::where(['id' => ['in', explode(',', $customer->ro_staff_id)]])->select();
  609. $staffs = [];
  610. if ($owner_staff) {
  611. $staffs[] = [
  612. 'id' => $owner_staff->id,
  613. 'name' => $owner_staff->name,
  614. 'img' => $owner_staff->img,
  615. 'post' => $owner_staff->post,
  616. 'mobile' => $owner_staff->mobile,
  617. 'roles' => 1,
  618. 'is_edit' => 1,
  619. ];
  620. }
  621. foreach ($rw_staffs as $v) {
  622. $staffs[] = [
  623. 'id' => $v->id,
  624. 'name' => $v->name,
  625. 'img' => $v->img,
  626. 'post' => $v->post,
  627. 'mobile' => $v->mobile,
  628. 'roles' => 2,
  629. 'is_edit' => 1,
  630. ];
  631. }
  632. foreach ($ro_staffs as $v) {
  633. $staffs[] = [
  634. 'id' => $v->id,
  635. 'name' => $v->name,
  636. 'img' => $v->img,
  637. 'post' => $v->post,
  638. 'mobile' => $v->mobile,
  639. 'roles' => 2,
  640. 'is_edit' => 0,
  641. ];
  642. }
  643. $this->assign('staffs', $staffs);
  644. return $this->view->fetch();
  645. }
  646. /**
  647. * 修改团队成员
  648. */
  649. public function editteam($ids = null)
  650. {
  651. $customer_id = input('customer_id');
  652. $customer = $this->model->get($customer_id);
  653. if (empty($customer)) {
  654. $this->error('客户不存在');
  655. }
  656. if ($this->request->isPost()) {
  657. $params = $this->request->post("row/a");
  658. $staff_id = $params['staff_id'];
  659. if (empty($staff_id)) {
  660. $this->error('员工不存在');
  661. }
  662. $ro_staff_id = explode(',', trim($customer->ro_staff_id, ','));
  663. $rw_staff_id = explode(',', trim($customer->rw_staff_id, ','));
  664. if ($params['rules'] == 1) {//读写
  665. $rw_staff_id[] = $staff_id;
  666. $rw_staff_id = array_unique($rw_staff_id);
  667. } else {
  668. foreach ($rw_staff_id as $k => $id) {
  669. if ($id == $staff_id) {
  670. unset($rw_staff_id[$k]);
  671. }
  672. }
  673. $ro_staff_id[] = $staff_id;
  674. $ro_staff_id = array_unique($ro_staff_id);
  675. }
  676. $ro_staff_id = array_diff($ro_staff_id, $rw_staff_id);
  677. $rw_staff_id = implode(',', $rw_staff_id);
  678. $ro_staff_id = implode(',', $ro_staff_id);
  679. $result = $customer->save(['rw_staff_id' => ",{$rw_staff_id},",
  680. 'ro_staff_id' => ",{$ro_staff_id},"]);
  681. if ($result === false) {
  682. $this->error('修改失败');
  683. }
  684. $this->success('修改成功');
  685. $this->success('修改成功');
  686. }
  687. if (in_array($ids, explode(',', $customer->rw_staff_id))) {
  688. $is_edit = 1;
  689. } else {
  690. $is_edit = 0;
  691. }
  692. $this->assign('is_edit', $is_edit);
  693. $this->assign('staff_id', $ids);
  694. return $this->view->fetch();
  695. }
  696. /**
  697. * 删除团队成员
  698. */
  699. public function delteam()
  700. {
  701. $customer_id = input('customer_id');
  702. $customer = $this->model->get($customer_id);
  703. if (empty($customer)) {
  704. $this->error('客户不存在');
  705. }
  706. if ($this->request->isPost()) {
  707. $staff_id = input('staff_id');
  708. if (empty($staff_id)) {
  709. $this->error('员工不存在');
  710. }
  711. $ro_staff_id = explode(',', trim($customer->ro_staff_id, ','));
  712. $rw_staff_id = explode(',', trim($customer->rw_staff_id, ','));
  713. foreach ($ro_staff_id as $k => $id) {
  714. if ($id == $staff_id || empty($id)) {
  715. unset($ro_staff_id[$k]);
  716. }
  717. }
  718. foreach ($rw_staff_id as $k => $id) {
  719. if ($id == $staff_id || empty($id)) {
  720. unset($rw_staff_id[$k]);
  721. }
  722. }
  723. $rw_staff_id = implode(',', $rw_staff_id);
  724. $ro_staff_id = implode(',', $ro_staff_id);
  725. $result = $customer->save(['rw_staff_id' => ",{$rw_staff_id},",
  726. 'ro_staff_id' => ",{$ro_staff_id},"]);
  727. if ($result === false) {
  728. $this->error('删除失败');
  729. }
  730. $this->success('删除成功');
  731. }
  732. }
  733. /**
  734. * 获取回款计划
  735. * @param null $ids
  736. */
  737. public function get_receivables_plan($ids = null)
  738. {
  739. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  740. $list = ReceivablesPlan::where(['customer_id' => $ids])->with([
  741. 'customer',
  742. 'contract'
  743. ])->order('id desc')->paginate($limit);
  744. $result = array("total" => $list->total(), "rows" => $list->items());
  745. return json($result);
  746. }
  747. /**
  748. * 获取回款记录
  749. */
  750. public function get_receivables($ids = null)
  751. {
  752. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  753. $list = Receivables::where(['customer_id' => $ids])->with([
  754. 'customer',
  755. 'contract',
  756. 'ownerStaff',
  757. ])->order('id desc')->paginate($limit);
  758. $result = array("total" => $list->total(), "rows" => $list->items());
  759. return json($result);
  760. }
  761. /**
  762. * 获取附件记录
  763. */
  764. public function get_file($ids = null)
  765. {
  766. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  767. $list = CustomerFile::where(['customer_id' => $ids])->with(['file'])->order('id desc')->field('file_id')->paginate($limit);
  768. $result = array("total" => $list->total(), "rows" => $list->items());
  769. return json($result);
  770. }
  771. /**
  772. * 移入公海
  773. */
  774. public function seas($ids = "")
  775. {
  776. $row = $this->model->where([
  777. 'id' => $ids,
  778. 'owner_staff_id' => ['in', Staff::getMyStaffIds()]
  779. ])->find();
  780. if (empty($row)) {
  781. $this->error(__('No Results were found'));
  782. }
  783. if ($this->request->isPost()) {
  784. $result = false;
  785. Db::startTrans();
  786. try {
  787. $result = $this->model::moveSeas($ids);
  788. Db::commit();
  789. } catch (Exception $e) {
  790. Db::rollback();
  791. $this->error($e->getMessage());
  792. }
  793. if ($result !== false) {
  794. $this->success();
  795. } else {
  796. $this->error(__('No rows were inserted'));
  797. }
  798. $this->error(__('Parameter %s can not be empty', ''));
  799. }
  800. }
  801. /**
  802. * 领取客户
  803. */
  804. public function receive($ids = "")
  805. {
  806. $row = $this->model->where([
  807. 'id' => $ids,
  808. 'owner_staff_id' => 0
  809. ])->find();
  810. if (empty($row)) {
  811. $this->error(__('No Results were found'));
  812. }
  813. if ($this->request->isPost()) {
  814. $result = false;
  815. Db::startTrans();
  816. try {
  817. $result = $this->model::receive($ids);
  818. Db::commit();
  819. } catch (Exception $e) {
  820. Db::rollback();
  821. $this->error($e->getMessage());
  822. }
  823. if ($result !== false) {
  824. $this->success('领取客户成功');
  825. }
  826. $this->error(__('Parameter %s can not be empty', ''));
  827. }
  828. }
  829. /**
  830. * 删除
  831. */
  832. public function del($ids = "")
  833. {
  834. if (!$this->request->isPost()) {
  835. $this->error(__("Invalid parameters"));
  836. }
  837. $ids = $ids ? $ids : $this->request->post("ids");
  838. $row = $this->model->where([
  839. 'id' => $ids,
  840. 'owner_staff_id' => ['in', Staff::getMyStaffIds()]
  841. ])->find();
  842. $this->modelValidate = true;
  843. if (!$row) {
  844. $this->error(__('No Results were found'));
  845. }
  846. //如果有合同和回款,不可删除客户
  847. $Contract = Contract::where(array('customer_id' => $ids))->find();
  848. if ($Contract) {
  849. $this->error('已创建合同不可删除');
  850. }
  851. $Receivables = Receivables::where(array('customer_id' => $ids))->find();
  852. if ($Receivables) {
  853. $this->error('已创建回款不可删除');
  854. }
  855. $map['id'] = $ids;
  856. $result = $this->model->destroy($map);
  857. if (!$result) {
  858. $this->error('删除失败');
  859. }
  860. $this->success();
  861. }
  862. /**
  863. * 获取团队人员列表
  864. */
  865. public function getstaff()
  866. {
  867. $pageSize = input('pageSize');
  868. $pageNumber = input('pageNumber');
  869. $where = [];
  870. if ($keyValue = $this->request->request("keyValue")) {
  871. $where['id'] = ['in', $keyValue];
  872. }
  873. $name = input('name');
  874. if (!empty($name)) {
  875. $where['name'] = ['like', '%' . $name . '%'];
  876. }
  877. $staff = Staff::where($where)->field('id,name')->order('id desc')->paginate($pageSize, false, ['page' => $pageNumber]);
  878. return json(['list' => $staff->items(), 'total' => $staff->total()]);
  879. }
  880. /**
  881. * 地图
  882. */
  883. public function map()
  884. {
  885. $key = AdminConfig::getConfigValue('map_key', 'wechat');
  886. $this->assign('key', $key);
  887. return $this->view->fetch();
  888. }
  889. /**
  890. * 获取签到记录
  891. */
  892. public function get_sign()
  893. {
  894. $customerId = input('customer_id', '');
  895. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  896. $list = StaffSignIn::where([
  897. 'customer_id' => $customerId,
  898. ])->order('id desc')->paginate($limit);
  899. $result = array("total" => $list->total(), "rows" => $list->items());
  900. return json($result);
  901. }
  902. /**
  903. * 获取签到记录
  904. */
  905. public function get_sign_detail($ids = null)
  906. {
  907. $staffSign = StaffSignIn::where(['id' => $ids])->find();
  908. if (empty($staffSign)) {
  909. $this->error('数据不存在');
  910. }
  911. if ($staffSign['other']) {
  912. $other = json_decode($staffSign['other'], true);
  913. $form = Form::getDataValue(Form::SIGNIN_TYPE);
  914. foreach ($form as $k => $v) {
  915. if ($v['component'] == 'uploadImage' || $v['component'] == 'uploadFile') {
  916. $other[$v['id'] . '_str'] = '';
  917. if (key_exists($v['id'], $other)) {
  918. if (isset($other[$v['id']]) && $other[$v['id']]) {
  919. $whereT['id'] = array('in', $other[$v['id']]);
  920. $fileinfo = File::where($whereT)->field('id,name,file_path,save_name')->select();
  921. if ($fileinfo) {
  922. $other[$v['id']] = $fileinfo;
  923. $fileinfodata = '';
  924. foreach ($fileinfo as $kss => $vss) {
  925. $fileinfodata = $vss['save_name'] . ',' . $fileinfodata;
  926. }
  927. $other[$v['id'] . '_str'] = rtrim($fileinfodata, ',');
  928. }
  929. }
  930. }
  931. }
  932. }
  933. $staffSign['other'] = $other;
  934. }
  935. $this->assign('form_data', Form::getDataValue(Form::SIGNIN_TYPE, $staffSign['other']));
  936. $this->assign('row', $staffSign['other']);
  937. return $this->view->fetch();
  938. }
  939. /**
  940. * 获取相关商机
  941. * @param null $ids
  942. * @return \think\response\Json
  943. */
  944. public function get_business()
  945. {
  946. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  947. $customer_id = input('customer_id');
  948. $list = Business::where(['customer_id' => $customer_id])->order('id desc')->paginate($limit);
  949. foreach ($list as $k => $v) {
  950. $types = BusinessStatus::where(array('business_id' => $v['id']))->order('id desc')->value('type');
  951. $list[$k]['type'] = $types ? (int)$types : 0;
  952. }
  953. $result = array("total" => $list->total(), "rows" => $list->items());
  954. return json($result);
  955. }
  956. /**
  957. * 导入客户
  958. * @return string|void
  959. */
  960. public function import()
  961. {
  962. set_time_limit(0);
  963. if ($this->request->isPost()) {
  964. $file = $this->request->request('file');
  965. $staff_id = $this->request->request('staff_id', 0);
  966. $seas_type_id = input('seas_type_id', 0);
  967. if (!$file) {
  968. $this->error(__('Parameter %s can not be empty', 'file'));
  969. }
  970. $filePath = ROOT_PATH . 'public' . $file;
  971. if (!is_file($filePath)) {
  972. $this->error(__('No results were found'));
  973. }
  974. //实例化reader
  975. $ext = pathinfo($filePath, PATHINFO_EXTENSION);
  976. if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
  977. $this->error(__('Unknown data format'));
  978. }
  979. if ($ext === 'csv') {
  980. $file = fopen($filePath, 'r');
  981. $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
  982. $fp = fopen($filePath, "w");
  983. $n = 0;
  984. while ($line = fgets($file)) {
  985. $line = rtrim($line, "\n\r\0");
  986. $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
  987. if ($encoding != 'utf-8') {
  988. $line = mb_convert_encoding($line, 'utf-8', $encoding);
  989. }
  990. if ($n == 0 || preg_match('/^".*"$/', $line)) {
  991. fwrite($fp, $line . "\n");
  992. } else {
  993. fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
  994. }
  995. $n++;
  996. }
  997. fclose($file) || fclose($fp);
  998. $reader = new Csv();
  999. } elseif ($ext === 'xls') {
  1000. $reader = new Xls();
  1001. } else {
  1002. $reader = new Xlsx();
  1003. }
  1004. if (!$PHPExcel = $reader->load($filePath)) {
  1005. $this->error(__('Unknown data format'));
  1006. }
  1007. $currentSheet = $PHPExcel->getSheet(0); //读取文件中的第一个工作表
  1008. $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
  1009. $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
  1010. $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
  1011. //开始读取数据
  1012. $fields = [];
  1013. for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
  1014. for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
  1015. $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  1016. $fields[$currentRow][] = $val;
  1017. if ($val instanceof RichText) {//富文本转换字符串
  1018. $val = $val->__toString();
  1019. }
  1020. $values[] = is_null($val) ? '' : trim($val);
  1021. }
  1022. }
  1023. if (!isset($fields[1])) {
  1024. $this->error('导入文件第一行没有数据');
  1025. }
  1026. $lastid = $this->model->withTrashed()->order('id desc')->value('id');
  1027. $lastid = $lastid + 5;//防止重复
  1028. $customerRow = [];
  1029. $errorInfo = [];
  1030. $formrow = [];
  1031. $names = $this->model->where([])->column('name');
  1032. $fieldnames = FormField::where(['types' => FormField::CUSTOMER_TYPE])->column('field', 'name');
  1033. if (!$fieldnames) {
  1034. $this->error('请在系统管理->字段管理中保存客户管理表单生成客户导入字段');
  1035. }
  1036. $forms = Form::getDataValue(Form::CUSTOMER_TYPE);
  1037. foreach ($forms as $k => $v) {
  1038. $formrow[$v['id']] = $v['name'];
  1039. }
  1040. $fn = [];
  1041. for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
  1042. $values = [];
  1043. for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
  1044. $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  1045. $values[] = is_null($val) ? '' : $val;
  1046. }
  1047. foreach ($values as $l) {
  1048. $fn[] = $fieldnames[$l] ?? '';
  1049. }
  1050. }
  1051. for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
  1052. $values = [];
  1053. for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
  1054. $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  1055. if ($val instanceof RichText) {//富文本转换字符串
  1056. $val = $val->__toString();
  1057. }
  1058. $values[] = is_null($val) ? NULL : trim($val);
  1059. }
  1060. $lastid++;
  1061. $addCustomers = ['id' => $lastid, 'owner_staff_id' => $staff_id, 'create_staff_id' => $staff_id];
  1062. foreach ($values as $kv => $value) {
  1063. if (!isset($fn[$kv]) || empty($fn[$kv])) {
  1064. continue;
  1065. }
  1066. $addCustomers[$fn[$kv]] = $value;
  1067. }
  1068. //日期格式处理
  1069. foreach ($formrow as $k => $v) {
  1070. if ($v == '日期选择框') {
  1071. if (isset($addCustomers[$k]) && $addCustomers[$k]) {
  1072. $addCustomers[$k] = date("Y-m-d", ($addCustomers[$k] - 25569) * 24 * 3600);
  1073. }
  1074. }
  1075. if ($v == '时间选择框') {
  1076. if (isset($addCustomers[$k]) && $addCustomers[$k]) {
  1077. $addCustomers[$k] = date("Y-m-d H:i:s", ($addCustomers[$k] - 25569) * 24 * 3600);
  1078. }
  1079. }
  1080. }
  1081. if (empty($addCustomers['name'])) {
  1082. $errorInfo[] = "第{$currentRow}行,客户名称不能为空;";
  1083. continue;
  1084. }
  1085. if (in_array($addCustomers['name'], $names)) {
  1086. $errorInfo[] = "第{$currentRow}行,客户名称`{$addCustomers['name']}`已存在;";
  1087. continue;
  1088. }
  1089. $addCustomers['seas_id'] = ",{$seas_type_id},";
  1090. if ($staff_id == 0) {
  1091. $addCustomers['is_seas'] = 1;
  1092. }
  1093. $customerRow[] = $addCustomers;
  1094. }
  1095. if (!empty($errorInfo)) {
  1096. $this->error(implode(',', $errorInfo));
  1097. }
  1098. Db::startTrans();
  1099. try {
  1100. $this->model::importCustomer($customerRow);
  1101. Db::commit();
  1102. } catch (Exception $e) {
  1103. Db::rollback();
  1104. $this->error($e->getMessage());
  1105. }
  1106. $this->success('导入成功');
  1107. }
  1108. $this->assign('seas_type', Seastype::where([])->field('id,name')->select());
  1109. $this->assign('staffs', Staff::getList([1, 15]));
  1110. return $this->view->fetch();
  1111. }
  1112. /**
  1113. * 模板
  1114. */
  1115. public function template()
  1116. {
  1117. $title = [];
  1118. $dataValue = Form::getDataValue(Form::CUSTOMER_TYPE);
  1119. foreach ($dataValue as $val) {
  1120. $title[] = $val['config']['label'];
  1121. }
  1122. $file = export_excel($title, [], '客户');
  1123. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  1124. header('Content-Disposition: attachment;filename=' . $file['fileName']);
  1125. header('Cache-Control: max-age=0');
  1126. $obj = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
  1127. // 以下内容是excel文件的信息描述信息
  1128. $obj->getProperties()->setTitle('导出文件'); //设置标题
  1129. $obj->setActiveSheetIndex(0);
  1130. $obj->getActiveSheet()->setTitle('导出文件');
  1131. /* 循环读取每个单元格的数据 */
  1132. $a = 'A';
  1133. $currentSheet = $obj->getActiveSheet();
  1134. foreach ($title as $key => $value) {
  1135. //读取工作表1
  1136. // 设置第一行加粗
  1137. $obj->getActiveSheet()->getStyle($a . '1')->getFont()->setBold(true);
  1138. //这里是设置单元格的内容
  1139. $currentSheet->getCell($a . '1')->setValue($value);
  1140. $a++;
  1141. }
  1142. $PHPWriter = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($obj);
  1143. $PHPWriter->save('php://output');
  1144. }
  1145. /**
  1146. * 导出信息
  1147. */
  1148. public function export()
  1149. {
  1150. $this->request->filter(['strip_tags', 'trim']);
  1151. $ids = input('ids');
  1152. $isall = input('isall');
  1153. $wheres = array();
  1154. //导出其中几条
  1155. if (isset($ids)) {
  1156. $wheres['id'] = array('in', $ids);
  1157. }
  1158. //导出全部
  1159. if (isset($isall)) {
  1160. if ($isall == 3) {
  1161. unset($wheres['id']);
  1162. }
  1163. }
  1164. //0:全部 1:我负责的 2:下属负责的 3:今日待跟进 4:今日已跟进 5:从未跟进的
  1165. $type = input('type', 0);
  1166. $staff = Staff::info();
  1167. $staff_id = $staff->id;
  1168. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  1169. switch ($type) {
  1170. case 1://我负责
  1171. $wheres['owner_staff_id'] = $staff_id;
  1172. break;
  1173. case 2://下属负责
  1174. $wheres['owner_staff_id'] = array('in', Staff::getLowerStaffId());
  1175. break;
  1176. case 3:
  1177. $start = date('Y-m-d 00:00:00');
  1178. $end = date('Y-m-d 23:59:59');
  1179. $record = collection(Record::where(array('relation_type' => 1, 'next_time' => array(array('egt', $start), array('elt', $end))))->field("id,relation_id")->select())->toArray();
  1180. $relationId = [];
  1181. foreach ($record as $k => $v) {
  1182. $whereRe['id'] = array('gt', $v['id']);
  1183. $whereRe['relation_id'] = $v['relation_id'];
  1184. $recordData = Record::where($whereRe)->count();
  1185. if ($recordData == 0) {
  1186. $relationId[] = $v['relation_id'];
  1187. }
  1188. }
  1189. $wheres['id'] = array('in', $relationId);
  1190. $staff = Staff::info();
  1191. $wheres['owner_staff_id'] = $staff->id;
  1192. break;
  1193. case 4:
  1194. $start = date('Y-m-d 00:00:00');
  1195. $end = date('Y-m-d 23:59:59');
  1196. $record = collection(Record::where(array('relation_type' => 1, 'next_time' => array(array('egt', $start), array('elt', $end))))->field("id,relation_id")->select())->toArray();
  1197. $relationId = [];
  1198. foreach ($record as $k => $v) {
  1199. $whereRe['id'] = array('gt', $v['id']);
  1200. $whereRe['relation_id'] = $v['relation_id'];
  1201. $recordData = Record::where($whereRe)->count();
  1202. if ($recordData >= 1) {
  1203. $relationId[] = $v['relation_id'];
  1204. }
  1205. }
  1206. $wheres['id'] = array('in', $relationId);
  1207. $staff = Staff::info();
  1208. $wheres['owner_staff_id'] = $staff->id;
  1209. break;
  1210. case 5:
  1211. $record = collection(Record::where(array('relation_type' => 1, 'next_time' => array('neq', '')))->column('relation_id'))->toArray();
  1212. $wheres['id'] = array('not in', $record);
  1213. $staff = Staff::info();
  1214. $wheres['owner_staff_id'] = $staff->id;
  1215. break;
  1216. default:
  1217. $wheres['owner_staff_id'] = array('in', Staff::getMyStaffIds());
  1218. break;
  1219. }
  1220. $owner_staff_id = $wheres['owner_staff_id'];
  1221. unset($wheres['owner_staff_id']);
  1222. $list = $this->model->where($where)->with(['ownerStaff', 'customerOther'])
  1223. ->where($wheres)
  1224. ->where(function ($query) use ($staff_id, $owner_staff_id, $type) {
  1225. if ($type == 0) {//全部
  1226. $query->where(['ro_staff_id' => ['like', "%,{$staff_id},%"]])
  1227. ->whereOr('rw_staff_id', 'like', "%,{$staff_id},%")
  1228. ->whereOr(['owner_staff_id' => $owner_staff_id]);
  1229. } else {
  1230. $query->where(['owner_staff_id' => $owner_staff_id]);
  1231. }
  1232. })
  1233. ->where('owner_staff_id != 0 and owner_staff_id is not null')->order($sort, $order)->select();
  1234. $list = collection($list)->toArray();
  1235. if (!$list) {
  1236. $this->error('无导出数据');
  1237. }
  1238. $title = [
  1239. '序号',
  1240. '归属人',
  1241. '创建时间',
  1242. '下次联系时间',
  1243. '最后跟进时间',
  1244. ];
  1245. $dataValue = Form::getDataValue(Form::CUSTOMER_TYPE);
  1246. foreach ($dataValue as $val) {
  1247. $title[] = $val['config']['label'];
  1248. }
  1249. $data = [];
  1250. foreach ($list as $k => $v) {
  1251. if ($v['customer_other']) {//其他客户
  1252. $other = $v['customer_other']['otherdata'];
  1253. $other = json_decode($other, true);
  1254. $v = array_merge($v, $other);
  1255. }
  1256. $field = array(
  1257. $v['id'],
  1258. $v['owner_staff']['name'],
  1259. $v['createtime'],
  1260. $v['next_time'],
  1261. $v['last_time'],
  1262. );
  1263. foreach ($dataValue as $val) {
  1264. if ($val['component'] == 'uploadImage' || $val['component'] == 'uploadFile') {
  1265. $field[] = $v[$val['id'] . '_str'] ?? '';
  1266. } else {
  1267. $field[] = ($v[$val['id']] ?? '');
  1268. }
  1269. }
  1270. $data[] = $field;
  1271. }
  1272. $file = export_excel($title, $data, '客户');
  1273. if ($file['filePath']) {
  1274. $this->success('导出成功', '', $file);
  1275. }
  1276. $this->error('导出失败');
  1277. }
  1278. /**
  1279. * 导出word
  1280. */
  1281. public function words($ids = null)
  1282. {
  1283. if ($this->request->isPost()) {
  1284. $file = input('file', '');
  1285. $is_template = input('is_template', 0);
  1286. $template_name = input('template_name', '');
  1287. if (empty($file)) {
  1288. $this->error('导出模板');
  1289. }
  1290. if ($is_template == 1) {
  1291. if (empty($template_name)) {
  1292. $this->error('模板名称不能为空');
  1293. }
  1294. $create = [
  1295. 'type' => 'customer',
  1296. 'name' => $template_name,
  1297. 'url' => $file
  1298. ];
  1299. $wordTemplateModel = new WordTemplate();
  1300. $wordTemplateModel->save($create);
  1301. }
  1302. $tmp = new TemplateProcessor('.' . $file);
  1303. Settings::setCompatibility(true);
  1304. Settings::setOutputEscapingEnabled(true);
  1305. $row = $this->model::get($ids);
  1306. $row = $row->toArray();
  1307. $other = CustomerOther::getOther($row);
  1308. $row = array_merge($row, $other);
  1309. $form = Form::getDataValue(Form::CUSTOMER_TYPE);
  1310. $imgNames = [];
  1311. foreach ($form as $k => $v) {
  1312. if ($v['component'] == 'uploadImage') {
  1313. $imgNames[] = $v['id'];
  1314. }
  1315. }
  1316. foreach ($row as $key => $item) {
  1317. if (in_array($key, $imgNames) && $item) {
  1318. if (is_array($item)) {
  1319. foreach ($item as $it) {
  1320. $tmp->setImageValue($key, ltrim(parse_url($it['file_path'])['path'], '/'));
  1321. }
  1322. } else {
  1323. $fileinfo = File::where(['id' => ['in', $item]])->field('id,name,file_path,save_name')->select();
  1324. foreach ($fileinfo as $it) {
  1325. $tmp->setImageValue($key, ltrim(parse_url($it['file_path'])['path'], '/'));
  1326. }
  1327. }
  1328. } else {
  1329. if (is_array($item)) {
  1330. $tmp->setValue($key, '');//
  1331. continue;
  1332. }
  1333. $tmp->setValue($key, $item);//
  1334. }
  1335. }
  1336. $contacts = Contacts::where(['customer_id' => $ids])->find();
  1337. if ($contacts) {
  1338. $contacts = $contacts->toArray();
  1339. $contactsOther = ContactsOther::getOther($contacts);
  1340. $contacts = array_merge($contacts, $contactsOther);
  1341. foreach ($contacts as $key => $item) {
  1342. if (is_array($item)) {
  1343. continue;
  1344. }
  1345. if ($key == 'name') {
  1346. $key = 'con_name';
  1347. }
  1348. if ($key == 'subname') {
  1349. $key = 'con_subname';
  1350. }
  1351. $tmp->setValue($key, $item);//
  1352. }
  1353. } else {
  1354. $form = Form::getDataValue(Form::CONTACTS_TYPE);
  1355. foreach ($form as $f) {
  1356. if ($f['id'] == 'name') {
  1357. $f['id'] = 'con_name';
  1358. }
  1359. if ($f['id'] == 'subname') {
  1360. $f['id'] = 'con_subname';
  1361. }
  1362. $tmp->setValue($f['id'], '');//
  1363. }
  1364. }
  1365. //end 配置
  1366. $filename = $row['name'];
  1367. $filepath = $filename . '.docx';
  1368. $fileurl = './uploads/' . date('Ymd') . '/';
  1369. if (!file_exists($fileurl)) {
  1370. mkdir($fileurl);
  1371. }
  1372. $tmp->saveAs($fileurl . $filepath);//另存为
  1373. $model = new File();
  1374. $data = [
  1375. 'types' => 'file',
  1376. 'name' => $filepath,
  1377. 'save_name' => $fileurl . $filepath,
  1378. 'size' => filesize($fileurl . $filepath),
  1379. 'file_path' => trim($fileurl, '.') . $filepath,
  1380. ];
  1381. $model->save($data);
  1382. $lastid = $model->id;
  1383. $file = cdnurl($model::getUrl($lastid), true);
  1384. $this->success('成功', '', ['file' => $file, 'id' => $lastid, 'filename' => $filepath]);
  1385. }
  1386. $form = Form::getDataValue(Form::CUSTOMER_TYPE);
  1387. $column = array();
  1388. foreach ($form as $k => $v) {
  1389. if ($v['config']['label'] == '备注信息') {
  1390. $v['config']['label'] = '客户备注';
  1391. }
  1392. $column[] = array(
  1393. 'key' => $v['id'],
  1394. 'name' => $v['config']['label'],
  1395. );
  1396. }
  1397. $templates = WordTemplate::where(['type' => 'customer'])->select();
  1398. $contacts = Form::getDataValue(Form::CONTACTS_TYPE);
  1399. $columns = array();
  1400. foreach ($contacts as $k => $v) {
  1401. if ($v['id'] == 'name') {
  1402. $v['id'] = 'con_name';
  1403. }
  1404. if ($v['id'] == 'subname') {
  1405. $v['id'] = 'con_subname';
  1406. }
  1407. if ($v['config']['label'] == '备注信息') {
  1408. $v['config']['label'] = '联系人备注';
  1409. }
  1410. $columns[] = array(
  1411. 'key' => $v['id'],
  1412. 'name' => $v['config']['label'],
  1413. );
  1414. }
  1415. $column = array_merge($column, $columns);
  1416. $this->assign('column', $column);
  1417. $this->assign('templates', $templates);
  1418. $this->assign('ids', $ids);
  1419. return $this->view->fetch();
  1420. }
  1421. /**
  1422. * 获取公司报价
  1423. */
  1424. public function get_quote($ids = null)
  1425. {
  1426. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  1427. $list = \addons\qingdongams\model\Quote::where(['customer_id' => $ids])->with(['product', 'createStaff'])->order('id desc')->paginate($limit);
  1428. $result = array("total" => $list->total(), "rows" => $list->items());
  1429. return json($result);
  1430. }
  1431. /**
  1432. * 获取公司产品
  1433. */
  1434. public function get_product($ids = null)
  1435. {
  1436. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  1437. $list = \addons\qingdongams\model\CustomerProduct::where(['customer_id' => $ids])->with(['product', 'contracts'])->order('id desc')->paginate($limit);
  1438. $result = array("total" => $list->total(), "rows" => $list->items());
  1439. return json($result);
  1440. }
  1441. /**
  1442. * 获取客户工单
  1443. */
  1444. public function get_workorder($ids = null)
  1445. {
  1446. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  1447. $list = \addons\qingdongams\model\Workorder::where(['customer_id' => $ids])->order('id desc')->paginate($limit);
  1448. $result = array("total" => $list->total(), "rows" => $list->items());
  1449. return json($result);
  1450. }
  1451. }