Customer.php 85KB

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