CustomService.php 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408
  1. <?php
  2. namespace app\admin\service\consultant;
  3. use app\model\Consultant;
  4. use app\model\MarketCustomer;
  5. use app\model\MarketCustomerFollow;
  6. use app\model\MarketCustomerLogs;
  7. use app\model\SysDept;
  8. use PhpOffice\PhpSpreadsheet\Reader\Csv;
  9. use PhpOffice\PhpSpreadsheet\Reader\Xls;
  10. use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
  11. use support\Db;
  12. use support\exception\BusinessException;
  13. use support\Request;
  14. use Tinywan\Jwt\JwtToken;
  15. class CustomService
  16. {
  17. const DIFF_TIME = (60 * 60 * 24 * 30); //调入团队公池 x4 = 调入集团公池
  18. /**
  19. * Notes: 返回选项配置信息
  20. * User: yb
  21. * Date: 2024/8/5
  22. * Time: 16:05
  23. * @return array
  24. */
  25. public static function config()
  26. {
  27. return MarketCustomer::config();
  28. }
  29. public static function commonSearch($params)
  30. {
  31. $where = [];
  32. $currentTime = time();
  33. $diffNums = self::DIFF_TIME;
  34. $deptIds = TeamService::getIdsByUser();
  35. $belongStatus = $params['belong_status'] ?? 1;
  36. if (false === $deptIds) {
  37. //无权限
  38. $where[] = ['dept_id', '=', 0];
  39. } else if (is_array($deptIds)) {
  40. //指定团队下的权限
  41. if (!empty($params['dept_id'])) {
  42. $deptId = end($params['dept_id']);
  43. $deptIds = SysDept::where('dept_super_path','like', "%/{$deptId}/%")->where('dept_category', '=', TeamService::DEPT_CATEGORY)->pluck('dept_id')->toArray();
  44. }
  45. $where[] = [function($query) use ($deptIds) {
  46. $query->whereIn('dept_id', $deptIds);
  47. }];
  48. $where[] = [function($query) use ($diffNums, $currentTime){
  49. $query->orWhereRaw("check_status IN (-1, 1)")
  50. ->orWhereRaw("check_status = 2 AND current_status IN (-1,3,4)")
  51. ->orWhereRaw("((visit_time + {$diffNums}) - {$currentTime} > 0 AND current_status = 2 AND check_status = 2)")
  52. ->orWhereRaw("((visit_time + {$diffNums}) - {$currentTime} <= 0 AND (visit_time + ({$diffNums} * 4)) - {$currentTime} > 0 AND current_status = 2 AND check_status = 2 AND belong_status = 1)")->whereOr('belong_status','<>', 1);
  53. }];
  54. } else {
  55. if (!empty($params['dept_id'])) {
  56. $deptId = end($params['dept_id']);
  57. $deptIds = SysDept::where('dept_super_path','like', "%/{$deptId}/%")->where('dept_category', '=', TeamService::DEPT_CATEGORY)->pluck('dept_id')->toArray();
  58. $where[] = [function($query) use ($deptIds) {
  59. $query->whereIn('dept_id', $deptIds);
  60. }];
  61. }
  62. }
  63. if (!empty($params['name'])) {
  64. $keywords = $params['name'];
  65. $where[] = [function($query) use ($keywords) {
  66. $query->orWhere('name', 'like', "%{$keywords}%")->orWhere('mobile', 'like', "%{$keywords}%");
  67. }];
  68. }
  69. if (!empty($params['mobile'])) {
  70. $mobile = $params['mobile'];
  71. $where[] = [function($query) use ($mobile) {
  72. $query->where('mobile', 'like', "%{$mobile}%");
  73. }];
  74. }
  75. if (!empty($params['consultant_name'])) {
  76. $consultantIds = Consultant::orWhere('name', 'like', "%{$params['consultant_name']}%")
  77. ->orWhere('mobile', 'like', "%{$params['consultant_name']}%")
  78. ->pluck('id')->toArray();
  79. $where[] = [function($query) use ($consultantIds) {
  80. $query->whereIn('consultant_id', $consultantIds);
  81. }];
  82. }
  83. if (!empty($params['report_name'])) {
  84. $consultantIds = Consultant::orWhere('name', 'like', "%{$params['report_name']}%")
  85. ->orWhere('mobile', 'like', "%{$params['report_name']}%")
  86. ->pluck('id')->toArray();
  87. $where[] = [function($query) use ($consultantIds) {
  88. $query->whereIn('report_consultant_id', $consultantIds);
  89. }];
  90. }
  91. if (!empty($params['type'])) {
  92. $where[] = ['type', '=', $params['type']];
  93. }
  94. if (!empty($params['visit_time'])) {
  95. $datetime = $params['visit_time'];
  96. $datetime[0] = strtotime($datetime[0].' 00:00:00');
  97. $datetime[1] = strtotime($datetime[1].' 23:59:59');
  98. $where[] = [function($query) use ($datetime) {
  99. $query->whereBetween('visit_time', $datetime);
  100. }];
  101. }
  102. if (!empty($params['visit_date'])) {
  103. $visitDate = $params['visit_date'];
  104. $visitDate[0] = strtotime($visitDate[0].' 00:00:00');
  105. $visitDate[1] = strtotime($visitDate[1].' 23:59:59');
  106. $where[] = [function($query) use ($visitDate) {
  107. $query->whereBetween('visit_time', $visitDate);
  108. }];
  109. }
  110. if (!empty($params['created_date'])) {
  111. $createdDate = $params['created_date'];
  112. $createdDate[0] = strtotime($createdDate[0].' 00:00:00');
  113. $createdDate[1] = strtotime($createdDate[1].' 23:59:59');
  114. $where[] = [function($query) use ($createdDate) {
  115. $query->whereBetween('created_at', $createdDate);
  116. }];
  117. }
  118. if (!empty($params['check_date'])) {
  119. $checkDate = $params['check_date'];
  120. $checkDate[0] = strtotime($checkDate[0].' 00:00:00');
  121. $checkDate[1] = strtotime($checkDate[1].' 23:59:59');
  122. $where[] = [function($query) use ($checkDate) {
  123. $query->whereBetween('check_time', $checkDate)->where('current_status', '>', 1);
  124. }];
  125. }
  126. if (!empty($params['current_status'])) {
  127. $currentStatus = $params['current_status'];
  128. if ($currentStatus == -2) {
  129. //检索公池状态
  130. $where[] = [function($query) use ($diffNums, $currentTime){
  131. $query->whereRaw("((visit_time + {$diffNums}) - {$currentTime} <= 0 AND (visit_time + ({$diffNums} * 4)) - {$currentTime} > 0 AND current_status = 2 AND check_status = 2 AND belong_status = 1)");
  132. }];
  133. } else {
  134. $where[] = ['current_status', '=', $currentStatus];
  135. $where[] = [function($query) use ($diffNums, $currentTime){
  136. $query->orWhereRaw("check_status IN (-1, 1)")
  137. ->orWhereRaw("check_status = 2 AND current_status IN (-1,3,4)")
  138. ->orWhereRaw("((visit_time + {$diffNums}) - {$currentTime} > 0 AND current_status = 2 AND check_status = 2)");
  139. }];
  140. }
  141. }
  142. if (!empty($params['consultant_id'])) {
  143. $consultantId = $params['consultant_id'];
  144. $where[] = [function($query) use ($consultantId) {
  145. $query->orWhere('consultant_id', $consultantId)->orWhere('report_consultant_id', $consultantId);
  146. }];
  147. }
  148. if (!empty($params['custom'])) {
  149. $keywords = $params['custom'];
  150. $where[] = [function($query) use ($keywords) {
  151. $query->orWhere('name', 'like', "%{$keywords}%")->orWhere('mobile', 'like', "%{$keywords}%");
  152. }];
  153. }
  154. if (!empty($params['check_status'])) {
  155. $where[] = ['check_status', '=', $params['check_status']];
  156. }
  157. if (!empty($params['stat_report_status'])) {
  158. //已报备 1
  159. $statReportStatus = $params['stat_report_status'];
  160. if ($statReportStatus == 1) {
  161. $where[] = [function($query) use ($diffNums, $currentTime) {
  162. $query->whereRaw("((visit_time + {$diffNums}) - {$currentTime} > 0)")->where('current_status', '=', 1)->where('check_status', '=', 2);
  163. }];
  164. }
  165. //已锁定 2
  166. if ($statReportStatus == 2) {
  167. $where[] = [function($query) {
  168. $query->whereIn('current_status', [2,3,4])->where('check_status', '=', 2);
  169. }];
  170. }
  171. //已失效 -1
  172. if ($statReportStatus == -1) {
  173. $where[] = [function($query) use ($diffNums, $currentTime){
  174. $query->orWhere('current_status', '=', -1)->orWhereRaw("((visit_time + {$diffNums}) - {$currentTime} <= 0 AND current_status = 1 AND check_status = 2)")->orWhere('check_status', '=', -1);
  175. }];
  176. }
  177. }
  178. if (isset($params['require_area'])) {
  179. if (is_numeric($params['require_area'])) {
  180. $where[] = ['require_area', '=', ($params['require_area'] + 1)];
  181. }
  182. }
  183. if (isset($params['requirement'])) {
  184. if (is_numeric($params['requirement'])) {
  185. $where[] = ['requirement', '=', ($params['requirement'] + 1)];
  186. }
  187. }
  188. if (isset($params['age_range'])) {
  189. if (is_numeric($params['age_range'])) {
  190. $where[] = ['age_range', '=', ($params['age_range'] + 1)];
  191. }
  192. }
  193. if (isset($params['visit_type'])) {
  194. if (is_numeric($params['visit_type'])) {
  195. $where[] = ['visit_type', '=', $params['visit_type']];
  196. }
  197. }
  198. if (isset($params['region'])) {
  199. if (is_numeric($params['region'])) {
  200. $where[] = ['region', '=', ($params['region'] + 1)];
  201. }
  202. }
  203. if (isset($params['purpose'])) {
  204. if (is_numeric($params['purpose'])) {
  205. $where[] = ['purpose', '=', ($params['purpose'] + 1)];
  206. }
  207. }
  208. if (isset($params['level'])) {
  209. if (is_numeric($params['level'])) {
  210. $where[] = ['level', '=', ($params['level'] + 1)];
  211. }
  212. }
  213. if (!empty($params['belong_status'])) {
  214. $belongStatus = $params['belong_status'];
  215. if ($belongStatus == 1) {
  216. //未流入公池
  217. $where[] = ['belong_status', '=', 1];
  218. $where[] = [function($query) use ($diffNums, $currentTime){
  219. $query->orWhereRaw("check_status IN (-1, 1)")
  220. ->orWhereRaw("check_status = 2 AND current_status IN (-1,3,4)")
  221. ->orWhereRaw("((visit_time + {$diffNums}) - {$currentTime} > 0 AND current_status = 2 AND check_status = 2)");
  222. }];
  223. } else {
  224. if (true === $deptIds) {
  225. if (!empty($params['pub_status'])) {
  226. if ($params['pub_status'] == 2) {
  227. //仅检索团队公池
  228. $where[] = [function($query) use ($diffNums, $currentTime){
  229. $query->orWhereRaw("((visit_time + {$diffNums}) - {$currentTime} <= 0 AND (visit_time + ({$diffNums} * 4)) - {$currentTime} > 0 AND current_status = 2 AND check_status = 2 AND belong_status = 1)")->whereOr('belong_status','<>', 1);
  230. }];
  231. } else {
  232. //仅检索集团公池
  233. $where[] = [function($query) use ($diffNums, $currentTime){
  234. $query->orWhereRaw("((visit_time + ({$diffNums} * 4)) - {$currentTime} <= 0 AND current_status = 2 AND check_status = 2 AND belong_status = 1)")->whereOr('belong_status','<>', 1);
  235. }];
  236. }
  237. } else {
  238. //超管权限
  239. $where[] = [function($query) use ($diffNums, $currentTime){
  240. $query->orWhereRaw("((visit_time + {$diffNums}) - {$currentTime} <= 0 AND current_status = 2 AND check_status = 2 AND belong_status = 1)")->whereOr('belong_status','<>', 1);
  241. }];
  242. }
  243. } else if (is_array($deptIds)) {
  244. //团队权限
  245. $where[] = [function($query) use ($diffNums, $currentTime){
  246. $query->orWhereRaw("((visit_time + {$diffNums}) - {$currentTime} <= 0 AND (visit_time + ({$diffNums} * 4)) - {$currentTime} > 0 AND current_status = 2 AND check_status = 2 AND belong_status = 1)")->whereOr('belong_status','<>', 1);
  247. }];
  248. } else {
  249. //无权限
  250. }
  251. }
  252. }
  253. return $where;
  254. }
  255. /**
  256. * Notes: 列表
  257. * User: yb
  258. * Date: 2024/8/6
  259. * Time: 15:07
  260. * @param Request $request
  261. */
  262. public static function index(Request $request)
  263. {
  264. $format = $request->get('format', 'normal');
  265. $limit = (int)$request->get('pageSize', $format === 'tree' ? 1000 : 10);
  266. $limit = $limit <= 0 ? 10 : $limit;
  267. $params = $request->get();
  268. $page = (int)$request->get('page');
  269. $page = $page > 0 ? $page : 1;
  270. $currentTime = time();
  271. $diffNums = self::DIFF_TIME;
  272. $where = self::commonSearch($params);
  273. $paginator = MarketCustomer::where($where)->orderBy('visit_time', 'desc')->paginate($limit, '*', 'page', $page);
  274. $total = $paginator->total();
  275. $items = $paginator->items();
  276. if (!empty($items)) {
  277. //查询顾问信息
  278. $consultantKeys = [];
  279. $reportConsultantIds = $paginator->pluck('report_consultant_id')->toArray();
  280. $consultantIds = $paginator->pluck('consultant_id')->toArray();
  281. if (!empty($consultantIds) || !empty($reportConsultantIds)) {
  282. if (!empty($consultantIds)) {
  283. //去重
  284. $consultantIds = array_unique($consultantIds);
  285. //排序
  286. $consultantIds = array_values($consultantIds);
  287. }
  288. if (!empty($reportConsultantIds)) {
  289. //去重
  290. $reportConsultantIds = array_unique($reportConsultantIds);
  291. //排序
  292. $reportConsultantIds = array_values($reportConsultantIds);
  293. }
  294. $consultantIds = array_merge($consultantIds, $reportConsultantIds);
  295. $consultantList = Consultant::whereIn('id', $consultantIds)->select(['id', 'name', 'mobile'])->get();
  296. if (!$consultantList->isEmpty()) {
  297. foreach ($consultantList->toArray() as $consultantItem) {
  298. $consultantKeys[$consultantItem['id']] = $consultantItem;
  299. }
  300. }
  301. }
  302. $teamKeys = TeamService::getItemKeys();
  303. foreach ($items as &$item) {
  304. $visitTime = $item->visit_time;
  305. $visitTimeStamp = strtotime($visitTime);
  306. $diff = ($visitTimeStamp + $diffNums) - $currentTime;
  307. if ($diff > 0) {
  308. $item->belong_status = 1;
  309. } else {
  310. if (abs($diff) - (4*$diffNums) > 0) {
  311. $item->belong_status = 3;
  312. } else {
  313. $item->belong_status = 2;
  314. }
  315. }
  316. $item->diff_nums = ($diff > 0) ? $diff : 0;
  317. $item->consultant_name = $consultantKeys[$item->consultant_id]['name'] ?? '';
  318. $item->consultant_mobile = $consultantKeys[$item->consultant_id]['mobile'] ?? '';
  319. $item->report_consultant_name = $consultantKeys[$item->report_consultant_id]['name'] ?? '';
  320. $item->report_consultant_mobile = $consultantKeys[$item->report_consultant_id]['mobile'] ?? '';
  321. $item->team_name = TeamService::getTeamName($teamKeys, $item->dept_id);
  322. $item->mask_mobile = self::handlePhone($item->mobile);
  323. }
  324. }
  325. $data = [
  326. 'total' => $total,
  327. 'rows' => $items
  328. ];
  329. return json_success('success', $data);
  330. }
  331. /**
  332. * Notes: 添加客户
  333. * User: yb
  334. * Date: 2024/8/6
  335. * Time: 11:20
  336. */
  337. public static function add($params)
  338. {
  339. $params = MarketCustomer::handleNumParams($params);
  340. $mobile = $params['mobile'];
  341. //查询客户手机号是否已经存在
  342. if (MarketCustomer::checkCustomExists($mobile)) {
  343. return json_fail('客户已经登记过了');
  344. }
  345. //查询顾问信息
  346. $reportConsultantId = $params['report_consultant_id'];
  347. $consultantInfo = Consultant::firstWhere(['id' => $reportConsultantId]);
  348. if (empty($consultantInfo)) {
  349. return json_fail('报备顾问信息不存在');
  350. }
  351. $deptId = $consultantInfo->dept_id;
  352. $insertData = [
  353. 'name' => $params['name'],
  354. 'mobile' => $mobile,
  355. 'consultant_id' => 0,
  356. 'create_consultant_id' => $reportConsultantId,
  357. 'report_consultant_id' => $reportConsultantId,
  358. 'dept_id' => $deptId,
  359. 'gender' => $params['gender'] ?? null,
  360. 'visit_type' => $params['visit_type'] ?? null,
  361. 'require_area' => $params['require_area'] ?? null,
  362. 'area' => $params['area'] ?? null,
  363. 'requirement' => $params['requirement'] ?? null,
  364. 'age_range' => $params['age_range'] ?? null,
  365. 'focus' => $params['focus'] ?? null,
  366. 'region' => $params['region'] ?? null,
  367. 'purpose' => $params['purpose'] ?? null,
  368. 'level' => $params['level'] ?? null,
  369. 'type' => $params['type'] ?? null,
  370. 'check_status' => 1,
  371. 'visit_time' => $params['visit_time'] ?? null,
  372. 'note' => $params['note'] ?? '',
  373. 'belong_status' => 1,
  374. 'current_status' => $params['current_status'] ?? null,
  375. 'created_at' => time()
  376. ];
  377. Db::beginTransaction();
  378. try {
  379. //查询会员表中是否存在该客户
  380. // $memberId = Member::where('member_mobile', $insertData['mobile'])->value('member_id');
  381. // if (empty($memberId)) {
  382. // $result = MemberService::add([
  383. // 'account_name'=> $insertData['name'],
  384. // 'member_category' => '售房客户',
  385. // 'mobile' => $insertData['mobile'],
  386. // 'source' => 'HOUSE']);
  387. // $code = $result->getStatusCode();
  388. // if ($code == 200) {
  389. // $content = $result->rawBody();
  390. // if (is_json($content)) {
  391. // $content = json_decode($content, 1);
  392. // if ($content['code'] == 200) {
  393. // $memberId = $content['data']['member_id'];
  394. // } else {
  395. // throw new BusinessException('新增会员失败');
  396. // }
  397. // } else {
  398. // throw new BusinessException('新增会员失败');
  399. // }
  400. // } else {
  401. // throw new BusinessException('新增会员失败');
  402. // }
  403. // }
  404. // $insertData['member_id'] = $memberId;
  405. $customId = MarketCustomer::insertGetId($insertData);
  406. Db::commit();
  407. }catch (BusinessException|\Exception $e){
  408. Db::rollBack();
  409. return json_fail($e->getMessage());
  410. }
  411. if ($customId) {
  412. return json_success('添加成功');
  413. } else {
  414. return json_fail('添加失败');
  415. }
  416. }
  417. /**
  418. * Notes: 编辑客户
  419. * User: yb
  420. * Date: 2024/8/6
  421. * Time: 16:53
  422. * @param $params
  423. */
  424. public static function update($params)
  425. {
  426. $params = MarketCustomer::handleNumParams($params);
  427. $mobile = $params['mobile'];
  428. //查询客户手机号是否已经存在
  429. if (MarketCustomer::checkCustomExists($mobile, $params['id'])) {
  430. return json_fail('客户已经登记过了');
  431. }
  432. $updateData = [
  433. 'name' => $params['name'],
  434. 'mobile' => $params['mobile'],
  435. 'gender' => $params['gender'] ?? null,
  436. 'visit_type' => $params['visit_type'] ?? null,
  437. 'require_area' => $params['require_area'] ?? null,
  438. 'area' => $params['area'] ?? null,
  439. 'requirement' => $params['requirement'] ?? null,
  440. 'age_range' => $params['age_range'] ?? null,
  441. 'focus' => $params['focus'] ?? null,
  442. 'region' => $params['region'] ?? null,
  443. 'purpose' => $params['purpose'] ?? null,
  444. 'level' => $params['level'] ?? null,
  445. 'type' => $params['type'] ?? null,
  446. 'note' => $params['note'] ?? '',
  447. 'current_status' => $params['current_status'] ?? null,
  448. 'updated_at' => time()
  449. ];
  450. if (!empty($params['update_visit_time'])) {
  451. if ($params['update_visit_time'] == 1) {
  452. $updateData['visit_time'] = $params['visit_time'] ?? null;
  453. }
  454. }
  455. $result = MarketCustomer::where('id', $params['id'])->update($updateData);
  456. if ($result) {
  457. return json_success('编辑成功');
  458. } else {
  459. return json_fail('编辑失败');
  460. }
  461. }
  462. /**
  463. * Notes: 删除客户
  464. * User: yb
  465. * Date: 2024/8/2
  466. * Time: 13:33
  467. * @param $ids
  468. * @return \support\Response
  469. */
  470. public static function delete($ids)
  471. {
  472. if (!$ids) {
  473. return json_fail("数据错误");
  474. }
  475. if (!is_array($ids)) {
  476. $ids = [$ids];
  477. }
  478. Db::beginTransaction();
  479. try {
  480. if (is_array($ids)) {
  481. MarketCustomer::whereIn('id', $ids)->delete();
  482. MarketCustomerFollow::whereIn('market_customer_id', $ids)->delete();//删除跟进记录
  483. MarketCustomerLogs::whereIn('market_customer_id', $ids)->delete();//删除移交记录
  484. } else {
  485. MarketCustomer::where('id', $ids)->delete();
  486. MarketCustomerFollow::where('market_customer_id', $ids)->delete();//删除跟进记录
  487. MarketCustomerLogs::where('market_customer_id', $ids)->delete();//删除移交记录
  488. }
  489. Db::commit();
  490. } catch (\Exception $e) {
  491. Db::rollBack();
  492. return json_fail('删除失败');
  493. }
  494. return json_success('删除成功');
  495. }
  496. /**
  497. * Notes: 跟进记录
  498. * User: yb
  499. * Date: 2024/8/7
  500. * Time: 9:00
  501. * @param Request $request
  502. */
  503. public static function follow(Request $request)
  504. {
  505. $format = $request->get('format', 'normal');
  506. $limit = (int)$request->get('pageSize', $format === 'tree' ? 1000 : 10);
  507. $limit = $limit <= 0 ? 10 : $limit;
  508. $params = $request->get();
  509. $page = (int)$request->get('page');
  510. $page = $page > 0 ? $page : 1;
  511. $where = [];
  512. $whereCustom = [];
  513. $whereConsultant = [];
  514. if (!empty($params['market_customer_id'])) {
  515. $marketCustomerIds = $params['market_customer_id'];
  516. $where[] = [function($query) use ($marketCustomerIds) {
  517. $query->whereIn('market_customer_id', $marketCustomerIds);
  518. }];
  519. }
  520. if (!empty($params['consultant_id'])) {
  521. $consultantId = $params['consultant_id'];
  522. $where[] = [function($query) use ($consultantId) {
  523. $query->whereIn('consultant_id', $consultantId);
  524. }];
  525. }
  526. if (!empty($params['follow_way'])) {
  527. $where[] = ['follow_way', '=', $params['follow_way']];
  528. }
  529. if (!empty($params['custom'])) {
  530. $custom = $params['custom'];
  531. $whereCustom[] = [function($query) use ($custom) {
  532. $query->orWhere('name', 'like', "%{$custom}%")->orWhere('mobile', 'like', "%{$custom}%");
  533. }];
  534. }
  535. if (!empty($params['consultant'])) {
  536. $consultant = $params['consultant'];
  537. $whereConsultant[] = [function($query) use ($consultant) {
  538. $query->orWhere('name', 'like', "%{$consultant}%")->orWhere('mobile', 'like', "%{$consultant}%");
  539. }];
  540. }
  541. if (!empty($params['follow_time'])) {
  542. $datetime = $params['follow_time'];
  543. $datetime[0] = strtotime($datetime[0].' 00:00:00');
  544. $datetime[1] = strtotime($datetime[1].' 23:59:59');
  545. $where[] = [function($query) use ($datetime) {
  546. $query->whereBetween('follow_time', $datetime);
  547. }];
  548. }
  549. $paginator = MarketCustomerFollow::with(['custom', 'consultant'])->whereHas('custom', function($query) use ($whereCustom){
  550. $query->where($whereCustom);
  551. })->whereHas('consultant', function($query) use ($whereConsultant) {
  552. $query->where($whereConsultant);
  553. })->where($where)->orderBy('follow_time', 'desc')->paginate($limit, '*', 'page', $page);
  554. $total = $paginator->total();
  555. $items = $paginator->items();
  556. foreach ($items as &$item) {
  557. if (!empty($item->custom)) {
  558. $item->custom->mask_mobile = self::handlePhone($item->custom->mobile);
  559. }
  560. }
  561. $data = [
  562. 'total' => $total,
  563. 'rows' => $items
  564. ];
  565. return json_success('success', $data);
  566. }
  567. /**
  568. * Notes: 删除跟进记录
  569. * User: yb
  570. * Date: 2024/8/7
  571. * Time: 11:25
  572. * @param $ids
  573. */
  574. public static function deleteFollow($ids)
  575. {
  576. if (!$ids) {
  577. return json_fail("数据错误");
  578. }
  579. if (!is_array($ids)) {
  580. $ids = [$ids];
  581. }
  582. try {
  583. if (is_array($ids)) {
  584. MarketCustomerFollow::whereIn('id', $ids)->delete();
  585. } else {
  586. MarketCustomerFollow::where('id', $ids)->delete();
  587. }
  588. } catch (\Exception $e) {
  589. return json_fail('删除失败');
  590. }
  591. return json_success('删除成功');
  592. }
  593. /**
  594. * Notes: 转移客户
  595. * User: yb
  596. * Date: 2024/8/7
  597. * Time: 14:27
  598. * @param $params
  599. */
  600. public static function moveCustom($params)
  601. {
  602. $userId = JwtToken::getCurrentId();
  603. $moveType = $params['move_type'] ?? 0;
  604. if ($moveType == 1) {
  605. $currentDeptId = $params['dept_id'];
  606. $currentConsultantId = 0;
  607. } else {
  608. $currentConsultantId = $params['consultant_id'] ?? 0; //当前顾问
  609. $consultantInfo = Consultant::firstWhere(['id' => $currentConsultantId]);
  610. if (empty($consultantInfo)) {
  611. return json_fail('顾问不存在');
  612. }
  613. $currentDeptId = $consultantInfo->dept_id; //当前部门
  614. }
  615. $consultantIds = $params['move_consultant_id'] ?? [];
  616. $customIds = $params['move_market_customer_id'] ?? [];
  617. $note = $params['note'] ?? '';
  618. $logsInertData = [];
  619. $now = time();
  620. $whereCustom = [];
  621. if (!empty($customIds)) {
  622. $whereCustom[] = [function($query) use ($customIds) {
  623. $query->whereIn('id', $customIds);
  624. }];
  625. }
  626. if (!empty($consultantIds)) {
  627. $whereCustom[] = [function($query) use ($consultantIds) {
  628. $query->whereIn('consultant_id', $consultantIds);
  629. }];
  630. }
  631. $customList = MarketCustomer::where($whereCustom)->select(['id','consultant_id','dept_id','visit_time','check_status','current_status'])->get();
  632. if (!$customList->isEmpty()) {
  633. foreach ($customList as$item) {
  634. $logsInertData[] = [
  635. 'market_customer_id' => $item->id,
  636. 'consultant_id' => $currentConsultantId,
  637. 'dept_id' => $currentDeptId,
  638. 'before_consultant_id' => $item->consultant_id,
  639. 'before_dept_id' => $item->dept_id,
  640. 'note' => $note,
  641. 'change_user_id' => $userId,
  642. 'created_at' => $now
  643. ];
  644. }
  645. }
  646. if ($customList->isEmpty()) {
  647. return json_fail('移交的客户信息不存在');
  648. }
  649. if (empty($logsInertData)) {
  650. return json_fail('移交记录不能为空');
  651. }
  652. $diffTime = self::DIFF_TIME;
  653. Db::beginTransaction();
  654. $result = false;
  655. try {
  656. foreach ($customList as $item) {
  657. if ($currentConsultantId != 0) {
  658. //移交至指定顾问
  659. //判断一下是否到了到访的过期时间,如果过期了就更新到访时间,没过期时间就不变
  660. if ($item->check_status == 2 && $item->current_status == 2) {
  661. $visitTime = $item->visit_time;
  662. $diff = strtotime($visitTime) + $diffTime - time();
  663. if ($diff <= 0) {
  664. $item->visit_time = time();
  665. }
  666. }
  667. } else {
  668. //移交至其他团队
  669. $item->visit_time = time() - self::DIFF_TIME;
  670. }
  671. $item->consultant_id = $currentConsultantId;
  672. $item->dept_id = $currentDeptId;
  673. $item->save();
  674. }
  675. $result = MarketCustomerLogs::insert($logsInertData);
  676. Db::commit();
  677. }catch (BusinessException|\Exception $e) {
  678. Db::rollBack();
  679. return json_fail($e->getMessage());
  680. }
  681. if ($result) {
  682. return json_success('移交成功');
  683. } else {
  684. return json_fail('移交失败');
  685. }
  686. }
  687. /**
  688. * Notes: 转移记录
  689. * User: yb
  690. * Date: 2024/8/7
  691. * Time: 15:33
  692. * @param Request $request
  693. */
  694. public static function moveLogs(Request $request)
  695. {
  696. $format = $request->get('format', 'normal');
  697. $limit = (int)$request->get('pageSize', $format === 'tree' ? 1000 : 10);
  698. $limit = $limit <= 0 ? 10 : $limit;
  699. $params = $request->get();
  700. $page = (int)$request->get('page');
  701. $page = $page > 0 ? $page : 1;
  702. $platform = 0;
  703. $where = [];
  704. $whereCustom = [];
  705. $whereCurrent = [];
  706. $whereBefore = [];
  707. $whereOpBack = [];
  708. $whereOpFront = [];
  709. if (!empty($params['market_customer_id'])) {
  710. $where[] = ['market_customer_id', '=', $params['market_customer_id']];
  711. }
  712. if (!empty($params['consultant_id'])) {
  713. $consultantIds = $params['consultant_id'];
  714. $where[] = [function($query) use ($consultantIds) {
  715. $query->orWhereIn('consultant_id', $consultantIds)->orWhereIn('before_consultant_id', $consultantIds);
  716. }];
  717. }
  718. if (!empty($params['custom'])) {
  719. //客户信息
  720. $custom = $params['custom'];
  721. $whereCustom[] = ['name', 'like', "%{$custom}%"];
  722. }
  723. if (!empty($params['current_consultant'])) {
  724. //当前员工信息
  725. $current = $params['current_consultant'];
  726. $whereCurrent[] = ['name', 'like', "%{$current}%"];
  727. }
  728. if (!empty($params['before_consultant'])) {
  729. //转移前员工信息
  730. $before = $params['before_consultant'];
  731. $whereBefore[] = ['name', 'like', "%{$before}%"];
  732. }
  733. if (!empty($params['platform'])) {
  734. $platform = $params['platform'];
  735. if ($platform == 1) {
  736. //后台
  737. $where[] = ['change_user_id', '<>', null];
  738. $where[] = ['change_user_id', '=', null];
  739. } else {
  740. //小程序
  741. $where[] = ['change_user_id', '=', null];
  742. $where[] = ['change_user_id', '<>', null];
  743. }
  744. }
  745. if (!empty($params['op_name'])) {
  746. $opName = $params['op_name'];
  747. if (!empty($platform)) {
  748. if ($platform == 1) {
  749. $whereOpBack[] = ['user_name', 'like', "%{$opName}%"];
  750. } else {
  751. $whereOpFront[] = ['name', 'like', "%{$opName}%"];
  752. }
  753. } else {
  754. $whereOpBack[] = [function($query) use ($opName) {
  755. $query->orWhere('user_name', 'like', "%{$opName}%");
  756. }];
  757. $whereOpFront[] = [function($query) use ($opName) {
  758. $query->orWhere('name', 'like', "%{$opName}%");
  759. }];
  760. }
  761. }
  762. if (!empty($params['created_at'])) {
  763. $createdDate = $params['created_at'];
  764. $createdDate[0] = strtotime($createdDate[0].' 00:00:00');
  765. $createdDate[1] = strtotime($createdDate[1].' 23:59:59');
  766. $where[] = [function($query) use ($createdDate) {
  767. $query->whereBetween('created_at', $createdDate);
  768. }];
  769. }
  770. $paginator = MarketCustomerLogs::with(['custom' => function($query) {
  771. $query->select('id', 'name', 'mobile');
  772. }, 'beforeMan' => function($query) {
  773. $query->select('id', 'name', 'mobile');
  774. }, 'currentMan' => function($query) {
  775. $query->select('id', 'name', 'mobile');
  776. }, 'beforeDept' => function($query) {
  777. $query->select('dept_id', 'dept_name');
  778. }, 'currentDept' => function($query) {
  779. $query->select('dept_id', 'dept_name');
  780. }])
  781. // ->whereHas('custom', function ($query) use ($whereCustom) {
  782. // $query->where($whereCustom);
  783. // })
  784. // ->whereHas('currentMan', function ($query) use ($whereCurrent) {
  785. // $query->where($whereCurrent);
  786. // })
  787. // ->whereHas('beforeMan', function ($query) use ($whereBefore) {
  788. // $query->where($whereBefore);
  789. // })
  790. ->where($where)
  791. ->orderBy('created_at', 'desc')
  792. ->paginate($limit, '*', 'page', $page);
  793. $total = $paginator->total();
  794. $items = $paginator->items();
  795. foreach ($items as &$item) {
  796. if (!empty($item->custom)) {
  797. $item->custom->mask_mobile = self::handlePhone($item->custom->mobile);
  798. }
  799. }
  800. $data = [
  801. 'total' => $total,
  802. 'rows' => $items
  803. ];
  804. return json_success('success', $data);
  805. }
  806. /**
  807. * Notes: 审核客户
  808. * User: yb
  809. * Date: 2024/8/16
  810. * Time: 11:21
  811. * @param $params
  812. */
  813. public static function checkCustom($params)
  814. {
  815. $adminId = JwtToken::getCurrentId();
  816. //查询客户是否已经存在
  817. $customId = $params['id'];
  818. $checkStatus = $params['check_status'];
  819. if (!in_array($checkStatus, [-1,2])) {
  820. return json_fail('状态值非法');
  821. }
  822. $info = MarketCustomer::firstWhere(['id' => $customId]);
  823. if (empty($info)) {
  824. return json_fail('客户不存在');
  825. }
  826. $status = $info->check_status;
  827. if ($status != 1) {
  828. return json_fail('客户不是待转到访状态');
  829. }
  830. $mobile = $info->mobile;
  831. if ($checkStatus == 2) {
  832. if (MarketCustomer::checkCustomExists($mobile)) {
  833. return json_fail('客户已经存在');
  834. }
  835. }
  836. //查询顾问的团队信息
  837. $deptId = Consultant::where('id', $params['consultant_id'])->value('dept_id');
  838. $result = false;
  839. Db::beginTransaction();
  840. try {
  841. $info->check_status = $checkStatus;
  842. $info->current_status = $checkStatus;
  843. if ($checkStatus == -1) {
  844. //拒绝录入拒绝理由
  845. $info->check_note = $params['note'] ?? '无拒绝理由';
  846. }
  847. if ($checkStatus == 2) {
  848. //更新到访保护期时间
  849. $info->visit_time = time();
  850. }
  851. $info->dept_id = $deptId ?? 0;
  852. $info->consultant_id = $params['consultant_id'];
  853. $info->check_time = time();
  854. $info->check_admin_id = $adminId;
  855. $result = $info->save();
  856. if ($checkStatus == 2) {
  857. //将其他待审的相同手机号的改拒绝
  858. $where = [
  859. ['mobile' , '=', $mobile],
  860. ['check_status', '=', 1],
  861. ['id', '<>', $customId]
  862. ];
  863. MarketCustomer::where($where)->update(['check_time' => time(),'check_status' => -1, 'current_status' => -1,'check_note' => '客户已经被其他登记']);
  864. }
  865. Db::commit();
  866. }catch (BusinessException|\Exception $e){
  867. Db::rollBack();
  868. return json_fail($e->getMessage());
  869. }
  870. if ($result) {
  871. return json_success('操作成功');
  872. } else {
  873. return json_fail('操作失败');
  874. }
  875. }
  876. /**
  877. * Notes: 数据统计分析
  878. * User: yb
  879. * Date: 2024/8/17
  880. * Time: 11:27
  881. * @param $params
  882. */
  883. public static function statisticsIndex(Request $request)
  884. {
  885. $params = $request->get();
  886. $where = self::commonSearch($params);
  887. //客户总数
  888. $total = MarketCustomer::where($where)->count();
  889. //公池客户
  890. $pubTotal = MarketCustomer::where($where)->where([[function($query){
  891. $diffNums = self::DIFF_TIME;
  892. $query->orWhereRaw("((visit_time + {$diffNums}) - UNIX_TIMESTAMP() <= 0 AND current_status = 2 AND check_status = 2 AND belong_status = 1)")->whereOr('belong_status','<>', 1);
  893. }]])->count();
  894. //已报备
  895. $checkTotal = MarketCustomer::where($where)->where('check_status', 1)->count();
  896. //已到访
  897. $visitTotal = MarketCustomer::where($where)->where(
  898. [[function($query) {
  899. $diffNums = self::DIFF_TIME;
  900. $query->whereRaw("((visit_time + {$diffNums}) - UNIX_TIMESTAMP() > 0) AND current_status = 2 AND check_status = 2")->where('belong_status', 1);
  901. }]]
  902. )->count();
  903. //已来电
  904. $mobileTotal = MarketCustomer::where($where)->where([[function($query) {
  905. $query->where('check_status', '=', 2)->where('current_status', '=', 1);
  906. }]])->count();
  907. //已到访
  908. // $visitTotal = MarketCustomer::where($where)->where([[function($query) {
  909. // $query->where('check_status', '=', 2)->where('current_status', '=', 2);
  910. // }]])->count();
  911. //已缴费
  912. $payTotal = MarketCustomer::where($where)->where([[function($query) {
  913. $query->where('check_status', '=', 2)->where('current_status', '=', 3)->where('belong_status', 1);
  914. }]])->count();
  915. //已成交
  916. $dealTotal = MarketCustomer::where($where)->where([[function($query) {
  917. $query->where('check_status', '=', 2)->where('current_status', '=', 4)->where('belong_status', 1);
  918. }]])->count();
  919. //已缴费 + 已成交 / 客户总数
  920. //报备失败
  921. $failTotal = MarketCustomer::where($where)->where('current_status', -1)->count();
  922. $rant = 0;
  923. if ($total > 0) {
  924. $rant = ($payTotal + $dealTotal) / $total;
  925. }
  926. $rant = sprintf('%.2f', $rant);
  927. $data = [
  928. 'total' => $total,
  929. 'pub_total' => $pubTotal,
  930. 'check_total' => $checkTotal,
  931. 'report_total' => 0,
  932. 'mobile_total' => $mobileTotal,
  933. 'visit_total' => $visitTotal,
  934. 'pay_total' => $payTotal,
  935. 'deal_total' => $dealTotal,
  936. 'fail_total' => $failTotal,
  937. 'rant' => $rant,
  938. ];
  939. return json_success('请求成功', $data);
  940. }
  941. /**
  942. * Notes: 前12个月统计数据
  943. * User: yb
  944. * Date: 2024/8/21
  945. * Time: 15:56
  946. */
  947. public static function statisticsMonth()
  948. {
  949. $months = month_12();
  950. sort($months);
  951. $startDate = $months[0];
  952. $startDateTime = strtotime($startDate.'/01 00:00:00');
  953. $endDateTime = time();
  954. $where = [
  955. ['created_at', '>=', $startDateTime],
  956. ['created_at', '<=', $endDateTime]
  957. ];
  958. $currentTime = time();
  959. $diffNums = self::DIFF_TIME;
  960. $deptIds = TeamService::getIdsByUser();
  961. if (false === $deptIds) {
  962. //无权限
  963. $where[] = ['dept_id', '=', 0];
  964. } else if (is_array($deptIds)) {
  965. //指定团队下的权限
  966. if (!empty($params['dept_id'])) {
  967. $deptId = end($params['dept_id']);
  968. $deptIds = SysDept::where('dept_super_path','like', "%/{$deptId}/%")->where('dept_category', '=', TeamService::DEPT_CATEGORY)->pluck('dept_id')->toArray();
  969. }
  970. $where[] = [function($query) use ($deptIds) {
  971. $query->whereIn('dept_id', $deptIds);
  972. }];
  973. } else {
  974. if (!empty($params['dept_id'])) {
  975. $deptId = end($params['dept_id']);
  976. $deptIds = SysDept::where('dept_super_path','like', "%/{$deptId}/%")->where('dept_category', '=', TeamService::DEPT_CATEGORY)->pluck('dept_id')->toArray();
  977. $where[] = [function($query) use ($deptIds) {
  978. $query->whereIn('dept_id', $deptIds);
  979. }];
  980. }
  981. }
  982. $selectRaw = Db::raw("DATE_FORMAT(FROM_UNIXTIME(created_at), '%Y/%m') as date,count(*) as nums");
  983. $groupRaw = Db::raw("DATE_FORMAT(FROM_UNIXTIME(created_at), '%Y/%m')");
  984. $totalData = MarketCustomer::where($where)->selectRaw($selectRaw)->groupByRaw($groupRaw)->get();
  985. $payData = MarketCustomer::where($where)->where([['current_status', '=', 3], ['check_status', '=', 2]])->selectRaw($selectRaw)->groupByRaw($groupRaw)->get();
  986. $visitData = MarketCustomer::where($where)->where([['current_status', '=', 2], ['check_status', '=', 2]])->selectRaw($selectRaw)->groupByRaw($groupRaw)->get();
  987. $dealData = MarketCustomer::where($where)->where([['current_status', '=', 4], ['check_status', '=', 2]])->selectRaw($selectRaw)->groupByRaw($groupRaw)->get();
  988. $returnData = [
  989. 'total' => $totalData->pluck('nums','date'),
  990. 'pay' => $payData->pluck('nums','date'),
  991. 'visit' => $visitData->pluck('nums','date'),
  992. 'deal' => $dealData->pluck('nums','date'),
  993. 'date' => $months
  994. ];
  995. return json_success('请求成功', $returnData);
  996. }
  997. /**
  998. * Notes: 导出数据
  999. * User: yb
  1000. * Date: 2024/8/17
  1001. * Time: 13:01
  1002. */
  1003. public static function exportData(Request $request)
  1004. {
  1005. $currentTime = time();
  1006. $diffNums = self::DIFF_TIME;
  1007. $params = $request->get();
  1008. $where = self::commonSearch($params);
  1009. if (!empty($params['custom_ids'])) {
  1010. $customIds = $params['custom_ids'];
  1011. $where[] = [function($query) use ($customIds){
  1012. $query->whereIn('id', $customIds);
  1013. }];
  1014. }
  1015. $list = MarketCustomer::where($where)->orderBy('visit_time', 'desc')->get();
  1016. if (!$list->isEmpty()) {
  1017. $consultantKeys = [];
  1018. //查询顾问信息
  1019. $consultantList = Consultant::select(['id', 'name', 'mobile'])->get();
  1020. if (!$consultantList->isEmpty()) {
  1021. foreach ($consultantList->toArray() as $consultantItem) {
  1022. $consultantKeys[$consultantItem['id']] = $consultantItem;
  1023. }
  1024. }
  1025. $teamKeys = TeamService::getItemKeys();
  1026. $returnData = [];
  1027. $genderData = ['', '男', '女'];
  1028. $typeData = ['', '来电', '来访'];
  1029. $currentStatusData = [-1 => '报备失败', 1 => '已报备', 2 => '已到访', 3 => '已缴费', 4 => '已成交'];
  1030. $textConfig = self::config();
  1031. //合并数组并去重
  1032. $type1 = $textConfig['visit_type']['type1'] ?? [];
  1033. $type2 = $textConfig['visit_type']['type2'] ?? [];
  1034. $textTypeKeys = [];
  1035. foreach ($type1 as $k1 => $v1) {
  1036. $textTypeKeys[$k1] = $v1;
  1037. }
  1038. foreach ($type2 as $k2 => $v2) {
  1039. $textTypeKeys[$k2] = $v2;
  1040. }
  1041. foreach ($list as &$item) {
  1042. $visitTime = $item->visit_time;
  1043. $visitTimeStamp = strtotime($visitTime);
  1044. $diff = ($visitTimeStamp + $diffNums) - $currentTime;
  1045. $currentStatus = $item->current_status;//当前状态
  1046. $checkStatus = $item->check_status;//审核状态
  1047. if ($diff <= 0 && $checkStatus == 2 && $currentStatus > 1) {
  1048. $currentStatusText = '公池';
  1049. } else {
  1050. $currentStatusText = $currentStatusData[$item->current_status] ?? '';
  1051. }
  1052. $ageRangeText = $item->age_range > 0 ? $textConfig['age_range'][$item->age_range - 1] ?? '' : '';
  1053. $levelText = $item->level > 0 ? $textConfig['level'][$item->level - 1] ?? '' : '';
  1054. $regionText = $item->region > 0 ? $textConfig['region'][$item->region - 1] ?? '' : '';
  1055. $visitTypeText = $textTypeKeys[$item->visit_type] ?? '';
  1056. $returnData[] = [
  1057. 'name' => $item->name, //客户姓名
  1058. 'mobile' => $item->mobile, //客户电话
  1059. 'mask_mobile' => self::handlePhone($item->mobile),
  1060. 'gender' => $genderData[$item->gender] ?? '', //客户性别
  1061. "report_consultant_name" => $consultantKeys[$item->report_consultant_id]['name'] ?? '', //报备人
  1062. 'consultant_name' => $consultantKeys[$item->consultant_id]['name'] ?? '', //健康顾问
  1063. 'team_name' => TeamService::getTeamName($teamKeys, $item->dept_id), //所属团队
  1064. 'current_status' => $currentStatusText, //当前状态
  1065. 'visit_time' => $item->visit_time, //最后一次跟进时间
  1066. 'check_time' => $item->current_status > 1 ? $item->check_time : '', //首次到访时间
  1067. "age_range" => $ageRangeText, //年龄区间
  1068. "level" => $levelText, //客户等级
  1069. "region" => $regionText, //所在区域
  1070. "visit_type" => $visitTypeText, //来源
  1071. 'created_at' => date('Y-m-d H:i:s', strtotime($item->created_at)) //报备时间
  1072. ];
  1073. }
  1074. return json_success('请求成功', $returnData);
  1075. }
  1076. }
  1077. /**
  1078. * Notes: 对手机号加密处理
  1079. * User: yb
  1080. * Date: 2024/8/8
  1081. * Time: 15:41
  1082. * @param $val
  1083. * @return string|string[]
  1084. */
  1085. public static function handlePhone($val)
  1086. {
  1087. return substr_replace($val, '****', 3, 4);
  1088. }
  1089. /**
  1090. * Notes: 指定顾问
  1091. * User: yb
  1092. * Date: 2024/9/5
  1093. * Time: 12:52
  1094. * @param $params
  1095. */
  1096. public static function appoint($params)
  1097. {
  1098. if (empty($params['id'])) {
  1099. return json_fail('请选择客户');
  1100. }
  1101. if (empty($params['report_consultant_id'])) {
  1102. return json_fail('请选择指定顾问');
  1103. }
  1104. $userId = JwtToken::getCurrentId();
  1105. $relationUserId = $userId;
  1106. $customId = $params['id'];
  1107. $reportConsultantId = $params['report_consultant_id'];
  1108. $customInfo = MarketCustomer::firstWhere(['id' => $customId]);
  1109. if (empty($customInfo)) {
  1110. return json_fail('客户信息不存在');
  1111. }
  1112. $consultantInfo = Consultant::firstWhere(['id' => $reportConsultantId]);
  1113. if (empty($consultantInfo)) {
  1114. return json_fail('顾问信息不存在');
  1115. }
  1116. $currentDeptId = $consultantInfo->dept_id; //当前部门
  1117. $now = time();
  1118. $logData = [
  1119. 'market_customer_id' => $customId,
  1120. 'consultant_id' => $reportConsultantId,
  1121. 'dept_id' => $currentDeptId,
  1122. 'before_consultant_id' => $customInfo->report_consultant_id,
  1123. 'before_dept_id' => $customInfo->dept_id,
  1124. 'note' => $params['note'] ?? '判客指定报备顾问',
  1125. 'change_user_id' => $relationUserId,
  1126. 'change_consultant_id' => 0,
  1127. 'created_at' => $now
  1128. ];
  1129. Db::beginTransaction();
  1130. $result = false;
  1131. try {
  1132. $customInfo->report_consultant_id = $reportConsultantId;
  1133. $customInfo->dept_id = $currentDeptId;
  1134. $result = $customInfo->save();
  1135. MarketCustomerLogs::insert($logData);
  1136. Db::commit();
  1137. }catch (BusinessException|\Exception $e) {
  1138. Db::rollBack();
  1139. return json_fail($e->getMessage());
  1140. }
  1141. if ($result) {
  1142. return json_success('指定成功');
  1143. } else {
  1144. return json_fail('指定失败');
  1145. }
  1146. }
  1147. /**
  1148. * Notes: 导入客户
  1149. * User: yb
  1150. * Date: 2024/9/10
  1151. * Time: 10:30
  1152. * @param $params
  1153. */
  1154. public static function import($params)
  1155. {
  1156. if (empty($params['path'])) {
  1157. return json_fail('文件地址不能为空');
  1158. }
  1159. $path = 'public'.$params['path'];
  1160. if (is_file($path)) {
  1161. $teamKeys = [];
  1162. //查询顾问信息
  1163. $teamData = Db::table('consultant')
  1164. ->leftJoin('sys_dept', 'consultant.dept_id', '=', 'sys_dept.dept_id')
  1165. ->select(['consultant.id', 'consultant.name', 'sys_dept.dept_name', 'sys_dept.dept_id'])
  1166. ->whereNull('consultant.deleted_at')
  1167. ->get();
  1168. if (!($teamData->isEmpty())) {
  1169. foreach ($teamData as $item) {
  1170. $key = $item->name.'-'.$item->dept_name;
  1171. $teamKeys[$key] = [
  1172. 'consultant_id' => $item->id,
  1173. 'dept_id' => $item->dept_id,
  1174. 'name' => $item->name,
  1175. 'dept_name' => $item->dept_name
  1176. ];
  1177. }
  1178. }
  1179. $data = self::readExcel($path);
  1180. // $fields = ['到访时间', '客户姓名', '客户手机号', 'A类', 'B类', 'C类', 'D类', '健康顾问', '报备人', '团队'];
  1181. if (empty($data)) {
  1182. return json_fail('无可导入内容');
  1183. } else {
  1184. $sucNums = 0;
  1185. $errNums = 0;
  1186. $validate = '/^1\d{10}$/';
  1187. $errorData = [];
  1188. Db::beginTransaction();
  1189. try {
  1190. foreach ($data as $key => $val) {
  1191. if ($val[3] == 1) {$level = 1;} else if ($val[4] == 1) {$level = 2;} else if ($val[5] == 1) {$level = 3;} else if ($val[6] == 1) {$level = 4;}
  1192. $line = '姓名:'.$val[1].' 第'.($key + 2).'行:';
  1193. $mobile = $val[2] ?? '';
  1194. $mobile = trim($mobile);
  1195. $error = [];
  1196. $msg = '';
  1197. if (empty($val[7]) && empty($val[8])) {
  1198. $msg = $line.'报备人和顾问必须存在其中之一';
  1199. $val[10] = '报备人和顾问必须存在其中之一';
  1200. // throw new \Exception($line.'报备人和顾问必须存在其中之一');
  1201. }
  1202. if (empty($val[9])) {
  1203. $msg = $line.'无团队信息';
  1204. $val[10] = '无团队信息';
  1205. // throw new \Exception($line.'无团队信息');
  1206. }
  1207. if ($val[0] == '1970-01-01 08:00:00') {
  1208. $msg = $line.'日期格式错误';
  1209. $val[10] = '日期格式错误';
  1210. // throw new \Exception($line.'日期格式错误');
  1211. }
  1212. if (empty($mobile)) {
  1213. $msg = $line.'手机号不能为空';
  1214. $val[10] = '手机号不能为空';
  1215. // throw new \Exception($line.'手机号不能为空');
  1216. }
  1217. if (!preg_match($validate, $mobile)) {
  1218. $msg = $line.'手机号格式非法';
  1219. $val[10] = '手机号格式非法';
  1220. // throw new \Exception($line.'手机号格式非法');
  1221. }
  1222. $consultantName = $val[7];
  1223. $reportName = $val[8];
  1224. $teamName = $val[9];
  1225. $consultantKey = $consultantName.'-'.$teamName;
  1226. $consultantId = $teamKeys[$consultantKey]['consultant_id'] ?? 0;
  1227. $reportKey = $reportName.'-'.$teamName;
  1228. $reportConsultantId = $teamKeys[$reportKey]['consultant_id'] ?? 0;
  1229. if ($consultantId <= 0 && $reportConsultantId <= 0) {
  1230. $msg = $line.'健康顾问或报备人都不存在';
  1231. $val[10] = '健康顾问或报备人都不存在';
  1232. // throw new \Exception($line.'健康顾问或报备人都不存在');
  1233. }
  1234. if ($consultantId > 0) {
  1235. $deptId = $teamKeys[$consultantKey]['dept_id'] ?? 0;
  1236. }
  1237. if ($reportConsultantId > 0) {
  1238. $deptId = $teamKeys[$reportKey]['dept_id'] ?? 0;
  1239. } else {
  1240. if ($consultantId > 0) {
  1241. $reportConsultantId = $consultantId;
  1242. }
  1243. }
  1244. if (empty($deptId)) {
  1245. $msg = $line.'健康顾问或报备人都不存在';
  1246. $val[10] = '健康顾问或报备人都不存在';
  1247. // throw new \Exception($line.'团队不存在');
  1248. }
  1249. if (MarketCustomer::checkCustomExists($val[2])) {
  1250. $msg = $line.'客户已转到访,无法二次录入';
  1251. $val[10] = '客户已转到访,无法二次录入';
  1252. // throw new \Exception($line.'客户已转到访,无法二次录入');
  1253. }
  1254. $result = false;
  1255. if (empty($msg)) {
  1256. //查看手机号是否存在
  1257. $insertData = [
  1258. 'name' => $val[1],
  1259. 'mobile' => $mobile,
  1260. 'level' => $level ?? null,
  1261. 'consultant_id' => $consultantId,
  1262. 'report_consultant_id' => $reportConsultantId,
  1263. 'create_consultant_id' => $reportConsultantId,
  1264. 'dept_id' => $deptId ?? 0,
  1265. 'belong_status' => 1,
  1266. 'current_status' => 1,
  1267. 'check_status' => 1,
  1268. 'check_note' => '',
  1269. 'type' => 1,
  1270. 'visit_time' => strtotime($val[0]),
  1271. 'created_at' => strtotime($val[0])
  1272. ];
  1273. $result = Db::table('market_customer')->insert($insertData);
  1274. } else {
  1275. $val[11] = $line;
  1276. $errorData[] = $val;
  1277. }
  1278. if ($result) {
  1279. $sucNums++;
  1280. } else {
  1281. $errNums++;
  1282. }
  1283. }
  1284. Db::commit();
  1285. }catch (\Exception $e) {
  1286. Db::rollBack();
  1287. return json_fail($e->getMessage());
  1288. }
  1289. }
  1290. } else {
  1291. return json_fail('文件不存在');
  1292. }
  1293. $total = count($data);
  1294. return json_success("全部数据:{$total},成功:{$sucNums},失败:{$errNums}", ['data' => $errorData]);
  1295. }
  1296. /**
  1297. * Notes: 读取excel文件
  1298. * User: yb
  1299. * Date: 2024/9/10
  1300. * Time: 10:41
  1301. * @param $filePath
  1302. */
  1303. public static function readExcel($filePath)
  1304. {
  1305. set_time_limit(0);
  1306. ini_set('memory_limit', '1024M');
  1307. $ext = pathinfo($filePath, PATHINFO_EXTENSION);
  1308. if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
  1309. return json_fail('未知的导入文件类型');
  1310. }
  1311. if ($ext === 'csv') {
  1312. $file = fopen($filePath, 'r');
  1313. $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
  1314. $fp = fopen($filePath, "w");
  1315. $n = 0;
  1316. while ($line = fgets($file)) {
  1317. $line = rtrim($line, "\n\r\0");
  1318. $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
  1319. if ($encoding != 'utf-8') {
  1320. $line = mb_convert_encoding($line, 'utf-8', $encoding);
  1321. }
  1322. if ($n == 0 || preg_match('/^".*"$/', $line)) {
  1323. fwrite($fp, $line . "\n");
  1324. } else {
  1325. fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
  1326. }
  1327. $n++;
  1328. }
  1329. fclose($file) || fclose($fp);
  1330. $reader = new Csv();
  1331. } else if ($ext === 'xls') {
  1332. $reader = new Xls();
  1333. } else {
  1334. $reader = new Xlsx();
  1335. }
  1336. try {
  1337. if (!$PHPExcel = $reader->load($filePath)) {
  1338. return json_fail('未知的导入文件类型');
  1339. }
  1340. $currentSheet = $PHPExcel->getSheet(0); //读取文件中的第一个工作表
  1341. $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
  1342. $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
  1343. $maxColumnNumber = 10;
  1344. $insertData = [];
  1345. for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
  1346. $values = [];
  1347. for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
  1348. $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getFormattedValue();
  1349. if ($currentColumn == 1) {
  1350. $val = date('Y-m-d H:i:s', strtotime($val)); //时间
  1351. }
  1352. $values[] = is_null($val) ? '' : $val;
  1353. }
  1354. $insertData[] = $values;
  1355. }
  1356. }catch (\Exception $e) {
  1357. return json_fail($e->getMessage());
  1358. }
  1359. return $insertData;
  1360. }
  1361. }