123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  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. # 处理人员和部门类型的排序报错问题(前端传来的是包含_name的别名字段)
  109. $temporaryField = str_replace('_name', '', $order_field);
  110. if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) {
  111. $order_field = $temporaryField;
  112. }
  113. //排序
  114. if ($order_type && $order_field) {
  115. $order = $fieldModel->getOrderByFormtype('crm_leads', 'leads', $order_field, $order_type);
  116. } else {
  117. $order = 'leads.update_time desc';
  118. }
  119. //过滤已转化线索
  120. if (!$map['leads.is_transform']) {
  121. $map['leads.is_transform'] = array('neq', 1);
  122. }
  123. // 待办事项下需联系线索(逾期)
  124. $overdueWhere = '';
  125. if (!empty($overdue)) {
  126. $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()."))";
  127. }
  128. $readAuthIds = $userModel->getUserByPer('crm', 'leads', 'read');
  129. $updateAuthIds = $userModel->getUserByPer('crm', 'leads', 'update');
  130. $deleteAuthIds = $userModel->getUserByPer('crm', 'leads', 'delete');
  131. $dataCount = db('crm_leads')->alias('leads')->where($map)->where($searchMap)->where($authMap)->where($overdueWhere)->count('leads_id');
  132. if (!empty($getCount) && $getCount == 1) {
  133. $data['dataCount'] = !empty($dataCount) ? $dataCount : 0;
  134. return $data;
  135. }
  136. $list = db('crm_leads')
  137. ->alias('leads')
  138. ->where($map)
  139. ->where($searchMap)
  140. ->where($authMap)
  141. ->where($overdueWhere)
  142. ->limit($request['offset'], $request['length'])
  143. ->field(implode(',', $indexField))
  144. ->orderRaw($order)
  145. ->select();
  146. // echo db('crm_leads')->getLastSql();exit;
  147. # 扩展数据
  148. $extraData = [];
  149. $leads_id_list = !empty($list) ? array_column($list, 'leads_id') : [];
  150. $extraList = db('crm_leads_data')->whereIn('leads_id', $leads_id_list)->select();
  151. foreach ($extraList AS $key => $value) {
  152. $extraData[$value['leads_id']][$value['field']] = $value['content'];
  153. }
  154. foreach ($list as $k => $v) {
  155. $list[$k]['create_user_id_info'] = isset($v['create_user_id']) ? $userModel->getUserById($v['create_user_id']) : [];
  156. $list[$k]['owner_user_id_info'] = isset($v['owner_user_id']) ? $userModel->getUserById($v['owner_user_id']) : [];
  157. $list[$k]['create_user_name'] = !empty($list[$k]['create_user_id_info']['realname']) ? $list[$k]['create_user_id_info']['realname'] : '';
  158. $list[$k]['owner_user_name'] = !empty($list[$k]['owner_user_id_info']['realname']) ? $list[$k]['owner_user_id_info']['realname'] : '';
  159. foreach ($userField as $key => $val) {
  160. $usernameField = !empty($v[$val]) ? db('admin_user')->whereIn('id', stringToArray($v[$val]))->column('realname') : [];
  161. $list[$k][$val] = implode($usernameField, ',');
  162. }
  163. foreach ($structureField as $key => $val) {
  164. $structureNameField = !empty($v[$val]) ? db('admin_structure')->whereIn('id', stringToArray($v[$val]))->column('name') : [];
  165. $list[$k][$val] = implode($structureNameField, ',');
  166. }
  167. foreach ($datetimeField as $key => $val) {
  168. $list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null;
  169. }
  170. foreach ($booleanField as $key => $val) {
  171. $list[$k][$val] = !empty($v[$val]) ? (string)$v[$val] : '0';
  172. }
  173. // 处理日期区间类型字段的格式
  174. foreach ($dateIntervalField AS $key => $val) {
  175. $list[$k][$val] = !empty($extraData[$v['leads_id']][$val]) ? json_decode($extraData[$v['leads_id']][$val], true) : null;
  176. }
  177. // 处理地址类型字段的格式
  178. foreach ($positionField AS $key => $val) {
  179. $list[$k][$val] = !empty($extraData[$v['leads_id']][$val]) ? json_decode($extraData[$v['leads_id']][$val], true) : null;
  180. }
  181. // 手写签名类型字段
  182. foreach ($handwritingField AS $key => $val) {
  183. $handwritingData = !empty($v[$val]) ? db('admin_file')->where('file_id', $v[$val])->value('file_path') : null;
  184. $list[$k][$val] = ['url' => !empty($handwritingData) ? getFullPath($handwritingData) : null];
  185. }
  186. // 定位类型字段
  187. foreach ($locationField AS $key => $val) {
  188. $list[$k][$val] = !empty($extraData[$v['leads_id']][$val]) ? json_decode($extraData[$v['leads_id']][$val], true) : null;
  189. }
  190. //权限
  191. $permission = [];
  192. $is_read = 0;
  193. $is_update = 0;
  194. $is_delete = 0;
  195. if (in_array($v['owner_user_id'], $readAuthIds)) $is_read = 1;
  196. if (in_array($v['owner_user_id'], $updateAuthIds)) $is_update = 1;
  197. if (in_array($v['owner_user_id'], $deleteAuthIds)) $is_delete = 1;
  198. $permission['is_read'] = $is_read;
  199. $permission['is_update'] = $is_update;
  200. $permission['is_delete'] = $is_delete;
  201. $list[$k]['permission'] = $permission;
  202. # 关注
  203. $starWhere = ['user_id' => $user_id, 'target_id' => $v['leads_id'], 'type' => 'crm_leads'];
  204. $star = Db::name('crm_star')->where($starWhere)->value('star_id');
  205. $list[$k]['star'] = !empty($star) ? 1 : 0;
  206. # 日期
  207. $list[$k]['create_time'] = !empty($v['create_time']) ? date('Y-m-d H:i:s', $v['create_time']) : null;
  208. $list[$k]['update_time'] = !empty($v['update_time']) ? date('Y-m-d H:i:s', $v['update_time']) : null;
  209. $list[$k]['last_time'] = !empty($v['last_time']) ? date('Y-m-d H:i:s', $v['last_time']) : null;
  210. }
  211. $data = [];
  212. $data['list'] = $list;
  213. $data['dataCount'] = $dataCount ?: 0;
  214. return $data;
  215. }
  216. //根据IDs获取数组
  217. public function getDataByStr($idstr)
  218. {
  219. $idArr = stringToArray($idstr);
  220. if (!$idArr) {
  221. return [];
  222. }
  223. $list = Db::name('CrmLeads')->where(['leads_id' => ['in', $idArr]])->select();
  224. return $list;
  225. }
  226. /**
  227. * 创建线索主表信息
  228. * @param
  229. * @return
  230. * @author Michael_xu
  231. */
  232. public function createData($param)
  233. {
  234. unset($param['excel']);
  235. // 线索扩展表数据
  236. $leadsData = [];
  237. $fieldModel = new \app\admin\model\Field();
  238. // // 自动验证
  239. // $validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
  240. // $validate = new Validate($validateArr['rule'], $validateArr['message']);
  241. // $result = $validate->check($param);
  242. // if (!$result) {
  243. // $this->error = $validate->getError();
  244. // return false;
  245. // }
  246. // 数据验证
  247. $validateResult = $this->fieldDataValidate($param, $this->name, $param['create_user_id']);
  248. if (!empty($validateResult)) {
  249. $this->error = $validateResult;
  250. return false;
  251. }
  252. // 处理部门、员工、附件、多选类型字段
  253. $arrFieldAtt = $fieldModel->getArrayField('crm_leads');
  254. foreach ($arrFieldAtt as $k => $v) {
  255. $param[$v] = arrayToString($param[$v]);
  256. }
  257. // 处理日期(date)类型
  258. $dateField = $fieldModel->getFieldByFormType('crm_leads', 'date');
  259. if (!empty($dateField)) {
  260. foreach ($param AS $key => $value) {
  261. if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
  262. }
  263. }
  264. // 处理手写签名类型
  265. $handwritingField = $fieldModel->getFieldByFormType('crm_leads', 'handwriting_sign');
  266. if (!empty($handwritingField)) {
  267. foreach ($param AS $key => $value) {
  268. if (in_array($key, $handwritingField)) {
  269. $param[$key] = !empty($value['file_id']) ? $value['file_id'] : '';
  270. }
  271. }
  272. }
  273. // 处理地址、定位、日期区间、明细表格类型字段
  274. $positionField = $fieldModel->getFieldByFormType($this->name, 'position');
  275. $locationField = $fieldModel->getFieldByFormType($this->name, 'location');
  276. $dateIntervalField = $fieldModel->getFieldByFormType($this->name, 'date_interval');
  277. $detailTableField = $fieldModel->getFieldByFormType($this->name, 'detail_table');
  278. foreach ($param AS $key => $value) {
  279. // 处理地址类型字段数据
  280. if (in_array($key, $positionField)) {
  281. if (!empty($value)) {
  282. $leadsData[] = [
  283. 'field' => $key,
  284. 'content' => json_encode($value, JSON_NUMERIC_CHECK),
  285. 'create_time' => time()
  286. ];
  287. $positionNames = array_column($value, 'name');
  288. $param[$key] = implode(',', $positionNames);
  289. } else {
  290. $param[$key] = '';
  291. }
  292. }
  293. // 处理定位类型字段数据
  294. if (in_array($key, $locationField)) {
  295. if (!empty($value)) {
  296. $leadsData[] = [
  297. 'field' => $key,
  298. 'content' => json_encode($value, JSON_NUMERIC_CHECK),
  299. 'create_time' => time()
  300. ];
  301. $param[$key] = $value['address'];
  302. } else {
  303. $param[$key] = '';
  304. }
  305. }
  306. // 处理日期区间类型字段数据
  307. if (in_array($key, $dateIntervalField)) {
  308. if (!empty($value)) {
  309. $leadsData[] = [
  310. 'field' => $key,
  311. 'content' => json_encode($value, JSON_NUMERIC_CHECK),
  312. 'create_time' => time()
  313. ];
  314. $param[$key] = implode('_', $value);
  315. } else {
  316. $param[$key] = '';
  317. }
  318. }
  319. // 处理明细表格类型字段数据
  320. if (in_array($key, $detailTableField)) {
  321. if (!empty($value)) {
  322. $leadsData[] = [
  323. 'field' => $key,
  324. 'content' => json_encode($value, JSON_NUMERIC_CHECK),
  325. 'create_time' => time()
  326. ];
  327. $param[$key] = $key;
  328. } else {
  329. $param[$key] = '';
  330. }
  331. }
  332. }
  333. # 设置今日需联系线索
  334. if (!empty($param['next_time']) && $param['next_time'] >= strtotime(date('Y-m-d 00:00:00'))) $param['is_dealt'] = 0;
  335. if ($this->data($param)->allowField(true)->isUpdate(false)->save()) {
  336. $data['leads_id'] = $this->leads_id;
  337. //修改记录
  338. updateActionLog($param['create_user_id'], 'crm_leads', $this->leads_id, '', '', '创建了线索');
  339. RecordActionLog($param['create_user_id'],'crm_leads','save',$param['name'],'','','新增了线索'.$param['name']);
  340. # 添加活动记录
  341. Db::name('crm_activity')->insert([
  342. 'type' => 2,
  343. 'activity_type' => 1,
  344. 'activity_type_id' => $this->leads_id,
  345. 'content' => $param['name'],
  346. 'create_user_id' => $param['create_user_id'],
  347. 'update_time' => time(),
  348. 'create_time' => time(),
  349. 'customer_ids' => null,
  350. 'contacts_ids' => null,
  351. 'business_ids' => null
  352. ]);
  353. // 添加线索扩展数据
  354. array_walk($leadsData, function (&$val) use ($data) {
  355. $val['leads_id'] = $data['leads_id'];
  356. });
  357. db('crm_leads_data')->insertAll($leadsData);
  358. return $data;
  359. } else {
  360. $this->error = '添加失败';
  361. return false;
  362. }
  363. }
  364. /**
  365. * 编辑线索信息
  366. * @param
  367. * @return
  368. * @author Michael_xu
  369. */
  370. public function updateDataById($param, $leads_id = '')
  371. {
  372. // 线索扩展表数据
  373. $leadsData = [];
  374. $userModel = new \app\admin\model\User();
  375. $dataInfo = $this->getDataById($leads_id);
  376. if (!$dataInfo) {
  377. $this->error = '数据不存在或已删除';
  378. return false;
  379. }
  380. //判断权限
  381. $auth_user_ids = $userModel->getUserByPer('crm', 'leads', 'update');
  382. if (!in_array($dataInfo['owner_user_id'], $auth_user_ids)) {
  383. $this->error = '无权操作';
  384. return false;
  385. }
  386. $param['leads_id'] = $leads_id;
  387. //过滤不能修改的字段
  388. $unUpdateField = ['create_user_id', 'is_deleted', 'delete_time'];
  389. foreach ($unUpdateField as $v) {
  390. unset($param[$v]);
  391. }
  392. $fieldModel = new \app\admin\model\Field();
  393. // 自动验证
  394. // $validateArr = $fieldModel->validateField($this->name, 0, 'update'); //获取自定义字段验证规则
  395. // $validate = new Validate($validateArr['rule'], $validateArr['message']);
  396. // $result = $validate->check($param);
  397. // if (!$result) {
  398. // $this->error = $validate->getError();
  399. // return false;
  400. // }
  401. // 数据验证
  402. $validateResult = $this->fieldDataValidate($param, $this->name, $param['user_id'], $leads_id);
  403. if (!empty($validateResult)) {
  404. $this->error = $validateResult;
  405. return false;
  406. }
  407. // 处理部门、员工、附件、多选类型字段
  408. $arrFieldAtt = $fieldModel->getArrayField('crm_leads');
  409. foreach ($arrFieldAtt as $k => $v) {
  410. if (isset($param[$v])) $param[$v] = arrayToString($param[$v]);
  411. }
  412. // 处理日期(date)类型
  413. $dateField = $fieldModel->getFieldByFormType('crm_leads', 'date');
  414. if (!empty($dateField)) {
  415. foreach ($param AS $key => $value) {
  416. if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
  417. }
  418. }
  419. // 处理手写签名类型
  420. $handwritingField = $fieldModel->getFieldByFormType('crm_leads', 'handwriting_sign');
  421. if (!empty($handwritingField)) {
  422. foreach ($param AS $key => $value) {
  423. if (in_array($key, $handwritingField)) {
  424. $param[$key] = !empty($value['file_id']) ? $value['file_id'] : '';
  425. }
  426. }
  427. }
  428. // 处理地址、定位、日期区间、明细表格类型字段
  429. $positionField = $fieldModel->getFieldByFormType($this->name, 'position');
  430. $locationField = $fieldModel->getFieldByFormType($this->name, 'location');
  431. $dateIntervalField = $fieldModel->getFieldByFormType($this->name, 'date_interval');
  432. $detailTableField = $fieldModel->getFieldByFormType($this->name, 'detail_table');
  433. foreach ($param AS $key => $value) {
  434. // 处理地址类型字段数据
  435. if (in_array($key, $positionField)) {
  436. if (!empty($value)) {
  437. $leadsData[] = [
  438. 'field' => $key,
  439. 'content' => json_encode($value, JSON_NUMERIC_CHECK),
  440. 'create_time' => time()
  441. ];
  442. $positionNames = array_column($value, 'name');
  443. $param[$key] = implode(',', $positionNames);
  444. } else {
  445. $param[$key] = '';
  446. }
  447. }
  448. // 处理定位类型字段数据
  449. if (in_array($key, $locationField)) {
  450. if (!empty($value)) {
  451. $leadsData[] = [
  452. 'field' => $key,
  453. 'content' => json_encode($value, JSON_NUMERIC_CHECK),
  454. 'create_time' => time()
  455. ];
  456. $param[$key] = $value['address'];
  457. } else {
  458. $param[$key] = '';
  459. }
  460. }
  461. // 处理日期区间类型字段数据
  462. if (in_array($key, $dateIntervalField)) {
  463. if (!empty($value)) {
  464. $leadsData[] = [
  465. 'field' => $key,
  466. 'content' => json_encode($value, JSON_NUMERIC_CHECK),
  467. 'create_time' => time()
  468. ];
  469. $param[$key] = implode('_', $value);
  470. } else {
  471. $param[$key] = '';
  472. }
  473. }
  474. // 处理明细表格类型字段数据
  475. if (in_array($key, $detailTableField)) {
  476. if (!empty($value)) {
  477. $leadsData[] = [
  478. 'field' => $key,
  479. 'content' => json_encode($value, JSON_NUMERIC_CHECK),
  480. 'create_time' => time()
  481. ];
  482. $param[$key] = $key;
  483. } else {
  484. $param[$key] = '';
  485. }
  486. }
  487. }
  488. # 设置今日需联系线索
  489. if (!empty($param['next_time']) && $param['next_time'] >= strtotime(date('Y-m-d 00:00:00'))) $param['is_dealt'] = 0;
  490. if ($this->update($param, ['leads_id' => $leads_id], true)) {
  491. $data['leads_id'] = $leads_id;
  492. //修改记录
  493. updateActionLog($param['user_id'], 'crm_leads', $leads_id, $dataInfo, $param);
  494. RecordActionLog($param['user_id'], 'crm_leads','update', $dataInfo['name'], $dataInfo, $param);
  495. // 添加线索扩展数据
  496. db('crm_leads_data')->where('leads_id', $leads_id)->delete();
  497. array_walk($leadsData, function (&$val) use ($leads_id) {
  498. $val['leads_id'] = $leads_id;
  499. });
  500. db('crm_leads_data')->insertAll($leadsData);
  501. return $data;
  502. } else {
  503. $this->error = '编辑失败';
  504. return false;
  505. }
  506. }
  507. /**
  508. * 线索数据
  509. *
  510. * @param string $id
  511. * @return Common|array|bool|\PDOStatement|string|\think\Model|null
  512. * @throws \think\db\exception\DataNotFoundException
  513. * @throws \think\db\exception\ModelNotFoundException
  514. * @throws \think\exception\DbException
  515. */
  516. public function getDataById($id = '', $userId = 0)
  517. {
  518. $map['leads_id'] = $id;
  519. $dataInfo = db('crm_leads')->where($map)->find();
  520. if (!$dataInfo) {
  521. $this->error = '暂无此数据';
  522. return false;
  523. }
  524. $userModel = new \app\admin\model\User();
  525. $dataInfo['create_user_id_info'] = isset($dataInfo['create_user_id']) ? $userModel->getUserById($dataInfo['create_user_id']) : [];
  526. $dataInfo['owner_user_id_info'] = isset($dataInfo['owner_user_id']) ? $userModel->getUserById($dataInfo['owner_user_id']) : [];
  527. $dataInfo['create_user_name'] = !empty($dataInfo['create_user_id_info']['realname']) ? $dataInfo['create_user_id_info']['realname'] : '';
  528. $dataInfo['owner_user_name'] = !empty($dataInfo['owner_user_id_info']['realname']) ? $dataInfo['owner_user_id_info']['realname'] : '';
  529. # 关注
  530. $starId = empty($userId) ? 0 : Db::name('crm_star')->where(['user_id' => $userId, 'target_id' => $id, 'type' => 'crm_leads'])->value('star_id');
  531. $dataInfo['star'] = !empty($starId) ? 1 : 0;
  532. # 处理时间格式处理
  533. $fieldModel = new \app\admin\model\Field();
  534. $datetimeField = $fieldModel->getFieldByFormType('crm_leads', 'datetime'); //日期时间类型
  535. foreach ($datetimeField as $key => $val) {
  536. $dataInfo[$val] = !empty($dataInfo[$val]) ? date('Y-m-d H:i:s', $dataInfo[$val]) : null;
  537. }
  538. $dataInfo['create_time'] = !empty($dataInfo['create_time']) ? date('Y-m-d H:i:s', $dataInfo['create_time']) : null;
  539. $dataInfo['update_time'] = !empty($dataInfo['update_time']) ? date('Y-m-d H:i:s', $dataInfo['update_time']) : null;
  540. $dataInfo['last_time'] = !empty($dataInfo['last_time']) ? date('Y-m-d H:i:s', $dataInfo['last_time']) : null;
  541. // 字段授权
  542. if (!empty($userId)) {
  543. $grantData = getFieldGrantData($userId);
  544. $userLevel = isSuperAdministrators($userId);
  545. foreach ($dataInfo AS $key => $value) {
  546. if (!$userLevel && !empty($grantData['crm_leads'])) {
  547. $status = getFieldGrantStatus($key, $grantData['crm_leads']);
  548. # 查看权限
  549. if ($status['read'] == 0) unset($dataInfo[$key]);
  550. }
  551. }
  552. }
  553. return $dataInfo;
  554. }
  555. /**
  556. * 获取系统信息
  557. *
  558. * @param $id
  559. * @return array
  560. * @throws \think\db\exception\DataNotFoundException
  561. * @throws \think\db\exception\ModelNotFoundException
  562. * @throws \think\exception\DbException
  563. */
  564. public
  565. function getSystemInfo($id)
  566. {
  567. # 线索
  568. $leads = Db::name('crm_leads')->field(['create_user_id', 'create_time', 'update_time', 'last_time'])->where('leads_id', $id)->find();
  569. # 创建人
  570. $realname = Db::name('admin_user')->where('id', $leads['create_user_id'])->value('realname');
  571. return [
  572. 'create_user_id' => $realname,
  573. 'create_time' => date('Y-m-d H:i:s', $leads['create_time']),
  574. 'update_time' => date('Y-m-d H:i:s', $leads['update_time']),
  575. 'last_time' => !empty($leads['last_time']) ? date('Y-m-d H:i:s', $leads['last_time']) : ''
  576. ];
  577. }
  578. }