CustomService.php 58 KB

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