Customer.php 49KB

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