Customer.php 55 KB

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