Contacts.php 36KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | Description: 联系人
  4. // +----------------------------------------------------------------------
  5. // | Author: Michael_xu | gengxiaoxu@5kcrm.com
  6. // +----------------------------------------------------------------------
  7. namespace app\crm\model;
  8. use app\admin\traits\FieldVerificationTrait;
  9. use think\Db;
  10. use app\admin\model\Common;
  11. use think\Validate;
  12. class Contacts extends Common
  13. {
  14. use FieldVerificationTrait;
  15. /**
  16. * 为了数据库的整洁,同时又不影响Model和Controller的名称
  17. * 我们约定每个模块的数据表都加上相同的前缀,比如CRM模块用crm作为数据表前缀
  18. */
  19. protected $name = 'crm_contacts';
  20. protected $createTime = 'create_time';
  21. protected $updateTime = 'update_time';
  22. protected $autoWriteTimestamp = true;
  23. /**
  24. * [getDataList 联系人list]
  25. * @param [string] $map [查询条件]
  26. * @param [number] $page [当前页数]
  27. * @param [number] $limit [每页数量]
  28. * @return [array] [description]
  29. * @author Michael_xu
  30. */
  31. public function getDataList($request)
  32. {
  33. $userModel = new \app\admin\model\User();
  34. $structureModel = new \app\admin\model\Structure();
  35. $fieldModel = new \app\admin\model\Field();
  36. $customerModel = new \app\crm\model\Customer();
  37. $search = $request['search'];
  38. $user_id = $request['user_id'];
  39. $scene_id = (int)$request['scene_id'];
  40. $is_excel = $request['is_excel']; //导出
  41. $business_id = $request['business_id'];
  42. $order_field = $request['order_field'];
  43. $order_type = $request['order_type'];
  44. $pageType = $request['pageType'];
  45. $getCount = $request['getCount'];
  46. //需要过滤的参数
  47. $unsetRequest = ['scene_id', 'search', 'user_id', 'is_excel', 'action', 'order_field', 'order_type', 'is_remind', 'getCount', 'type', 'otherMap', 'business_id', 'check_status'];
  48. foreach ($unsetRequest as $v) {
  49. unset($request[$v]);
  50. }
  51. $request = $this->fmtRequest($request);
  52. $requestMap = $request['map'] ?: [];
  53. $sceneModel = new \app\admin\model\Scene();
  54. if ($scene_id) {
  55. //自定义场景
  56. $sceneMap = $sceneModel->getDataById($scene_id, $user_id, 'contacts') ?: [];
  57. } else {
  58. //默认场景
  59. $sceneMap = $sceneModel->getDefaultData('crm_contacts', $user_id) ?: [];
  60. }
  61. $searchMap = [];
  62. if ($search || $search == '0') {
  63. //普通筛选
  64. $searchMap = function ($query) use ($search) {
  65. $query->where('contacts.name', array('like', '%' . $search . '%'))
  66. ->whereOr('contacts.mobile', array('like', '%' . $search . '%'))
  67. ->whereOr('contacts.telephone', array('like', '%' . $search . '%'));
  68. };
  69. }
  70. $partMap = [];
  71. //优先级:普通筛选>高级筛选>场景
  72. if ($requestMap['team_id']) {
  73. //相关团队查询
  74. $map = $requestMap;
  75. $partMap= advancedQueryFormatForTeam($requestMap,'crm_contacts','contacts_id');
  76. unset($map['team_id']);
  77. } else {
  78. $map = $requestMap ? array_merge($sceneMap, $requestMap) : $sceneMap;
  79. }
  80. //高级筛选
  81. $map = advancedQuery($map, 'crm', 'contacts', 'index');
  82. //权限
  83. if (!$partMap) {
  84. $a = 'index';
  85. if ($is_excel) $a = 'excelExport';
  86. $authMap = [];
  87. $auth_user_ids = $userModel->getUserByPer('crm', 'contacts', $a);
  88. if (isset($map['contacts.owner_user_id']) && $map['contacts.owner_user_id'][0] != 'like') {
  89. if (!is_array($map['contacts.owner_user_id'][1])) {
  90. $map['contacts.owner_user_id'][1] = [$map['contacts.owner_user_id'][1]];
  91. }
  92. if (in_array($map['contacts.owner_user_id'][0], ['neq', 'notin'])) {
  93. $auth_user_ids = array_diff($auth_user_ids, $map['contacts.owner_user_id'][1]) ?: []; //取差集
  94. } else {
  95. $auth_user_ids = array_intersect($map['contacts.owner_user_id'][1], $auth_user_ids) ?: []; //取交集
  96. }
  97. unset($map['contacts.owner_user_id']);
  98. $auth_user_ids = array_merge(array_unique(array_filter($auth_user_ids))) ?: ['-1'];
  99. //负责人、相关团队
  100. $authMap['contacts.owner_user_id'] = ['in', $auth_user_ids];
  101. } else {
  102. $authMapData = [];
  103. $authMapData['auth_user_ids'] = $auth_user_ids;
  104. $authMapData['user_id'] = $user_id;
  105. $authMap = function ($query) use ($authMapData) {
  106. $query->where('contacts.owner_user_id', array('in', $authMapData['auth_user_ids']))
  107. ->whereOr('contacts.ro_user_id', array('like', '%,' . $authMapData['user_id'] . ',%'))
  108. ->whereOr('contacts.rw_user_id', array('like', '%,' . $authMapData['user_id'] . ',%'));
  109. };
  110. }
  111. }
  112. //联系人商机
  113. if ($business_id) {
  114. $contacts_id = Db::name('crm_contacts_business')->where(['business_id' => $business_id])->column('contacts_id');
  115. if ($contacts_id) {
  116. $map['contacts.contacts_id'] = array('in', $contacts_id);
  117. } else {
  118. $map['contacts.contacts_id'] = array('eq', -1);
  119. }
  120. }
  121. //列表展示字段
  122. $indexField = $fieldModel->getIndexField('crm_contacts', $user_id, 1) ?: array('name');
  123. $userField = $fieldModel->getFieldByFormType('crm_contacts', 'user'); //人员类型
  124. $structureField = $fieldModel->getFieldByFormType('crm_contacts', 'structure'); //部门类型
  125. $datetimeField = $fieldModel->getFieldByFormType('crm_contacts', 'datetime'); //日期时间类型
  126. $booleanField = $fieldModel->getFieldByFormType('crm_contacts', 'boolean_value'); //布尔值
  127. $dateIntervalField = $fieldModel->getFieldByFormType('crm_contacts', 'date_interval'); // 日期区间类型字段
  128. $positionField = $fieldModel->getFieldByFormType('crm_contacts', 'position'); // 地址类型字段
  129. $handwritingField = $fieldModel->getFieldByFormType('crm_contacts', 'handwriting_sign'); // 手写签名类型字段
  130. $locationField = $fieldModel->getFieldByFormType('crm_contacts', 'location'); // 定位类型字段
  131. $boxField = $fieldModel->getFieldByFormType('crm_contacts', 'checkbox'); // 多选类型字段
  132. $floatField = $fieldModel->getFieldByFormType('crm_contacts', 'floatnumber'); // 货币类型字段
  133. // $fieldGrant = db('admin_field_mask')->where('types', 'contacts')->select();
  134. # 处理人员和部门类型的排序报错问题(前端传来的是包含_name的别名字段)
  135. $temporaryField = str_replace('_name', '', $order_field);
  136. if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) {
  137. $order_field = $temporaryField;
  138. }
  139. //排序
  140. if ($order_type && $order_field) {
  141. $order = $fieldModel->getOrderByFormtype('crm_contacts', 'contacts', $order_field, $order_type);
  142. } else {
  143. $order = 'contacts.update_time desc';
  144. }
  145. $readAuthIds = $userModel->getUserByPer('crm', 'contacts', 'read');
  146. $updateAuthIds = $userModel->getUserByPer('crm', 'contacts', 'update');
  147. $deleteAuthIds = $userModel->getUserByPer('crm', 'contacts', 'delete');
  148. $customerWhere = [];
  149. if ($pageType == !'all') {
  150. //非客户池条件
  151. $customerWhere = $customerModel->getWhereByCustomer();
  152. }
  153. $dataCount = db('crm_contacts')
  154. ->alias('contacts')
  155. ->join('__CRM_CUSTOMER__ customer', 'contacts.customer_id = customer.customer_id', 'LEFT')
  156. ->where($map)
  157. ->where($searchMap)
  158. ->where($authMap)
  159. ->where($partMap)
  160. ->where($customerWhere)
  161. ->count('contacts_id');
  162. if ($getCount == 1) {
  163. $data['dataCount'] = $dataCount ?: 0;
  164. return $data;
  165. }
  166. $list = db('crm_contacts')
  167. ->alias('contacts')
  168. ->join('__CRM_CUSTOMER__ customer', 'contacts.customer_id = customer.customer_id', 'LEFT')
  169. ->where($map)
  170. ->where($searchMap)
  171. ->where($partMap)
  172. ->where($authMap)
  173. ->where($customerWhere)
  174. ->limit($request['offset'], $request['length'])
  175. ->field('contacts.*,customer.name as customer_name')
  176. ->orderRaw($order)
  177. ->select();
  178. # 扩展数据
  179. $extraData = [];
  180. $contacts_id_list = !empty($list) ? array_column($list, 'contacts_id') : [];
  181. $extraList = db('crm_contacts_data')->whereIn('contacts_id', $contacts_id_list)->select();
  182. foreach ($extraList as $key => $value) {
  183. $extraData[$value['contacts_id']][$value['field']] = $value['content'];
  184. }
  185. $grantData = getFieldGrantData($user_id);
  186. foreach ($grantData['crm_contacts'] as $key => $value) {
  187. foreach ($value as $ke => $va) {
  188. if($va['maskType']!=0){
  189. $fieldGrant[$ke]['maskType'] = $va['maskType'];
  190. $fieldGrant[$ke]['form_type'] = $va['form_type'];
  191. $fieldGrant[$ke]['field'] = $va['field'];
  192. }
  193. }
  194. }
  195. foreach ($list as $k => $v) {
  196. $list[$k]['create_user_id_info'] = isset($v['create_user_id']) ? $userModel->getUserById($v['create_user_id']) : [];
  197. $list[$k]['owner_user_id_info'] = isset($v['owner_user_id']) ? $userModel->getUserById($v['owner_user_id']) : [];
  198. $list[$k]['customer_id_info']['customer_id'] = $v['customer_id'] ?: '';
  199. $list[$k]['customer_id_info']['name'] = $v['customer_name'] ?: '';
  200. foreach ($userField as $key => $val) {
  201. $usernameField = !empty($v[$val]) ? db('admin_user')->whereIn('id', stringToArray($v[$val]))->column('realname') : [];
  202. $list[$k][$val] = implode($usernameField, ',');
  203. }
  204. foreach ($structureField as $key => $val) {
  205. $structureNameField = !empty($v[$val]) ? db('admin_structure')->whereIn('id', stringToArray($v[$val]))->column('name') : [];
  206. $list[$k][$val] = implode($structureNameField, ',');
  207. }
  208. foreach ($datetimeField as $key => $val) {
  209. $list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null;
  210. }
  211. foreach ($booleanField as $key => $val) {
  212. $list[$k][$val] = !empty($v[$val]) ? (string)$v[$val] : '0';
  213. }
  214. // 处理日期区间类型字段的格式
  215. foreach ($dateIntervalField as $key => $val) {
  216. $list[$k][$val] = !empty($extraData[$v['contacts_id']][$val]) ? json_decode($extraData[$v['contacts_id']][$val], true) : null;
  217. }
  218. // 处理地址类型字段的格式
  219. foreach ($positionField as $key => $val) {
  220. $list[$k][$val] = !empty($extraData[$v['contacts_id']][$val]) ? json_decode($extraData[$v['contacts_id']][$val], true) : null;
  221. }
  222. // 手写签名类型字段
  223. foreach ($handwritingField as $key => $val) {
  224. $handwritingData = !empty($v[$val]) ? db('admin_file')->where('file_id', $v[$val])->value('file_path') : null;
  225. $list[$k][$val] = ['url' => !empty($handwritingData) ? getFullPath($handwritingData) : null];
  226. }
  227. // 定位类型字段
  228. foreach ($locationField AS $key => $val) {
  229. $list[$k][$val] = !empty($extraData[$v['contacts_id']][$val]) ? json_decode($extraData[$v['contacts_id']][$val], true) : null;
  230. }
  231. // 多选框类型字段
  232. foreach ($boxField AS $key => $val) {
  233. $list[$k][$val] = !empty($v[$val]) ? trim($v[$val], ',') : null;
  234. }
  235. // 货币类型字段
  236. foreach ($floatField AS $key => $val) {
  237. $list[$k][$val] = $v[$val]!='0.00' ? (string)$v[$val] : null;
  238. }
  239. //掩码相关类型字段
  240. foreach ($fieldGrant AS $key => $val){
  241. //掩码相关类型字段
  242. if ($val['maskType']!=0 && $val['form_type'] == 'mobile') {
  243. $pattern = "/(1[3458]{1}[0-9])[0-9]{4}([0-9]{4})/i";
  244. $rs = preg_replace($pattern, "$1****$2", $v[$val['field']]);
  245. $list[$k][$val['field']] = !empty($v[$val['field']]) ? (string)$rs : null;
  246. } elseif ($val['maskType']!=0 && $val['form_type'] == 'email') {
  247. $email_array = explode("@", $v[$val['field']]);
  248. $prevfix = (strlen($email_array[0]) < 4) ? "" : substr($v[$val['field']], 0, 2); //邮箱前缀
  249. $str = preg_replace('/([\d\w+_-]{0,100})@/', "***@", $v[$val['field']], -1, $count);
  250. $rs = $prevfix . $str;
  251. $list[$k][$val['field']] = !empty($v[$val['field']]) ?$rs: null;
  252. } elseif ($val['maskType']!=0 && in_array($val['form_type'],['position','floatnumber'])) {
  253. $list[$k][$val['field']] = !empty($v[$val['field']]) ? (string)substr_replace($v[$val['field']], '*****',0,strlen($v[$val['field']])) : null;
  254. }
  255. }
  256. //权限
  257. $permission = [];
  258. $is_read = 0;
  259. $is_update = 0;
  260. $is_delete = 0;
  261. if (in_array($v['owner_user_id'], $readAuthIds)) $is_read = 1;
  262. if (in_array($v['owner_user_id'], $updateAuthIds)) $is_update = 1;
  263. if (in_array($v['owner_user_id'], $deleteAuthIds)) $is_delete = 1;
  264. $permission['is_read'] = $is_read;
  265. $permission['is_update'] = $is_update;
  266. $permission['is_delete'] = $is_delete;
  267. $list[$k]['permission'] = $permission;
  268. # 关注
  269. $starWhere = ['user_id' => $user_id, 'target_id' => $v['contacts_id'], 'type' => 'crm_contacts'];
  270. $star = Db::name('crm_star')->where($starWhere)->value('star_id');
  271. $list[$k]['star'] = !empty($star) ? 1 : 0;
  272. # 日期
  273. $list[$k]['create_time'] = !empty($v['create_time']) ? date('Y-m-d H:i:s', $v['create_time']) : null;
  274. $list[$k]['update_time'] = !empty($v['update_time']) ? date('Y-m-d H:i:s', $v['update_time']) : null;
  275. $list[$k]['last_time'] = !empty($v['last_time']) ? date('Y-m-d H:i:s', $v['last_time']) : null;
  276. # 创建人
  277. $list[$k]['create_user_name'] = !empty($list[$k]['create_user_id_info']['realname']) ? $list[$k]['create_user_id_info']['realname'] : '';
  278. # 负责人
  279. $list[$k]['owner_user_name'] = !empty($list[$k]['owner_user_id_info']['realname']) ? $list[$k]['owner_user_id_info']['realname'] : '';
  280. # 系统字段 负责人部门 zjf 20210726
  281. $list[$k]['owner_user_structure_name'] = $list[$k]['owner_user_id_info']['structure_name'];
  282. }
  283. $data = [];
  284. $data['list'] = $list;
  285. $data['dataCount'] = $dataCount ?: 0;
  286. return $data;
  287. }
  288. /**
  289. * 创建联系人主表信息
  290. * @param
  291. * @return
  292. * @author Michael_xu
  293. */
  294. public function createData($param)
  295. {
  296. unset($param['excel']);
  297. // 联系人扩展表数据
  298. $contactsData = [];
  299. $businessId = $param['business_id'];
  300. unset($param['business_id']);
  301. $fieldModel = new \app\admin\model\Field();
  302. // 数据验证
  303. $validateResult = $this->fieldDataValidate($param, $this->name, $param['create_user_id']);
  304. if (!empty($validateResult)) {
  305. $this->error = $validateResult;
  306. return false;
  307. }
  308. # 处理客户首要联系人
  309. $primaryStatus = Db::name('crm_contacts')->where('customer_id', $param['customer_id'])->value('contacts_id');
  310. if (!empty($param['primary']) && $param['primary'] == 1 && !empty($primaryStatus)) {
  311. # 设置首要联系人,去除其他首要联系人状态
  312. Db::name('crm_contacts')->where('customer_id', $param['customer_id'])->update(['primary' => 0]);
  313. }
  314. if (!empty($param['customer_id']) && empty($primaryStatus)) {
  315. # 为客户添加第一个联系人默认设置成首要联系人
  316. $param['primary'] = 1;
  317. }
  318. // 处理部门、员工、附件、多选类型字段
  319. $arrFieldAtt = $fieldModel->getArrayField('crm_contacts');
  320. foreach ($arrFieldAtt as $k => $v) {
  321. $param[$v] = arrayToString($param[$v]);
  322. }
  323. // 处理日期(date)类型
  324. $dateField = $fieldModel->getFieldByFormType('crm_contacts', 'date');
  325. if (!empty($dateField)) {
  326. foreach ($param as $key => $value) {
  327. if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
  328. }
  329. }
  330. // 处理手写签名类型
  331. $handwritingField = $fieldModel->getFieldByFormType('crm_contacts', 'handwriting_sign');
  332. if (!empty($handwritingField)) {
  333. foreach ($param as $key => $value) {
  334. if (in_array($key, $handwritingField)) {
  335. $param[$key] = !empty($value['file_id']) ? $value['file_id'] : '';
  336. }
  337. }
  338. }
  339. // 处理地址、定位、日期区间、明细表格类型字段
  340. $positionField = $fieldModel->getFieldByFormType($this->name, 'position');
  341. $locationField = $fieldModel->getFieldByFormType($this->name, 'location');
  342. $dateIntervalField = $fieldModel->getFieldByFormType($this->name, 'date_interval');
  343. $detailTableField = $fieldModel->getFieldByFormType($this->name, 'detail_table');
  344. foreach ($param as $key => $value) {
  345. // 处理地址类型字段数据
  346. if (in_array($key, $positionField)) {
  347. if (!empty($value)) {
  348. $contactsData[] = [
  349. 'field' => $key,
  350. 'content' => json_encode($value, JSON_NUMERIC_CHECK),
  351. 'create_time' => time()
  352. ];
  353. $positionNames = array_column($value, 'name');
  354. $param[$key] = implode(',', $positionNames);
  355. } else {
  356. $param[$key] = '';
  357. }
  358. }
  359. // 处理定位类型字段数据
  360. if (in_array($key, $locationField)) {
  361. if (!empty($value)) {
  362. $contactsData[] = [
  363. 'field' => $key,
  364. 'content' => json_encode($value, JSON_NUMERIC_CHECK),
  365. 'create_time' => time()
  366. ];
  367. $param[$key] = $value['address'];
  368. } else {
  369. $param[$key] = '';
  370. }
  371. }
  372. // 处理日期区间类型字段数据
  373. if (in_array($key, $dateIntervalField)) {
  374. if (!empty($value)) {
  375. $contactsData[] = [
  376. 'field' => $key,
  377. 'content' => json_encode($value, JSON_NUMERIC_CHECK),
  378. 'create_time' => time()
  379. ];
  380. $param[$key] = implode('_', $value);
  381. } else {
  382. $param[$key] = '';
  383. }
  384. }
  385. // 处理明细表格类型字段数据
  386. if (in_array($key, $detailTableField)) {
  387. if (!empty($value)) {
  388. $contactsData[] = [
  389. 'field' => $key,
  390. 'content' => json_encode($value, JSON_NUMERIC_CHECK),
  391. 'create_time' => time()
  392. ];
  393. $param[$key] = $key;
  394. } else {
  395. $param[$key] = '';
  396. }
  397. }
  398. }
  399. if ($this->data($param)->allowField(true)->isUpdate(false)->save()) {
  400. updateActionLog($param['create_user_id'], 'crm_contacts', $this->contacts_id, '', '', '创建了联系人');
  401. RecordActionLog($param['create_user_id'], 'crm_contacts', 'save', $param['name'], '', '', '新增了联系人' . $param['name']);
  402. $data = [];
  403. $data['contacts_id'] = $this->contacts_id;
  404. # 添加活动记录
  405. Db::name('crm_activity')->insert([
  406. 'type' => 2,
  407. 'activity_type' => 3,
  408. 'activity_type_id' => $data['contacts_id'],
  409. 'content' => $param['name'],
  410. 'create_user_id' => $param['create_user_id'],
  411. 'update_time' => time(),
  412. 'create_time' => time(),
  413. 'customer_ids' => ',' . $param['customer_id'] . ','
  414. ]);
  415. # 处理商机首要联系人
  416. if (!empty($businessId)) {
  417. Db::name('crm_business')->where('business_id', $businessId)->update(['contacts_id' => $data['contacts_id']]);
  418. }
  419. // 添加联系人扩展数据
  420. array_walk($contactsData, function (&$val) use ($data) {
  421. $val['contacts_id'] = $data['contacts_id'];
  422. });
  423. db('crm_contacts_data')->insertAll($contactsData);
  424. return $data;
  425. } else {
  426. $this->error = '添加失败';
  427. return false;
  428. }
  429. }
  430. //根据IDs获取数组
  431. public function getDataByStr($idstr)
  432. {
  433. $idArr = stringToArray($idstr);
  434. if (!$idArr) {
  435. return [];
  436. }
  437. $list = Db::name('CrmContacts')->where(['contacts_id' => ['in', $idArr]])->select();
  438. return $list;
  439. }
  440. /**
  441. * 编辑联系人主表信息
  442. *
  443. * @param $param
  444. * @param string $contacts_id
  445. * @return array|bool
  446. * @throws \think\Exception
  447. * @throws \think\db\exception\DataNotFoundException
  448. * @throws \think\db\exception\ModelNotFoundException
  449. * @throws \think\exception\DbException
  450. * @throws \think\exception\PDOException
  451. */
  452. public function updateDataById($param, $contacts_id = '')
  453. {
  454. // 联系人扩展表数据
  455. $contactsData = [];
  456. $userModel = new \app\admin\model\User();
  457. $dataInfo = $this->getDataById($contacts_id);
  458. if (!$dataInfo) {
  459. $this->error = '数据不存在或已删除';
  460. return false;
  461. }
  462. //判断权限
  463. $auth_user_ids = $userModel->getUserByPer('crm', 'contacts', 'update');
  464. if (!in_array($dataInfo['owner_user_id'], $auth_user_ids)) {
  465. $this->error = '无权操作';
  466. return false;
  467. }
  468. $param['contacts_id'] = $contacts_id;
  469. //过滤不能修改的字段
  470. $unUpdateField = ['create_user_id', 'is_deleted', 'delete_time'];
  471. foreach ($unUpdateField as $v) {
  472. unset($param[$v]);
  473. }
  474. $fieldModel = new \app\admin\model\Field();
  475. // 数据验证
  476. $validateResult = $this->fieldDataValidate($param, $this->name, $param['user_id'], $param['contacts_id']);
  477. if (!empty($validateResult)) {
  478. $this->error = $validateResult;
  479. return false;
  480. }
  481. // 处理部门、员工、附件、多选类型字段
  482. $arrFieldAtt = $fieldModel->getArrayField('crm_contacts');
  483. foreach ($arrFieldAtt as $k => $v) {
  484. if (isset($param[$v])) $param[$v] = arrayToString($param[$v]);
  485. }
  486. // 处理日期(date)类型
  487. $dateField = $fieldModel->getFieldByFormType('crm_contacts', 'date');
  488. if (!empty($dateField)) {
  489. foreach ($param as $key => $value) {
  490. if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
  491. }
  492. }
  493. // 处理手写签名类型
  494. $handwritingField = $fieldModel->getFieldByFormType('crm_contacts', 'handwriting_sign');
  495. if (!empty($handwritingField)) {
  496. foreach ($param as $key => $value) {
  497. if (in_array($key, $handwritingField)) {
  498. $param[$key] = !empty($value['file_id']) ? $value['file_id'] : '';
  499. }
  500. }
  501. }
  502. // 处理地址、定位、日期区间、明细表格类型字段
  503. $positionField = $fieldModel->getFieldByFormType($this->name, 'position');
  504. $locationField = $fieldModel->getFieldByFormType($this->name, 'location');
  505. $dateIntervalField = $fieldModel->getFieldByFormType($this->name, 'date_interval');
  506. $detailTableField = $fieldModel->getFieldByFormType($this->name, 'detail_table');
  507. foreach ($param as $key => $value) {
  508. // 处理地址类型字段数据
  509. if (in_array($key, $positionField)) {
  510. if (!empty($value)) {
  511. $contactsData[] = [
  512. 'field' => $key,
  513. 'content' => json_encode($value, JSON_NUMERIC_CHECK),
  514. 'create_time' => time()
  515. ];
  516. $positionNames = array_column($value, 'name');
  517. $param[$key] = implode(',', $positionNames);
  518. } else {
  519. $param[$key] = '';
  520. }
  521. }
  522. // 处理定位类型字段数据
  523. if (in_array($key, $locationField)) {
  524. if (!empty($value)) {
  525. $contactsData[] = [
  526. 'field' => $key,
  527. 'content' => json_encode($value, JSON_NUMERIC_CHECK),
  528. 'create_time' => time()
  529. ];
  530. $param[$key] = $value['address'];
  531. } else {
  532. $param[$key] = '';
  533. }
  534. }
  535. // 处理日期区间类型字段数据
  536. if (in_array($key, $dateIntervalField)) {
  537. if (!empty($value)) {
  538. $contactsData[] = [
  539. 'field' => $key,
  540. 'content' => json_encode($value, JSON_NUMERIC_CHECK),
  541. 'create_time' => time()
  542. ];
  543. $param[$key] = implode('_', $value);
  544. } else {
  545. $param[$key] = '';
  546. }
  547. }
  548. // 处理明细表格类型字段数据
  549. if (in_array($key, $detailTableField)) {
  550. if (!empty($value)) {
  551. $contactsData[] = [
  552. 'field' => $key,
  553. 'content' => json_encode($value, JSON_NUMERIC_CHECK),
  554. 'create_time' => time()
  555. ];
  556. $param[$key] = $key;
  557. } else {
  558. $param[$key] = '';
  559. }
  560. }
  561. }
  562. # 处理首要联系人
  563. $primaryStatus = Db::name('crm_contacts')->where('customer_id', $param['customer_id'])->value('contacts_id');
  564. if (!empty($param['primary']) && $param['primary'] == 1 && !empty($primaryStatus)) {
  565. # 设置首要联系人,去除其他首要联系人状态
  566. Db::name('crm_contacts')->where('customer_id', $param['customer_id'])->update(['primary' => 0]);
  567. }
  568. if (!empty($param['customer_id']) && empty($primaryStatus)) {
  569. # 为客户添加第一个联系人默认设置成首要联系人
  570. $param['primary'] = 1;
  571. }
  572. if ($this->update($param, ['contacts_id' => $contacts_id], true)) {
  573. $data['contacts_id'] = $contacts_id;
  574. //修改记录
  575. updateActionLog($param['user_id'], 'crm_contacts', $contacts_id, $dataInfo, $param);
  576. RecordActionLog($param['user_id'], 'crm_contacts', 'update', $dataInfo['name'], $dataInfo, $param);
  577. // 添加联系人扩展数据
  578. db('crm_contacts_data')->where('contacts_id', $contacts_id)->delete();
  579. array_walk($contactsData, function (&$val) use ($contacts_id) {
  580. $val['contacts_id'] = $contacts_id;
  581. });
  582. db('crm_contacts_data')->insertAll($contactsData);
  583. return $data;
  584. } else {
  585. $this->error = '编辑失败';
  586. return false;
  587. }
  588. }
  589. /**
  590. * 联系人数据
  591. *
  592. * @param string $id
  593. * @param int $userId
  594. * @return Common|array|bool|\PDOStatement|string|\think\Model|null
  595. * @throws \think\db\exception\DataNotFoundException
  596. * @throws \think\db\exception\ModelNotFoundException
  597. * @throws \think\exception\DbException
  598. */
  599. public function getDataById($id = '', $userId = 0,$model='')
  600. {
  601. $map['contacts_id'] = $id;
  602. $dataInfo = db('crm_contacts')->where($map)->find();
  603. if (!$dataInfo) {
  604. $this->error = '暂无此数据';
  605. return false;
  606. }
  607. if(empty($model) && $model!='update'){
  608. $grantData = getFieldGrantData($userId);
  609. foreach ($grantData['crm_contacts'] as $key => $value) {
  610. foreach ($value as $ke => $va) {
  611. if($va['maskType']!=0){
  612. $fieldGrant[$ke]['maskType'] = $va['maskType'];
  613. $fieldGrant[$ke]['form_type'] = $va['form_type'];
  614. $fieldGrant[$ke]['field'] = $va['field'];
  615. }
  616. }
  617. }
  618. foreach ($fieldGrant AS $key => $val){
  619. //掩码相关类型字段
  620. if ($val['maskType']!=0 && $val['form_type'] == 'mobile') {
  621. $pattern = "/(1[3458]{1}[0-9])[0-9]{4}([0-9]{4})/i";
  622. $rs = preg_replace($pattern, "$1****$2", $dataInfo[$val['field']]);
  623. $dataInfo[$val['field']] = !empty($dataInfo[$val['field']]) ? (string)$rs : null;
  624. } elseif ($val['maskType']!=0 && $val['form_type'] == 'email') {
  625. $email_array = explode("@", $dataInfo[$val['field']]);
  626. $prevfix = (strlen($email_array[0]) < 4) ? "" : substr($dataInfo[$val['field']], 0, 2); //邮箱前缀
  627. $str = preg_replace('/([\d\w+_-]{0,100})@/', "***@", $dataInfo[$val['field']], -1, $count);
  628. $rs = $prevfix . $str;
  629. $dataInfo[$val['field']] = !empty($dataInfo[$val['field']]) ?$rs: null;
  630. } elseif ($val['maskType']!=0 && in_array($val['form_type'],['position','floatnumber'])) {
  631. $dataInfo[$val['field']] = !empty($dataInfo[$val['field']]) ? (string)substr_replace($dataInfo[$val['field']], '*****',0,strlen($dataInfo[$val['field']])) : null;
  632. }
  633. }
  634. }
  635. $userModel = new \app\admin\model\User();
  636. $dataInfo['create_user_id_info'] = isset($dataInfo['create_user_id']) ? $userModel->getUserById($dataInfo['create_user_id']) : [];
  637. $dataInfo['owner_user_id_info'] = isset($dataInfo['owner_user_id']) ? $userModel->getUserById($dataInfo['owner_user_id']) : [];
  638. $dataInfo['customer_id_info'] = db('crm_customer')->where(['customer_id' => $dataInfo['customer_id']])->field('customer_id,name,mobile,telephone,deal_status')->find();
  639. $dataInfo['customer_name'] = !empty($dataInfo['customer_id_info']['name']) ? $dataInfo['customer_id_info']['name'] : '';
  640. $dataInfo['create_user_name'] = !empty($dataInfo['create_user_id_info']['realname']) ? $dataInfo['create_user_id_info']['realname'] : '';
  641. $dataInfo['owner_user_name'] = !empty($dataInfo['owner_user_id_info']['realname']) ? $dataInfo['owner_user_id_info']['realname'] : '';
  642. # 关注
  643. $starId = empty($userId) ? 0 : Db::name('crm_star')->where(['user_id' => $userId, 'target_id' => $id, 'type' => 'crm_contacts'])->value('star_id');
  644. $dataInfo['star'] = !empty($starId) ? 1 : 0;
  645. # 处理决策人显示问题
  646. $dataInfo['decision'] = !empty($dataInfo['decision']) && $dataInfo['decision'] == '是' ? '是' : '否';
  647. # 处理时间格式
  648. $fieldModel = new \app\admin\model\Field();
  649. $datetimeField = $fieldModel->getFieldByFormType('crm_contacts', 'datetime'); //日期时间类型
  650. foreach ($datetimeField as $key => $val) {
  651. $dataInfo[$val] = !empty($dataInfo[$val]) ? date('Y-m-d H:i:s', $dataInfo[$val]) : null;
  652. }
  653. $dataInfo['create_time'] = !empty($dataInfo['create_time']) ? date('Y-m-d H:i:s', $dataInfo['create_time']) : null;
  654. $dataInfo['update_time'] = !empty($dataInfo['update_time']) ? date('Y-m-d H:i:s', $dataInfo['update_time']) : null;
  655. $dataInfo['last_time'] = !empty($dataInfo['last_time']) ? date('Y-m-d H:i:s', $dataInfo['last_time']) : null;
  656. // 字段授权
  657. if (!empty($userId)) {
  658. $grantData = getFieldGrantData($userId);
  659. $userLevel = isSuperAdministrators($userId);
  660. foreach ($dataInfo as $key => $value) {
  661. if (!$userLevel && !empty($grantData['crm_contacts'])) {
  662. $status = getFieldGrantStatus($key, $grantData['crm_contacts']);
  663. # 查看权限
  664. if ($status['read'] == 0) unset($dataInfo[$key]);
  665. }
  666. }
  667. }
  668. return $dataInfo;
  669. }
  670. /**
  671. * [联系人转移]
  672. * @param ids 联系人ID数组
  673. * @param owner_user_id 变更负责人
  674. * @param is_remove 1移出,2转为团队成员
  675. * @return
  676. * @author Michael_xu
  677. */
  678. public function transferDataById($ids, $owner_user_id, $type = 1, $is_remove)
  679. {
  680. $settingModel = new \app\crm\model\Setting();
  681. foreach ($ids as $id) {
  682. $data = [];
  683. $data['owner_user_id'] = $owner_user_id;
  684. $data['update_time'] = time();
  685. db('crm_contacts')->where(['contacts_id' => $id])->update($data);
  686. }
  687. return true;
  688. }
  689. /**
  690. * 设置首要联系人
  691. *
  692. * @param $customerId
  693. * @param $contactsId
  694. * @return bool
  695. * @throws \think\Exception
  696. * @throws \think\exception\PDOException
  697. */
  698. public function setPrimary($customerId, $contactsId)
  699. {
  700. Db::name('crm_contacts')->where('customer_id', $customerId)->update(['primary' => 0]);
  701. Db::name('crm_contacts')->where(['customer_id' => $customerId, 'contacts_id' => $contactsId])->update(['primary' => 1]);
  702. return true;
  703. }
  704. /**
  705. * 获取跟进记录联系人
  706. *
  707. * @param $customerId
  708. * @return bool|\PDOStatement|string|\think\Collection
  709. * @throws \think\db\exception\DataNotFoundException
  710. * @throws \think\db\exception\ModelNotFoundException
  711. * @throws \think\exception\DbException
  712. */
  713. public function getContactsList($customerId)
  714. {
  715. return Db::name('crm_contacts')->field(['contacts_id', 'name', 'mobile', 'telephone', 'detail_address'])->where('customer_id', $customerId)->order('primary', 'desc')->select();
  716. }
  717. /**
  718. * 获取系统信息
  719. *
  720. * @param $id
  721. * @return array
  722. * @throws \think\db\exception\DataNotFoundException
  723. * @throws \think\db\exception\ModelNotFoundException
  724. * @throws \think\exception\DbException
  725. */
  726. public function getSystemInfo($id)
  727. {
  728. # 联系人
  729. $contacts = Db::name('crm_contacts')->field(['create_user_id','owner_user_id' , 'create_time', 'update_time', 'last_time'])->where('contacts_id', $id)->find();
  730. # 创建人
  731. $realname = Db::name('admin_user')->where('id', $contacts['create_user_id'])->value('realname');
  732. # zjf 20210726
  733. $userModel = new \app\admin\model\User();
  734. $ownerUserInfo = $userModel->getUserById($contacts['owner_user_id']);
  735. # 负责人部门
  736. $ownerStructureName = $ownerUserInfo['structure_name'];
  737. # 负责人
  738. $ownerUserName = $ownerUserInfo['realname'];
  739. return [
  740. 'create_user_id' => $realname,
  741. 'owner_user_id' => $ownerUserName,
  742. 'create_time' => date('Y-m-d H:i:s', $contacts['create_time']),
  743. 'update_time' => date('Y-m-d H:i:s', $contacts['update_time']),
  744. 'last_time' => !empty($contacts['last_time']) ? date('Y-m-d H:i:s', $contacts['last_time']) : '',
  745. 'owner_user_structure_name' => $ownerStructureName
  746. ];
  747. }
  748. }