Customer.php 40KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | Description: 客户
  4. // +----------------------------------------------------------------------
  5. // | Author: Michael_xu | gengxiaoxu@5kcrm.com
  6. // +----------------------------------------------------------------------
  7. namespace app\crm\controller;
  8. use app\admin\controller\ApiCommon;
  9. use app\crm\logic\CustomerLogic;
  10. use app\crm\traits\StarTrait;
  11. use think\Hook;
  12. use think\Request;
  13. use think\Db;
  14. class Customer extends ApiCommon
  15. {
  16. use StarTrait;
  17. /**
  18. * 用于判断权限
  19. * @permission 无限制
  20. * @allow 登录用户可访问
  21. * @other 其他根据系统设置
  22. **/
  23. public function _initialize()
  24. {
  25. $action = [
  26. 'permission'=>['exceldownload','setfollow', 'delete'],
  27. 'allow'=>['read', 'system', 'count', 'poolauthority']
  28. ];
  29. Hook::listen('check_auth',$action);
  30. $request = Request::instance();
  31. $a = strtolower($request->action());
  32. if (!in_array($a, $action['permission'])) {
  33. parent::_initialize();
  34. } else {
  35. $param = Request::instance()->param();
  36. $this->param = $param;
  37. }
  38. }
  39. /**
  40. * 客户列表
  41. * @author Michael_xu
  42. * @return
  43. */
  44. public function index()
  45. {
  46. $customerModel = model('Customer');
  47. $param = $this->param;
  48. $userInfo = $this->userInfo;
  49. $param['user_id'] = $userInfo['id'];
  50. $data = $customerModel->getDataList($param);
  51. return resultArray(['data' => $data]);
  52. }
  53. /**
  54. * 客户公海(没有负责人或已经到期)
  55. * @author Michael_xu
  56. * @return
  57. */
  58. public function pool()
  59. {
  60. $param = $this->param;
  61. $param['action'] = 'pool';
  62. $data = model('Customer')->getDataList($param);
  63. return resultArray(['data' => $data]);
  64. }
  65. /**
  66. * 添加客户
  67. * @author Michael_xu
  68. * @param
  69. * @return
  70. */
  71. public function save()
  72. {
  73. $customerModel = model('Customer');
  74. $param = $this->param;
  75. $userInfo = $this->userInfo;
  76. $param['create_user_id'] = $userInfo['id'];
  77. $param['owner_user_id'] = $userInfo['id'];
  78. if ($res = $customerModel->createData($param)) {
  79. return resultArray(['data' => $res]);
  80. } else {
  81. return resultArray(['error' => $customerModel->getError()]);
  82. }
  83. }
  84. /**
  85. * 客户详情
  86. * @author Michael_xu
  87. * @param
  88. * @return
  89. */
  90. public function read()
  91. {
  92. $customerModel = model('Customer');
  93. $param = $this->param;
  94. $userInfo = $this->userInfo;
  95. $data = $customerModel->getDataById($param['id'], $userInfo['id']);
  96. if (!$data) {
  97. return resultArray(['error' => $customerModel->getError()]);
  98. }
  99. //数据权限判断
  100. $userModel = new \app\admin\model\User();
  101. $auth_user_ids = $userModel->getUserByPer('crm', 'customer', 'read');
  102. //读权限
  103. $roPre = $userModel->rwPre($userInfo['id'], $data['ro_user_id'], $data['rw_user_id'], 'read');
  104. $rwPre = $userModel->rwPre($userInfo['id'], $data['ro_user_id'], $data['rw_user_id'], 'update');
  105. //判断是否客户池数据
  106. $wherePool = $customerModel->getWhereByPool();
  107. $resPool = db('crm_customer')->alias('customer')->where(['customer_id' => $param['id']])->where($wherePool)->find();
  108. if (!$resPool && !in_array($data['owner_user_id'],$auth_user_ids) && !$roPre && !$rwPre) {
  109. $authData['dataAuth'] = 0;
  110. return resultArray(['data' => $authData]);
  111. }
  112. return resultArray(['data' => $data]);
  113. }
  114. /**
  115. * 编辑客户
  116. * @author Michael_xu
  117. * @param
  118. * @return
  119. */
  120. public function update()
  121. {
  122. $customerModel = model('Customer');
  123. $param = $this->param;
  124. $userInfo = $this->userInfo;
  125. //数据详情
  126. $data = $customerModel->getDataById($param['id']);
  127. if (!$data) {
  128. return resultArray(['error' => $customerModel->getError()]);
  129. }
  130. $param['user_id'] = $userInfo['id'];
  131. if ($customerModel->updateDataById($param, $param['id'])) {
  132. return resultArray(['data' => '编辑成功']);
  133. } else {
  134. return resultArray(['error' => $customerModel->getError()]);
  135. }
  136. }
  137. /**
  138. * 删除客户
  139. * @author Michael_xu
  140. * @param
  141. * @return
  142. */
  143. public function delete()
  144. {
  145. $param = $this->param;
  146. // 是否客户池
  147. if ($param['isSeas'] == 1) {
  148. $permission = checkPerByAction('crm', 'customer', 'poolDelete');
  149. } else {
  150. $permission = checkPerByAction('crm', 'customer', 'delete');
  151. }
  152. if ($permission == false) {
  153. return resultArray(['error' => '无权操作']);
  154. }
  155. $customerModel = model('Customer');
  156. $userModel = new \app\admin\model\User();
  157. $recordModel = new \app\admin\model\Record();
  158. $fileModel = new \app\admin\model\File();
  159. $actionRecordModel = new \app\admin\model\ActionRecord();
  160. if (!is_array($param['id'])) {
  161. $customer_id[] = $param['id'];
  162. } else {
  163. $customer_id = $param['id'];
  164. }
  165. $delIds = [];
  166. $errorMessage = [];
  167. //数据权限判断
  168. $auth_user_ids = $userModel->getUserByPer('crm', 'customer', 'delete');
  169. //判断是否客户池数据(客户池数据只有管理员可以删)
  170. $adminId = $userModel->getAdminId();
  171. $wherePool = $customerModel->getWhereByPool();
  172. foreach ($customer_id as $k=>$v) {
  173. $isDel = true;
  174. //数据详情
  175. $data = db('crm_customer')->where(['customer_id' => $v])->find();
  176. if (!$data) {
  177. $isDel = false;
  178. $errorMessage[] = 'id为'.$v.'的客户删除失败,错误原因:'.$customerModel->getError();
  179. }
  180. $resPool = db('crm_customer')->alias('customer')->where(['customer_id' => $v])->where($wherePool)->find();
  181. if (!$resPool && !in_array($data['owner_user_id'],$auth_user_ids) && $isDel) {
  182. $isDel = false;
  183. $errorMessage[] = '名称为'.$data['name'].'的客户删除失败,错误原因:无权操作';
  184. }
  185. // 公海 (原逻辑,公海仅允许管理员删除,修改为授权,不再限制)
  186. // if ($resPool && !in_array($data['owner_user_id'],$adminId)) {
  187. // $isDel = false;
  188. // $errorMessage[] = '名称为'.$data['name'].'的客户删除失败,错误原因:无权操作';
  189. // }
  190. //有商机、合同、联系人则不能删除
  191. if ($isDel) {
  192. $resBusiness = db('crm_business')->where(['customer_id' => $v])->find();
  193. if ($resBusiness) {
  194. $isDel = false;
  195. $errorMessage[] = '名称为'.$data['name'].'的客户删除失败,错误原因:客户下存在商机,不能删除';
  196. }
  197. }
  198. if ($isDel) {
  199. $resContacts = db('crm_contacts')->where(['customer_id' => $v])->find();
  200. if ($resContacts) {
  201. $isDel = false;
  202. $errorMessage[] = '名称为'.$data['name'].'的客户删除失败,错误原因:客户下存在联系人,不能删除';
  203. }
  204. }
  205. if ($isDel) {
  206. $resContract = db('crm_contract')->where(['customer_id' => $v])->find();
  207. if ($resContract) {
  208. $isDel = false;
  209. $errorMessage[] = '名称为'.$data['name'].'的客户删除失败,错误原因:客户下存在合同,不能删除';
  210. }
  211. }
  212. if ($isDel) {
  213. $delIds[] = $v;
  214. }
  215. }
  216. if ($delIds) {
  217. $delRes = $customerModel->delDatas($delIds);
  218. if (!$delRes) {
  219. return resultArray(['error' => $customerModel->getError()]);
  220. }
  221. //删除跟进记录
  222. $recordModel->delDataByTypes(2,$delIds);
  223. //删除关联附件
  224. $fileModel->delRFileByModule('crm_customer',$delIds);
  225. //删除关联操作记录
  226. $actionRecordModel->delDataById(['types'=>'crm_customer','action_id'=>$delIds]);
  227. actionLog($delIds,'','','');
  228. }
  229. if ($errorMessage) {
  230. return resultArray(['error' => $errorMessage]);
  231. } else {
  232. return resultArray(['data' => '删除成功']);
  233. }
  234. }
  235. /**
  236. * 客户转移
  237. * @author Michael_xu
  238. * @param owner_user_id 变更负责人
  239. * @param is_remove 1移出,2转为团队成员
  240. * @param types business,contract 相关模块
  241. * @param type 权限 1只读2读写
  242. * @return
  243. */
  244. public function transfer()
  245. {
  246. $param = $this->param;
  247. $userInfo = $this->userInfo;
  248. $customerModel = model('Customer');
  249. $businessModel = model('Business');
  250. $contractModel = model('Contract');
  251. $contactsModel = model('Contacts');
  252. $settingModel = model('Setting');
  253. $customerConfigModel = model('CustomerConfig');
  254. $userModel = new \app\admin\model\User();
  255. if (!$param['owner_user_id']) {
  256. return resultArray(['error' => '变更负责人不能为空']);
  257. }
  258. if (!$param['customer_id'] || !is_array($param['customer_id'])) {
  259. return resultArray(['error' => '请选择需要转移的客户']);
  260. }
  261. $is_remove = ($param['is_remove'] == 2) ? 2 : 1;
  262. $type = $param['type'] == 2 ? : 1;
  263. $types = $param['types'] ? : [];
  264. $data = [];
  265. $data['owner_user_id'] = $param['owner_user_id'];
  266. $data['update_time'] = time();
  267. $data['follow'] = '待跟进';
  268. # 获取客户的时间
  269. $data['obtain_time'] = time();
  270. $ownerUserName = $userModel->getUserNameById($param['owner_user_id']);
  271. $errorMessage = [];
  272. foreach ($param['customer_id'] as $customer_id) {
  273. $customerInfo = db('crm_customer')->where(['customer_id' => $customer_id])->find();
  274. if (!$customerInfo) {
  275. $errorMessage[] = '名称:为《'.$customerInfo['name'].'》的客户转移失败,错误原因:数据不存在;';
  276. continue;
  277. }
  278. $resCustomer = true;
  279. //权限判断
  280. if (!$customerModel->checkData($customer_id)) {
  281. $errorMessage[] = $customerInfo['name'].'转移失败,错误原因:无权限;';
  282. continue;
  283. }
  284. //拥有客户数上限检测
  285. if (!$customerConfigModel->checkData($param['owner_user_id'],1)) {
  286. $errorMessage[] = $customerInfo['name'].'转移失败,错误原因:'.$customerConfigModel->getError();
  287. continue;
  288. }
  289. //团队成员
  290. $teamData = [];
  291. $teamData['type'] = $type; //权限 1只读2读写
  292. $teamData['user_id'] = [$customerInfo['owner_user_id']]; //协作人
  293. $teamData['types'] = 'crm_customer'; //类型
  294. $teamData['types_id'] = $customer_id; //类型ID
  295. $teamData['is_del'] = ($is_remove == 1) ? 1 : '';
  296. $res = $settingModel->createTeamData($teamData);
  297. $resCustomer = db('crm_customer')->where(['customer_id' => $customer_id])->update($data);
  298. if (!$resCustomer) {
  299. $errorMessage[] = $customerInfo['name'].'转移失败,错误原因:数据出错;';
  300. continue;
  301. } else {
  302. # 处理转移时,负责人出现在只读和读写成员列表中
  303. $customerArray = [];
  304. $teamCustomer = db('crm_customer')->field(['owner_user_id', 'ro_user_id', 'rw_user_id'])->where('customer_id', $customer_id)->find();
  305. if (!empty($teamCustomer['ro_user_id'])) {
  306. $customerRo = arrayToString(array_diff(stringToArray($teamCustomer['ro_user_id']), [$teamCustomer['owner_user_id']]));
  307. $customerArray['ro_user_id'] = $customerRo;
  308. }
  309. if (!empty($teamCustomer['rw_user_id'])) {
  310. $customerRo = arrayToString(array_diff(stringToArray($teamCustomer['rw_user_id']), [$teamCustomer['owner_user_id']]));
  311. $customerArray['rw_user_id'] = $customerRo;
  312. }
  313. db('crm_customer')->where('customer_id', $customer_id)->update($customerArray);
  314. }
  315. if (in_array('crm_contacts',$types)) {
  316. $contactsIds = [];
  317. $contactsIds = db('crm_contacts')->where(['customer_id' => $customer_id])->column('contacts_id');
  318. if ($contactsIds) {
  319. $resContacts = $contactsModel->transferDataById($contactsIds, $param['owner_user_id'], $type, $is_remove);
  320. if ($resContacts !== true) {
  321. $errorMessage[] = $resContacts;
  322. continue;
  323. }
  324. }
  325. }
  326. //商机、合同转移
  327. if (in_array('crm_business',$types)) {
  328. $businessIds = [];
  329. $businessIds = db('crm_business')->where(['customer_id' => $customer_id])->column('business_id');
  330. if ($businessIds) {
  331. $resBusiness = $businessModel->transferDataById($businessIds, $param['owner_user_id'], $type, $is_remove);
  332. if ($resBusiness !== true) {
  333. $errorMessage = $errorMessage ? array_merge($errorMessage,$resBusiness) : $resBusiness;
  334. continue;
  335. }
  336. }
  337. }
  338. if (in_array('crm_contract',$types)) {
  339. $contractIds = [];
  340. $contractIds = db('crm_contract')->where(['customer_id' => $customer_id])->column('contract_id');
  341. if ($contractIds) {
  342. $resContract = $contractModel->transferDataById($contractIds, $param['owner_user_id'], $type, $is_remove);
  343. if ($resContract !== true) {
  344. $errorMessage = $errorMessage ? array_merge($errorMessage,$resContract) : $resContract;
  345. continue;
  346. }
  347. }
  348. }
  349. //修改记录
  350. updateActionLog($userInfo['id'], 'crm_customer', $customer_id, '', '', '将客户转移给:'.$ownerUserName);
  351. }
  352. if (!$errorMessage) {
  353. return resultArray(['data' => '转移成功']);
  354. } else {
  355. return resultArray(['error' => $errorMessage]);
  356. }
  357. }
  358. /**
  359. * 客户放入公海(负责人置为0)
  360. * @author Michael_xu
  361. * @param
  362. * @return
  363. */
  364. public function putInPool()
  365. {
  366. $param = $this->param;
  367. $userInfo = $this->userInfo;
  368. $customerModel = model('Customer');
  369. $settingModel = new \app\crm\model\Setting();
  370. if (!$param['customer_id'] || !is_array($param['customer_id'])) {
  371. return resultArray(['error' => '请选择需要放入公海的客户']);
  372. }
  373. $data = [];
  374. $data['owner_user_id'] = 0;
  375. $data['is_lock'] = 0;
  376. $data['update_time'] = time();
  377. $errorMessage = [];
  378. foreach ($param['customer_id'] as $customer_id) {
  379. $customerInfo = [];
  380. $customerInfo = db('crm_customer')->where(['customer_id' => $customer_id])->find();
  381. if (!$customerInfo) {
  382. $errorMessage[] = '名称:为《'.$customerInfo['name'].'》的客户放入公海失败,错误原因:数据不存在;';
  383. continue;
  384. }
  385. //权限判断
  386. if (!$customerModel->checkData($customer_id)) {
  387. $errorMessage[] = '"'.$customerInfo['name'].'"放入公海失败,错误原因:无权限';
  388. continue;
  389. }
  390. //将团队成员全部清除
  391. $data['ro_user_id'] = '';
  392. $data['rw_user_id'] = '';
  393. $resCustomer = db('crm_customer')->where(['customer_id' => $customer_id])->update($data);
  394. if (!$resCustomer) {
  395. $errorMessage[] = '"'.$customerInfo['name'].'"放入公海失败,错误原因:数据出错;';
  396. continue;
  397. }
  398. //联系人负责人清除
  399. db('crm_contacts')->where(['customer_id' => $customer_id])->update(['owner_user_id' => 0]);
  400. //修改记录
  401. updateActionLog($userInfo['id'], 'crm_customer', $customer_id, '', '', '将客户放入公海');
  402. }
  403. if (!$errorMessage) {
  404. return resultArray(['data' => '操作成功']);
  405. } else {
  406. return resultArray(['error' => $errorMessage]);
  407. }
  408. }
  409. /**
  410. * 客户锁定,解锁
  411. * @author Michael_xu
  412. * @param is_lock 1锁定,2解锁
  413. * @return
  414. */
  415. public function lock()
  416. {
  417. $param = $this->param;
  418. $userInfo = $this->userInfo;
  419. $customerModel = model('Customer');
  420. $customerConfigModel = model('CustomerConfig');
  421. $is_lock = ((int)$param['is_lock'] == 2) ? (int)$param['is_lock'] : 1;
  422. $lock_name = ($is_lock == 2) ? '解锁' : '锁定';
  423. if (!$param['customer_id'] || !is_array($param['customer_id'])) {
  424. return resultArray(['error' => '请选择需要'.$lock_name.'的客户']);
  425. }
  426. $data = [];
  427. $data['is_lock'] = ($is_lock == 1) ? $is_lock : 0;
  428. $data['update_time'] = time();
  429. $errorMessage = [];
  430. foreach ($param['customer_id'] as $customer_id) {
  431. $customerInfo = [];
  432. $customerInfo = $customerModel->getDataById($customer_id);
  433. if (!$customerInfo) {
  434. $errorMessage[] = '名称:为《'.$customerInfo['name'].'》的客户'.$lock_name.'失败,错误原因:数据不存在;';
  435. continue;
  436. }
  437. //权限判断
  438. if (!$customerModel->checkData($customer_id)) {
  439. $errorMessage[] = $customerInfo['name'].$lock_name.'失败,错误原因:无权限';
  440. continue;
  441. }
  442. //锁定上限检测
  443. if ($is_lock == 1 && !$customerConfigModel->checkData($customerInfo['owner_user_id'],2)) {
  444. $errorMessage[] = $customerInfo['name'].$lock_name.'失败,错误原因:'.$customerConfigModel->getError();
  445. continue;
  446. }
  447. //已成交客户,锁定,提示无需锁定
  448. // if ($customerInfo['deal_status'] == '已成交' && $is_lock == 1) {
  449. // $errorMessage[] = $customerInfo['name'].$lock_name.'失败,错误原因:已成交状态,无需锁定';
  450. // continue;
  451. // }
  452. $resCustomer = db('crm_customer')->where(['customer_id' => $customer_id])->update($data);
  453. if (!$resCustomer) {
  454. $errorMessage[] = $customerInfo['name'].$lock_name.'失败,错误原因:数据出错;';
  455. }
  456. //修改记录
  457. updateActionLog($userInfo['id'], 'crm_customer', $customer_id, '', '', '将客户'.$lock_name);
  458. }
  459. if (!$errorMessage) {
  460. return resultArray(['data' => '操作成功']);
  461. } else {
  462. return resultArray(['error' => $errorMessage]);
  463. }
  464. }
  465. /**
  466. * 客户领取
  467. * @author Michael_xu
  468. * @param
  469. * @return
  470. */
  471. public function receive()
  472. {
  473. $param = $this->param;
  474. $userInfo = $this->userInfo;
  475. $customerModel = model('Customer');
  476. $customerConfigModel = model('CustomerConfig');
  477. $customer_ids = $param['customer_id'];
  478. if (!$customer_ids || !is_array($customer_ids)) {
  479. return resultArray(['error' => '请选择需要领取的客户']);
  480. }
  481. $errorMessage = [];
  482. $wherePool = $customerModel->getWhereByPool();
  483. foreach ($customer_ids as $k=>$v) {
  484. $dataName = db('crm_customer')->where(['customer_id' => $v])->value('name');
  485. //判断是否是客户池数据
  486. $resPool = db('crm_customer')->alias('customer')->where(['customer_id' => $v])->where($wherePool)->find();
  487. if (!$resPool) {
  488. $errorMessage[] = '客户《'.$dataName.'》领取失败,错误原因:非公海数据无权操作;';
  489. continue;
  490. }
  491. //拥有客户数上限检测
  492. if (!$customerConfigModel->checkData($userInfo['id'],1)) {
  493. $errorMessage[] = '客户《'.$dataName.'》领取失败,错误原因:'.$customerConfigModel->getError();
  494. continue;
  495. }
  496. $data = [];
  497. $data['owner_user_id'] = $userInfo['id'];
  498. $data['update_time'] = time();
  499. $data['deal_time'] = time();
  500. $data['follow'] = '待跟进';
  501. //将团队成员全部清除
  502. $data['ro_user_id'] = '';
  503. $data['rw_user_id'] = '';
  504. # 获取客户的时间
  505. $data['obtain_time'] = time();
  506. $resCustomer = db('crm_customer')->where(['customer_id' => $v])->update($data);
  507. if (!$resCustomer) {
  508. $errorMessage[] = '客户《'.$dataName.'》领取失败,错误原因:数据出错;';
  509. continue;
  510. }
  511. //联系人领取
  512. db('crm_contacts')->where(['customer_id' => $v])->update(['owner_user_id' => $userInfo['id']]);
  513. //修改记录
  514. updateActionLog($userInfo['id'], 'crm_customer', $v, '', '', '领取了客户');
  515. }
  516. if (!$errorMessage) {
  517. return resultArray(['data' => '领取成功']);
  518. } else {
  519. return resultArray(['error' => $errorMessage]);
  520. }
  521. }
  522. /**
  523. * 客户分配
  524. * @author Michael_xu
  525. * @param
  526. * @return
  527. */
  528. public function distribute()
  529. {
  530. $param = $this->param;
  531. $userInfo = $this->userInfo;
  532. $customerModel = model('Customer');
  533. $userModel = new \app\admin\model\User();
  534. $customerConfigModel = model('CustomerConfig');
  535. $customer_ids = $param['customer_id'];
  536. $owner_user_id = $param['owner_user_id'];
  537. if (!$customer_ids || !is_array($customer_ids)) {
  538. return resultArray(['error' => '请选择需要分配的客户']);
  539. }
  540. if (!$owner_user_id) {
  541. return resultArray(['error' => '请选择分配人']);
  542. }
  543. $ownerUserName = $userModel->getUserNameById($owner_user_id);
  544. $errorMessage = [];
  545. $wherePool = $customerModel->getWhereByPool();
  546. foreach ($customer_ids as $k=>$v) {
  547. $dataName = db('crm_customer')->where(['customer_id' => $v])->value('name');
  548. //判断是否是客户池数据
  549. $resPool = db('crm_customer')->alias('customer')->where(['customer_id' => $v])->where($wherePool)->find();
  550. if (!$resPool) {
  551. $errorMessage[] = '客户《'.$dataName.'》分配失败,错误原因:非公海数据无权操作;';
  552. continue;
  553. }
  554. //拥有客户数上限检测
  555. if (!$customerConfigModel->checkData($owner_user_id,1)) {
  556. $errorMessage[] = '客户《'.$dataName.'》分配失败,错误原因:'.$customerConfigModel->getError();
  557. continue;
  558. }
  559. $data = [];
  560. $data['owner_user_id'] = $owner_user_id;
  561. $data['update_time'] = time();
  562. $data['deal_time'] = time();
  563. $data['follow'] = '待跟进';
  564. //将团队成员全部清除
  565. $data['ro_user_id'] = '';
  566. $data['rw_user_id'] = '';
  567. $resCustomer = db('crm_customer')->where(['customer_id' => $v])->update($data);
  568. if (!$resCustomer) {
  569. $errorMessage[] = '客户《'.$dataName.'》分配失败,错误原因:数据出错;';
  570. }
  571. db('crm_contacts')->where(['customer_id' => $v])->update(['owner_user_id' => $owner_user_id]);
  572. //修改记录
  573. updateActionLog($userInfo['id'], 'crm_customer', $v, '', '', '将客户分配给:'.$ownerUserName);
  574. //站内信
  575. $send_user_id[] = $owner_user_id;
  576. $sendContent = $userInfo['realname'].'将客户《'.$dataName.'》,分配给您';
  577. if ($send_user_id) {
  578. sendMessage($send_user_id, $sendContent, $v, 1);
  579. }
  580. }
  581. if (!$errorMessage) {
  582. return resultArray(['data' => '分配成功']);
  583. } else {
  584. return resultArray(['error' => $errorMessage]);
  585. }
  586. }
  587. /**
  588. * 客户导出
  589. * @author Michael_xu
  590. * @param
  591. * @return
  592. */
  593. public function excelExport()
  594. {
  595. $param = $this->param;
  596. $userInfo = $this->userInfo;
  597. $param['user_id'] = $userInfo['id'];
  598. if ($param['customer_id']) {
  599. $param['customer_id'] = ['condition' => 'in','value' => $param['customer_id'],'form_type' => 'text','name' => ''];
  600. }
  601. $param['is_excel'] = 1;
  602. $excelModel = new \app\admin\model\Excel();
  603. // 导出的字段列表
  604. $fieldModel = new \app\admin\model\Field();
  605. $field_list = $fieldModel->getIndexFieldConfig('crm_customer', $userInfo['id']);
  606. // 文件名
  607. $file_name = '5kcrm_customer_'.date('Ymd');
  608. $model = model('Customer');
  609. $temp_file = $param['temp_file'];
  610. unset($param['temp_file']);
  611. $page = $param['page'] ?: 1;
  612. unset($param['page']);
  613. unset($param['export_queue_index']);
  614. return $excelModel->batchExportCsv($file_name, $temp_file, $field_list, $page, function($page, $limit) use ($model, $param, $field_list) {
  615. $param['page'] = $page;
  616. $param['limit'] = $limit;
  617. $data = $model->getDataList($param);
  618. $data['list'] = $model->exportHandle($data['list'], $field_list, 'customer');
  619. return $data;
  620. });
  621. }
  622. /**
  623. * 客户导入模板下载
  624. * @author Michael_xu
  625. * @param string $save_path 本地保存路径 用于错误数据导出,在 Admin\Model\Excel::batchImportData()调用
  626. * @return
  627. */
  628. public function excelDownload($save_path = '')
  629. {
  630. $param = $this->param;
  631. $userInfo = $this->userInfo;
  632. $excelModel = new \app\admin\model\Excel();
  633. // 导入的字段列表
  634. $fieldModel = new \app\admin\model\Field();
  635. $fieldParam['types'] = 'crm_customer';
  636. $fieldParam['action'] = 'excel';
  637. $field_list = $fieldModel->field($fieldParam);
  638. $excelModel->excelImportDownload($field_list, 'crm_customer', $save_path);
  639. }
  640. /**
  641. * 客户数据导入
  642. * @author Michael_xu
  643. * @param
  644. * @return
  645. */
  646. public function excelImport()
  647. {
  648. $param = $this->param;
  649. $userInfo = $this->userInfo;
  650. $excelModel = new \app\admin\model\Excel();
  651. $param['create_user_id'] = $userInfo['id'];
  652. $param['owner_user_id'] = $param['owner_user_id'] ? : 0;
  653. $param['deal_time'] = time();
  654. $param['deal_status'] = '未成交';
  655. $param['types'] = 'crm_customer';
  656. $file = request()->file('file');
  657. // $res = $excelModel->importExcel($file, $param, $this);
  658. $res = $excelModel->batchImportData($file, $param, $this);
  659. return resultArray(['data' => $excelModel->getError()]);
  660. }
  661. /**
  662. * 客户标记为已跟进
  663. * @author Michael_xu
  664. * @param
  665. * @return
  666. */
  667. public function setFollow(){
  668. $param = $this->param;
  669. $customerIds = $param['id'] ? : [];
  670. if (!$customerIds || !is_array($customerIds)) {
  671. return resultArray(['error'=>'参数错误']);
  672. }
  673. $data['follow'] = '已跟进';
  674. $data['update_time'] = time();
  675. $res = db('crm_customer')->where(['customer_id' => ['in',$customerIds]])->update($data);
  676. if (!$res) {
  677. return resultArray(['error'=>'操作失败,请重试']);
  678. }
  679. return resultArray(['data'=>'跟进成功']);
  680. }
  681. /**
  682. * 置顶 / 取消置顶
  683. * @return [type] [description]
  684. */
  685. public function top()
  686. {
  687. $param = $this->param;
  688. $userInfo = $this->userInfo;
  689. $param['create_role_id'] = $userInfo['id'];
  690. $param['top_time'] = time();
  691. $top_id = Db::name('crm_top')->where(['module' => ['eq',$param['module']],'create_role_id' => ['eq',$userInfo['id']],'module_id' => ['eq',$param['module_id']]])->column('top_id');
  692. if ($top_id) {
  693. if ($res = Db::name('crm_top')->where('top_id',$top_id[0])->update($param)) {
  694. return resultArray(['data' => $res]);
  695. } else {
  696. return resultArray(['error' => Db::name('crm_top')->getError()]);
  697. }
  698. } else {
  699. if ($res = Db::name('crm_top')->data($param)->insert()) {
  700. return resultArray(['data' => $res]);
  701. } else {
  702. return resultArray(['error' => $customerModel->getError()]);
  703. }
  704. }
  705. }
  706. /**
  707. * 客户公海导出
  708. * @author Michael_xu
  709. * @param
  710. * @return
  711. */
  712. public function poolExcelExport()
  713. {
  714. $param = $this->param;
  715. $userInfo = $this->userInfo;
  716. $param['user_id'] = $userInfo['id'];
  717. if ($param['customer_id']) {
  718. $param['customer_id'] = ['condition' => 'in','value' => $param['customer_id'],'form_type' => 'text','name' => ''];
  719. }
  720. $param['is_excel'] = 1;
  721. $excelModel = new \app\admin\model\Excel();
  722. // 导出的字段列表
  723. $fieldModel = new \app\admin\model\Field();
  724. $field_list = $fieldModel->getIndexFieldConfig('crm_customer', $userInfo['id']);
  725. $field_list = array_filter($field_list, function ($val) {
  726. return $val['field'] != 'owner_user_id';
  727. });
  728. // 文件名
  729. $file_name = '5kcrm_customer_pool_'.date('Ymd');
  730. $param['action'] = 'pool';
  731. $model = model('Customer');
  732. $temp_file = $param['temp_file'];
  733. unset($param['temp_file']);
  734. $page = $param['page'] ?: 1;
  735. unset($param['page']);
  736. unset($param['export_queue_index']);
  737. return $excelModel->batchExportCsv($file_name, $temp_file, $field_list, $page, function($page, $limit) use ($model, $param) {
  738. $param['page'] = $page;
  739. $param['limit'] = $limit;
  740. $data = $model->getDataList($param);
  741. $data['list'] = $model->exportHandle($data['list'], $field_list, 'crm_customer');
  742. return $data;
  743. });
  744. }
  745. /**
  746. * 客户成交状态
  747. * @author Michael_xu
  748. * @param status 1已成交,2未成交
  749. * @return
  750. */
  751. public function deal_status()
  752. {
  753. $param = $this->param;
  754. $userInfo = $this->userInfo;
  755. $statusArr = ['1' => '已成交','2' => '未成交'];
  756. $statusList = ['1','2'];
  757. if (!$param['customer_id'] || !in_array($param['status'],$statusList)) {
  758. return resultArray(['error' => '参数错误']);
  759. }
  760. $customerModel = model('Customer');
  761. $customerConfigModel = model('CustomerConfig');
  762. $userModel = new \app\admin\model\User();
  763. $customer_ids = $param['customer_id'];
  764. if (!is_array($customer_ids) || !$customer_ids) {
  765. $customer_ids[] = $customer_ids;
  766. }
  767. $data = [];
  768. $data['update_time'] = time();
  769. $data['deal_time'] = time();
  770. $data['deal_status'] = $statusArr[$param['status']];
  771. $errorMessage = [];
  772. foreach ($customer_ids as $customer_id) {
  773. $dataInfo = [];
  774. $dataInfo = db('crm_customer')->where(['customer_id' => $customer_id])->field('owner_user_id,deal_status,name')->find();
  775. //权限判断
  776. if (!$customerModel->checkData($customer_id, 1)) {
  777. $errorMessage[] = '名称:为《'.$dataInfo['name'].'》的客户更改失败,错误原因:'.$customerModel->getError();
  778. continue;
  779. }
  780. $owner_user_id = $dataInfo['owner_user_id'];;
  781. if (!$owner_user_id) {
  782. $errorMessage[] = '名称:为《'.$dataInfo['name'].'》的客户更改失败,错误原因:公海数据无权操作';
  783. continue;
  784. }
  785. //拥有客户数上限检测
  786. if ($statusArr[$param['status']] == '未成交' && $dataInfo['deal_status'] == '已成交') {
  787. if (!$customerConfigModel->checkData($owner_user_id,1,1)) {
  788. $errorMessage[] = '名称:为《'.$dataInfo['name'].'》的客户更改失败,错误原因:'.$customerConfigModel->getError();
  789. continue;
  790. }
  791. }
  792. if ($statusArr[$param['status']] == '已成交') {
  793. $data['is_lock'] = 0;
  794. }
  795. $res = db('crm_customer')->where(['customer_id' => $customer_id])->update($data);
  796. if (!$res) {
  797. $errorMessage[] = '名称:为《'.$dataInfo['name'].'》的客户更改失败,错误原因:操作失败,请重试!';
  798. continue;
  799. }
  800. //修改记录
  801. updateActionLog($userInfo['id'], 'crm_customer', $customer_id, ['deal_status' => $dataInfo['deal_status']], ['deal_status' => $data['deal_status']]);
  802. }
  803. if (!$errorMessage) {
  804. return resultArray(['data' => '操作成功']);
  805. } else {
  806. return resultArray(['error' => $errorMessage]);
  807. }
  808. }
  809. /**
  810. * 设置关注
  811. *
  812. * @return \think\response\Json
  813. * @throws \think\Exception
  814. * @throws \think\exception\PDOException
  815. */
  816. public function star()
  817. {
  818. $userId = $this->userInfo['id'];
  819. $targetId = $this->param['target_id'];
  820. $type = $this->param['type'];
  821. if (empty($userId) || empty($targetId) || empty($type)) return resultArray(['error' => '缺少必要参数!']);
  822. if (!$this->setStar($type, $userId, $targetId)) {
  823. return resultArray(['error' => '设置关注失败!']);
  824. }
  825. return resultArray(['data' => '设置关注成功!']);
  826. }
  827. /**
  828. * 附近客户
  829. *
  830. * @return \think\response\Json
  831. */
  832. public function nearby()
  833. {
  834. if (empty($this->param['lng'])) return resultArray(['error' => '缺少经度参数!']);
  835. if (empty($this->param['lat'])) return resultArray(['error' => '缺少纬度参数!']);
  836. if (empty($this->param['distance'])) return resultArray(['error' => '请选择距离!']);
  837. $customerModel = model('Customer');
  838. $data = $customerModel->getNearbyList($this->param);
  839. return resultArray(['data' => $data]);
  840. }
  841. /**
  842. * 系统信息
  843. *
  844. * @return \think\response\Json
  845. * @throws \think\db\exception\DataNotFoundException
  846. * @throws \think\db\exception\ModelNotFoundException
  847. * @throws \think\exception\DbException
  848. */
  849. public function system()
  850. {
  851. if (empty($this->param['id'])) return resultArray(['error' => '参数错误!']);
  852. $customerModel = new \app\crm\model\Customer();
  853. $data = $customerModel->getSystemInfo($this->param['id']);
  854. return resultArray(['data' => $data]);
  855. }
  856. /**
  857. * table标签栏数量
  858. *
  859. * @return \think\response\Json
  860. * @throws \think\db\exception\DataNotFoundException
  861. * @throws \think\db\exception\ModelNotFoundException
  862. * @throws \think\exception\DbException
  863. */
  864. public function count()
  865. {
  866. if (empty($this->param['customer_id'])) return resultArray(['error' => '参数错误!']);
  867. $userInfo = $this->userInfo;
  868. $customerId = $this->param['customer_id'];
  869. # 联系人
  870. $contactsCount = Db::name('crm_contacts')->where('customer_id', $customerId)->where('owner_user_id', '<>', 0)->count();
  871. # 团队成员
  872. $customer = Db::name('crm_customer')->field(['owner_user_id', 'ro_user_id', 'rw_user_id'])->where('customer_id', $customerId)->find();
  873. $customer['ro_user_id'] = explode(',', trim($customer['ro_user_id'], ','));
  874. $customer['rw_user_id'] = explode(',', trim($customer['rw_user_id'], ','));
  875. $customer['owner_user_id'] = [$customer['owner_user_id']];
  876. $teamCount = array_filter(array_unique(array_merge($customer['ro_user_id'], $customer['rw_user_id'], $customer['owner_user_id'])));
  877. # 商机
  878. $businessCount = Db::name('crm_business')->where('customer_id', $customerId)->count();
  879. # 合同
  880. $contractCount = Db::name('crm_contract')->where('customer_id', $customerId)->count();
  881. # 回款
  882. $receivablesCount = Db::name('crm_receivables')->where('customer_id', $customerId)->count();
  883. # 回访
  884. $visitCount = Db::name('crm_visit')->where(['customer_id' => $customerId, 'deleted_state' => 0, 'owner_user_id' => $userInfo['id']])->count();
  885. # 发票
  886. $invoiceCount = Db::name('crm_invoice')->where('customer_id', $customerId)->count();
  887. # 附件
  888. $fileCount = Db::name('crm_customer_file')->alias('customer')->join('__ADMIN_FILE__ file', 'file.file_id = customer.file_id')->where('customer_id', $customerId)->count();
  889. $data = [
  890. 'businessCount' => $businessCount,
  891. 'contactCount' => $contactsCount,
  892. 'contractCount' => $contractCount,
  893. 'fileCount' => $fileCount,
  894. 'invoiceCount' => $invoiceCount,
  895. 'memberCount' => count($teamCount),
  896. 'receivablesCount' => $receivablesCount,
  897. 'returnVisitCount' => $visitCount
  898. ];
  899. return resultArray(['data' => $data]);
  900. }
  901. /**
  902. * 公海权限
  903. *
  904. * @param CustomerLogic $customerLogic
  905. * @return \think\response\Json
  906. * @throws \think\db\exception\DataNotFoundException
  907. * @throws \think\db\exception\ModelNotFoundException
  908. * @throws \think\exception\DbException
  909. */
  910. public function poolAuthority(CustomerLogic $customerLogic)
  911. {
  912. $authority = [
  913. 'delete' => false, # 删除
  914. 'distribute' => false, # 分配
  915. 'excelexport' => false, # 导出
  916. 'index' => false, # 列表
  917. 'receive' => false, # 领取
  918. ];
  919. $userId = $this->userInfo['id'];
  920. if (empty($userId)) return resultArray(['data' => $authority]);
  921. # 员工角色数据
  922. $groupIds = $customerLogic->getEmployeeGroups($userId);
  923. # 员工角色下的规则数据
  924. $ruleIds = $customerLogic->getEmployeeRules($groupIds);
  925. # 公海规则数据
  926. $poolRules = $customerLogic->getPoolRules();
  927. # 整理员工规则数据
  928. $rules = [];
  929. $ruleIds = implode(',',$ruleIds);
  930. $rules = array_filter(array_unique(explode(',', $ruleIds)));
  931. # 整理公海规则数据
  932. $deleteId = $distributeId = $exportId = $indexId = $receiveId = 0;
  933. foreach ($poolRules AS $key => $value) {
  934. if ($value['name'] == 'pool') $indexId = $value['id'];
  935. if ($value['name'] == 'distribute') $distributeId = $value['id'];
  936. if ($value['name'] == 'receive') $receiveId = $value['id'];
  937. if ($value['name'] == 'poolExcelExport') $exportId = $value['id'];
  938. if ($value['name'] == 'poolDelete') $deleteId = $value['id'];
  939. }
  940. # 权限判断
  941. $authority['delete'] = $userId == 1 || in_array(1, $groupIds) || in_array($deleteId, $rules) ? true : false;
  942. $authority['distribute'] = $userId == 1 || in_array(1, $groupIds) || in_array($distributeId, $rules) ? true : false;
  943. $authority['excelexport'] = $userId == 1 || in_array(1, $groupIds) || in_array($exportId, $rules) ? true : false;
  944. $authority['index'] = $userId == 1 || in_array(1, $groupIds) || in_array($indexId, $rules) ? true : false;
  945. $authority['receive'] = $userId == 1 || in_array(1, $groupIds) || in_array($receiveId, $rules) ? true : false;
  946. return resultArray(['data' => $authority]);
  947. }
  948. }