Contacts.php 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  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. // 处理日期(date)类型
  230. $dateField = $fieldModel->getFieldByFormType('crm_contacts', 'date');
  231. if (!empty($dateField)) {
  232. foreach ($param AS $key => $value) {
  233. if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
  234. }
  235. }
  236. if ($this->data($param)->allowField(true)->isUpdate(false)->save()) {
  237. updateActionLog($param['create_user_id'], 'crm_contacts', $this->contacts_id, '', '', '创建了联系人');
  238. RecordActionLog($param['create_user_id'],'crm_contacts','save',$param['name'],'','','新增了联系人'.$param['name']);
  239. $data = [];
  240. $data['contacts_id'] = $this->contacts_id;
  241. # 添加活动记录
  242. Db::name('crm_activity')->insert([
  243. 'type' => 2,
  244. 'activity_type' => 3,
  245. 'activity_type_id' => $data['contacts_id'],
  246. 'content' => $param['name'],
  247. 'create_user_id' => $param['create_user_id'],
  248. 'update_time' => time(),
  249. 'create_time' => time(),
  250. 'customer_ids' => ',' . $param['customer_id'] . ','
  251. ]);
  252. # 处理商机首要联系人
  253. if (!empty($businessId)) {
  254. Db::name('crm_business')->where('business_id', $businessId)->update(['contacts_id' => $data['contacts_id']]);
  255. }
  256. return $data;
  257. } else {
  258. $this->error = '添加失败';
  259. return false;
  260. }
  261. }
  262. //根据IDs获取数组
  263. public function getDataByStr($idstr)
  264. {
  265. $idArr = stringToArray($idstr);
  266. if (!$idArr) {
  267. return [];
  268. }
  269. $list = Db::name('CrmContacts')->where(['contacts_id' => ['in',$idArr]])->select();
  270. return $list;
  271. }
  272. /**
  273. * 编辑联系人主表信息
  274. *
  275. * @param $param
  276. * @param string $contacts_id
  277. * @return array|bool
  278. * @throws \think\Exception
  279. * @throws \think\db\exception\DataNotFoundException
  280. * @throws \think\db\exception\ModelNotFoundException
  281. * @throws \think\exception\DbException
  282. * @throws \think\exception\PDOException
  283. */
  284. public function updateDataById($param, $contacts_id = '')
  285. {
  286. $userModel = new \app\admin\model\User();
  287. $dataInfo = $this->getDataById($contacts_id);
  288. if (!$dataInfo) {
  289. $this->error = '数据不存在或已删除';
  290. return false;
  291. }
  292. //判断权限
  293. $auth_user_ids = $userModel->getUserByPer('crm', 'contacts', 'update');
  294. if (!in_array($dataInfo['owner_user_id'],$auth_user_ids)) {
  295. $this->error = '无权操作';
  296. return false;
  297. }
  298. $param['contacts_id'] = $contacts_id;
  299. //过滤不能修改的字段
  300. $unUpdateField = ['create_user_id','is_deleted','delete_time'];
  301. foreach ($unUpdateField as $v) {
  302. unset($param[$v]);
  303. }
  304. $fieldModel = new \app\admin\model\Field();
  305. // 自动验证
  306. // $validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
  307. $validateArr = $fieldModel->validateField($this->name, 0, 'update'); //获取自定义字段验证规则
  308. $validate = new Validate($validateArr['rule'], $validateArr['message']);
  309. $result = $validate->check($param);
  310. if (!$result) {
  311. $this->error = $validate->getError();
  312. return false;
  313. }
  314. // 处理部门、员工、附件、多选类型字段
  315. $arrFieldAtt = $fieldModel->getArrayField('crm_contacts');
  316. foreach ($arrFieldAtt as $k=>$v) {
  317. if (isset($param[$v])) $param[$v] = arrayToString($param[$v]);
  318. }
  319. // 处理日期(date)类型
  320. $dateField = $fieldModel->getFieldByFormType('crm_contacts', 'date');
  321. if (!empty($dateField)) {
  322. foreach ($param AS $key => $value) {
  323. if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
  324. }
  325. }
  326. # 处理首要联系人
  327. $primaryStatus = Db::name('crm_contacts')->where('customer_id', $param['customer_id'])->value('contacts_id');
  328. if (!empty($param['primary']) && $param['primary'] == 1 && !empty($primaryStatus)) {
  329. # 设置首要联系人,去除其他首要联系人状态
  330. Db::name('crm_contacts')->where('customer_id', $param['customer_id'])->update(['primary' => 0]);
  331. }
  332. if (!empty($param['customer_id']) && empty($primaryStatus)) {
  333. # 为客户添加第一个联系人默认设置成首要联系人
  334. $param['primary'] = 1;
  335. }
  336. if ($this->update($param, ['contacts_id' => $contacts_id], true)) {
  337. //修改记录
  338. updateActionLog($param['user_id'], 'crm_contacts', $contacts_id, $dataInfo, $param);
  339. RecordActionLog($param['user_id'], 'crm_contacts', 'update',$dataInfo['name'], $dataInfo, $param);
  340. $data = [];
  341. $data['contacts_id'] = $contacts_id;
  342. return $data;
  343. } else {
  344. $this->error = '编辑失败';
  345. return false;
  346. }
  347. }
  348. /**
  349. * 联系人数据
  350. *
  351. * @param string $id
  352. * @param int $userId
  353. * @return Common|array|bool|\PDOStatement|string|\think\Model|null
  354. * @throws \think\db\exception\DataNotFoundException
  355. * @throws \think\db\exception\ModelNotFoundException
  356. * @throws \think\exception\DbException
  357. */
  358. public function getDataById($id = '', $userId = 0)
  359. {
  360. $map['contacts_id'] = $id;
  361. $dataInfo = db('crm_contacts')->where($map)->find();
  362. if (!$dataInfo) {
  363. $this->error = '暂无此数据';
  364. return false;
  365. }
  366. $userModel = new \app\admin\model\User();
  367. $dataInfo['create_user_id_info'] = isset($dataInfo['create_user_id']) ? $userModel->getUserById($dataInfo['create_user_id']) : [];
  368. $dataInfo['owner_user_id_info'] = isset($dataInfo['owner_user_id']) ? $userModel->getUserById($dataInfo['owner_user_id']) : [];
  369. $dataInfo['customer_id_info'] = db('crm_customer')->where(['customer_id' => $dataInfo['customer_id']])->field('customer_id,name,mobile,telephone,deal_status')->find();
  370. $dataInfo['customer_name'] = !empty($dataInfo['customer_id_info']['name']) ? $dataInfo['customer_id_info']['name'] : '';
  371. $dataInfo['create_user_name'] = !empty($dataInfo['create_user_id_info']['realname']) ? $dataInfo['create_user_id_info']['realname'] : '';
  372. $dataInfo['owner_user_name'] = !empty($dataInfo['owner_user_id_info']['realname']) ? $dataInfo['owner_user_id_info']['realname'] : '';
  373. # 关注
  374. $starId = empty($userId) ? 0 : Db::name('crm_star')->where(['user_id' => $userId, 'target_id' => $id, 'type' => 'crm_contacts'])->value('star_id');
  375. $dataInfo['star'] = !empty($starId) ? 1 : 0;
  376. # 处理决策人显示问题
  377. $dataInfo['decision'] = !empty($dataInfo['decision']) && $dataInfo['decision'] == '是' ? '是' : '否';
  378. # 处理时间格式
  379. $fieldModel = new \app\admin\model\Field();
  380. $datetimeField = $fieldModel->getFieldByFormType('crm_contacts', 'datetime'); //日期时间类型
  381. foreach ($datetimeField as $key => $val) {
  382. $dataInfo[$val] = !empty($dataInfo[$val]) ? date('Y-m-d H:i:s', $dataInfo[$val]) : null;
  383. }
  384. $dataInfo['create_time'] = !empty($dataInfo['create_time']) ? date('Y-m-d H:i:s', $dataInfo['create_time']) : null;
  385. $dataInfo['update_time'] = !empty($dataInfo['update_time']) ? date('Y-m-d H:i:s', $dataInfo['update_time']) : null;
  386. $dataInfo['last_time'] = !empty($dataInfo['last_time']) ? date('Y-m-d H:i:s', $dataInfo['last_time']) : null;
  387. // 字段授权
  388. if (!empty($userId)) {
  389. $grantData = getFieldGrantData($userId);
  390. $userLevel = isSuperAdministrators($userId);
  391. foreach ($dataInfo AS $key => $value) {
  392. if (!$userLevel && !empty($grantData['crm_contacts'])) {
  393. $status = getFieldGrantStatus($key, $grantData['crm_contacts']);
  394. # 查看权限
  395. if ($status['read'] == 0) unset($dataInfo[$key]);
  396. }
  397. }
  398. }
  399. return $dataInfo;
  400. }
  401. /**
  402. * [联系人转移]
  403. * @author Michael_xu
  404. * @param ids 联系人ID数组
  405. * @param owner_user_id 变更负责人
  406. * @param is_remove 1移出,2转为团队成员
  407. * @return
  408. */
  409. public function transferDataById($ids, $owner_user_id, $type = 1, $is_remove)
  410. {
  411. $settingModel = new \app\crm\model\Setting();
  412. foreach ($ids as $id) {
  413. $data = [];
  414. $data['owner_user_id'] = $owner_user_id;
  415. $data['update_time'] = time();
  416. db('crm_contacts')->where(['contacts_id' => $id])->update($data);
  417. }
  418. return true;
  419. }
  420. /**
  421. * 设置首要联系人
  422. *
  423. * @param $customerId
  424. * @param $contactsId
  425. * @return bool
  426. * @throws \think\Exception
  427. * @throws \think\exception\PDOException
  428. */
  429. public function setPrimary($customerId, $contactsId)
  430. {
  431. Db::name('crm_contacts')->where('customer_id', $customerId)->update(['primary' => 0]);
  432. Db::name('crm_contacts')->where(['customer_id' => $customerId, 'contacts_id' => $contactsId])->update(['primary' => 1]);
  433. return true;
  434. }
  435. /**
  436. * 获取跟进记录联系人
  437. *
  438. * @param $customerId
  439. * @return bool|\PDOStatement|string|\think\Collection
  440. * @throws \think\db\exception\DataNotFoundException
  441. * @throws \think\db\exception\ModelNotFoundException
  442. * @throws \think\exception\DbException
  443. */
  444. public function getContactsList($customerId)
  445. {
  446. return Db::name('crm_contacts')->field(['contacts_id', 'name', 'mobile', 'telephone', 'detail_address'])->where('customer_id', $customerId)->order('primary', 'desc')->select();
  447. }
  448. /**
  449. * 获取系统信息
  450. *
  451. * @param $id
  452. * @return array
  453. * @throws \think\db\exception\DataNotFoundException
  454. * @throws \think\db\exception\ModelNotFoundException
  455. * @throws \think\exception\DbException
  456. */
  457. public function getSystemInfo($id)
  458. {
  459. # 联系人
  460. $contacts = Db::name('crm_contacts')->field(['create_user_id', 'create_time', 'update_time', 'last_time'])->where('contacts_id', $id)->find();
  461. # 创建人
  462. $realname = Db::name('admin_user')->where('id', $contacts['create_user_id'])->value('realname');
  463. return [
  464. 'create_user_id' => $realname,
  465. 'create_time' => date('Y-m-d H:i:s', $contacts['create_time']),
  466. 'update_time' => date('Y-m-d H:i:s', $contacts['update_time']),
  467. 'last_time' => !empty($contacts['last_time']) ? date('Y-m-d H:i:s', $contacts['last_time']) : ''
  468. ];
  469. }
  470. }