Customer.php 68KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618
  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 app\admin\model\User;
  10. use think\Db;
  11. use app\admin\model\Common;
  12. use app\admin\model\User as UserModel;
  13. use app\admin\model\Record as RecordModel;
  14. use think\Request;
  15. use think\response\Json;
  16. use think\Validate;
  17. class Customer extends Common
  18. {
  19. /**
  20. * 为了数据库的整洁,同时又不影响Model和Controller的名称
  21. * 我们约定每个模块的数据表都加上相同的前缀,比如CRM模块用crm作为数据表前缀
  22. */
  23. protected $name = 'crm_customer';
  24. protected $createTime = 'create_time';
  25. protected $updateTime = 'update_time';
  26. protected $autoWriteTimestamp = true;
  27. protected $type = [
  28. // 'next_time' => 'timestamp',
  29. ];
  30. public static $address = [
  31. '北京', '上海', '天津', '广东', '浙江', '海南', '福建', '湖南',
  32. '湖北', '重庆', '辽宁', '吉林', '黑龙江', '河北', '河南', '山东',
  33. '陕西', '甘肃', '青海', '新疆', '山西', '四川', '贵州', '安徽',
  34. '江西', '江苏', '云南', '内蒙古', '广西', '西藏', '宁夏'
  35. ];
  36. /**
  37. * [getDataList 客户list]
  38. * @author Michael_xu
  39. * @param [string] $map [查询条件]
  40. * @param [number] $page [当前页数]
  41. * @param [number] $limit [每页数量]
  42. * @return [array] [description]
  43. */
  44. public function getDataList($request)
  45. {
  46. $userModel = new \app\admin\model\User();
  47. $structureModel = new \app\admin\model\Structure();
  48. $fieldModel = new \app\admin\model\Field();
  49. $search = $request['search'];
  50. $user_id = $request['user_id'];
  51. $scene_id = (int)$request['scene_id'];
  52. $is_excel = $request['is_excel']; //导出
  53. $action = $request['action'];
  54. $order_field = $request['order_field'];
  55. $order_type = $request['order_type'];
  56. $is_remind = $request['is_remind'];
  57. $getCount = $request['getCount'];
  58. $otherMap = $request['otherMap'];
  59. unset($request['poolId']);
  60. //需要过滤的参数
  61. $unsetRequest = ['scene_id','search','user_id','is_excel','action','order_field','order_type','is_remind','getCount','type','otherMap'];
  62. foreach ($unsetRequest as $v) {
  63. unset($request[$v]);
  64. }
  65. $request = $this->fmtRequest( $request );
  66. $requestMap = $request['map'] ? : [];
  67. $sceneModel = new \app\admin\model\Scene();
  68. # 默认条件
  69. $customerMap = $this->getWhereByCustomer();
  70. # getCount是代办事项传来的参数,代办事项不需要使用场景
  71. $sceneMap = [];
  72. if (empty($getCount)) {
  73. if ($scene_id) {
  74. //自定义场景
  75. $sceneMap = $sceneModel->getDataById($scene_id, $user_id, 'customer') ? : [];
  76. } else {
  77. //默认场景
  78. $sceneMap = $sceneModel->getDefaultData('crm_customer', $user_id) ? : [];
  79. }
  80. }
  81. $searchMap = [];
  82. if ($search || $search == '0') {
  83. //普通筛选
  84. $searchMap = function($query) use ($search){
  85. $query->where('customer.name',array('like','%'.$search.'%'))
  86. ->whereOr('customer.mobile',array('like','%'.$search.'%'))
  87. ->whereOr('customer.telephone',array('like','%'.$search.'%'));
  88. };
  89. }
  90. //优先级:普通筛选>高级筛选>场景
  91. $map = [];
  92. $partMap = [];
  93. if (is_array($sceneMap)) {
  94. if ($sceneMap['ro_user_id'] && $sceneMap['rw_user_id']) {
  95. //相关团队查询
  96. $map = $requestMap;
  97. $partMap = function($query) use ($sceneMap){
  98. $query->where('FIND_IN_SET('.$sceneMap['ro_user_id'].', customer.ro_user_id)')
  99. ->whereOr('FIND_IN_SET('.$sceneMap['rw_user_id'].', customer.rw_user_id)');
  100. };
  101. } else {
  102. $map = $requestMap ? array_merge($sceneMap, $requestMap) : $sceneMap;
  103. }
  104. }
  105. //高级筛选
  106. $map = where_arr($map, 'crm', 'customer', 'index');
  107. //工作台仪表盘
  108. $requestData = $this->requestData();
  109. $dashboardWhere = [];
  110. if ($requestData['a'] == 'indexlist' && $requestData['c'] == 'index') {
  111. $dashboardWhere = function ($query) use ($requestMap) {
  112. $query->where('customer.create_time', array('between', [$requestMap['create_time']['start'],$requestMap['create_time']['end']]))
  113. ->whereOr('customer.obtain_time', array('between', [$requestMap['create_time']['start'],$requestMap['create_time']['end']]));
  114. };
  115. unset($map['customer.create_time']);
  116. }
  117. //权限
  118. $authMap = [];
  119. $auth_user_ids = [];
  120. if (!$partMap) {
  121. $a = 'index';
  122. if ($is_excel) $a = 'excelExport';
  123. $auth_user_ids = $userModel->getUserByPer('crm', 'customer', $a);
  124. //过滤权限
  125. if (isset($map['customer.owner_user_id']) && $map['customer.owner_user_id'][0] != 'like') {
  126. if (!is_array($map['customer.owner_user_id'][1])) {
  127. $map['customer.owner_user_id'][1] = [$map['customer.owner_user_id'][1]];
  128. }
  129. if (in_array($map['customer.owner_user_id'][0], ['neq', 'notin'])) {
  130. $auth_user_ids = array_diff($auth_user_ids, $map['customer.owner_user_id'][1]) ? : []; //取差集
  131. } else {
  132. $auth_user_ids = array_intersect($map['customer.owner_user_id'][1], $auth_user_ids) ? : []; //取交集
  133. }
  134. unset($map['customer.owner_user_id']);
  135. $auth_user_ids = array_merge(array_unique(array_filter($auth_user_ids))) ? : ['-1'];
  136. //负责人、相关团队
  137. $authMap['customer.owner_user_id'] = array('in',$auth_user_ids);
  138. } else {
  139. $authMapData = [];
  140. $authMapData['auth_user_ids'] = $auth_user_ids;
  141. $authMapData['user_id'] = $user_id;
  142. $authMap = function($query) use ($authMapData){
  143. $query->where(['customer.owner_user_id' => array('in',$authMapData['auth_user_ids'])])
  144. ->whereOr(function ($query) use ($authMapData) {
  145. $query->where('FIND_IN_SET("'.$authMapData['user_id'].'", customer.ro_user_id)')->where(['customer.owner_user_id' => array('neq','')]);
  146. })
  147. ->whereOr(function ($query) use ($authMapData) {
  148. $query->where('FIND_IN_SET("'.$authMapData['user_id'].'", customer.rw_user_id)')->where(['customer.owner_user_id' => array('neq','')]);
  149. });
  150. };
  151. }
  152. }
  153. # 代办事项 - 待进入公海
  154. $remindWhere = [];
  155. if ($is_remind) {
  156. $userIds = getSubUserId(false, 0, $user_id);
  157. $userIds[] = $user_id;
  158. $poolDays = $this->getPoolDay([], $userIds);
  159. $remindWhere['customer.customer_id'] = ['in', array_keys($poolDays)];
  160. if ($getCount == 1) return ['dataCount' => count($poolDays)];
  161. }
  162. $dataCount = db('crm_customer')->alias('customer')
  163. ->where($map)
  164. ->where($dashboardWhere)
  165. ->where($searchMap)
  166. ->where($customerMap)
  167. ->where($authMap)
  168. ->where($partMap)
  169. ->where($otherMap)
  170. ->where($remindWhere)
  171. ->count();
  172. if ($getCount == 1) {
  173. $data['dataCount'] = $dataCount ? : 0;
  174. return $data;
  175. }
  176. //列表展示字段
  177. $indexField = $fieldModel->getIndexField('crm_customer', $user_id, 1) ? : array('name');
  178. $userField = $fieldModel->getFieldByFormType('crm_customer', 'user'); //人员类型
  179. $structureField = $fieldModel->getFieldByFormType('crm_customer', 'structure'); //部门类型
  180. $datetimeField = $fieldModel->getFieldByFormType('crm_customer', 'datetime'); //日期时间类型
  181. # 处理人员和部门类型的排序报错问题(前端传来的是包含_name的别名字段)
  182. $temporaryField = str_replace('_name', '', $order_field);
  183. if (in_array($temporaryField, $userField) || in_array($temporaryField, $structureField)) {
  184. $order_field = $temporaryField;
  185. }
  186. //排序
  187. if ($order_type && $order_field) {
  188. $order = $fieldModel->getOrderByFormtype('crm_customer','customer',$order_field,$order_type);
  189. } else {
  190. $order = 'customer.update_time desc';
  191. }
  192. $list = db('crm_customer')->alias('customer')
  193. ->where($map)
  194. ->where($dashboardWhere)
  195. ->where($searchMap)
  196. ->where($customerMap)
  197. ->where($authMap)
  198. ->where($partMap)
  199. ->where($otherMap)
  200. ->where($remindWhere)
  201. ->limit($request['offset'], $request['length'])
  202. ->field($indexField)
  203. ->orderRaw($order)
  204. ->select();
  205. # 查询公海数据的条件
  206. $poolWhere = [];
  207. $readAuthIds = $userModel->getUserByPer('crm', 'customer', 'read');
  208. $updateAuthIds = $userModel->getUserByPer('crm', 'customer', 'update');
  209. $deleteAuthIds = $userModel->getUserByPer('crm', 'customer', 'delete');
  210. if (!empty($list)) {
  211. $customer_id_list = array_column($list, 'customer_id');
  212. $business_count = db('crm_business')
  213. ->field([
  214. 'COUNT(*)' => 'count',
  215. 'customer_id'
  216. ])
  217. ->where([
  218. 'customer_id' => ['IN', $customer_id_list]
  219. ])
  220. ->group('customer_id')
  221. ->select();
  222. $business_count = array_column($business_count, null, 'customer_id');
  223. $field_list = $fieldModel->getIndexFieldConfig('crm_customer', $user_id);
  224. $field_list = array_column($field_list, 'field');
  225. foreach ($list as $k => $v) {
  226. $list[$k]['create_user_id_info'] = isset($v['create_user_id']) ? $userModel->getUserById($v['create_user_id']) : [];
  227. $list[$k]['owner_user_id_info'] = isset($v['owner_user_id']) ? $userModel->getUserById($v['owner_user_id']) : [];
  228. $list[$k]['create_user_name'] = !empty($list[$k]['create_user_id_info']['realname']) ? $list[$k]['create_user_id_info']['realname'] : '';
  229. $list[$k]['owner_user_name'] = !empty($list[$k]['owner_user_id_info']['realname']) ? $list[$k]['owner_user_id_info']['realname'] : '';
  230. foreach ($userField as $key => $val) {
  231. if (in_array($val, $field_list)) {
  232. $usernameField = !empty($v[$val]) ? db('admin_user')->whereIn('id', stringToArray($v[$val]))->column('realname') : [];
  233. $list[$k][$val.'_name'] = implode($usernameField, ',');
  234. }
  235. }
  236. foreach ($structureField as $key => $val) {
  237. if (in_array($val, $field_list)) {
  238. $structureNameField = !empty($v[$val]) ? db('admin_structure')->whereIn('id', stringToArray($v[$val]))->column('name') : [];
  239. $list[$k][$val.'_name'] = implode($structureNameField, ',');
  240. }
  241. }
  242. foreach ($datetimeField as $key => $val) {
  243. $list[$k][$val] = !empty($v[$val]) ? date('Y-m-d H:i:s', $v[$val]) : null;
  244. }
  245. //商机数
  246. $list[$k]['business_count'] = $business_count[$v['customer_id']]['count'] ?: 0;
  247. //权限
  248. $roPre = $userModel->rwPre($user_id, $v['ro_user_id'], $v['rw_user_id'], 'read');
  249. $rwPre = $userModel->rwPre($user_id, $v['ro_user_id'], $v['rw_user_id'], 'update');
  250. $permission = [];
  251. $is_read = 0;
  252. $is_update = 0;
  253. $is_delete = 0;
  254. if (in_array($v['owner_user_id'],$readAuthIds) || $roPre || $rwPre) $is_read = 1;
  255. if (in_array($v['owner_user_id'],$updateAuthIds) || $rwPre) $is_update = 1;
  256. if (in_array($v['owner_user_id'],$deleteAuthIds)) $is_delete = 1;
  257. $permission['is_read'] = $is_read;
  258. $permission['is_update'] = $is_update;
  259. $permission['is_delete'] = $is_delete;
  260. $list[$k]['permission'] = $permission;
  261. # 关注
  262. $starWhere = ['user_id' => $user_id, 'target_id' => $v['customer_id'], 'type' => 'crm_customer'];
  263. $star = Db::name('crm_star')->where($starWhere)->value('star_id');
  264. $list[$k]['star'] = !empty($star) ? 1 : 0;
  265. # 日期
  266. $list[$k]['create_time'] = !empty($v['create_time']) ? date('Y-m-d H:i:s', $v['create_time']) : null;
  267. $list[$k]['update_time'] = !empty($v['update_time']) ? date('Y-m-d H:i:s', $v['update_time']) : null;
  268. $list[$k]['last_time'] = !empty($v['last_time']) ? date('Y-m-d H:i:s', $v['last_time']) : null;
  269. //查询公海数据的条件
  270. $poolWhere[] = $v['customer_id'];
  271. $list[$k]['pool_day'] = '';
  272. $list[$k]['is_pool'] = 0;
  273. }
  274. # 获取公海天数
  275. $poolDays = !empty($poolWhere) ? $this->getPoolDay($poolWhere) : [];
  276. if (!empty($poolDays)) {
  277. foreach ($list AS $key => $value) {
  278. $list[$key]['pool_day'] = isset($poolDays[$value['customer_id']]) ? $poolDays[$value['customer_id']] : '';
  279. }
  280. }
  281. }
  282. $data = [];
  283. $data['list'] = $list ? : [];
  284. $data['dataCount'] = $dataCount ? : 0;
  285. return $data;
  286. }
  287. /**
  288. * 创建客户主表信息
  289. * @author Michael_xu
  290. * @param
  291. * @return
  292. */
  293. public function createData($param)
  294. {
  295. $fieldModel = new \app\admin\model\Field();
  296. $userModel = new \app\admin\model\User();
  297. $customerConfigModel = new \app\crm\model\CustomerConfig();
  298. //添加上限检测
  299. if (!$customerConfigModel->checkData($param['create_user_id'],1)) {
  300. $this->error = $customerConfigModel->getError();
  301. return false;
  302. }
  303. // 获取客户时间
  304. $param['obtain_time'] = time();
  305. //地址
  306. $param['address'] = $param['address'] ? implode(chr(10),$param['address']) : '';
  307. $param['deal_time'] = time(); //领取、分配时间
  308. $param['deal_status'] = '未成交';
  309. //线索转客户
  310. if ($param['leads_id']) {
  311. $leadsData = $param;
  312. $leadsData['create_user_id'] = $param['create_user_id'];
  313. $leadsData['owner_user_id'] = $param['owner_user_id'];
  314. $leadsData['ro_user_id'] = '';
  315. $leadsData['rw_user_id'] = '';
  316. $leadsData['detail_address'] = $param['detail_address'] ? : '';
  317. $param = $leadsData;
  318. }
  319. // 自动验证
  320. $validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
  321. $validate = new Validate($validateArr['rule'], $validateArr['message']);
  322. $result = $validate->check($param);
  323. if (!$result) {
  324. $this->error = $validate->getError();
  325. return false;
  326. }
  327. unset($param['customer_id']);
  328. // 处理部门、员工、附件、多选类型字段
  329. $arrFieldAtt = $fieldModel->getArrayField('crm_customer');
  330. foreach ($arrFieldAtt as $k=>$v) {
  331. $param[$v] = arrayToString($param[$v]);
  332. }
  333. // 处理日期(date)类型
  334. $dateField = $fieldModel->getFieldByFormType('crm_customer', 'date');
  335. if (!empty($dateField)) {
  336. foreach ($param AS $key => $value) {
  337. if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
  338. }
  339. }
  340. # 设置今日需联系客户
  341. if (!empty($param['next_time']) && $param['next_time'] >= strtotime(date('Y-m-d 00:00:00'))) $param['is_dealt'] = 0;
  342. if ($this->data($param)->allowField(true)->isUpdate(false)->save()) {
  343. if(!empty($param['pool_id'])){
  344. db('crm_customer_pool_relation') ->insertGetId(['pool_id'=>$param['pool_id'],'customer_id'=>$this->customer_id]);
  345. }
  346. //修改记录
  347. if(empty($param['leads_id'])){
  348. updateActionLog($param['create_user_id'], 'crm_customer', $this->customer_id, '', '', '创建了客户');
  349. RecordActionLog($param['create_user_id'],'crm_customer','save',$param['name'],'','','新增了客户'.$param['name']);
  350. }
  351. $data = [];
  352. $data['customer_id'] = $this->customer_id;
  353. $data['name'] = $param['name'];
  354. # 添加活动记录
  355. Db::name('crm_activity')->insert([
  356. 'type' => 2,
  357. 'activity_type' => 2,
  358. 'activity_type_id' => $data['customer_id'],
  359. 'content' => $data['name'],
  360. 'create_user_id' => $param['create_user_id'],
  361. 'update_time' => time(),
  362. 'create_time' => time()
  363. ]);
  364. return $data;
  365. } else {
  366. $this->error = '添加失败';
  367. return false;
  368. }
  369. }
  370. //根据IDs获取数组
  371. public function getDataByStr($idstr)
  372. {
  373. $idArr = stringToArray($idstr);
  374. if (!$idArr) {
  375. return [];
  376. }
  377. $list = db('crm_customer')->where(['customer_id' => ['in',$idArr]])->select();
  378. return $list;
  379. }
  380. /**
  381. * 编辑客户主表信息
  382. * @author Michael_xu
  383. * @param
  384. * @return
  385. */
  386. public function updateDataById($param, $customer_id = '')
  387. {
  388. $user_id = $param['user_id'];
  389. $dataInfo = $this->get($customer_id);
  390. if (!$dataInfo) {
  391. $this->error = '数据不存在或已删除';
  392. return false;
  393. }
  394. $id = $param['id']?:$customer_id;
  395. //数据权限判断
  396. $userModel = new \app\admin\model\User();
  397. $auth_user_ids = $userModel->getUserByPer('crm', 'customer', 'update');
  398. //读写权限
  399. $rwPre = $userModel->rwPre($user_id, $dataInfo['ro_user_id'], $dataInfo['rw_user_id'], 'update');
  400. //判断是否客户池数据
  401. if(empty($param['pool_id'])){
  402. $wherePool = $this->getWhereByPool();
  403. $resPool = db('crm_customer')->alias('customer')->where(['customer_id' => $id])->where($wherePool)->find();
  404. if ($resPool || (!in_array($dataInfo['owner_user_id'],$auth_user_ids) && !$rwPre)) {
  405. $this->error = '无权操作';
  406. return false;
  407. }
  408. }
  409. $param['customer_id'] = $customer_id;
  410. //过滤不能修改的字段
  411. $unUpdateField = ['create_user_id','is_deleted','delete_time','user_id'];
  412. foreach ($unUpdateField as $v) {
  413. unset($param[$v]);
  414. }
  415. $param['deal_status'] = $dataInfo['deal_status'];
  416. $fieldModel = new \app\admin\model\Field();
  417. // 自动验证
  418. // $validateArr = $fieldModel->validateField($this->name); //获取自定义字段验证规则
  419. $validateArr = $fieldModel->validateField($this->name, 0, 'update'); //获取自定义字段验证规则
  420. $validate = new Validate($validateArr['rule'], $validateArr['message']);
  421. $result = $validate->check($param);
  422. if (!$result) {
  423. $this->error = $validate->getError();
  424. return false;
  425. }
  426. //地址
  427. $param['address'] = $param['address'] ? implode(chr(10),$param['address']) : '';
  428. if ($param['deal_status'] == '已成交' && $dataInfo->data['deal_status'] == '未成交') {
  429. $param['deal_time'] = time();
  430. }
  431. // 处理部门、员工、附件、多选类型字段
  432. $arrFieldAtt = $fieldModel->getArrayField('crm_customer');
  433. foreach ($arrFieldAtt as $k=>$v) {
  434. if (isset($param[$v])) $param[$v] = arrayToString($param[$v]);
  435. }
  436. // 处理日期(date)类型
  437. $dateField = $fieldModel->getFieldByFormType('crm_customer', 'date');
  438. if (!empty($dateField)) {
  439. foreach ($param AS $key => $value) {
  440. if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
  441. }
  442. }
  443. # 设置今日需联系客户
  444. if (!empty($param['next_time']) && $param['next_time'] >= strtotime(date('Y-m-d 00:00:00'))) $param['is_dealt'] = 0;
  445. if ($this->update($param, ['customer_id' => $customer_id], true)) {
  446. if(!empty($param['pool_id'])){
  447. db('crm_customer_pool_relation')->where('customer_id',$customer_id) ->update(['pool_id'=>$param['pool_id']]);
  448. }
  449. //修改记录
  450. updateActionLog($user_id, 'crm_customer', $customer_id, $dataInfo->data, $param);
  451. RecordActionLog($user_id, 'crm_customer', 'update',$dataInfo['name'], $dataInfo->data, $param);
  452. $data = [];
  453. $data['customer_id'] = $customer_id;
  454. return $data;
  455. } else {
  456. $this->error = '编辑失败';
  457. return false;
  458. }
  459. }
  460. /**
  461. * 客户数据
  462. *
  463. * @param string $id
  464. * @param int $userId
  465. * @return Common|array|bool|\PDOStatement|string|\think\Model|null
  466. * @throws \think\db\exception\DataNotFoundException
  467. * @throws \think\db\exception\ModelNotFoundException
  468. * @throws \think\exception\DbException
  469. */
  470. public function getDataById($id = '', $userId = 0)
  471. {
  472. $dataInfo = db('crm_customer')->where(['customer_id' => $id])->find();
  473. if (!$dataInfo) {
  474. $this->error = '数据不存在或已删除';
  475. return false;
  476. }
  477. $userModel = new \app\admin\model\User();
  478. $dataInfo['create_user_id_info'] = isset($dataInfo['create_user_id']) ? $userModel->getUserById($dataInfo['create_user_id']) : [];
  479. $dataInfo['owner_user_id_info'] = !empty($dataInfo['owner_user_id']) ? $userModel->getUserById($dataInfo['owner_user_id']) : [];
  480. $dataInfo['before_owner_user_id_info'] = !empty($dataInfo['before_owner_user_id']) ? $userModel->getUserById($dataInfo['before_owner_user_id']) : [];
  481. $dataInfo['create_user_name'] = !empty($dataInfo['create_user_id_info']['realname']) ? $dataInfo['create_user_id_info']['realname'] : '';
  482. $dataInfo['owner_user_name'] = !empty($dataInfo['owner_user_id_info']['realname']) ? $dataInfo['owner_user_id_info']['realname'] : '';
  483. $dataInfo['before_owner_user_name'] = !empty($dataInfo['before_owner_user_id_info']['realname']) ? $dataInfo['before_owner_user_id_info']['realname'] : '';
  484. # 公海信息
  485. $poolData = $this->getPoolDay([$id]);
  486. $dataInfo['pool_day'] = !empty($poolData[$id]) ? $poolData[$id] : '';
  487. $dataInfo['is_pool'] = !empty($dataInfo['owner_user_id']) ? 0 : 1;
  488. # 关注
  489. $starId = empty($userId) ? 0 : Db::name('crm_star')->where(['user_id' => $userId, 'target_id' => $id, 'type' => 'crm_customer'])->value('star_id');
  490. $dataInfo['star'] = !empty($starId) ? 1 : 0;
  491. # 首要联系人
  492. $primaryId = Db::name('crm_contacts')->where(['customer_id' => $id, 'primary' => 1])->value('contacts_id');
  493. $dataInfo['contacts_id'] = !empty($primaryId) && $this->getContactsAuth($primaryId) ? $primaryId : 0;
  494. # 处理时间格式
  495. $fieldModel = new \app\admin\model\Field();
  496. $datetimeField = $fieldModel->getFieldByFormType('crm_customer', 'datetime'); //日期时间类型
  497. foreach ($datetimeField as $key => $val) {
  498. $dataInfo[$val] = !empty($dataInfo[$val]) ? date('Y-m-d H:i:s', $dataInfo[$val]) : null;
  499. }
  500. $dataInfo['create_time'] = !empty($dataInfo['create_time']) ? date('Y-m-d H:i:s', $dataInfo['create_time']) : null;
  501. $dataInfo['update_time'] = !empty($dataInfo['update_time']) ? date('Y-m-d H:i:s', $dataInfo['update_time']) : null;
  502. $dataInfo['last_time'] = !empty($dataInfo['last_time']) ? date('Y-m-d H:i:s', $dataInfo['last_time']) : null;
  503. $dataInfo['into_pool_time'] = !empty($dataInfo['into_pool_time']) ? date('Y-m-d H:i:s', $dataInfo['into_pool_time']) : null;
  504. // 字段授权
  505. if (!empty($userId)) {
  506. $grantData = getFieldGrantData($userId);
  507. $userLevel = isSuperAdministrators($userId);
  508. foreach ($dataInfo AS $key => $value) {
  509. if (!$userLevel && !empty($grantData['crm_customer'])) {
  510. $status = getFieldGrantStatus($key, $grantData['crm_customer']);
  511. # 查看权限
  512. if ($status['read'] == 0) unset($dataInfo[$key]);
  513. }
  514. }
  515. }
  516. return $dataInfo;
  517. }
  518. /**
  519. * [客户统计]
  520. * @author Michael_xu
  521. * @param
  522. * @return
  523. */
  524. public function getStatistics($request)
  525. {
  526. $userModel = new \app\admin\model\User();
  527. $adminModel = new \app\admin\model\Admin();
  528. $request['start_time']=strtotime($request['start_time']);
  529. $request['end_time']=strtotime($request['end_time']);
  530. $perUserIds = $userModel->getUserByPer('bi', 'customer', 'read'); //权限范围内userIds
  531. $whereArr = $adminModel->getWhere($request, '', $perUserIds); //统计条件
  532. $userIds = $whereArr['userIds'];
  533. $request = $this->fmtRequest( $request );
  534. $map = $request['map'] ? : [];
  535. unset($map['search']);
  536. $where = [];
  537. //时间段
  538. $start_time = $map['start_time'];
  539. $end_time = $map['end_time'] ? $map['end_time'] : time();
  540. if ($start_time && $end_time) {
  541. $start_date = date('Y-m-d',$start_time);
  542. $end_date = date('Y-m-d',$end_time);
  543. $where_time = " BETWEEN {$start_time} AND {$end_time} ";
  544. $where_date = " BETWEEN '{$start_date}' AND '{$end_date}' ";
  545. } else {
  546. $where_time = " > 0 ";
  547. $where_date = " != '' ";
  548. }
  549. //员工IDS
  550. $map_user_ids = [];
  551. if (!empty($map['user_id'])) {
  552. $map_user_ids = array($map['user_id']);
  553. } elseif (!empty($map['structure_id'])) {
  554. $map_user_ids = $userModel->getSubUserByStr($map['structure_id'], 2);
  555. }
  556. $prefix = config('database.prefix');
  557. $count = count($userIds);
  558. $configModel = new \app\crm\model\ConfigData();
  559. $configInfo = $configModel->getData();
  560. $follow_day = $configInfo['follow_day'] ? : 0;
  561. $deal_day = $configInfo['deal_day'] ? : 0;
  562. //默认公海条件(没有负责人或已经到期)
  563. $data['follow_time'] = time()-$follow_day*86400;
  564. $data['deal_time'] = time()-$deal_day*86400;
  565. $data['deal_status'] = '未成交';
  566. $sql = '';
  567. foreach ($userIds as $key => $user_id) {
  568. $sql .= "
  569. SELECT
  570. (SELECT realname FROM {$prefix}admin_user WHERE id = {$user_id}) as realname,
  571. COUNT(cu.customer_id) AS customer_num,
  572. SUM(cu.deal_status = '已成交') AS deal_customer_num,
  573. IFNULL(
  574. (SELECT SUM(money) FROM {$prefix}crm_contract WHERE
  575. owner_user_id = {$user_id}
  576. AND order_date {$where_date}
  577. AND check_status = 2
  578. ),
  579. 0
  580. ) as contract_money,
  581. IFNULL(
  582. (SELECT SUM(money) FROM {$prefix}crm_receivables WHERE
  583. owner_user_id = {$user_id}
  584. AND return_time {$where_date}
  585. AND check_status = 2
  586. ),
  587. 0
  588. ) as receivables_money
  589. FROM
  590. {$prefix}crm_customer as cu
  591. WHERE
  592. (cu.create_time {$where_time} OR obtain_time {$where_time})
  593. AND cu.owner_user_id = {$user_id}
  594. AND (( ( deal_time > ".$data['deal_time']." ) OR (update_time > ".$data['follow_time']." AND deal_time > ".$data['deal_time']."))OR deal_status = '已成交' OR is_lock = 1 )
  595. ";
  596. if ($count > 1 && $key != $count - 1) {
  597. $sql .= " UNION ALL ";
  598. }
  599. }
  600. if ($sql == '') {
  601. return [];
  602. }
  603. $customerCount = 0; # 客户总数
  604. $dealCustomerCount = 0; # 成交客户总数
  605. $contractMoneyCount = 0; # 合同总金额
  606. $receivablesMoneyCount = 0; # 回款总金额
  607. $list = queryCache($sql);
  608. foreach ($list as &$val) {
  609. $val['deal_customer_num'] = Floor($val['deal_customer_num']);
  610. $val['contract_money'] = Floor($val['contract_money']);
  611. $val['receivables_money'] = Floor($val['receivables_money']);
  612. $val['deal_customer_rate'] = $val['customer_num'] ? round(($val['deal_customer_num'] / $val['customer_num']) * 100, 2) : 0;
  613. $val['un_receivables_money'] = $val['contract_money'] - $val['receivables_money'] >= 0 ? $val['contract_money'] - $val['receivables_money'] : '0.00';
  614. $val['deal_receivables_rate'] = $val['contract_money'] ? round(($val['receivables_money'] / $val['contract_money']) * 100, 2) : 0;
  615. $customerCount += $val['customer_num'];
  616. $dealCustomerCount += $val['deal_customer_num'];
  617. $contractMoneyCount += $val['contract_money'];
  618. $receivablesMoneyCount += $val['receivables_money'];
  619. }
  620. return ['list' => $list, 'total' => [
  621. 'realname' => '总计',
  622. 'customer_num' => $customerCount,
  623. 'deal_customer_num' => $dealCustomerCount,
  624. 'contract_money' => $contractMoneyCount,
  625. 'receivables_money' => $receivablesMoneyCount
  626. ]];
  627. }
  628. /**
  629. * [客户数量]
  630. * @author Michael_xu
  631. * @param
  632. * @return
  633. */
  634. public function getDataCount($map)
  635. {
  636. $dataCount = $this->where($map)->fetchSql(false)->count();
  637. $count = $dataCount ? : 0;
  638. return $count;
  639. }
  640. /**
  641. * [客户默认条件]
  642. * @author Michael_xu
  643. * @param
  644. * @return
  645. */
  646. public function getWhereByCustomer()
  647. {
  648. return ['customer.owner_user_id' => ['neq', 0]];
  649. // $configModel = new \app\crm\model\ConfigData();
  650. // $userModel = new \app\admin\model\User();
  651. // $configInfo = $configModel->getData();
  652. // $config = $configInfo['config'] ? : 0;
  653. // $follow_day = $configInfo['follow_day'] ? : 0;
  654. // $deal_day = $configInfo['deal_day'] ? : 0;
  655. // //默认条件(没有到期或已锁定)
  656. // $data['follow_time'] = time()-$follow_day*86400;
  657. // $data['deal_time'] = time()-$deal_day*86400;
  658. // if ($config == 1) {
  659. // if ($follow_day < $deal_day) {
  660. // $whereData = function($query) use ($data){
  661. // $query->where(function ($query) use ($data) {
  662. // $query->where(['customer.update_time' => array('gt',$data['follow_time']),'customer.deal_time' => array('gt',$data['deal_time'])]);
  663. // })
  664. // ->whereOr(['customer.deal_status' => '已成交'])
  665. // ->whereOr(['customer.is_lock' => 1]);
  666. // };
  667. // } else {
  668. // $whereData = function($query) use ($data){
  669. // $query->where(function ($query) use ($data) {
  670. // $query->where(['customer.deal_time' => array('gt',$data['deal_time'])]);
  671. // })
  672. // ->whereOr(['customer.deal_status' => '已成交'])
  673. // ->whereOr(['customer.is_lock' => 1]);
  674. // };
  675. // }
  676. // }
  677. // return $whereData ? : '';
  678. }
  679. /**
  680. * [客户公海条件]
  681. * @author Michael_xu
  682. * @param
  683. * @return
  684. */
  685. public function getWhereByPool()
  686. {
  687. // $configModel = new \app\crm\model\ConfigData();
  688. // $configInfo = $configModel->getData();
  689. // $config = $configInfo['config'] ? : 0;
  690. // $follow_day = $configInfo['follow_day'] ? : 0;
  691. // $deal_day = $configInfo['deal_day'] ? : 0;
  692. // $whereData = [];
  693. // //启用
  694. // if ($config == 1) {
  695. // //默认公海条件(没有负责人或已经到期)
  696. // $data['follow_time'] = time()-$follow_day*86400;
  697. // $data['deal_time'] = time()-$deal_day*86400;
  698. // $data['deal_status'] = '未成交';
  699. // if ($follow_day < $deal_day) {
  700. // $whereData = function($query) use ($data){
  701. // $query->where(['customer.owner_user_id'=>0])
  702. // ->whereOr(function ($query) use ($data) {
  703. // $query->where(function ($query) use ($data) {
  704. // $query->where(['customer.update_time' => array('elt',$data['follow_time'])])
  705. // ->whereOr(['customer.deal_time' => array('elt',$data['deal_time'])]);
  706. // })
  707. // ->where(['customer.is_lock' => 0])
  708. // ->where(['customer.deal_status' => ['neq','已成交']]);
  709. // });
  710. // };
  711. // } else {
  712. // $whereData = function($query) use ($data){
  713. // $query->where(['customer.owner_user_id'=>0])
  714. // ->whereOr(function ($query) use ($data) {
  715. // $query->where(function ($query) use ($data) {
  716. // $query->where(['customer.deal_time' => array('elt',$data['deal_time'])]);
  717. // })
  718. // ->where(['customer.is_lock' => 0])
  719. // ->where(['customer.deal_status' => ['neq','已成交']]);
  720. // });
  721. // };
  722. // }
  723. // } else {
  724. $whereData['customer.owner_user_id'] = 0;
  725. // }
  726. return !empty($whereData) ? $whereData : '';
  727. }
  728. /**
  729. * 客户权限判断(是否客户公海)
  730. * @author Michael_xu
  731. * @param type 1 是公海返回false,默认是公海返回true
  732. * @return
  733. */
  734. public function checkData($customer_id, $type = '')
  735. {
  736. //权限范围
  737. $userModel = new \app\admin\model\User();
  738. $authIds = $userModel->getUserByPer(); //权限范围的user_id
  739. //是否客户公海
  740. $map = $this->getWhereByPool();
  741. $where['customer_id'] = $customer_id;
  742. $customerInfo = db('crm_customer')->alias('customer')->where($where)->where($map)->find();
  743. if ($customerInfo && !$type) {
  744. return true;
  745. } else {
  746. $customerInfo = db('crm_customer')->where(['customer_id' => $customer_id])->find();
  747. if (in_array($customerInfo['owner_user_id'], $authIds)) {
  748. return true;
  749. }
  750. }
  751. $this->error = '没有权限';
  752. return false;
  753. }
  754. /**
  755. * 客户到期天数
  756. *
  757. * @param array $customerIds 客户ID
  758. * @author fanqi
  759. * @since 2021-04-19
  760. * @return array
  761. */
  762. public function getPoolDay($customerIds = [], $userIds = [])
  763. {
  764. $result = [];
  765. $where['pool.status'] = 1; # 公海开启
  766. $where['pool.remind_conf'] = 1; # 提醒开启
  767. $poolRules = db('crm_customer_pool_rule')->alias('rule')->field(['rule.*', 'pool.remain_day'])->join('__CRM_CUSTOMER_POOL__ pool', 'rule.pool_id = pool.pool_id', 'LEFT')->where($where)->select();
  768. if (!empty($poolRules)) {
  769. foreach ($poolRules AS $key => $value) {
  770. if ($value['type'] == 1) $result[] = $this->getFollowUpQueryResult($value['level_conf'], $value['level'], $value['deal_handle'], $value['business_handle'], $value['remain_day'], $customerIds, $userIds);
  771. if ($value['type'] == 2) $result[] = $this->getBusinessQueryResult($value['level_conf'], $value['level'], $value['deal_handle'], $value['remain_day'], $customerIds, $userIds);
  772. if ($value['type'] == 3) $result[] = $this->getDealQueryResult($value['level_conf'], $value['level'], $value['business_handle'], $value['remain_day'], $customerIds, $userIds);
  773. }
  774. }
  775. return $this->getMinIntoPoolDay($result);
  776. }
  777. /**
  778. * 获取每个客户最快进入公海天数
  779. *
  780. * @param $data
  781. * @author fanqi
  782. * @since 2021-04-19
  783. * @return array
  784. */
  785. private function getMinIntoPoolDay($data)
  786. {
  787. $result = [];
  788. $temporary = [];
  789. # 整理数据
  790. foreach ($data AS $k1 => $v1) {
  791. if (empty($v1)) continue;
  792. foreach ($v1 AS $k2 => $v2) {
  793. $temporary[$k2][] = $v2;
  794. }
  795. }
  796. # 每个客户最快进入公海天数
  797. foreach ($temporary AS $k1 => $v1) {
  798. $result[$k1] = min($v1);
  799. }
  800. return $result;
  801. }
  802. /**
  803. * 获取公海规则最小数字(最快进入公海天数)
  804. *
  805. * @param $data
  806. * @author fanqi
  807. * @since 2021-04-19
  808. * @return int
  809. */
  810. private function getMinDay($data)
  811. {
  812. $number = 1;
  813. foreach ($data AS $k1 => $v1) {
  814. if (empty($number) || $v1['limit_day'] < $number) $number = $v1['limit_day'];
  815. }
  816. return $number;
  817. }
  818. /**
  819. * N天内无新建跟进记录的客户
  820. *
  821. * @param int $type 类型:1 所有用户,不分级别,2 根据用户级别区分
  822. * @param Json $levels 级别数据
  823. * @param int $dealStatus 是否排除成交用户:1 排除,0 不排除
  824. * @param int $businessStatus 是否排除有商机用户:1 排除,0 不排除
  825. * @param int $remainDay 提前几天提醒
  826. * @param array $customerIds 客户ID
  827. * @param array $userIds 员工ID
  828. * @author fanqi
  829. * @since 2021-04-01
  830. * @return array
  831. */
  832. private function getFollowUpQueryResult($type, $levels, $dealStatus, $businessStatus, $remainDay, $customerIds = [], $userIds = [])
  833. {
  834. # 结果数据
  835. $result = [];
  836. # 转换格式
  837. $levels = json_decode($levels, true);
  838. # 用于最后计算还有几天进入公海池
  839. $limitDay = [];
  840. # 数据权限
  841. $authUserIds = (new User())->getUserByPer('crm', 'customer', 'index');
  842. if (empty($authUserIds)) return $result;
  843. # 默认条件
  844. $where = "`customer`.`owner_user_id` IN (".implode(',', $authUserIds).")";
  845. # 所有用户,不区分级别
  846. if ($type == 1) {
  847. foreach ($levels AS $k1 => $v1) {
  848. if (!empty($v1['limit_day'])) {
  849. $time = strtotime(date('Y-m-d 00:00:00', time() - 86400 * $v1['limit_day']));
  850. $where .= " AND ((`customer`.`last_time` > ".$time." AND `customer`.`last_time` > `customer`.`obtain_time`) OR (`customer`.`obtain_time` > ".$time." AND `customer`.`obtain_time` > `customer`.`last_time`) OR (`customer`.`obtain_time` > ".$time." AND ISNULL(`customer`.`last_time`)))";
  851. $limitDay['all'] = $v1['limit_day'];
  852. }
  853. }
  854. }
  855. # 根据用户级别设置条件
  856. if ($type == 2) {
  857. foreach ($levels AS $k1 => $v1) {
  858. if (!empty($v1['level']) && !empty($v1['limit_day'])) {
  859. $time = strtotime(date('Y-m-d 00:00:00', time() - 86400 * $v1['limit_day']));
  860. if ($k1 == 0) {
  861. $where .= " AND ( ((`customer`.`level` = '".$v1['level']."' AND `customer`.`last_time` > " . $time . " AND `customer`.`last_time` > `customer`.`obtain_time`) OR (`customer`.`level` = '".$v1['level']."' AND `customer`.`obtain_time` > ".$time." AND `customer`.`obtain_time` > `customer`.`last_time`) OR (`customer`.`level` = '".$v1['level']."' AND `customer`.`obtain_time` > " . $time . " AND ISNULL(`customer`.`last_time`)))";
  862. } else {
  863. $where .= " OR ((`customer`.`level` = '".$v1['level']."' AND `customer`.`last_time` > " . $time . " AND `customer`.`last_time` > `customer`.`obtain_time`) OR (`customer`.`level` = '".$v1['level']."' AND `customer`.`obtain_time` > ".$time." AND `customer`.`obtain_time` > `customer`.`last_time`) OR (`customer`.`level` = '".$v1['level']."' AND `customer`.`obtain_time` > " . $time . " AND ISNULL(`customer`.`last_time`)))";
  864. }
  865. $limitDay[$v1['level']] = $v1['limit_day'];
  866. }
  867. }
  868. # 获取最小天数,对于没有设置级别的客户数据使用
  869. $minLimit = $this->getMinDay($levels);
  870. $minTime = strtotime(date('Y-m-d 00:00:00', time() - 86400 * $minLimit));
  871. $where .= " OR ((!`customer`.`level` AND `customer`.`last_time` > ".$minTime." AND `customer`.`last_time` > `customer`.`obtain_time`) OR (!`customer`.`level` AND `customer`.`obtain_time` > ".$time." AND `customer`.`obtain_time` > `customer`.`last_time`) OR (!`customer`.`level` AND `customer`.`obtain_time` > ".$minTime." AND ISNULL(`customer`.`last_time`))) )";
  872. }
  873. # 选择不进入公海的客户(已成交客户)
  874. if (!empty($dealStatus)) $where .= " AND (`customer`.`deal_status` <> '已成交' OR ISNULL(`customer`.`deal_status`))";
  875. # 选择不进入公海的客户(有商机客户)
  876. if (!empty($businessStatus)) $where .= " AND ISNULL(`business`.`customer_id`)";
  877. # 查询指定客户
  878. if (!empty($customerIds)) $where .= " AND `customer`.`customer_id` IN (".implode(',', $customerIds).")";
  879. # 查询指定员工
  880. if (!empty($userIds)) $where .= " AND `customer`.`owner_user_id` IN (".implode(',', $userIds).")";
  881. # 锁定的客户不提醒
  882. $where .= " AND `customer`.`is_lock` = 0";
  883. # 查询符合条件的客户
  884. $data = db('crm_customer')->alias('customer')
  885. ->field(['customer.customer_id', 'customer.obtain_time', 'customer.level', 'customer.last_time'])
  886. ->join('__CRM_BUSINESS__ business', 'business.customer_id = customer.customer_id', 'LEFT')
  887. ->where($where)->select();
  888. # 计算到期天数
  889. foreach ($data AS $k1 => $v1) {
  890. if ($type == 1) {
  891. $customerTime = !empty($v1['last_time']) && $v1['last_time'] > $v1['obtain_time'] ? $v1['last_time'] : $v1['obtain_time'];
  892. $date = date('Y-m-d 00:00:00', ($customerTime + $limitDay['all'] * 86400) - $remainDay * 86400);
  893. $dateRange = strtotime($date);
  894. if (time() > $dateRange) {
  895. $inPool = (($customerTime + $limitDay['all'] * 86400) - time()) / 86400;
  896. $result[$v1['customer_id']] = $inPool > 0 ? round($inPool) : 0;
  897. }
  898. }
  899. if ($type == 2) {
  900. $customerTime = !empty($v1['last_time']) && $v1['last_time'] > $v1['obtain_time'] ? $v1['last_time'] : $v1['obtain_time'];
  901. $day = !empty($limitDay[$v1['level']]) ? $limitDay[$v1['level']] : min($limitDay);
  902. $date = date('Y-m-d 00:00:00', ($customerTime + $day * 86400) - $remainDay * 86400);
  903. $dateRange = strtotime($date);
  904. if (time() > $dateRange) {
  905. $inPool = (($customerTime + $day * 86400) - time()) / 86400;
  906. $result[$v1['customer_id']] = $inPool > 0 ? round($inPool) : 0;
  907. }
  908. }
  909. }
  910. return $result;
  911. }
  912. /**
  913. * N天内无新建商机的客户
  914. *
  915. * @param int $type 类型:1 所有用户,不分级别,2 根据用户级别区分
  916. * @param Json $levels 级别数据
  917. * @param int $dealStatus 是否排除成交用户:1 排除,0 不排除
  918. * @param int $remainDay 提前几天提醒
  919. * @param array $customerIds 客户ID
  920. * @param array $userIds 员工ID
  921. * @author fanqi
  922. * @since 2021-04-01
  923. * @return array|false|string
  924. */
  925. private function getBusinessQueryResult($type, $levels, $dealStatus, $remainDay, $customerIds = [], $userIds = [])
  926. {
  927. # 结果数据
  928. $result = [];
  929. # 转换格式
  930. $levels = json_decode($levels, true);
  931. # 用于最后计算还有几天进入公海池
  932. $limitDay = [];
  933. # 数据权限
  934. $authUserIds = (new User())->getUserByPer('crm', 'customer', 'index');
  935. if (empty($authUserIds)) return $result;
  936. # 默认条件
  937. $where = "`customer`.`owner_user_id` IN (".implode(',', $authUserIds).")";
  938. # 所有用户,不区分级别
  939. if ($type == 1) {
  940. foreach ($levels AS $k1 => $v1) {
  941. if (!empty($v1['limit_day'])) {
  942. $time = strtotime(date('Y-m-d 00:00:00', time() - 86400 * $v1['limit_day']));
  943. $where .= " AND ( (ISNULL(`business`.`customer_id`) AND `customer`.`obtain_time` > ".$time.") OR (`customer`.`obtain_time` > ".$time." AND `customer`.`obtain_time` > `business`.`create_time`) OR (`business`.`create_time` > ".$time." AND `business`.`create_time` > `customer`.`obtain_time`) )";
  944. $limitDay['all'] = $v1['limit_day'];
  945. }
  946. }
  947. }
  948. # 根据用户级别设置条件
  949. if ($type == 2) {
  950. foreach ($levels AS $k1 => $v1) {
  951. if (!empty($v1['level']) && !empty($v1['limit_day'])) {
  952. $time = strtotime(date('Y-m-d 00:00:00', time() - 86400 * $v1['limit_day']));
  953. if ($k1 == 0) {
  954. $where .= " AND ( ((ISNULL(`business`.`customer_id`) AND `customer`.`obtain_time` > ".$time." AND `customer`.`level` = '".$v1['level']."') OR (`customer`.`obtain_time` > ".$time." AND `customer`.`obtain_time` > `business`.`create_time` AND `customer`.`level` = '".$v1['level']."') OR (`business`.`create_time` > $time AND `business`.`create_time` > `customer`.`obtain_time` AND `customer`.`level` = '".$v1['level']."'))";
  955. } else {
  956. $where .= " OR ((ISNULL(`business`.`customer_id`) AND `customer`.`obtain_time` > ".$time." AND `customer`.`level` = '".$v1['level']."') OR (`customer`.`obtain_time` > ".$time." AND `customer`.`obtain_time` > `business`.`create_time` AND `customer`.`level` = '".$v1['level']."') OR (`business`.`create_time` > $time AND `business`.`create_time` > `customer`.`obtain_time` AND `customer`.`level` = '".$v1['level']."'))";
  957. }
  958. }
  959. $limitDay[$v1['level']] = $v1['limit_day'];
  960. }
  961. # 获取最小天数,对于没有设置级别的客户数据使用
  962. $minLimit = $this->getMinDay($levels);
  963. $minTime = strtotime(date('Y-m-d 00:00:00', time() - 86400 * $minLimit));
  964. $where .= " OR ((ISNULL(`business`.`customer_id`) AND `customer`.`obtain_time` > ".$minTime." AND !`customer`.`level`) OR (`customer`.`obtain_time` > ".$minTime." AND `customer`.`obtain_time` > `business`.`create_time` AND !`customer`.`level`) OR (`business`.`create_time` > ".$minTime." AND `business`.`create_time` > `customer`.`obtain_time` AND !`customer`.`level`)) )";
  965. }
  966. # 选择不进入公海的客户(已成交客户)
  967. if (!empty($dealStatus)) $where .= " AND (`customer`.`deal_status` <> '已成交' OR ISNULL(`customer`.`deal_status`))";
  968. # 查询指定客户
  969. if (!empty($customerIds)) $where .= " AND `customer`.`customer_id` IN (".implode(',', $customerIds).")";
  970. # 查询指定员工
  971. if (!empty($userIds)) $where .= " AND `customer`.`owner_user_id` IN (".implode(',', $userIds).")";
  972. # 锁定的客户不提醒
  973. $where .= " AND `customer`.`is_lock` = 0";
  974. # 查询匹配条件的客户
  975. $data = db('crm_customer')->alias('customer')
  976. ->field(['customer.customer_id', 'customer.obtain_time AS customer_time', 'customer.level', 'business.create_time AS business_time'])
  977. ->join('__CRM_BUSINESS__ business', 'business.customer_id = customer.customer_id', 'LEFT')
  978. ->where($where)->select();
  979. # 计算到期天数
  980. foreach ($data AS $k1 => $v1) {
  981. if ($type == 1) {
  982. $customerTime = !empty($v1['business_time']) && $v1['business_time'] > $v1['customer_time'] ? $v1['business_time'] : $v1['customer_time'];
  983. $date = date('Y-m-d 00:00:00', ($customerTime + $limitDay['all'] * 86400) - $remainDay * 86400);
  984. $dateRange = strtotime($date);
  985. if (time() > $dateRange) {
  986. $inPool = (($customerTime + $limitDay['all'] * 86400) - time()) / 86400;
  987. $result[$v1['customer_id']] = $inPool > 0 ? round($inPool) : 0;
  988. }
  989. }
  990. if ($type == 2) {
  991. $customerTime = !empty($v1['business_time']) && $v1['business_time'] > $v1['customer_time'] ? $v1['business_time'] : $v1['customer_time'];
  992. $day = !empty($limitDay[$v1['level']]) ? $limitDay[$v1['level']] : min($limitDay);
  993. $date = date('Y-m-d 00:00:00', ($customerTime + $day * 86400) - $remainDay * 86400);
  994. $dateRange = strtotime($date);
  995. if (time() > $dateRange) {
  996. $inPool = (($customerTime + $day * 86400) - time()) / 86400;
  997. $result[$v1['customer_id']] = $inPool > 0 ? round($inPool) : 0;
  998. }
  999. }
  1000. }
  1001. return $result;
  1002. }
  1003. /**
  1004. * N天内没有成交的客户
  1005. *
  1006. * @param int $type 类型:1 所有用户,不分级别,2 根据用户级别区分
  1007. * @param Json $levels 级别数据
  1008. * @param int $businessStatus 是否排除有商机用户:1 排除,0 不排除
  1009. * @param int $remainDay 提前几天提醒
  1010. * @param array $customerIds 客户ID
  1011. * @param array $userIds 员工ID
  1012. * @author fanqi
  1013. * @since 2021-04-01
  1014. * @return array|false|string
  1015. */
  1016. private function getDealQueryResult($type, $levels, $businessStatus, $remainDay, $customerIds = [], $userIds = [])
  1017. {
  1018. # 结果数据
  1019. $result = [];
  1020. # 转换格式
  1021. $levels = json_decode($levels, true);
  1022. # 用于最后计算还有几天进入公海池
  1023. $limitDay = [];
  1024. # 数据权限
  1025. $authUserIds = (new User())->getUserByPer('crm', 'customer', 'index');
  1026. if (empty($authUserIds)) return $result;
  1027. # 默认条件
  1028. $where = "`customer`.`owner_user_id` IN (".implode(',', $authUserIds).")";
  1029. # 所有用户,不区分级别
  1030. if ($type == 1) {
  1031. foreach ($levels AS $k1 => $v1) {
  1032. if (!empty($v1['limit_day'])) {
  1033. $time = strtotime(date('Y-m-d 00:00:00', time() - 86400 * $v1['limit_day']));
  1034. $where .= " AND ( (ISNULL(`contract`.`customer_id`) AND `customer`.`obtain_time` > ".$time.") OR (`customer`.`obtain_time` > ".$time." AND `customer`.`obtain_time` > `contract`.`create_time`) OR (`contract`.`create_time` > ".$time." AND `contract`.`create_time` > `customer`.`obtain_time`) )";
  1035. $limitDay['all'] = $v1['limit_day'];
  1036. }
  1037. }
  1038. }
  1039. # 根据用户级别设置条件
  1040. if ($type == 2) {
  1041. foreach ($levels AS $k1 => $v1) {
  1042. if (!empty($v1['level']) && !empty($v1['limit_day'])) {
  1043. $time = strtotime(date('Y-m-d 00:00:00', time() - 86400 * $v1['limit_day']));
  1044. if ($k1 == 0) {
  1045. $where .= " AND ( ((ISNULL(`contract`.`customer_id`) AND `customer`.`level` = '".$v1['level']."' AND `customer`.`obtain_time` > ".$time.") OR (`customer`.`level` = '".$v1['level']."' AND `customer`.`obtain_time` > ".$time." AND `customer`.`obtain_time` > `contract`.`create_time`) OR (`contract`.`create_time` > ".$time." AND `contract`.`create_time` > `customer`.`obtain_time` AND `customer`.`level` = '".$v1['level']."'))";
  1046. } else {
  1047. $where .= " OR ((ISNULL(`contract`.`customer_id`) AND `customer`.`level` = '".$v1['level']."' AND `customer`.`obtain_time` > ".$time.") OR (`customer`.`level` = '".$v1['level']."' AND `customer`.`obtain_time` > ".$time." AND `customer`.`obtain_time` > `contract`.`create_time`) OR (`contract`.`create_time` > ".$time." AND `contract`.`create_time` > `customer`.`obtain_time` AND `customer`.`level` = '".$v1['level']."'))";
  1048. }
  1049. }
  1050. $limitDay[$v1['level']] = $v1['limit_day'];
  1051. }
  1052. # 获取最小天数,对于没有设置级别的客户数据使用
  1053. $minLimit = $this->getMinDay($levels);
  1054. $minTime = strtotime(date('Y-m-d 00:00:00', time() - 86400 * $minLimit));
  1055. $where .= " OR ((ISNULL(`contract`.`customer_id`) AND !`customer`.`level` AND `customer`.`obtain_time` > ".$minTime.") OR (!`customer`.`level` AND `customer`.`obtain_time` > ".$minTime." AND `customer`.`obtain_time` > `contract`.`create_time`) OR (`contract`.`create_time` > ".$minTime." AND `contract`.`create_time` > `customer`.`obtain_time` AND !`customer`.`level`)) )";
  1056. }
  1057. # 选择不进入公海的客户(有商机客户)
  1058. if (!empty($businessStatus)) $where .= " AND ISNULL(`business`.`customer_id`)";
  1059. # 查询指定客户
  1060. if (!empty($customerIds)) $where .= " AND `customer`.`customer_id` IN (".implode(',', $customerIds).")";
  1061. # 查询指定员工
  1062. if (!empty($userIds)) $where .= " AND `customer`.`owner_user_id` IN (".implode(',', $userIds).")";
  1063. # 锁定的客户不提醒
  1064. $where .= " AND `customer`.`is_lock` = 0";
  1065. # 查询符合条件的客户
  1066. $data = db('crm_customer')->alias('customer')
  1067. ->field(['customer.customer_id', 'customer.obtain_time AS customer_time', 'customer.level', 'contract.create_time AS contract_time'])
  1068. ->join('__CRM_BUSINESS__ business', 'business.customer_id = customer.customer_id', 'LEFT')
  1069. ->join('__CRM_CONTRACT__ contract', 'contract.customer_id = customer.customer_id', 'LEFT')
  1070. ->where($where)->select();
  1071. # 计算到期天数
  1072. foreach ($data AS $k1 => $v1) {
  1073. if ($type == 1) {
  1074. $customerTime = !empty($v1['contract_time']) && $v1['contract_time'] > $v1['customer_time'] ? $v1['contract_time'] : $v1['customer_time'];
  1075. $date = date('Y-m-d 00:00:00', ($customerTime + $limitDay['all'] * 86400) - $remainDay * 86400);
  1076. $dateRange = strtotime($date);
  1077. if (time() > $dateRange) {
  1078. $inPool = (($customerTime + $limitDay['all'] * 86400) - time()) / 86400;
  1079. $result[$v1['customer_id']] = $inPool > 0 ? round($inPool) : 0;
  1080. }
  1081. }
  1082. if ($type == 2) {
  1083. $customerTime = !empty($v1['contract_time']) && $v1['contract_time'] > $v1['customer_time'] ? $v1['contract_time'] : $v1['customer_time'];
  1084. $day = !empty($limitDay[$v1['level']]) ? $limitDay[$v1['level']] : min($limitDay);
  1085. $date = date('Y-m-d 00:00:00', ($customerTime + $day * 86400) - $remainDay * 86400);
  1086. $dateRange = strtotime($date);
  1087. if (time() > $dateRange) {
  1088. $inPool = (($customerTime + $day * 86400) - time()) / 86400;
  1089. $result[$v1['customer_id']] = $inPool > 0 ? round($inPool) : 0;
  1090. }
  1091. }
  1092. }
  1093. return $result;
  1094. }
  1095. /**
  1096. * [今日进入客户池条件]
  1097. * @author Michael_xu
  1098. * @param
  1099. * @return
  1100. */
  1101. public function getWhereByToday()
  1102. {
  1103. $configModel = new \app\crm\model\ConfigData();
  1104. $configInfo = $configModel->getData();
  1105. $config = $configInfo['config'] ? : 0;
  1106. $follow_day = $configInfo['follow_day'] ? : 0;
  1107. $deal_day = $configInfo['deal_day'] ? : 0;
  1108. $whereData = [];
  1109. //启用
  1110. if ($config == 1) {
  1111. //默认公海条件(没有负责人或已经到期)
  1112. //通过提前提醒时间,计算查询时间段
  1113. if (($follow_day > 0) && ($deal_day > 0)) {
  1114. $follow_between = array(strtotime(date('Y-m-d',time()-$follow_day*86400)),time()-$follow_day*86400);
  1115. $deal_between = array(strtotime(date('Y-m-d',time()-$deal_day*86400)),time()-$deal_day*86400);
  1116. $data['update_time'] = time()-$follow_day*86400;
  1117. $data['deal_time'] = time()-$deal_day*86400;
  1118. $data['update_between'] = $follow_between;
  1119. $data['deal_between'] = $deal_between;
  1120. if ($follow_day < $deal_day) {
  1121. $whereData = function($query) use ($data){
  1122. $query->where(['customer.owner_user_id'=>0])
  1123. ->whereOr(function ($query) use ($data) {
  1124. $query->where(function ($query) use ($data) {
  1125. $query->where(['customer.update_time' => array('between',$data['update_between'])])
  1126. ->whereOr(['customer.deal_time' => array('between',$data['deal_between'])]);
  1127. })
  1128. ->where(['customer.is_lock' => 0])
  1129. ->where(['customer.deal_status' => ['neq','已成交']]);
  1130. });
  1131. };
  1132. } else {
  1133. $whereData = function($query) use ($data){
  1134. $query->where(['customer.owner_user_id'=>0])
  1135. ->whereOr(function ($query) use ($data) {
  1136. $query->where(function ($query) use ($data) {
  1137. $query->where(['customer.deal_time' => array('between',$data['deal_between'])]);
  1138. })
  1139. ->where(['customer.is_lock' => 0])
  1140. ->where(['customer.deal_status' => ['neq','已成交']]);
  1141. });
  1142. };
  1143. }
  1144. } else {
  1145. $whereData['customer.customer_id'] = 0;
  1146. }
  1147. } else {
  1148. $whereData['customer.owner_user_id'] = 0;
  1149. $whereData['customer.update_time'] = array('between',array(strtotime(date('Y-m-d',time())),time()));
  1150. }
  1151. return $whereData ? : '';
  1152. }
  1153. /**
  1154. * 获取客户拥有数或锁定数
  1155. *
  1156. * @param int $userId 用户ID
  1157. * @param int $isDeal 成交客户是否占用拥有客户数条件:1 占用 0 不占用
  1158. * @param int $types 类型:1 拥有客户数,2 锁定客户数
  1159. * @author fanqi
  1160. * @since 2021-04-15
  1161. * @return int
  1162. */
  1163. public function getCountByHave($userId, $isDeal = 0, $types = 1)
  1164. {
  1165. # 默认条件
  1166. $where['owner_user_id'] = $userId;
  1167. # 成交客户是否占用拥有客户数条件
  1168. if ($types == 1 && empty($isDeal)) {
  1169. $where['deal_status'] = ['neq', '已成交'];
  1170. }
  1171. # 锁定客户数条件,默认排除已成交客户
  1172. if ($types == 2) {
  1173. $where['deal_status'] = ['neq', '已成交'];
  1174. $where['is_lock'] = 1;
  1175. }
  1176. return $this->where($where)->count();
  1177. }
  1178. // public function getCountByHave($user_id, $is_deal = 0,$types = 1)
  1179. // {
  1180. // $where = [];
  1181. // $where['owner_user_id'] = $user_id;
  1182. // //公海逻辑
  1183. // $configModel = new \app\crm\model\ConfigData();
  1184. // $userModel = new \app\admin\model\User();
  1185. // $configInfo = $configModel->getData();
  1186. // $config = $configInfo['config'] ? : 0;
  1187. // $follow_day = $configInfo['follow_day'] ? : 0;
  1188. // $deal_day = $configInfo['deal_day'] ? : 0;
  1189. // //默认条件(没有到期或已锁定)
  1190. // $data['follow_time'] = time()-$follow_day*86400;
  1191. // $data['deal_time'] = time()-$deal_day*86400;
  1192. // $whereData = '';
  1193. // //公海开启
  1194. // if ($config == 1) {
  1195. // switch ($types) {
  1196. // case '1' :
  1197. // if ($is_deal !== 1) {
  1198. // //不包含成交客户
  1199. // $where['deal_status'] = ['neq','已成交'];
  1200. // if ($follow_day < $deal_day) {
  1201. // $whereData = function($query) use ($data){
  1202. // $query->where(function ($query) use ($data) {
  1203. // $query->where(['update_time' => array('gt',$data['follow_time']),'deal_time' => array('gt',$data['deal_time'])]);
  1204. // });
  1205. // };
  1206. // } else {
  1207. // $whereData = function($query) use ($data){
  1208. // $query->where(function ($query) use ($data) {
  1209. // $query->where(['deal_time' => array('gt',$data['deal_time'])]);
  1210. // });
  1211. // };
  1212. // }
  1213. // } else {
  1214. // if ($follow_day < $deal_day) {
  1215. // $whereData = function($query) use ($data){
  1216. // $query->where(function ($query) use ($data) {
  1217. // $query->where(['update_time' => array('gt',$data['follow_time']),'deal_time' => array('gt',$data['deal_time'])]);
  1218. // })
  1219. // ->whereOr(['deal_status' => ['eq','已成交']]);
  1220. // };
  1221. // } else {
  1222. // $whereData = function($query) use ($data){
  1223. // $query->where(function ($query) use ($data) {
  1224. // $query->where(['deal_time' => array('gt',$data['deal_time'])]);
  1225. // })
  1226. // ->whereOr(['deal_status' => ['eq','已成交']]);
  1227. // };
  1228. // }
  1229. // }
  1230. // break;
  1231. // case '2' :
  1232. // $where['is_lock'] = ['eq',1];
  1233. // //默认不包含成交客户
  1234. // $where['deal_status'] = ['neq','已成交'];
  1235. // break;
  1236. // }
  1237. // } else {
  1238. // //公海未开启
  1239. // if ($is_deal !== 1) {
  1240. // //不包含成交客户
  1241. // $where['deal_status'] = ['neq','已成交'];
  1242. // }
  1243. // switch ($types) {
  1244. // case '2' :
  1245. // //锁定,默认不包含成交客户
  1246. // $where['deal_status'] = ['neq','已成交'];
  1247. // $where['is_lock'] = 1;
  1248. // break;
  1249. // }
  1250. // }
  1251. // $count = $this->where($where)->where($whereData)->count();
  1252. // return $count ? : 0;
  1253. // }
  1254. /**
  1255. * [客户成交新增数量]
  1256. * @author Michael_xu
  1257. * @param
  1258. * @return
  1259. */
  1260. public function getAddDealSql($map)
  1261. {
  1262. $prefix = config('database.prefix');
  1263. $sql = "SELECT
  1264. '{$map['type']}' AS type,
  1265. '{$map['start_time']}' AS start_time,
  1266. '{$map['end_time']}' AS end_time,
  1267. IFNULL(
  1268. (
  1269. SELECT
  1270. count(customer_id)
  1271. FROM
  1272. {$prefix}crm_customer
  1273. WHERE
  1274. create_time BETWEEN {$map['start_time']} AND {$map['end_time']}
  1275. AND owner_user_id IN ({$map['create_user_id']})
  1276. ),
  1277. 0
  1278. ) AS customer_num,
  1279. IFNULL(
  1280. count(customer_id),
  1281. 0
  1282. ) AS deal_customer_num
  1283. FROM
  1284. {$prefix}crm_customer
  1285. WHERE
  1286. create_time BETWEEN {$map['start_time']} AND {$map['end_time']}
  1287. AND deal_status = '{$map['deal_status']}'
  1288. AND owner_user_id IN ({$map['create_user_id']})";
  1289. return $sql;
  1290. }
  1291. /**
  1292. * [客户统计sql]
  1293. * @author Michael_xu
  1294. * @param
  1295. * @return
  1296. */
  1297. public function getAddressCountBySql($map)
  1298. {
  1299. $prefix = config('database.prefix');
  1300. $sql = "SELECT
  1301. '{$map['address']}' AS address,
  1302. IFNULL(
  1303. (
  1304. SELECT
  1305. count(customer_id)
  1306. FROM
  1307. {$prefix}crm_customer
  1308. WHERE
  1309. address LIKE '%{$map['address']}%'
  1310. AND owner_user_id IN ({$map['owner_user_id']})
  1311. ),
  1312. 0
  1313. ) AS allCustomer,
  1314. IFNULL(
  1315. count(customer_id),
  1316. 0
  1317. ) AS dealCustomer
  1318. FROM
  1319. {$prefix}crm_customer
  1320. WHERE
  1321. address LIKE '%{$map['address']}%'
  1322. AND deal_status = '{$map['deal_status']}'
  1323. AND owner_user_id IN ({$map['owner_user_id']})";
  1324. $list = $this->query($sql) ? : [];
  1325. return $list;
  1326. }
  1327. /**
  1328. * 获取附近的客户
  1329. *
  1330. * @param $param
  1331. * @return array
  1332. * @throws \think\db\exception\DataNotFoundException
  1333. * @throws \think\db\exception\ModelNotFoundException
  1334. * @throws \think\exception\DbException
  1335. */
  1336. public function getNearbyList($param)
  1337. {
  1338. $apiCommon = new ApiCommon();
  1339. $userModel = new \app\admin\model\User();
  1340. $poolStatus = checkPerByAction('crm', 'customer', 'pool');
  1341. # 客户
  1342. $customerAuth = [];
  1343. $customerWhere = [];
  1344. if ((!empty($param['type']) && $param['type'] == 2) || !$poolStatus) {
  1345. $customerWhere = $this->getWhereByCustomer();
  1346. }
  1347. # 公海
  1348. $poolWhere = [];
  1349. if (!empty($param['type']) && $param['type'] == 9 && $poolStatus) {
  1350. $poolWhere = ['customer.customer_id' => 0];
  1351. $model = '公海客户管理模块';
  1352. }
  1353. if (!empty($param['type']) && $param['type'] == 9 && !$poolStatus) {
  1354. $model = '客户管理模块';
  1355. return [];
  1356. }
  1357. # 附近
  1358. $lngLatRange = $this->getLngLatRange($param['lng'], $param['lat'], $param['distance']);
  1359. $lngLatWhere = function ($query) use ($lngLatRange) {
  1360. $query->where(['lng' => ['egt', $lngLatRange['minLng']]]);
  1361. $query->where(['lng' => ['elt', $lngLatRange['maxLng']]]);
  1362. $query->where(['lat' => ['egt', $lngLatRange['minLat']]]);
  1363. $query->where(['lat' => ['elt', $lngLatRange['maxLat']]]);
  1364. };
  1365. # 经纬度值计算出错
  1366. if (empty($lngLatRange['minLng']) || empty($lngLatRange['maxLng']) || empty($lngLatRange['minLat']) || empty($lngLatRange['maxLat'])) {
  1367. return ['list' => [], 'count' => 0];
  1368. }
  1369. $count = db('crm_customer')->alias('customer')->where($customerWhere)->where($poolWhere)->where($lngLatWhere)->count();
  1370. $list = db('crm_customer')->alias('customer')
  1371. ->where($customerWhere)
  1372. ->where($poolWhere)
  1373. ->where($lngLatWhere)
  1374. ->where($customerAuth)
  1375. ->field(['customer_id', 'name', 'address', 'detail_address', 'owner_user_id', 'lat', 'lng','next_time','last_time'])
  1376. ->order('update_time', 'desc')
  1377. ->select();
  1378. # 组装数据
  1379. foreach ($list as $key => $value) {
  1380. # todo 暂时将查询写在循环中
  1381. $ownerUserInfo = !empty($value['owner_user_id']) ? $userModel->getUserById($value['owner_user_id']) : [];
  1382. $ownerUserName = !empty($ownerUserInfo['realname']) ? $ownerUserInfo['realname'] : '';
  1383. $list[$key]['owner_user_name'] = !empty($ownerUserName) ? $ownerUserName : '暂无负责人';
  1384. $list[$key]['distance'] = $this->getLngLatDistance($param['lng'], $param['lat'], $value['lng'], $value['lat'], 1, 0);
  1385. $list[$key]['last_time'] = !empty($value['last_time'])?date('y-m-d H:i:s',$value['last_time']):!empty($value['next_time'])?date('y-m-d H:i:s',$value['next_time']):null;
  1386. $list[$key]['model']=$model;
  1387. }
  1388. return ['list' => $list, 'count' => $count];
  1389. }
  1390. /**
  1391. * 计算两点地理坐标之间的距离
  1392. *
  1393. * @param number $longitude1 起点经度
  1394. * @param number $latitude1 起点纬度
  1395. * @param number $longitude2 终点经度
  1396. * @param number $latitude2 终点纬度
  1397. * @param int $unit 单位:1米;2公里
  1398. * @param int $decimal 精度:保留小数位数
  1399. * @return float
  1400. */
  1401. private function getLngLatDistance($longitude1, $latitude1, $longitude2, $latitude2, $unit=2, $decimal=2)
  1402. {
  1403. $EARTH_RADIUS = 6370.996; // 地球半径系数
  1404. $PI = 3.1415926;
  1405. $radLat1 = $latitude1 * $PI / 180.0;
  1406. $radLat2 = $latitude2 * $PI / 180.0;
  1407. $radLng1 = $longitude1 * $PI / 180.0;
  1408. $radLng2 = $longitude2 * $PI /180.0;
  1409. $a = $radLat1 - $radLat2;
  1410. $b = $radLng1 - $radLng2;
  1411. $distance = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));
  1412. $distance = $distance * $EARTH_RADIUS * 1000;
  1413. if( $unit==2 ) $distance = $distance / 1000;
  1414. return round($distance, $decimal);
  1415. }
  1416. /**
  1417. * 获取经纬度范围值
  1418. *
  1419. * @param $myLng
  1420. * @param $myLat
  1421. * @param $distance
  1422. * @return array
  1423. */
  1424. private function getLngLatRange($myLng, $myLat, $distance)
  1425. {
  1426. $pi = pi();
  1427. # 公里
  1428. $distance = $distance / 1000;
  1429. # 计算纬度区间
  1430. $latRange = 180 / $pi * $distance / 6372.797;
  1431. # 计算进度区间
  1432. $lngRang = $latRange / cos($myLat * $pi / 180);
  1433. $maxLng = $myLng + $lngRang; # 最大经度
  1434. $minLng = $myLng - $lngRang; # 最小经度
  1435. $maxLat = $myLat + $latRange; # 最大纬度
  1436. $minLat = $myLat - $latRange; # 最小纬度
  1437. return ['maxLng' => $maxLng, 'minLng' => $minLng, 'maxLat' => $maxLat, 'minLat' => $minLat];
  1438. }
  1439. /**
  1440. * 获取系统信息
  1441. *
  1442. * @param $id
  1443. * @return array
  1444. * @throws \think\db\exception\DataNotFoundException
  1445. * @throws \think\db\exception\ModelNotFoundException
  1446. * @throws \think\exception\DbException
  1447. */
  1448. public function getSystemInfo($id)
  1449. {
  1450. # 客户
  1451. $field = ['obtain_time', 'deal_status', 'create_time', 'update_time', 'create_time', 'last_time', 'last_record'];
  1452. $customer = Db::name('crm_customer')->field($field)->where('customer_id', $id)->find();
  1453. # 创建人
  1454. $realname = Db::name('admin_user')->where('id', $customer['create_user_id'])->value('realname');
  1455. return [
  1456. 'obtain_time' => !empty($customer['obtain_time']) ? date('Y-m-d H:i:s', $customer['obtain_time']) : '',
  1457. 'last_record' => !empty($customer['last_record']) ? $customer['last_record'] : '',
  1458. 'create_user_id' => $realname,
  1459. 'create_time' => date('Y-m-d H:i:s', $customer['create_time']),
  1460. 'update_time' => date('Y-m-d H:i:s', $customer['update_time']),
  1461. 'last_time' => !empty($customer['last_time']) ? date('Y-m-d H:i:s', $customer['last_time']) : '',
  1462. 'deal_status' => $customer['deal_status']
  1463. ];
  1464. }
  1465. /**
  1466. * 判断联系人详情权限 todo 商机模块也在用,以后抽成一个公共的方法
  1467. *
  1468. * @param $contactsId
  1469. * @return bool
  1470. */
  1471. private function getContactsAuth($contactsId)
  1472. {
  1473. $ownerUserId = db('crm_contacts')->where('contacts_id', $contactsId)->value('owner_user_id');
  1474. $authUserIds = (new \app\admin\model\User())->getUserByPer('crm', 'contacts', 'read');
  1475. return in_array($ownerUserId, $authUserIds);
  1476. }
  1477. }