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