Contacts.php 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | Description: 联系人
  4. // +----------------------------------------------------------------------
  5. // | Author: Michael_xu | gengxiaoxu@5kcrm.com
  6. // +----------------------------------------------------------------------
  7. namespace app\crm\model;
  8. use think\Db;
  9. use app\admin\model\Common;
  10. use think\Request;
  11. use think\Validate;
  12. class Contacts extends Common
  13. {
  14. /**
  15. * 为了数据库的整洁,同时又不影响Model和Controller的名称
  16. * 我们约定每个模块的数据表都加上相同的前缀,比如CRM模块用crm作为数据表前缀
  17. */
  18. protected $name = 'crm_contacts';
  19. protected $createTime = 'create_time';
  20. protected $updateTime = 'update_time';
  21. protected $autoWriteTimestamp = true;
  22. /**
  23. * [getDataList 联系人list]
  24. * @author Michael_xu
  25. * @param [string] $map [查询条件]
  26. * @param [number] $page [当前页数]
  27. * @param [number] $limit [每页数量]
  28. * @return [array] [description]
  29. */
  30. public function getDataList($request)
  31. {
  32. $userModel = new \app\admin\model\User();
  33. $structureModel = new \app\admin\model\Structure();
  34. $fieldModel = new \app\admin\model\Field();
  35. $customerModel = new \app\crm\model\Customer();
  36. $search = $request['search'];
  37. $user_id = $request['user_id'];
  38. $scene_id = (int)$request['scene_id'];
  39. $is_excel = $request['is_excel']; //导出
  40. $business_id = $request['business_id'];
  41. $order_field = $request['order_field'];
  42. $order_type = $request['order_type'];
  43. $pageType = $request['pageType'];
  44. $getCount = $request['getCount'];
  45. //需要过滤的参数
  46. $unsetRequest = ['scene_id','search','user_id','is_excel','action','order_field','order_type','is_remind','getCount','type','otherMap','business_id','check_status'];
  47. foreach ($unsetRequest as $v) {
  48. unset($request[$v]);
  49. }
  50. $request = $this->fmtRequest( $request );
  51. $requestMap = $request['map'] ? : [];
  52. $sceneModel = new \app\admin\model\Scene();
  53. if ($scene_id) {
  54. //自定义场景
  55. $sceneMap = $sceneModel->getDataById($scene_id, $user_id, 'contacts') ? : [];
  56. } else {
  57. //默认场景
  58. $sceneMap = $sceneModel->getDefaultData('crm_contacts', $user_id) ? : [];
  59. }
  60. $searchMap = [];
  61. if ($search || $search == '0') {
  62. //普通筛选
  63. $searchMap = function($query) use ($search){
  64. $query->where('contacts.name',array('like','%'.$search.'%'))
  65. ->whereOr('contacts.mobile',array('like','%'.$search.'%'))
  66. ->whereOr('contacts.telephone',array('like','%'.$search.'%'));
  67. };
  68. // $sceneMap['name'] = ['condition' => 'contains','value' => $search,'form_type' => 'text','name' => '联系人姓名'];
  69. }
  70. //优先级:普通筛选>高级筛选>场景
  71. $map = $requestMap ? array_merge($sceneMap, $requestMap) : $sceneMap;
  72. //高级筛选
  73. $map = where_arr($map, 'crm', 'contacts', 'index');
  74. //权限
  75. $a = 'index';
  76. if ($is_excel) $a = 'excelExport';
  77. $authMap = [];
  78. $auth_user_ids = $userModel->getUserByPer('crm', 'contacts', $a);
  79. if (isset($map['contacts.owner_user_id']) && $map['contacts.owner_user_id'][0] != 'like') {
  80. if (!is_array($map['contacts.owner_user_id'][1])) {
  81. $map['contacts.owner_user_id'][1] = [$map['contacts.owner_user_id'][1]];
  82. }
  83. if (in_array($map['contacts.owner_user_id'][0], ['neq', 'notin'])) {
  84. $auth_user_ids = array_diff($auth_user_ids, $map['contacts.owner_user_id'][1]) ? : []; //取差集
  85. } else {
  86. $auth_user_ids = array_intersect($map['contacts.owner_user_id'][1], $auth_user_ids) ? : []; //取交集
  87. }
  88. unset($map['contacts.owner_user_id']);
  89. }
  90. $auth_user_ids = array_merge(array_unique(array_filter($auth_user_ids))) ? : ['-1'];
  91. //负责人、相关团队
  92. $authMap['contacts.owner_user_id'] = ['in',$auth_user_ids];
  93. //联系人商机
  94. if ($business_id) {
  95. $contacts_id = Db::name('crm_contacts_business')->where(['business_id' => $business_id])->column('contacts_id');
  96. if ($contacts_id) {
  97. $map['contacts.contacts_id'] = array('in',$contacts_id);
  98. }else{
  99. $map['contacts.contacts_id'] = array('eq',-1);
  100. }
  101. }
  102. //列表展示字段
  103. $indexField = $fieldModel->getIndexField('crm_contacts', $user_id, 1) ? : array('name');
  104. $userField = $fieldModel->getFieldByFormType('crm_contacts', 'user'); //人员类型
  105. $structureField = $fieldModel->getFieldByFormType('crm_contacts', 'structure'); //部门类型
  106. $datetimeField = $fieldModel->getFieldByFormType('crm_contacts', 'datetime'); //日期时间类型
  107. # 处理人员和部门类型的排序报错问题(前端传来的是包含_name的别名字段)
  108. $temporaryField = str_replace('_name', '', $order_field);
  109. if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) {
  110. $order_field = $temporaryField;
  111. }
  112. //排序
  113. if ($order_type && $order_field) {
  114. $order = $fieldModel->getOrderByFormtype('crm_contacts','contacts',$order_field,$order_type);
  115. } else {
  116. $order = 'contacts.update_time desc';
  117. }
  118. $readAuthIds = $userModel->getUserByPer('crm', 'contacts', 'read');
  119. $updateAuthIds = $userModel->getUserByPer('crm', 'contacts', 'update');
  120. $deleteAuthIds = $userModel->getUserByPer('crm', 'contacts', 'delete');
  121. $customerWhere = [];
  122. if ($pageType == !'all') {
  123. //非客户池条件
  124. $customerWhere = $customerModel->getWhereByCustomer();
  125. }
  126. $dataCount = db('crm_contacts')
  127. ->alias('contacts')
  128. ->join('__CRM_CUSTOMER__ customer','contacts.customer_id = customer.customer_id','LEFT')
  129. ->where($map)
  130. ->where($searchMap)
  131. ->where($authMap)
  132. ->where($customerWhere)
  133. ->count('contacts_id');
  134. if ($getCount == 1) {
  135. $data['dataCount'] = $dataCount ? : 0;
  136. return $data;
  137. }
  138. $list = db('crm_contacts')
  139. ->alias('contacts')
  140. ->join('__CRM_CUSTOMER__ customer','contacts.customer_id = customer.customer_id','LEFT')
  141. ->where($map)
  142. ->where($searchMap)
  143. ->where($authMap)
  144. ->where($customerWhere)
  145. ->limit($request['offset'], $request['length'])
  146. ->field('contacts.*,customer.name as customer_name')
  147. ->orderRaw($order)
  148. ->select();
  149. foreach ($list as $k=>$v) {
  150. $list[$k]['create_user_id_info'] = isset($v['create_user_id']) ? $userModel->getUserById($v['create_user_id']) : [];
  151. $list[$k]['owner_user_id_info'] = isset($v['owner_user_id']) ? $userModel->getUserById($v['owner_user_id']) : [];
  152. $list[$k]['customer_id_info']['customer_id'] = $v['customer_id'] ? : '';
  153. $list[$k]['customer_id_info']['name'] = $v['customer_name'] ? : '';
  154. foreach ($userField as $key => $val) {
  155. $usernameField = !empty($v[$val]) ? db('admin_user')->whereIn('id', stringToArray($v[$val]))->column('realname') : [];
  156. $list[$k][$val.'_name'] = implode($usernameField, ',');
  157. }
  158. foreach ($structureField as $key => $val) {
  159. $structureNameField = !empty($v[$val]) ? db('admin_structure')->whereIn('id', stringToArray($v[$val]))->column('name') : [];
  160. $list[$k][$val.'_name'] = implode($structureNameField, ',');
  161. }
  162. foreach ($datetimeField as $key => $val) {
  163. $list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null;
  164. }
  165. //权限
  166. $permission = [];
  167. $is_read = 0;
  168. $is_update = 0;
  169. $is_delete = 0;
  170. if (in_array($v['owner_user_id'],$readAuthIds)) $is_read = 1;
  171. if (in_array($v['owner_user_id'],$updateAuthIds)) $is_update = 1;
  172. if (in_array($v['owner_user_id'],$deleteAuthIds)) $is_delete = 1;
  173. $permission['is_read'] = $is_read;
  174. $permission['is_update'] = $is_update;
  175. $permission['is_delete'] = $is_delete;
  176. $list[$k]['permission'] = $permission;
  177. # 关注
  178. $starWhere = ['user_id' => $user_id, 'target_id' => $v['contacts_id'], 'type' => 'crm_contacts'];
  179. $star = Db::name('crm_star')->where($starWhere)->value('star_id');
  180. $list[$k]['star'] = !empty($star) ? 1 : 0;
  181. # 日期
  182. $list[$k]['create_time'] = !empty($v['create_time']) ? date('Y-m-d H:i:s', $v['create_time']) : null;
  183. $list[$k]['update_time'] = !empty($v['update_time']) ? date('Y-m-d H:i:s', $v['update_time']) : null;
  184. $list[$k]['last_time'] = !empty($v['last_time']) ? date('Y-m-d H:i:s', $v['last_time']) : null;
  185. # 创建人
  186. $list[$k]['create_user_name'] = !empty($list[$k]['create_user_id_info']['realname']) ? $list[$k]['create_user_id_info']['realname'] : '';
  187. # 负责人
  188. $list[$k]['owner_user_name'] = !empty($list[$k]['owner_user_id_info']['realname']) ? $list[$k]['owner_user_id_info']['realname'] : '';
  189. }
  190. $data = [];
  191. $data['list'] = $list;
  192. $data['dataCount'] = $dataCount ? : 0;
  193. return $data;
  194. }
  195. /**
  196. * 创建联系人主表信息
  197. * @author Michael_xu
  198. * @param
  199. * @return
  200. */
  201. public function createData($param)
  202. {
  203. $businessId = $param['business_id'];
  204. unset($param['business_id']);
  205. $fieldModel = new \app\admin\model\Field();
  206. // 自动验证
  207. $validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
  208. $validate = new Validate($validateArr['rule'], $validateArr['message']);
  209. $result = $validate->check($param);
  210. if (!$result) {
  211. $this->error = $validate->getError();
  212. return false;
  213. }
  214. # 处理客户首要联系人
  215. $primaryStatus = Db::name('crm_contacts')->where('customer_id', $param['customer_id'])->value('contacts_id');
  216. if (!empty($param['primary']) && $param['primary'] == 1 && !empty($primaryStatus)) {
  217. # 设置首要联系人,去除其他首要联系人状态
  218. Db::name('crm_contacts')->where('customer_id', $param['customer_id'])->update(['primary' => 0]);
  219. }
  220. if (!empty($param['customer_id']) && empty($primaryStatus)) {
  221. # 为客户添加第一个联系人默认设置成首要联系人
  222. $param['primary'] = 1;
  223. }
  224. //处理部门、员工、附件、多选类型字段
  225. $arrFieldAtt = $fieldModel->getArrayField('crm_contacts');
  226. foreach ($arrFieldAtt as $k=>$v) {
  227. $param[$v] = arrayToString($param[$v]);
  228. }
  229. if ($this->data($param)->allowField(true)->isUpdate(false)->save()) {
  230. updateActionLog($param['create_user_id'], 'crm_contacts', $this->contacts_id, '', '', '创建了联系人');
  231. $data = [];
  232. $data['contacts_id'] = $this->contacts_id;
  233. # 添加活动记录
  234. Db::name('crm_activity')->insert([
  235. 'type' => 2,
  236. 'activity_type' => 3,
  237. 'activity_type_id' => $data['contacts_id'],
  238. 'content' => $param['name'],
  239. 'create_user_id' => $param['create_user_id'],
  240. 'update_time' => time(),
  241. 'create_time' => time(),
  242. 'customer_ids' => ',' . $param['customer_id'] . ','
  243. ]);
  244. # 处理商机首要联系人
  245. if (!empty($businessId)) {
  246. Db::name('crm_business')->where('business_id', $businessId)->update(['contacts_id' => $data['contacts_id']]);
  247. }
  248. return $data;
  249. } else {
  250. $this->error = '添加失败';
  251. return false;
  252. }
  253. }
  254. //根据IDs获取数组
  255. public function getDataByStr($idstr)
  256. {
  257. $idArr = stringToArray($idstr);
  258. if (!$idArr) {
  259. return [];
  260. }
  261. $list = Db::name('CrmContacts')->where(['contacts_id' => ['in',$idArr]])->select();
  262. return $list;
  263. }
  264. /**
  265. * 编辑联系人主表信息
  266. *
  267. * @param $param
  268. * @param string $contacts_id
  269. * @return array|bool
  270. * @throws \think\Exception
  271. * @throws \think\db\exception\DataNotFoundException
  272. * @throws \think\db\exception\ModelNotFoundException
  273. * @throws \think\exception\DbException
  274. * @throws \think\exception\PDOException
  275. */
  276. public function updateDataById($param, $contacts_id = '')
  277. {
  278. $userModel = new \app\admin\model\User();
  279. $dataInfo = $this->getDataById($contacts_id);
  280. if (!$dataInfo) {
  281. $this->error = '数据不存在或已删除';
  282. return false;
  283. }
  284. //判断权限
  285. $auth_user_ids = $userModel->getUserByPer('crm', 'contacts', 'update');
  286. if (!in_array($dataInfo['owner_user_id'],$auth_user_ids)) {
  287. $this->error = '无权操作';
  288. return false;
  289. }
  290. $param['contacts_id'] = $contacts_id;
  291. //过滤不能修改的字段
  292. $unUpdateField = ['create_user_id','is_deleted','delete_time'];
  293. foreach ($unUpdateField as $v) {
  294. unset($param[$v]);
  295. }
  296. $fieldModel = new \app\admin\model\Field();
  297. // 自动验证
  298. $validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
  299. $validate = new Validate($validateArr['rule'], $validateArr['message']);
  300. $result = $validate->check($param);
  301. if (!$result) {
  302. $this->error = $validate->getError();
  303. return false;
  304. }
  305. //处理部门、员工、附件、多选类型字段
  306. $arrFieldAtt = $fieldModel->getArrayField('crm_contacts');
  307. foreach ($arrFieldAtt as $k=>$v) {
  308. $param[$v] = arrayToString($param[$v]);
  309. }
  310. # 处理首要联系人
  311. $primaryStatus = Db::name('crm_contacts')->where('customer_id', $param['customer_id'])->value('contacts_id');
  312. if (!empty($param['primary']) && $param['primary'] == 1 && !empty($primaryStatus)) {
  313. # 设置首要联系人,去除其他首要联系人状态
  314. Db::name('crm_contacts')->where('customer_id', $param['customer_id'])->update(['primary' => 0]);
  315. }
  316. if (!empty($param['customer_id']) && empty($primaryStatus)) {
  317. # 为客户添加第一个联系人默认设置成首要联系人
  318. $param['primary'] = 1;
  319. }
  320. if ($this->update($param, ['contacts_id' => $contacts_id], true)) {
  321. //修改记录
  322. updateActionLog($param['user_id'], 'crm_contacts', $contacts_id, $dataInfo, $param);
  323. $data = [];
  324. $data['contacts_id'] = $contacts_id;
  325. return $data;
  326. } else {
  327. $this->error = '编辑失败';
  328. return false;
  329. }
  330. }
  331. /**
  332. * 联系人数据
  333. *
  334. * @param string $id
  335. * @param int $userId
  336. * @return Common|array|bool|\PDOStatement|string|\think\Model|null
  337. * @throws \think\db\exception\DataNotFoundException
  338. * @throws \think\db\exception\ModelNotFoundException
  339. * @throws \think\exception\DbException
  340. */
  341. public function getDataById($id = '', $userId = 0)
  342. {
  343. $map['contacts_id'] = $id;
  344. $dataInfo = db('crm_contacts')->where($map)->find();
  345. if (!$dataInfo) {
  346. $this->error = '暂无此数据';
  347. return false;
  348. }
  349. $userModel = new \app\admin\model\User();
  350. $dataInfo['create_user_id_info'] = isset($dataInfo['create_user_id']) ? $userModel->getUserById($dataInfo['create_user_id']) : [];
  351. $dataInfo['owner_user_id_info'] = isset($dataInfo['owner_user_id']) ? $userModel->getUserById($dataInfo['owner_user_id']) : [];
  352. $dataInfo['customer_id_info'] = db('crm_customer')->where(['customer_id' => $dataInfo['customer_id']])->field('customer_id,name,mobile,telephone,deal_status')->find();
  353. $dataInfo['customer_name'] = !empty($dataInfo['customer_id_info']['name']) ? $dataInfo['customer_id_info']['name'] : '';
  354. $dataInfo['create_user_name'] = !empty($dataInfo['create_user_id_info']['realname']) ? $dataInfo['create_user_id_info']['realname'] : '';
  355. $dataInfo['owner_user_name'] = !empty($dataInfo['owner_user_id_info']['realname']) ? $dataInfo['owner_user_id_info']['realname'] : '';
  356. # 关注
  357. $starId = empty($userId) ? 0 : Db::name('crm_star')->where(['user_id' => $userId, 'target_id' => $id, 'type' => 'crm_contacts'])->value('star_id');
  358. $dataInfo['star'] = !empty($starId) ? 1 : 0;
  359. # 处理决策人显示问题
  360. $dataInfo['decision'] = !empty($dataInfo['decision']) && $dataInfo['decision'] == '是' ? '是' : '否';
  361. # 处理时间格式
  362. $fieldModel = new \app\admin\model\Field();
  363. $datetimeField = $fieldModel->getFieldByFormType('crm_contacts', 'datetime'); //日期时间类型
  364. foreach ($datetimeField as $key => $val) {
  365. $dataInfo[$val] = !empty($dataInfo[$val]) ? date('Y-m-d H:i:s', $dataInfo[$val]) : null;
  366. }
  367. $dataInfo['create_time'] = !empty($dataInfo['create_time']) ? date('Y-m-d H:i:s', $dataInfo['create_time']) : null;
  368. $dataInfo['update_time'] = !empty($dataInfo['update_time']) ? date('Y-m-d H:i:s', $dataInfo['update_time']) : null;
  369. $dataInfo['last_time'] = !empty($dataInfo['last_time']) ? date('Y-m-d H:i:s', $dataInfo['last_time']) : null;
  370. return $dataInfo;
  371. }
  372. /**
  373. * [联系人转移]
  374. * @author Michael_xu
  375. * @param ids 联系人ID数组
  376. * @param owner_user_id 变更负责人
  377. * @param is_remove 1移出,2转为团队成员
  378. * @return
  379. */
  380. public function transferDataById($ids, $owner_user_id, $type = 1, $is_remove)
  381. {
  382. $settingModel = new \app\crm\model\Setting();
  383. foreach ($ids as $id) {
  384. $data = [];
  385. $data['owner_user_id'] = $owner_user_id;
  386. $data['update_time'] = time();
  387. db('crm_contacts')->where(['contacts_id' => $id])->update($data);
  388. }
  389. return true;
  390. }
  391. /**
  392. * 设置首要联系人
  393. *
  394. * @param $customerId
  395. * @param $contactsId
  396. * @return bool
  397. * @throws \think\Exception
  398. * @throws \think\exception\PDOException
  399. */
  400. public function setPrimary($customerId, $contactsId)
  401. {
  402. Db::name('crm_contacts')->where('customer_id', $customerId)->update(['primary' => 0]);
  403. Db::name('crm_contacts')->where(['customer_id' => $customerId, 'contacts_id' => $contactsId])->update(['primary' => 1]);
  404. return true;
  405. }
  406. /**
  407. * 获取跟进记录联系人
  408. *
  409. * @param $customerId
  410. * @return bool|\PDOStatement|string|\think\Collection
  411. * @throws \think\db\exception\DataNotFoundException
  412. * @throws \think\db\exception\ModelNotFoundException
  413. * @throws \think\exception\DbException
  414. */
  415. public function getContactsList($customerId)
  416. {
  417. return Db::name('crm_contacts')->field(['contacts_id', 'name', 'mobile', 'telephone', 'detail_address'])->where('customer_id', $customerId)->order('primary', 'desc')->select();
  418. }
  419. /**
  420. * 获取系统信息
  421. *
  422. * @param $id
  423. * @return array
  424. * @throws \think\db\exception\DataNotFoundException
  425. * @throws \think\db\exception\ModelNotFoundException
  426. * @throws \think\exception\DbException
  427. */
  428. public function getSystemInfo($id)
  429. {
  430. # 联系人
  431. $contacts = Db::name('crm_contacts')->field(['create_user_id', 'create_time', 'update_time'])->where('contacts_id', $id)->find();
  432. # 创建人
  433. $realname = Db::name('admin_user')->where('id', $contacts['create_user_id'])->value('realname');
  434. # 跟进时间
  435. $followTime = Db::name('crm_activity')->where(['type' => 1, 'activity_type' => 3, 'activity_type_id' => $id])->order('activity_id', 'desc')->value('update_time');
  436. return [
  437. 'create_user_name' => $realname,
  438. 'create_time' => date('Y-m-d H:i:s', $contacts['create_time']),
  439. 'update_time' => date('Y-m-d H:i:s', $contacts['update_time']),
  440. 'follow_time' => !empty($followTime) ? date('Y-m-d H:i:s', $followTime) : ''
  441. ];
  442. }
  443. }