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