Customer.php 48KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | Description: 客户
  4. // +----------------------------------------------------------------------
  5. // | Author: Michael_xu | gengxiaoxu@5kcrm.com
  6. // +----------------------------------------------------------------------
  7. namespace app\crm\model;
  8. use app\admin\controller\ApiCommon;
  9. use think\Db;
  10. use app\admin\model\Common;
  11. use app\admin\model\User as UserModel;
  12. use app\admin\model\Record as RecordModel;
  13. use think\Request;
  14. use think\Validate;
  15. class Customer extends Common
  16. {
  17. /**
  18. * 为了数据库的整洁,同时又不影响Model和Controller的名称
  19. * 我们约定每个模块的数据表都加上相同的前缀,比如CRM模块用crm作为数据表前缀
  20. */
  21. protected $name = 'crm_customer';
  22. protected $createTime = 'create_time';
  23. protected $updateTime = 'update_time';
  24. protected $autoWriteTimestamp = true;
  25. protected $type = [
  26. // 'next_time' => 'timestamp',
  27. ];
  28. public static $address = [
  29. '北京', '上海', '天津', '广东', '浙江', '海南', '福建', '湖南',
  30. '湖北', '重庆', '辽宁', '吉林', '黑龙江', '河北', '河南', '山东',
  31. '陕西', '甘肃', '青海', '新疆', '山西', '四川', '贵州', '安徽',
  32. '江西', '江苏', '云南', '内蒙古', '广西', '西藏', '宁夏'
  33. ];
  34. /**
  35. * [getDataList 客户list]
  36. * @author Michael_xu
  37. * @param [string] $map [查询条件]
  38. * @param [number] $page [当前页数]
  39. * @param [number] $limit [每页数量]
  40. * @return [array] [description]
  41. */
  42. public function getDataList($request)
  43. {
  44. $userModel = new \app\admin\model\User();
  45. $structureModel = new \app\admin\model\Structure();
  46. $fieldModel = new \app\admin\model\Field();
  47. $search = $request['search'];
  48. $user_id = $request['user_id'];
  49. $scene_id = (int)$request['scene_id'];
  50. $is_excel = $request['is_excel']; //导出
  51. $action = $request['action'];
  52. $order_field = $request['order_field'];
  53. $order_type = $request['order_type'];
  54. $is_remind = $request['is_remind'];
  55. $getCount = $request['getCount'];
  56. $otherMap = $request['otherMap'];
  57. //需要过滤的参数
  58. $unsetRequest = ['scene_id','search','user_id','is_excel','action','order_field','order_type','is_remind','getCount','type','otherMap'];
  59. foreach ($unsetRequest as $v) {
  60. unset($request[$v]);
  61. }
  62. $request = $this->fmtRequest( $request );
  63. $requestMap = $request['map'] ? : [];
  64. $sceneModel = new \app\admin\model\Scene();
  65. # getCount是代办事项传来的参数,代办事项不需要使用场景
  66. $sceneMap = [];
  67. if (empty($getCount)) {
  68. if ($scene_id) {
  69. //自定义场景
  70. $sceneMap = $sceneModel->getDataById($scene_id, $user_id, 'customer') ? : [];
  71. } else {
  72. //默认场景
  73. $sceneMap = $sceneModel->getDefaultData('crm_customer', $user_id) ? : [];
  74. }
  75. }
  76. $searchMap = [];
  77. if ($search) {
  78. //普通筛选
  79. $searchMap = function($query) use ($search){
  80. $query->where('customer.name',array('like','%'.$search.'%'))
  81. ->whereOr('customer.mobile',array('like','%'.$search.'%'))
  82. ->whereOr('customer.telephone',array('like','%'.$search.'%'));
  83. };
  84. }
  85. $partMap = [];
  86. //优先级:普通筛选>高级筛选>场景
  87. if (is_array($sceneMap)) {
  88. if ($sceneMap['ro_user_id'] && $sceneMap['rw_user_id']) {
  89. //相关团队查询
  90. $map = $requestMap;
  91. $partMap = function($query) use ($sceneMap){
  92. $query->where('FIND_IN_SET('.$sceneMap['ro_user_id'].', customer.ro_user_id)')
  93. ->whereOr('FIND_IN_SET('.$sceneMap['rw_user_id'].', customer.rw_user_id)');
  94. };
  95. } else {
  96. $map = $requestMap ? array_merge($sceneMap, $requestMap) : $sceneMap;
  97. }
  98. }
  99. //高级筛选
  100. $map = where_arr($map, 'crm', 'customer', 'index');
  101. //公海
  102. $customerMap = [];
  103. $authMap = [];
  104. $poolMap = [];
  105. $requestData = $this->requestData();
  106. if ($requestData['a'] == 'pool' || $action == 'pool') {
  107. //客户公海条件(没有负责人或已经到期)
  108. $poolMap = is_object($sceneMap) ? $sceneMap : $this->getWhereByPool();
  109. } else {
  110. $customerMap = ($is_remind == 1) ? $this->getWhereByRemind() : $this->getWhereByCustomer(); //默认条件
  111. //工作台仪表盘
  112. if ($requestData['a'] == 'indexlist' && $requestData['c'] == 'index') {
  113. $customerMap =$this->getWhereByCustomer();
  114. }
  115. if (!$partMap) {
  116. //权限
  117. $a = 'index';
  118. if ($is_excel) $a = 'excelExport';
  119. $auth_user_ids = $userModel->getUserByPer('crm', 'customer', $a);
  120. //过滤权限
  121. if (isset($map['customer.owner_user_id']) && $map['customer.owner_user_id'][0] != 'like') {
  122. if (!is_array($map['customer.owner_user_id'][1])) {
  123. $map['customer.owner_user_id'][1] = [$map['customer.owner_user_id'][1]];
  124. }
  125. if (in_array($map['customer.owner_user_id'][0], ['neq', 'notin'])) {
  126. $auth_user_ids = array_diff($auth_user_ids, $map['customer.owner_user_id'][1]) ? : []; //取差集
  127. } else {
  128. $auth_user_ids = array_intersect($map['customer.owner_user_id'][1], $auth_user_ids) ? : []; //取交集
  129. }
  130. unset($map['customer.owner_user_id']);
  131. $auth_user_ids = array_merge(array_unique(array_filter($auth_user_ids))) ? : ['-1'];
  132. //负责人、相关团队
  133. $authMap['customer.owner_user_id'] = array('in',$auth_user_ids);
  134. } else {
  135. $authMapData = [];
  136. $authMapData['auth_user_ids'] = $auth_user_ids;
  137. $authMapData['user_id'] = $user_id;
  138. $authMap = function($query) use ($authMapData){
  139. $query->where(['customer.owner_user_id' => array('in',$authMapData['auth_user_ids'])])
  140. ->whereOr(function ($query) use ($authMapData) {
  141. $query->where('FIND_IN_SET("'.$authMapData['user_id'].'", customer.ro_user_id)')->where(['customer.owner_user_id' => array('neq','')]);
  142. })
  143. ->whereOr(function ($query) use ($authMapData) {
  144. $query->where('FIND_IN_SET("'.$authMapData['user_id'].'", customer.rw_user_id)')->where(['customer.owner_user_id' => array('neq','')]);
  145. });
  146. };
  147. }
  148. }
  149. }
  150. $dataCount = db('crm_customer')->alias('customer')
  151. ->where($map)
  152. ->where($searchMap)
  153. ->where($customerMap)
  154. ->where($authMap)
  155. ->where($partMap)
  156. ->where($poolMap)
  157. ->where($otherMap)
  158. ->count();
  159. if ($getCount == 1) {
  160. $data['dataCount'] = $dataCount ? : 0;
  161. return $data;
  162. }
  163. //列表展示字段
  164. $indexField = $fieldModel->getIndexField('crm_customer', $user_id, 1) ? : array('name');
  165. $userField = $fieldModel->getFieldByFormType('crm_customer', 'user'); //人员类型
  166. $structureField = $fieldModel->getFieldByFormType('crm_customer', 'structure'); //部门类型
  167. $datetimeField = $fieldModel->getFieldByFormType('crm_customer', 'datetime'); //日期时间类型
  168. //排序
  169. if ($order_type && $order_field) {
  170. $order = $fieldModel->getOrderByFormtype('crm_customer','customer',$order_field,$order_type);
  171. } else {
  172. $order = 'customer.update_time desc';
  173. }
  174. //置顶
  175. // $tops = Db::name('crm_top')->where(['module' => ['eq','customer'],'create_role_id' => ['eq',$user_id],'set_top' => ['eq',1]])->order('top_time asc')->column('module_id');
  176. // $top_ids = implode(",", $tops);
  177. // if ($tops) {
  178. // $order_t = DB::raw("field(customer_id, $top_ids) desc");
  179. // }
  180. $list = db('crm_customer')->alias('customer')
  181. ->where($map)
  182. ->where($searchMap)
  183. ->where($customerMap)
  184. ->where($authMap)
  185. ->where($partMap)
  186. ->where($poolMap)
  187. ->where($otherMap)
  188. ->limit($request['offset'], $request['length'])
  189. ->field('customer.*')
  190. ->orderRaw($order)
  191. ->select();
  192. //保护规则
  193. $configModel = new \app\crm\model\ConfigData();
  194. $configInfo = $configModel->getData();
  195. $paramPool = [];
  196. $paramPool['config'] = $configInfo['config'] ? : 0;
  197. $paramPool['follow_day'] = $configInfo['follow_day'] ? : 0;
  198. $paramPool['deal_day'] = $configInfo['deal_day'] ? : 0;
  199. $paramPool['remind_config'] = $configInfo['remind_config'] ? : 0;
  200. $readAuthIds = $userModel->getUserByPer('crm', 'customer', 'read');
  201. $updateAuthIds = $userModel->getUserByPer('crm', 'customer', 'update');
  202. $deleteAuthIds = $userModel->getUserByPer('crm', 'customer', 'delete');
  203. if (!empty($list)) {
  204. $customer_id_list = array_column($list, 'customer_id');
  205. $business_count = db('crm_business')
  206. ->field([
  207. 'COUNT(*)' => 'count',
  208. 'customer_id'
  209. ])
  210. ->where([
  211. 'customer_id' => ['IN', $customer_id_list]
  212. ])
  213. ->group('customer_id')
  214. ->select();
  215. $business_count = array_column($business_count, null, 'customer_id');
  216. $field_list = $fieldModel->getIndexFieldConfig('crm_customer', $user_id);
  217. $field_list = array_column($field_list, 'field');
  218. foreach ($list as $k => $v) {
  219. $list[$k]['create_user_id_info'] = isset($v['create_user_id']) ? $userModel->getUserById($v['create_user_id']) : [];
  220. $list[$k]['owner_user_id_info'] = isset($v['owner_user_id']) ? $userModel->getUserById($v['owner_user_id']) : [];
  221. $list[$k]['create_user_name'] = !empty($list[$k]['create_user_id_info']['realname']) ? $list[$k]['create_user_id_info']['realname'] : '';
  222. $list[$k]['owner_user_name'] = !empty($list[$k]['owner_user_id_info']['realname']) ? $list[$k]['owner_user_id_info']['realname'] : '';
  223. foreach ($userField as $key => $val) {
  224. if (in_array($val, $field_list)) {
  225. $usernameField = !empty($v[$val]) ? db('admin_user')->whereIn('id', stringToArray($v[$val]))->column('realname') : [];
  226. $list[$k][$val] = implode($usernameField, ',');
  227. }
  228. }
  229. foreach ($structureField as $key => $val) {
  230. if (in_array($val, $field_list)) {
  231. $structureNameField = !empty($v[$val]) ? db('admin_structure')->whereIn('id', stringToArray($v[$val]))->column('name') : [];
  232. $list[$k][$val] = implode($structureNameField, ',');
  233. }
  234. }
  235. foreach ($datetimeField as $key => $val) {
  236. $list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null;
  237. }
  238. //商机数
  239. $list[$k]['business_count'] = $business_count[$v['customer_id']]['count'] ?: 0;
  240. //距进入公海天数
  241. $poolData = [];
  242. if ($paramPool['config'] == 1 && $requestData['a'] !== 'pool') {
  243. $paramPool['update_time'] = $v['update_time'];
  244. $paramPool['deal_time'] = $v['deal_time'];
  245. $paramPool['is_lock'] = $v['is_lock'];
  246. $paramPool['deal_status'] = $v['deal_status'];
  247. $poolData = $this->getPoolDay($paramPool);
  248. $list[$k]['pool_day'] = $poolData ? $poolData['poolDay'] : '';
  249. $list[$k]['is_pool'] = $poolData ? $poolData['isPool'] : '';
  250. }
  251. if ($paramPool['remind_config'] == 0) {
  252. $list[$k]['pool_day'] = '';
  253. }
  254. //权限
  255. $roPre = $userModel->rwPre($user_id, $v['ro_user_id'], $v['rw_user_id'], 'read');
  256. $rwPre = $userModel->rwPre($user_id, $v['ro_user_id'], $v['rw_user_id'], 'update');
  257. $permission = [];
  258. $is_read = 0;
  259. $is_update = 0;
  260. $is_delete = 0;
  261. if (in_array($v['owner_user_id'],$readAuthIds) || $roPre || $rwPre) $is_read = 1;
  262. if (in_array($v['owner_user_id'],$updateAuthIds) || $rwPre) $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['customer_id'], 'type' => 'crm_customer'];
  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. }
  278. $data = [];
  279. $data['list'] = $list ? : [];
  280. $data['dataCount'] = $dataCount ? : 0;
  281. return $data;
  282. }
  283. /**
  284. * 创建客户主表信息
  285. * @author Michael_xu
  286. * @param
  287. * @return
  288. */
  289. public function createData($param)
  290. {
  291. $fieldModel = new \app\admin\model\Field();
  292. $userModel = new \app\admin\model\User();
  293. $customerConfigModel = new \app\crm\model\CustomerConfig();
  294. //添加上限检测
  295. if (!$customerConfigModel->checkData($param['create_user_id'],1)) {
  296. $this->error = $customerConfigModel->getError();
  297. return false;
  298. }
  299. //地址
  300. $param['address'] = $param['address'] ? implode(chr(10),$param['address']) : '';
  301. $param['deal_time'] = time(); //领取、分配时间
  302. $param['deal_status'] = '未成交';
  303. //线索转客户
  304. if ($param['leads_id']) {
  305. $leadsData = $param;
  306. $leadsData['create_user_id'] = $param['create_user_id'];
  307. $leadsData['owner_user_id'] = $param['owner_user_id'];
  308. $leadsData['ro_user_id'] = '';
  309. $leadsData['rw_user_id'] = '';
  310. $leadsData['detail_address'] = $param['detail_address'] ? : '';
  311. $param = $leadsData;
  312. }
  313. // 自动验证
  314. $validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
  315. $validate = new Validate($validateArr['rule'], $validateArr['message']);
  316. $result = $validate->check($param);
  317. if (!$result) {
  318. $this->error = $validate->getError();
  319. return false;
  320. }
  321. unset($param['customer_id']);
  322. //处理部门、员工、附件、多选类型字段
  323. $arrFieldAtt = $fieldModel->getArrayField('crm_customer');
  324. foreach ($arrFieldAtt as $k=>$v) {
  325. $param[$v] = arrayToString($param[$v]);
  326. }
  327. if ($this->data($param)->allowField(true)->isUpdate(false)->save()) {
  328. //修改记录
  329. updateActionLog($param['create_user_id'], 'crm_customer', $this->customer_id, '', '', '创建了客户');
  330. $data = [];
  331. $data['customer_id'] = $this->customer_id;
  332. $data['name'] = $param['name'];
  333. # 添加活动记录
  334. Db::name('crm_activity')->insert([
  335. 'type' => 2,
  336. 'activity_type' => 2,
  337. 'activity_type_id' => $data['customer_id'],
  338. 'content' => $data['name'],
  339. 'create_user_id' => $param['create_user_id'],
  340. 'update_time' => time(),
  341. 'create_time' => time()
  342. ]);
  343. return $data;
  344. } else {
  345. $this->error = '添加失败';
  346. return false;
  347. }
  348. }
  349. //根据IDs获取数组
  350. public function getDataByStr($idstr)
  351. {
  352. $idArr = stringToArray($idstr);
  353. if (!$idArr) {
  354. return [];
  355. }
  356. $list = db('crm_customer')->where(['customer_id' => ['in',$idArr]])->select();
  357. return $list;
  358. }
  359. /**
  360. * 编辑客户主表信息
  361. * @author Michael_xu
  362. * @param
  363. * @return
  364. */
  365. public function updateDataById($param, $customer_id = '')
  366. {
  367. $user_id = $param['user_id'];
  368. $dataInfo = $this->get($customer_id);
  369. if (!$dataInfo) {
  370. $this->error = '数据不存在或已删除';
  371. return false;
  372. }
  373. $id = $param['id']?:$customer_id;
  374. //数据权限判断
  375. $userModel = new \app\admin\model\User();
  376. $auth_user_ids = $userModel->getUserByPer('crm', 'customer', 'update');
  377. //读写权限
  378. $rwPre = $userModel->rwPre($user_id, $dataInfo['ro_user_id'], $dataInfo['rw_user_id'], 'update');
  379. //判断是否客户池数据
  380. $wherePool = $this->getWhereByPool();
  381. $resPool = db('crm_customer')->alias('customer')->where(['customer_id' => $id])->where($wherePool)->find();
  382. if ($resPool || (!in_array($dataInfo['owner_user_id'],$auth_user_ids) && !$rwPre)) {
  383. $this->error = '无权操作';
  384. return false;
  385. }
  386. $param['customer_id'] = $customer_id;
  387. //过滤不能修改的字段
  388. $unUpdateField = ['create_user_id','is_deleted','delete_time','user_id'];
  389. foreach ($unUpdateField as $v) {
  390. unset($param[$v]);
  391. }
  392. $param['deal_status'] = $dataInfo['deal_status'];
  393. $fieldModel = new \app\admin\model\Field();
  394. // 自动验证
  395. $validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
  396. $validate = new Validate($validateArr['rule'], $validateArr['message']);
  397. $result = $validate->check($param);
  398. if (!$result) {
  399. $this->error = $validate->getError();
  400. return false;
  401. }
  402. //地址
  403. $param['address'] = $param['address'] ? implode(chr(10),$param['address']) : '';
  404. if ($param['deal_status'] == '已成交' && $dataInfo->data['deal_status'] == '未成交') {
  405. $param['deal_time'] = time();
  406. }
  407. //处理部门、员工、附件、多选类型字段
  408. $arrFieldAtt = $fieldModel->getArrayField('crm_customer');
  409. foreach ($arrFieldAtt as $k=>$v) {
  410. $param[$v] = arrayToString($param[$v]);
  411. }
  412. $param['follow'] = '已跟进';
  413. if ($this->update($param, ['customer_id' => $customer_id], true)) {
  414. //修改记录
  415. updateActionLog($user_id, 'crm_customer', $customer_id, $dataInfo->data, $param);
  416. $data = [];
  417. $data['customer_id'] = $customer_id;
  418. return $data;
  419. } else {
  420. $this->error = '编辑失败';
  421. return false;
  422. }
  423. }
  424. /**
  425. * 客户数据
  426. *
  427. * @param string $id
  428. * @param int $userId
  429. * @return Common|array|bool|\PDOStatement|string|\think\Model|null
  430. * @throws \think\db\exception\DataNotFoundException
  431. * @throws \think\db\exception\ModelNotFoundException
  432. * @throws \think\exception\DbException
  433. */
  434. public function getDataById($id = '', $userId = 0)
  435. {
  436. $dataInfo = db('crm_customer')->where(['customer_id' => $id])->find();
  437. if (!$dataInfo) {
  438. $this->error = '数据不存在或已删除';
  439. return false;
  440. }
  441. $userModel = new \app\admin\model\User();
  442. $dataInfo['create_user_id_info'] = isset($dataInfo['create_user_id']) ? $userModel->getUserById($dataInfo['create_user_id']) : [];
  443. $dataInfo['owner_user_id_info'] = isset($dataInfo['owner_user_id']) ? $userModel->getUserById($dataInfo['owner_user_id']) : [];
  444. $dataInfo['create_user_name'] = !empty($dataInfo['create_user_id_info']['realname']) ? $dataInfo['create_user_id_info']['realname'] : '';
  445. $dataInfo['owner_user_name'] = !empty($dataInfo['owner_user_id_info']['realname']) ? $dataInfo['owner_user_id_info']['realname'] : '';
  446. //保护规则
  447. $configModel = new \app\crm\model\ConfigData();
  448. $configInfo = $configModel->getData();
  449. $paramPool = [];
  450. $paramPool['config'] = $configInfo['config'] ? : 0;
  451. $paramPool['follow_day'] = $configInfo['follow_day'] ? : 0;
  452. $paramPool['deal_day'] = $configInfo['deal_day'] ? : 0;
  453. //是否公海
  454. $poolData = [];
  455. if ($paramPool['config'] == 1) {
  456. $paramPool['update_time'] = $dataInfo['update_time'];
  457. $paramPool['deal_time'] = $dataInfo['deal_time'];
  458. $paramPool['is_lock'] = $dataInfo['is_lock'];
  459. $paramPool['deal_status'] = $dataInfo['deal_status'];
  460. $paramPool['owner_user_id'] = $dataInfo['owner_user_id'];
  461. $poolData = $this->getPoolDay($paramPool);
  462. } else {
  463. if (!$dataInfo['owner_user_id']) {
  464. $poolData['isPool'] = 1;
  465. }
  466. }
  467. $dataInfo['pool_day'] = $poolData ? $poolData['poolDay'] : '';
  468. $dataInfo['is_pool'] = $poolData ? $poolData['isPool'] : '';
  469. # 关注
  470. $starId = empty($userId) ? 0 : Db::name('crm_star')->where(['user_id' => $userId, 'target_id' => $id, 'type' => 'crm_customer'])->value('star_id');
  471. $dataInfo['star'] = !empty($starId) ? 1 : 0;
  472. # 首要联系人
  473. $primaryId = Db::name('crm_contacts')->where(['customer_id' => $id, 'primary' => 1])->value('contacts_id');
  474. $dataInfo['contacts_id'] = !empty($primaryId) && $this->getContactsAuth($primaryId) ? $primaryId : 0;
  475. # 处理时间格式
  476. $fieldModel = new \app\admin\model\Field();
  477. $datetimeField = $fieldModel->getFieldByFormType('crm_customer', 'datetime'); //日期时间类型
  478. foreach ($datetimeField as $key => $val) {
  479. $dataInfo[$val] = !empty($dataInfo[$val]) ? date('Y-m-d H:i:s', $dataInfo[$val]) : null;
  480. }
  481. $dataInfo['create_time'] = !empty($dataInfo['create_time']) ? date('Y-m-d H:i:s', $dataInfo['create_time']) : null;
  482. $dataInfo['update_time'] = !empty($dataInfo['update_time']) ? date('Y-m-d H:i:s', $dataInfo['update_time']) : null;
  483. $dataInfo['last_time'] = !empty($dataInfo['last_time']) ? date('Y-m-d H:i:s', $dataInfo['last_time']) : null;
  484. return $dataInfo;
  485. }
  486. /**
  487. * [客户统计]
  488. * @author Michael_xu
  489. * @param
  490. * @return
  491. */
  492. public function getStatistics($request)
  493. {
  494. $userModel = new \app\admin\model\User();
  495. $request = $this->fmtRequest( $request );
  496. $map = $request['map'] ? : [];
  497. unset($map['search']);
  498. $where = [];
  499. //时间段
  500. $start_time = $map['start_time'];
  501. $end_time = $map['end_time'] ? $map['end_time'] : time();
  502. if ($start_time && $end_time) {
  503. $start_date = date('Y-m-d',$start_time);
  504. $end_date = date('Y-m-d',$end_time);
  505. $where_time = " BETWEEN {$start_time} AND {$end_time} ";
  506. $where_date = " BETWEEN '{$start_date}' AND '{$end_date}' ";
  507. } else {
  508. $where_time = " > 0 ";
  509. $where_date = " != '' ";
  510. }
  511. //员工IDS
  512. $map_user_ids = [];
  513. if (!empty($map['user_id'])) {
  514. $map_user_ids = array($map['user_id']);
  515. } elseif (!empty($map['structure_id'])) {
  516. $map_user_ids = $userModel->getSubUserByStr($map['structure_id'], 2);
  517. }
  518. # 没有传递员工参数并且部门下没员工的情况
  519. if (empty($map_user_ids)) return [];
  520. $perUserIds = $userModel->getUserByPer('bi', 'customer', 'read'); //权限范围内userIds
  521. $userIds = $map_user_ids ? array_intersect($map_user_ids, $perUserIds) : $perUserIds; //数组交集
  522. $userIds = array_values($userIds);
  523. $prefix = config('database.prefix');
  524. $count = count($userIds);
  525. $sql = '';
  526. foreach ($userIds as $key => $user_id) {
  527. $sql .= "
  528. SELECT
  529. (SELECT realname FROM {$prefix}admin_user WHERE id = {$user_id}) as realname,
  530. COUNT(cu.customer_id) AS customer_num,
  531. SUM(cu.deal_status = '已成交') AS deal_customer_num,
  532. IFNULL(
  533. (SELECT SUM(money) FROM {$prefix}crm_contract WHERE
  534. owner_user_id = {$user_id}
  535. AND order_date {$where_date}
  536. AND check_status = 2
  537. ),
  538. 0
  539. ) as contract_money,
  540. IFNULL(
  541. (SELECT SUM(money) FROM {$prefix}crm_receivables WHERE
  542. owner_user_id = {$user_id}
  543. AND return_time {$where_date}
  544. AND check_status = 2
  545. ),
  546. 0
  547. ) as receivables_money
  548. FROM
  549. {$prefix}crm_customer as cu
  550. WHERE
  551. cu.create_time {$where_time}
  552. AND cu.owner_user_id = {$user_id}
  553. ";
  554. if ($count > 1 && $key != $count - 1) {
  555. $sql .= " UNION ALL ";
  556. }
  557. }
  558. if ($sql == '') {
  559. return [];
  560. }
  561. $customerCount = 0; # 客户总数
  562. $dealCustomerCount = 0; # 成交客户总数
  563. $contractMoneyCount = 0; # 合同总金额
  564. $receivablesMoneyCount = 0; # 回款总金额
  565. $list = queryCache($sql);
  566. foreach ($list as &$val) {
  567. $val['deal_customer_num'] = Floor($val['deal_customer_num']);
  568. $val['contract_money'] = Floor($val['contract_money']);
  569. $val['receivables_money'] = Floor($val['receivables_money']);
  570. $val['deal_customer_rate'] = $val['customer_num'] ? round(($val['deal_customer_num'] / $val['customer_num']) * 100, 2) : 0;
  571. $val['un_receivables_money'] = $val['contract_money'] - $val['receivables_money'] >= 0 ? $val['contract_money'] - $val['receivables_money'] : '0.00';
  572. $val['deal_receivables_rate'] = $val['contract_money'] ? round(($val['receivables_money'] / $val['contract_money']) * 100, 2) : 0;
  573. $customerCount += $val['customer_num'];
  574. $dealCustomerCount += $val['deal_customer_num'];
  575. $contractMoneyCount += $val['contract_money'];
  576. $receivablesMoneyCount += $val['receivables_money'];
  577. }
  578. return ['list' => $list, 'total' => [
  579. 'realname' => '总计',
  580. 'customer_num' => $customerCount,
  581. 'deal_customer_num' => $dealCustomerCount,
  582. 'contract_money' => $contractMoneyCount,
  583. 'receivables_money' => $receivablesMoneyCount
  584. ]];
  585. }
  586. /**
  587. * [客户数量]
  588. * @author Michael_xu
  589. * @param
  590. * @return
  591. */
  592. public function getDataCount($map)
  593. {
  594. //非公海条件
  595. // $where = $this->getWhereByCustomer();
  596. $where = [];
  597. $dataCount = $this->where($map)->fetchSql(false)->count();
  598. $count = $dataCount ? : 0;
  599. return $count;
  600. }
  601. /**
  602. * [客户默认条件]
  603. * @author Michael_xu
  604. * @param
  605. * @return
  606. */
  607. public function getWhereByCustomer()
  608. {
  609. $configModel = new \app\crm\model\ConfigData();
  610. $userModel = new \app\admin\model\User();
  611. $configInfo = $configModel->getData();
  612. $config = $configInfo['config'] ? : 0;
  613. $follow_day = $configInfo['follow_day'] ? : 0;
  614. $deal_day = $configInfo['deal_day'] ? : 0;
  615. //默认条件(没有到期或已锁定)
  616. $data['follow_time'] = time()-$follow_day*86400;
  617. $data['deal_time'] = time()-$deal_day*86400;
  618. if ($config == 1) {
  619. if ($follow_day < $deal_day) {
  620. $whereData = function($query) use ($data){
  621. $query->where(function ($query) use ($data) {
  622. $query->where(['customer.update_time' => array('gt',$data['follow_time']),'customer.deal_time' => array('gt',$data['deal_time'])]);
  623. })
  624. ->whereOr(['customer.deal_status' => '已成交'])
  625. ->whereOr(['customer.is_lock' => 1]);
  626. };
  627. } else {
  628. $whereData = function($query) use ($data){
  629. $query->where(function ($query) use ($data) {
  630. $query->where(['customer.deal_time' => array('gt',$data['deal_time'])]);
  631. })
  632. ->whereOr(['customer.deal_status' => '已成交'])
  633. ->whereOr(['customer.is_lock' => 1]);
  634. };
  635. }
  636. }
  637. return $whereData ? : '';
  638. }
  639. /**
  640. * [客户公海条件]
  641. * @author Michael_xu
  642. * @param
  643. * @return
  644. */
  645. public function getWhereByPool()
  646. {
  647. $configModel = new \app\crm\model\ConfigData();
  648. $configInfo = $configModel->getData();
  649. $config = $configInfo['config'] ? : 0;
  650. $follow_day = $configInfo['follow_day'] ? : 0;
  651. $deal_day = $configInfo['deal_day'] ? : 0;
  652. $whereData = [];
  653. //启用
  654. if ($config == 1) {
  655. //默认公海条件(没有负责人或已经到期)
  656. $data['follow_time'] = time()-$follow_day*86400;
  657. $data['deal_time'] = time()-$deal_day*86400;
  658. $data['deal_status'] = '未成交';
  659. if ($follow_day < $deal_day) {
  660. $whereData = function($query) use ($data){
  661. $query->where(['customer.owner_user_id'=>0])
  662. ->whereOr(function ($query) use ($data) {
  663. $query->where(function ($query) use ($data) {
  664. $query->where(['customer.update_time' => array('elt',$data['follow_time'])])
  665. ->whereOr(['customer.deal_time' => array('elt',$data['deal_time'])]);
  666. })
  667. ->where(['customer.is_lock' => 0])
  668. ->where(['customer.deal_status' => ['neq','已成交']]);
  669. });
  670. };
  671. } else {
  672. $whereData = function($query) use ($data){
  673. $query->where(['customer.owner_user_id'=>0])
  674. ->whereOr(function ($query) use ($data) {
  675. $query->where(function ($query) use ($data) {
  676. $query->where(['customer.deal_time' => array('elt',$data['deal_time'])]);
  677. })
  678. ->where(['customer.is_lock' => 0])
  679. ->where(['customer.deal_status' => ['neq','已成交']]);
  680. });
  681. };
  682. }
  683. } else {
  684. $whereData['customer.owner_user_id'] = 0;
  685. }
  686. return $whereData ? : '';
  687. }
  688. /**
  689. * 客户权限判断(是否客户公海)
  690. * @author Michael_xu
  691. * @param type 1 是公海返回false,默认是公海返回true
  692. * @return
  693. */
  694. public function checkData($customer_id, $type = '')
  695. {
  696. //权限范围
  697. $userModel = new \app\admin\model\User();
  698. $authIds = $userModel->getUserByPer(); //权限范围的user_id
  699. //是否客户公海
  700. $map = $this->getWhereByPool();
  701. $where['customer_id'] = $customer_id;
  702. $customerInfo = db('crm_customer')->alias('customer')->where($where)->where($map)->find();
  703. if ($customerInfo && !$type) {
  704. return true;
  705. } else {
  706. $customerInfo = db('crm_customer')->where(['customer_id' => $customer_id])->find();
  707. if (in_array($customerInfo['owner_user_id'], $authIds)) {
  708. return true;
  709. }
  710. }
  711. $this->error = '没有权限';
  712. return false;
  713. }
  714. /**
  715. * 客户到期天数
  716. * @author Michael_xu
  717. * @param
  718. * @return
  719. */
  720. public function getPoolDay($param)
  721. {
  722. $poolDay = '';
  723. $isPool = 0;
  724. $is_lock = $param['is_lock'] ? : 0;
  725. $deal_status = $param['deal_status'] ? : '未成交';
  726. $update_time = $param['update_time'];
  727. if (strtotime($param['update_time'])) {
  728. $update_time = strtotime($param['update_time']);
  729. }
  730. if (!$is_lock && $deal_status !== '已成交') {
  731. $follow_time = time()-$param['follow_day']*86400;
  732. $deal_time = time()-$param['deal_day']*86400;
  733. if (($update_time < $follow_time) || ($param['deal_time'] < $deal_time)) {
  734. $isPool = 1; //是公海
  735. } else {
  736. $sub_follow_day = ceil(($update_time-$follow_time)/86400);
  737. $sub_deal_day = ceil(($param['deal_time']-$deal_time)/86400);
  738. $poolDay = ($sub_deal_day > $sub_follow_day) ? $sub_follow_day : $sub_deal_day;
  739. $poolDay = $poolDay ? : 0;
  740. if ($poolDay < 0) {
  741. $isPool = 1; //是公海
  742. }
  743. }
  744. } elseif ($is_lock == 1) {
  745. $poolDay = ''; //锁定
  746. } elseif ($deal_status == '已成交') {
  747. $poolDay = '';
  748. }
  749. if (!$param['owner_user_id']) {
  750. $isPool = 1; //是公海
  751. }
  752. $data = [];
  753. $data['poolDay'] = $poolDay;
  754. $data['isPool'] = $isPool;
  755. return $data;
  756. }
  757. /**
  758. * [待进入客户池条件]
  759. * @author Michael_xu
  760. * @param
  761. * @return
  762. */
  763. public function getWhereByRemind()
  764. {
  765. $configModel = new \app\crm\model\ConfigData();
  766. $configInfo = $configModel->getData();
  767. $config = $configInfo['config'] ? : 0;
  768. $follow_day = $configInfo['follow_day'] ? : 0;
  769. $deal_day = $configInfo['deal_day'] ? : 0;
  770. $remind_config = $configInfo['remind_config'] ? : 0;
  771. $remind_day = $configInfo['remind_day'] ? : 0;
  772. $whereData = [];
  773. //启用
  774. if ($config == 1 && $remind_config == 1) {
  775. //默认公海条件(没有负责人或已经到期)
  776. //通过提前提醒时间,计算查询时间段
  777. $remind_follow_day = ($follow_day-$remind_day > 0) ? ($follow_day-$remind_day) : $follow_day-1;
  778. $remind_deal_day = ($deal_day-$remind_day > 0) ? ($deal_day-$remind_day) : $deal_day-1;
  779. if (($follow_day > 0) && ($deal_day > 0)) {
  780. $follow_between = array(time()-$follow_day*86400,time()-$remind_follow_day*86400);
  781. $deal_between = array(time()-$deal_day*86400,time()-$remind_deal_day*86400);
  782. $data['update_between'] = $follow_between;
  783. $data['deal_between'] = $deal_between;
  784. if ($follow_day < $deal_day) {
  785. $whereData = function($query) use ($data){
  786. $query->where(function ($query) use ($data) {
  787. $query->where(function ($query) use ($data) {
  788. $query->where(['customer.update_time' => array('between',$data['update_between'])])
  789. ->whereOr(['customer.deal_time' => array('between',$data['deal_between'])]);
  790. })
  791. ->where(['customer.is_lock' => 0])
  792. ->where(['customer.deal_status' => ['neq','已成交']]);
  793. });
  794. };
  795. } else {
  796. $whereData = function($query) use ($data){
  797. $query->where(function ($query) use ($data) {
  798. $query->where(function ($query) use ($data) {
  799. $query->where(['customer.deal_time' => array('between',$data['deal_between'])]);
  800. })
  801. ->where(['customer.is_lock' => 0])
  802. ->where(['customer.deal_status' => ['neq','已成交']]);
  803. });
  804. };
  805. }
  806. } else {
  807. $whereData['customer.customer_id'] = 0;
  808. }
  809. } else {
  810. $whereData['customer.customer_id'] = 0;
  811. }
  812. return $whereData ? : '';
  813. }
  814. /**
  815. * [今日进入客户池条件]
  816. * @author Michael_xu
  817. * @param
  818. * @return
  819. */
  820. public function getWhereByToday()
  821. {
  822. $configModel = new \app\crm\model\ConfigData();
  823. $configInfo = $configModel->getData();
  824. $config = $configInfo['config'] ? : 0;
  825. $follow_day = $configInfo['follow_day'] ? : 0;
  826. $deal_day = $configInfo['deal_day'] ? : 0;
  827. $whereData = [];
  828. //启用
  829. if ($config == 1) {
  830. //默认公海条件(没有负责人或已经到期)
  831. //通过提前提醒时间,计算查询时间段
  832. if (($follow_day > 0) && ($deal_day > 0)) {
  833. $follow_between = array(strtotime(date('Y-m-d',time()-$follow_day*86400)),time()-$follow_day*86400);
  834. $deal_between = array(strtotime(date('Y-m-d',time()-$deal_day*86400)),time()-$deal_day*86400);
  835. $data['update_time'] = time()-$follow_day*86400;
  836. $data['deal_time'] = time()-$deal_day*86400;
  837. $data['update_between'] = $follow_between;
  838. $data['deal_between'] = $deal_between;
  839. if ($follow_day < $deal_day) {
  840. $whereData = function($query) use ($data){
  841. $query->where(['customer.owner_user_id'=>0])
  842. ->whereOr(function ($query) use ($data) {
  843. $query->where(function ($query) use ($data) {
  844. $query->where(['customer.update_time' => array('between',$data['update_between'])])
  845. ->whereOr(['customer.deal_time' => array('between',$data['deal_between'])]);
  846. })
  847. ->where(['customer.is_lock' => 0])
  848. ->where(['customer.deal_status' => ['neq','已成交']]);
  849. });
  850. };
  851. } else {
  852. $whereData = function($query) use ($data){
  853. $query->where(['customer.owner_user_id'=>0])
  854. ->whereOr(function ($query) use ($data) {
  855. $query->where(function ($query) use ($data) {
  856. $query->where(['customer.deal_time' => array('between',$data['deal_between'])]);
  857. })
  858. ->where(['customer.is_lock' => 0])
  859. ->where(['customer.deal_status' => ['neq','已成交']]);
  860. });
  861. };
  862. }
  863. } else {
  864. $whereData['customer.customer_id'] = 0;
  865. }
  866. } else {
  867. $whereData['customer.owner_user_id'] = 0;
  868. $whereData['customer.update_time'] = array('between',array(strtotime(date('Y-m-d',time())),time()));
  869. }
  870. return $whereData ? : '';
  871. }
  872. /**
  873. * [客户拥有、锁定数]
  874. * @author Michael_xu
  875. * @param is_deal 1包含成交客户
  876. * @param types 1拥有客户上限2锁定客户上限
  877. * @return
  878. */
  879. public function getCountByHave($user_id, $is_deal = 0,$types = 1)
  880. {
  881. $where = [];
  882. $where['owner_user_id'] = $user_id;
  883. //公海逻辑
  884. $configModel = new \app\crm\model\ConfigData();
  885. $userModel = new \app\admin\model\User();
  886. $configInfo = $configModel->getData();
  887. $config = $configInfo['config'] ? : 0;
  888. $follow_day = $configInfo['follow_day'] ? : 0;
  889. $deal_day = $configInfo['deal_day'] ? : 0;
  890. //默认条件(没有到期或已锁定)
  891. $data['follow_time'] = time()-$follow_day*86400;
  892. $data['deal_time'] = time()-$deal_day*86400;
  893. $whereData = '';
  894. //公海开启
  895. if ($config == 1) {
  896. switch ($types) {
  897. case '1' :
  898. if ($is_deal !== 1) {
  899. //不包含成交客户
  900. $where['deal_status'] = ['neq','已成交'];
  901. if ($follow_day < $deal_day) {
  902. $whereData = function($query) use ($data){
  903. $query->where(function ($query) use ($data) {
  904. $query->where(['update_time' => array('gt',$data['follow_time']),'deal_time' => array('gt',$data['deal_time'])]);
  905. });
  906. };
  907. } else {
  908. $whereData = function($query) use ($data){
  909. $query->where(function ($query) use ($data) {
  910. $query->where(['deal_time' => array('gt',$data['deal_time'])]);
  911. });
  912. };
  913. }
  914. } else {
  915. if ($follow_day < $deal_day) {
  916. $whereData = function($query) use ($data){
  917. $query->where(function ($query) use ($data) {
  918. $query->where(['update_time' => array('gt',$data['follow_time']),'deal_time' => array('gt',$data['deal_time'])]);
  919. })
  920. ->whereOr(['deal_status' => ['eq','已成交']]);
  921. };
  922. } else {
  923. $whereData = function($query) use ($data){
  924. $query->where(function ($query) use ($data) {
  925. $query->where(['deal_time' => array('gt',$data['deal_time'])]);
  926. })
  927. ->whereOr(['deal_status' => ['eq','已成交']]);
  928. };
  929. }
  930. }
  931. break;
  932. case '2' :
  933. $where['is_lock'] = ['eq',1];
  934. //默认不包含成交客户
  935. $where['deal_status'] = ['neq','已成交'];
  936. break;
  937. }
  938. } else {
  939. //公海未开启
  940. if ($is_deal !== 1) {
  941. //不包含成交客户
  942. $where['deal_status'] = ['neq','已成交'];
  943. }
  944. switch ($types) {
  945. case '2' :
  946. //锁定,默认不包含成交客户
  947. $where['deal_status'] = ['neq','已成交'];
  948. $where['is_lock'] = 1;
  949. break;
  950. }
  951. }
  952. $count = $this->where($where)->where($whereData)->count();
  953. return $count ? : 0;
  954. }
  955. /**
  956. * [客户成交新增数量]
  957. * @author Michael_xu
  958. * @param
  959. * @return
  960. */
  961. public function getAddDealSql($map)
  962. {
  963. $prefix = config('database.prefix');
  964. $sql = "SELECT
  965. '{$map['type']}' AS type,
  966. '{$map['start_time']}' AS start_time,
  967. '{$map['end_time']}' AS end_time,
  968. IFNULL(
  969. (
  970. SELECT
  971. count(customer_id)
  972. FROM
  973. {$prefix}crm_customer
  974. WHERE
  975. create_time BETWEEN {$map['start_time']} AND {$map['end_time']}
  976. AND owner_user_id IN ({$map['create_user_id']})
  977. ),
  978. 0
  979. ) AS customer_num,
  980. IFNULL(
  981. count(customer_id),
  982. 0
  983. ) AS deal_customer_num
  984. FROM
  985. {$prefix}crm_customer
  986. WHERE
  987. create_time BETWEEN {$map['start_time']} AND {$map['end_time']}
  988. AND deal_status = '{$map['deal_status']}'
  989. AND owner_user_id IN ({$map['create_user_id']})";
  990. return $sql;
  991. }
  992. /**
  993. * [客户统计sql]
  994. * @author Michael_xu
  995. * @param
  996. * @return
  997. */
  998. public function getAddressCountBySql($map)
  999. {
  1000. $prefix = config('database.prefix');
  1001. $sql = "SELECT
  1002. '{$map['address']}' AS address,
  1003. IFNULL(
  1004. (
  1005. SELECT
  1006. count(customer_id)
  1007. FROM
  1008. {$prefix}crm_customer
  1009. WHERE
  1010. address LIKE '%{$map['address']}%'
  1011. AND owner_user_id IN ({$map['owner_user_id']})
  1012. ),
  1013. 0
  1014. ) AS allCustomer,
  1015. IFNULL(
  1016. count(customer_id),
  1017. 0
  1018. ) AS dealCustomer
  1019. FROM
  1020. {$prefix}crm_customer
  1021. WHERE
  1022. address LIKE '%{$map['address']}%'
  1023. AND deal_status = '{$map['deal_status']}'
  1024. AND owner_user_id IN ({$map['owner_user_id']})";
  1025. $list = $this->query($sql) ? : [];
  1026. return $list;
  1027. }
  1028. /**
  1029. * 获取附近的客户
  1030. *
  1031. * @param $param
  1032. * @return array
  1033. * @throws \think\db\exception\DataNotFoundException
  1034. * @throws \think\db\exception\ModelNotFoundException
  1035. * @throws \think\exception\DbException
  1036. */
  1037. public function getNearbyList($param)
  1038. {
  1039. $apiCommon = new ApiCommon();
  1040. $userModel = new \app\admin\model\User();
  1041. $poolStatus = checkPerByAction('crm', 'customer', 'pool');
  1042. # 客户
  1043. $customerWhere = [];
  1044. if ((!empty($param['type']) && $param['type'] == 2) || !$poolStatus) {
  1045. $customerWhere = $this->getWhereByCustomer();
  1046. }
  1047. # 公海
  1048. $poolWhere = [];
  1049. if (!empty($param['type']) && $param['type'] == 9 && $poolStatus) {
  1050. $poolWhere = $this->getWhereByPool();
  1051. }
  1052. if (!empty($param['type']) && $param['type'] == 9 && !$poolStatus) {
  1053. return [];
  1054. }
  1055. # 基本权限
  1056. // $auth_user_ids = $userModel->getUserByPer('crm', 'customer', 'index');
  1057. // $authMapData['auth_user_ids'] = $auth_user_ids;
  1058. // $authMapData['user_id'] = $apiCommon->userInfo['id'];
  1059. // $authMap = function($query) use ($authMapData){
  1060. // $query->where(['customer.owner_user_id' => array('in',$authMapData['auth_user_ids'])])
  1061. // ->whereOr(function ($query) use ($authMapData) {
  1062. // $query->where('FIND_IN_SET("'.$authMapData['user_id'].'", customer.ro_user_id)')->where(['customer.owner_user_id' => array('neq','')]);
  1063. // })
  1064. // ->whereOr(function ($query) use ($authMapData) {
  1065. // $query->where('FIND_IN_SET("'.$authMapData['user_id'].'", customer.rw_user_id)')->where(['customer.owner_user_id' => array('neq','')]);
  1066. // });
  1067. // };
  1068. # 附近
  1069. $lngLatRange = $this->getLngLatRange($param['lng'], $param['lat'], $param['distance']);
  1070. $lngLatWhere = function ($query) use ($lngLatRange) {
  1071. $query->where(['lng' => ['egt', $lngLatRange['minLng']]]);
  1072. $query->where(['lng' => ['elt', $lngLatRange['maxLng']]]);
  1073. $query->where(['lat' => ['egt', $lngLatRange['minLat']]]);
  1074. $query->where(['lat' => ['elt', $lngLatRange['maxLat']]]);
  1075. };
  1076. # 经纬度值计算出错
  1077. if (empty($lngLatRange['minLng']) || empty($lngLatRange['maxLng']) || empty($lngLatRange['minLat']) || empty($lngLatRange['maxLat'])) {
  1078. return ['list' => [], 'count' => 0];
  1079. }
  1080. $count = db('crm_customer')->alias('customer')->where($customerWhere)->where($poolWhere)->where($lngLatWhere)->count();
  1081. $list = db('crm_customer')->alias('customer')
  1082. ->where($customerWhere)
  1083. ->where($poolWhere)
  1084. ->where($lngLatWhere)
  1085. // ->where($authMap)
  1086. ->field(['customer_id', 'name', 'address', 'detail_address', 'owner_user_id', 'lat', 'lng'])
  1087. ->order('update_time', 'desc')
  1088. ->select();
  1089. # 组装数据
  1090. foreach ($list as $key => $value) {
  1091. # todo 暂时将查询写在循环中
  1092. $ownerUserInfo = !empty($value['owner_user_id']) ? $userModel->getUserById($value['owner_user_id']) : [];
  1093. $ownerUserName = !empty($ownerUserInfo['realname']) ? $ownerUserInfo['realname'] : '';
  1094. $list[$key]['owner_user_name'] = $ownerUserName;
  1095. $list[$key]['distance'] = $this->getLngLatDistance($param['lng'], $param['lat'], $value['lng'], $value['lat'], 1, 0);
  1096. }
  1097. return ['list' => $list, 'count' => $count];
  1098. }
  1099. /**
  1100. * 计算两点地理坐标之间的距离
  1101. *
  1102. * @param number $longitude1 起点经度
  1103. * @param number $latitude1 起点纬度
  1104. * @param number $longitude2 终点经度
  1105. * @param number $latitude2 终点纬度
  1106. * @param int $unit 单位:1米;2公里
  1107. * @param int $decimal 精度:保留小数位数
  1108. * @return float
  1109. */
  1110. private function getLngLatDistance($longitude1, $latitude1, $longitude2, $latitude2, $unit=2, $decimal=2)
  1111. {
  1112. $EARTH_RADIUS = 6370.996; // 地球半径系数
  1113. $PI = 3.1415926;
  1114. $radLat1 = $latitude1 * $PI / 180.0;
  1115. $radLat2 = $latitude2 * $PI / 180.0;
  1116. $radLng1 = $longitude1 * $PI / 180.0;
  1117. $radLng2 = $longitude2 * $PI /180.0;
  1118. $a = $radLat1 - $radLat2;
  1119. $b = $radLng1 - $radLng2;
  1120. $distance = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));
  1121. $distance = $distance * $EARTH_RADIUS * 1000;
  1122. if( $unit==2 ) $distance = $distance / 1000;
  1123. return round($distance, $decimal);
  1124. }
  1125. /**
  1126. * 获取经纬度范围值
  1127. *
  1128. * @param $myLng
  1129. * @param $myLat
  1130. * @param $distance
  1131. * @return array
  1132. */
  1133. private function getLngLatRange($myLng, $myLat, $distance)
  1134. {
  1135. $pi = pi();
  1136. # 公里
  1137. $distance = $distance / 1000;
  1138. # 计算纬度区间
  1139. $latRange = 180 / $pi * $distance / 6372.797;
  1140. # 计算进度区间
  1141. $lngRang = $latRange / cos($myLat * $pi / 180);
  1142. $maxLng = $myLng + $lngRang; # 最大经度
  1143. $minLng = $myLng - $lngRang; # 最小经度
  1144. $maxLat = $myLat + $latRange; # 最大纬度
  1145. $minLat = $myLat - $latRange; # 最小纬度
  1146. return ['maxLng' => $maxLng, 'minLng' => $minLng, 'maxLat' => $maxLat, 'minLat' => $minLat];
  1147. }
  1148. /**
  1149. * 获取系统信息
  1150. *
  1151. * @param $id
  1152. * @return array
  1153. * @throws \think\db\exception\DataNotFoundException
  1154. * @throws \think\db\exception\ModelNotFoundException
  1155. * @throws \think\exception\DbException
  1156. */
  1157. public function getSystemInfo($id)
  1158. {
  1159. # 客户
  1160. $field = ['obtain_time', 'deal_status', 'create_time', 'update_time', 'create_time'];
  1161. $customer = Db::name('crm_customer')->field($field)->where('customer_id', $id)->find();
  1162. # 创建人
  1163. $realname = Db::name('admin_user')->where('id', $customer['create_user_id'])->value('realname');
  1164. # 最后跟进时间
  1165. $follow = Db::name('crm_activity')->field(['content', 'update_time'])->where(['type' => 1, 'activity_type' => 2, 'activity_type_id' => $id])->order('activity_id', 'desc')->find();
  1166. return [
  1167. 'obtain_time' => !empty($customer['obtain_time']) ? date('Y-m-d H:i:s', $customer['obtain_time']) : '',
  1168. 'follow_record' => !empty($follow['content']) ? $follow['content'] : '',
  1169. 'create_user_name' => $realname,
  1170. 'create_time' => date('Y-m-d H:i:s', $customer['create_time']),
  1171. 'update_time' => date('Y-m-d H:i:s', $customer['update_time']),
  1172. 'follow_time' => !empty($follow['update_time']) ? date('Y-m-d H:i:s', $follow['update_time']) : '',
  1173. 'deal_status' => $customer['deal_status']
  1174. ];
  1175. }
  1176. /**
  1177. * 判断联系人详情权限 todo 商机模块也在用,以后抽成一个公共的方法
  1178. *
  1179. * @param $contactsId
  1180. * @return bool
  1181. */
  1182. private function getContactsAuth($contactsId)
  1183. {
  1184. $ownerUserId = db('crm_contacts')->where('contacts_id', $contactsId)->value('owner_user_id');
  1185. $authUserIds = (new \app\admin\model\User())->getUserByPer('crm', 'contacts', 'read');
  1186. return in_array($ownerUserId, $authUserIds);
  1187. }
  1188. }