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