Contacts.php 36KB

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