Contacts.php 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  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) {
  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. //排序
  108. if ($order_type && $order_field) {
  109. $order = $fieldModel->getOrderByFormtype('crm_contacts','contacts',$order_field,$order_type);
  110. } else {
  111. $order = 'contacts.update_time desc';
  112. }
  113. $readAuthIds = $userModel->getUserByPer('crm', 'contacts', 'read');
  114. $updateAuthIds = $userModel->getUserByPer('crm', 'contacts', 'update');
  115. $deleteAuthIds = $userModel->getUserByPer('crm', 'contacts', 'delete');
  116. $customerWhere = [];
  117. if ($pageType == !'all') {
  118. //非客户池条件
  119. $customerWhere = $customerModel->getWhereByCustomer();
  120. }
  121. $dataCount = db('crm_contacts')
  122. ->alias('contacts')
  123. ->join('__CRM_CUSTOMER__ customer','contacts.customer_id = customer.customer_id','LEFT')
  124. ->where($map)
  125. ->where($searchMap)
  126. ->where($authMap)
  127. ->where($customerWhere)
  128. ->count('contacts_id');
  129. if ($getCount == 1) {
  130. $data['dataCount'] = $dataCount ? : 0;
  131. return $data;
  132. }
  133. $list = db('crm_contacts')
  134. ->alias('contacts')
  135. ->join('__CRM_CUSTOMER__ customer','contacts.customer_id = customer.customer_id','LEFT')
  136. ->where($map)
  137. ->where($searchMap)
  138. ->where($authMap)
  139. ->where($customerWhere)
  140. ->limit($request['offset'], $request['length'])
  141. ->field('contacts.*,customer.name as customer_name')
  142. ->orderRaw($order)
  143. ->select();
  144. foreach ($list as $k=>$v) {
  145. $list[$k]['create_user_id_info'] = isset($v['create_user_id']) ? $userModel->getUserById($v['create_user_id']) : [];
  146. $list[$k]['owner_user_id_info'] = isset($v['owner_user_id']) ? $userModel->getUserById($v['owner_user_id']) : [];
  147. $list[$k]['customer_id_info']['customer_id'] = $v['customer_id'] ? : '';
  148. $list[$k]['customer_id_info']['name'] = $v['customer_name'] ? : '';
  149. foreach ($userField as $key => $val) {
  150. $usernameField = !empty($v[$val]) ? db('admin_user')->whereIn('id', stringToArray($v[$val]))->column('realname') : [];
  151. $list[$k][$val] = implode($usernameField, ',');
  152. }
  153. foreach ($structureField as $key => $val) {
  154. $structureNameField = !empty($v[$val]) ? db('admin_structure')->whereIn('id', stringToArray($v[$val]))->column('name') : [];
  155. $list[$k][$val] = implode($structureNameField, ',');
  156. }
  157. foreach ($datetimeField as $key => $val) {
  158. $list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null;
  159. }
  160. //权限
  161. $permission = [];
  162. $is_read = 0;
  163. $is_update = 0;
  164. $is_delete = 0;
  165. if (in_array($v['owner_user_id'],$readAuthIds)) $is_read = 1;
  166. if (in_array($v['owner_user_id'],$updateAuthIds)) $is_update = 1;
  167. if (in_array($v['owner_user_id'],$deleteAuthIds)) $is_delete = 1;
  168. $permission['is_read'] = $is_read;
  169. $permission['is_update'] = $is_update;
  170. $permission['is_delete'] = $is_delete;
  171. $list[$k]['permission'] = $permission;
  172. # 关注
  173. $starWhere = ['user_id' => $user_id, 'target_id' => $v['contacts_id'], 'type' => 'crm_contacts'];
  174. $star = Db::name('crm_star')->where($starWhere)->value('star_id');
  175. $list[$k]['star'] = !empty($star) ? 1 : 0;
  176. # 日期
  177. $list[$k]['create_time'] = !empty($v['create_time']) ? date('Y-m-d H:i:s', $v['create_time']) : null;
  178. $list[$k]['update_time'] = !empty($v['update_time']) ? date('Y-m-d H:i:s', $v['update_time']) : null;
  179. $list[$k]['last_time'] = !empty($v['last_time']) ? date('Y-m-d H:i:s', $v['last_time']) : null;
  180. # 创建人
  181. $list[$k]['create_user_name'] = !empty($list[$k]['create_user_id_info']['realname']) ? $list[$k]['create_user_id_info']['realname'] : '';
  182. # 负责人
  183. $list[$k]['owner_user_name'] = !empty($list[$k]['owner_user_id_info']['realname']) ? $list[$k]['owner_user_id_info']['realname'] : '';
  184. }
  185. $data = [];
  186. $data['list'] = $list;
  187. $data['dataCount'] = $dataCount ? : 0;
  188. return $data;
  189. }
  190. /**
  191. * 创建联系人主表信息
  192. * @author Michael_xu
  193. * @param
  194. * @return
  195. */
  196. public function createData($param)
  197. {
  198. $businessId = $param['business_id'];
  199. unset($param['business_id']);
  200. $fieldModel = new \app\admin\model\Field();
  201. // 自动验证
  202. $validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
  203. $validate = new Validate($validateArr['rule'], $validateArr['message']);
  204. $result = $validate->check($param);
  205. if (!$result) {
  206. $this->error = $validate->getError();
  207. return false;
  208. }
  209. # 处理客户首要联系人
  210. $primaryStatus = Db::name('crm_contacts')->where('customer_id', $param['customer_id'])->value('contacts_id');
  211. if (!empty($param['primary']) && $param['primary'] == 1 && !empty($primaryStatus)) {
  212. # 设置首要联系人,去除其他首要联系人状态
  213. Db::name('crm_contacts')->where('customer_id', $param['customer_id'])->update(['primary' => 0]);
  214. }
  215. if (!empty($param['customer_id']) && empty($primaryStatus)) {
  216. # 为客户添加第一个联系人默认设置成首要联系人
  217. $param['primary'] = 1;
  218. }
  219. //处理部门、员工、附件、多选类型字段
  220. $arrFieldAtt = $fieldModel->getArrayField('crm_contacts');
  221. foreach ($arrFieldAtt as $k=>$v) {
  222. $param[$v] = arrayToString($param[$v]);
  223. }
  224. if ($this->data($param)->allowField(true)->isUpdate(false)->save()) {
  225. updateActionLog($param['create_user_id'], 'crm_contacts', $this->contacts_id, '', '', '创建了联系人');
  226. $data = [];
  227. $data['contacts_id'] = $this->contacts_id;
  228. # 添加活动记录
  229. Db::name('crm_activity')->insert([
  230. 'type' => 2,
  231. 'activity_type' => 3,
  232. 'activity_type_id' => $data['contacts_id'],
  233. 'content' => $param['name'],
  234. 'create_user_id' => $param['create_user_id'],
  235. 'update_time' => time(),
  236. 'create_time' => time(),
  237. 'customer_ids' => $param['customer_id']
  238. ]);
  239. # 处理商机首要联系人
  240. if (!empty($businessId)) {
  241. Db::name('crm_business')->where('business_id', $businessId)->update(['contacts_id' => $data['contacts_id']]);
  242. }
  243. return $data;
  244. } else {
  245. $this->error = '添加失败';
  246. return false;
  247. }
  248. }
  249. //根据IDs获取数组
  250. public function getDataByStr($idstr)
  251. {
  252. $idArr = stringToArray($idstr);
  253. if (!$idArr) {
  254. return [];
  255. }
  256. $list = Db::name('CrmContacts')->where(['contacts_id' => ['in',$idArr]])->select();
  257. return $list;
  258. }
  259. /**
  260. * 编辑联系人主表信息
  261. *
  262. * @param $param
  263. * @param string $contacts_id
  264. * @return array|bool
  265. * @throws \think\Exception
  266. * @throws \think\db\exception\DataNotFoundException
  267. * @throws \think\db\exception\ModelNotFoundException
  268. * @throws \think\exception\DbException
  269. * @throws \think\exception\PDOException
  270. */
  271. public function updateDataById($param, $contacts_id = '')
  272. {
  273. $userModel = new \app\admin\model\User();
  274. $dataInfo = $this->getDataById($contacts_id);
  275. if (!$dataInfo) {
  276. $this->error = '数据不存在或已删除';
  277. return false;
  278. }
  279. //判断权限
  280. $auth_user_ids = $userModel->getUserByPer('crm', 'contacts', 'update');
  281. if (!in_array($dataInfo['owner_user_id'],$auth_user_ids)) {
  282. $this->error = '无权操作';
  283. return false;
  284. }
  285. $param['contacts_id'] = $contacts_id;
  286. //过滤不能修改的字段
  287. $unUpdateField = ['create_user_id','is_deleted','delete_time'];
  288. foreach ($unUpdateField as $v) {
  289. unset($param[$v]);
  290. }
  291. $fieldModel = new \app\admin\model\Field();
  292. // 自动验证
  293. $validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
  294. $validate = new Validate($validateArr['rule'], $validateArr['message']);
  295. $result = $validate->check($param);
  296. if (!$result) {
  297. $this->error = $validate->getError();
  298. return false;
  299. }
  300. //处理部门、员工、附件、多选类型字段
  301. $arrFieldAtt = $fieldModel->getArrayField('crm_contacts');
  302. foreach ($arrFieldAtt as $k=>$v) {
  303. $param[$v] = arrayToString($param[$v]);
  304. }
  305. # 处理首要联系人
  306. $primaryStatus = Db::name('crm_contacts')->where('customer_id', $param['customer_id'])->value('contacts_id');
  307. if (!empty($param['primary']) && $param['primary'] == 1 && !empty($primaryStatus)) {
  308. # 设置首要联系人,去除其他首要联系人状态
  309. Db::name('crm_contacts')->where('customer_id', $param['customer_id'])->update(['primary' => 0]);
  310. }
  311. if (!empty($param['customer_id']) && empty($primaryStatus)) {
  312. # 为客户添加第一个联系人默认设置成首要联系人
  313. $param['primary'] = 1;
  314. }
  315. if ($this->update($param, ['contacts_id' => $contacts_id], true)) {
  316. //修改记录
  317. updateActionLog($param['user_id'], 'crm_contacts', $contacts_id, $dataInfo, $param);
  318. $data = [];
  319. $data['contacts_id'] = $contacts_id;
  320. return $data;
  321. } else {
  322. $this->error = '编辑失败';
  323. return false;
  324. }
  325. }
  326. /**
  327. * 联系人数据
  328. *
  329. * @param string $id
  330. * @param int $userId
  331. * @return Common|array|bool|\PDOStatement|string|\think\Model|null
  332. * @throws \think\db\exception\DataNotFoundException
  333. * @throws \think\db\exception\ModelNotFoundException
  334. * @throws \think\exception\DbException
  335. */
  336. public function getDataById($id = '', $userId = 0)
  337. {
  338. $map['contacts_id'] = $id;
  339. $dataInfo = db('crm_contacts')->where($map)->find();
  340. if (!$dataInfo) {
  341. $this->error = '暂无此数据';
  342. return false;
  343. }
  344. $userModel = new \app\admin\model\User();
  345. $dataInfo['create_user_id_info'] = isset($dataInfo['create_user_id']) ? $userModel->getUserById($dataInfo['create_user_id']) : [];
  346. $dataInfo['owner_user_id_info'] = isset($dataInfo['owner_user_id']) ? $userModel->getUserById($dataInfo['owner_user_id']) : [];
  347. $dataInfo['customer_id_info'] = db('crm_customer')->where(['customer_id' => $dataInfo['customer_id']])->field('customer_id,name,mobile,telephone,deal_status')->find();
  348. $dataInfo['customer_name'] = !empty($dataInfo['customer_id_info']['name']) ? $dataInfo['customer_id_info']['name'] : '';
  349. $dataInfo['create_user_name'] = !empty($dataInfo['create_user_id_info']['realname']) ? $dataInfo['create_user_id_info']['realname'] : '';
  350. $dataInfo['owner_user_name'] = !empty($dataInfo['owner_user_id_info']['realname']) ? $dataInfo['owner_user_id_info']['realname'] : '';
  351. # 关注
  352. $starId = empty($userId) ? 0 : Db::name('crm_star')->where(['user_id' => $userId, 'target_id' => $id, 'type' => 'crm_contacts'])->value('star_id');
  353. $dataInfo['star'] = !empty($starId) ? 1 : 0;
  354. # 处理决策人显示问题
  355. $dataInfo['decision'] = !empty($dataInfo['decision']) && $dataInfo['decision'] == '是' ? '是' : '';
  356. # 处理时间格式
  357. $fieldModel = new \app\admin\model\Field();
  358. $datetimeField = $fieldModel->getFieldByFormType('crm_contacts', 'datetime'); //日期时间类型
  359. foreach ($datetimeField as $key => $val) {
  360. $dataInfo[$val] = !empty($dataInfo[$val]) ? date('Y-m-d H:i:s', $dataInfo[$val]) : null;
  361. }
  362. $dataInfo['create_time'] = !empty($dataInfo['create_time']) ? date('Y-m-d H:i:s', $dataInfo['create_time']) : null;
  363. $dataInfo['update_time'] = !empty($dataInfo['update_time']) ? date('Y-m-d H:i:s', $dataInfo['update_time']) : null;
  364. $dataInfo['last_time'] = !empty($dataInfo['last_time']) ? date('Y-m-d H:i:s', $dataInfo['last_time']) : null;
  365. return $dataInfo;
  366. }
  367. /**
  368. * [联系人转移]
  369. * @author Michael_xu
  370. * @param ids 联系人ID数组
  371. * @param owner_user_id 变更负责人
  372. * @param is_remove 1移出,2转为团队成员
  373. * @return
  374. */
  375. public function transferDataById($ids, $owner_user_id, $type = 1, $is_remove)
  376. {
  377. $settingModel = new \app\crm\model\Setting();
  378. foreach ($ids as $id) {
  379. $data = [];
  380. $data['owner_user_id'] = $owner_user_id;
  381. $data['update_time'] = time();
  382. db('crm_contacts')->where(['contacts_id' => $id])->update($data);
  383. }
  384. return true;
  385. }
  386. /**
  387. * 设置首要联系人
  388. *
  389. * @param $customerId
  390. * @param $contactsId
  391. * @return bool
  392. * @throws \think\Exception
  393. * @throws \think\exception\PDOException
  394. */
  395. public function setPrimary($customerId, $contactsId)
  396. {
  397. Db::name('crm_contacts')->where('customer_id', $customerId)->update(['primary' => 0]);
  398. Db::name('crm_contacts')->where(['customer_id' => $customerId, 'contacts_id' => $contactsId])->update(['primary' => 1]);
  399. return true;
  400. }
  401. /**
  402. * 获取跟进记录联系人
  403. *
  404. * @param $customerId
  405. * @return bool|\PDOStatement|string|\think\Collection
  406. * @throws \think\db\exception\DataNotFoundException
  407. * @throws \think\db\exception\ModelNotFoundException
  408. * @throws \think\exception\DbException
  409. */
  410. public function getContactsList($customerId)
  411. {
  412. return Db::name('crm_contacts')->field(['contacts_id', 'name', 'mobile', 'telephone', 'detail_address'])->where('customer_id', $customerId)->order('primary', 'desc')->select();
  413. }
  414. /**
  415. * 获取系统信息
  416. *
  417. * @param $id
  418. * @return array
  419. * @throws \think\db\exception\DataNotFoundException
  420. * @throws \think\db\exception\ModelNotFoundException
  421. * @throws \think\exception\DbException
  422. */
  423. public function getSystemInfo($id)
  424. {
  425. # 联系人
  426. $contacts = Db::name('crm_contacts')->field(['create_user_id', 'create_time', 'update_time'])->where('contacts_id', $id)->find();
  427. # 创建人
  428. $realname = Db::name('admin_user')->where('id', $contacts['create_user_id'])->value('realname');
  429. # 跟进时间
  430. $followTime = Db::name('crm_activity')->where(['type' => 1, 'activity_type' => 3, 'activity_type_id' => $id])->order('activity_id', 'desc')->value('update_time');
  431. return [
  432. 'create_user_name' => $realname,
  433. 'create_time' => date('Y-m-d H:i:s', $contacts['create_time']),
  434. 'update_time' => date('Y-m-d H:i:s', $contacts['update_time']),
  435. 'follow_time' => !empty($followTime) ? date('Y-m-d H:i:s', $followTime) : ''
  436. ];
  437. }
  438. }