CustomService.php 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387
  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::where('name', 'like', "%{$params['consultant_name']}%")
  77. ->where('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::where('name', 'like', "%{$params['report_name']}%")
  85. ->where('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. try {
  471. if (is_array($ids)) {
  472. MarketCustomer::whereIn('id', $ids)->delete();
  473. } else {
  474. MarketCustomer::where('id', $ids)->delete();
  475. }
  476. } catch (\Exception $e) {
  477. return json_fail('删除失败');
  478. }
  479. return json_success('删除成功');
  480. }
  481. /**
  482. * Notes: 跟进记录
  483. * User: yb
  484. * Date: 2024/8/7
  485. * Time: 9:00
  486. * @param Request $request
  487. */
  488. public static function follow(Request $request)
  489. {
  490. $format = $request->get('format', 'normal');
  491. $limit = (int)$request->get('pageSize', $format === 'tree' ? 1000 : 10);
  492. $limit = $limit <= 0 ? 10 : $limit;
  493. $params = $request->get();
  494. $page = (int)$request->get('page');
  495. $page = $page > 0 ? $page : 1;
  496. $where = [];
  497. $whereCustom = [];
  498. $whereConsultant = [];
  499. if (!empty($params['market_customer_id'])) {
  500. $marketCustomerIds = $params['market_customer_id'];
  501. $where[] = [function($query) use ($marketCustomerIds) {
  502. $query->whereIn('market_customer_id', $marketCustomerIds);
  503. }];
  504. }
  505. if (!empty($params['consultant_id'])) {
  506. $consultantId = $params['consultant_id'];
  507. $where[] = [function($query) use ($consultantId) {
  508. $query->whereIn('consultant_id', $consultantId);
  509. }];
  510. }
  511. if (!empty($params['follow_way'])) {
  512. $where[] = ['follow_way', '=', $params['follow_way']];
  513. }
  514. if (!empty($params['custom'])) {
  515. $custom = $params['custom'];
  516. $whereCustom[] = [function($query) use ($custom) {
  517. $query->orWhere('name', 'like', "%{$custom}%")->orWhere('mobile', 'like', "%{$custom}%");
  518. }];
  519. }
  520. if (!empty($params['consultant'])) {
  521. $consultant = $params['consultant'];
  522. $whereConsultant[] = [function($query) use ($consultant) {
  523. $query->orWhere('name', 'like', "%{$consultant}%")->orWhere('mobile', 'like', "%{$consultant}%");
  524. }];
  525. }
  526. if (!empty($params['follow_time'])) {
  527. $datetime = $params['follow_time'];
  528. $datetime[0] = strtotime($datetime[0].' 00:00:00');
  529. $datetime[1] = strtotime($datetime[1].' 23:59:59');
  530. $where[] = [function($query) use ($datetime) {
  531. $query->whereBetween('follow_time', $datetime);
  532. }];
  533. }
  534. $paginator = MarketCustomerFollow::with(['custom', 'consultant'])->whereHas('custom', function($query) use ($whereCustom){
  535. $query->where($whereCustom);
  536. })->whereHas('consultant', function($query) use ($whereConsultant) {
  537. $query->where($whereConsultant);
  538. })->where($where)->orderBy('follow_time', 'desc')->paginate($limit, '*', 'page', $page);
  539. $total = $paginator->total();
  540. $items = $paginator->items();
  541. foreach ($items as &$item) {
  542. if (!empty($item->custom)) {
  543. $item->custom->mask_mobile = self::handlePhone($item->custom->mobile);
  544. }
  545. }
  546. $data = [
  547. 'total' => $total,
  548. 'rows' => $items
  549. ];
  550. return json_success('success', $data);
  551. }
  552. /**
  553. * Notes: 删除跟进记录
  554. * User: yb
  555. * Date: 2024/8/7
  556. * Time: 11:25
  557. * @param $ids
  558. */
  559. public static function deleteFollow($ids)
  560. {
  561. if (!$ids) {
  562. return json_fail("数据错误");
  563. }
  564. if (!is_array($ids)) {
  565. $ids = [$ids];
  566. }
  567. try {
  568. if (is_array($ids)) {
  569. MarketCustomerFollow::whereIn('id', $ids)->delete();
  570. } else {
  571. MarketCustomerFollow::where('id', $ids)->delete();
  572. }
  573. } catch (\Exception $e) {
  574. return json_fail('删除失败');
  575. }
  576. return json_success('删除成功');
  577. }
  578. /**
  579. * Notes: 转移客户
  580. * User: yb
  581. * Date: 2024/8/7
  582. * Time: 14:27
  583. * @param $params
  584. */
  585. public static function moveCustom($params)
  586. {
  587. $userId = JwtToken::getCurrentId();
  588. $moveType = $params['move_type'] ?? 0;
  589. if ($moveType == 1) {
  590. $currentDeptId = $params['dept_id'];
  591. $currentConsultantId = 0;
  592. } else {
  593. $currentConsultantId = $params['consultant_id'] ?? 0; //当前顾问
  594. $consultantInfo = Consultant::firstWhere(['id' => $currentConsultantId]);
  595. if (empty($consultantInfo)) {
  596. return json_fail('顾问不存在');
  597. }
  598. $currentDeptId = $consultantInfo->dept_id; //当前部门
  599. }
  600. $consultantIds = $params['move_consultant_id'] ?? [];
  601. $customIds = $params['move_market_customer_id'] ?? [];
  602. $note = $params['note'] ?? '';
  603. $logsInertData = [];
  604. $now = time();
  605. $whereCustom = [];
  606. if (!empty($customIds)) {
  607. $whereCustom[] = [function($query) use ($customIds) {
  608. $query->whereIn('id', $customIds);
  609. }];
  610. }
  611. if (!empty($consultantIds)) {
  612. $whereCustom[] = [function($query) use ($consultantIds) {
  613. $query->whereIn('consultant_id', $consultantIds);
  614. }];
  615. }
  616. $customList = MarketCustomer::where($whereCustom)->select(['id','consultant_id','dept_id','visit_time','check_status','current_status'])->get();
  617. if (!$customList->isEmpty()) {
  618. foreach ($customList as$item) {
  619. $logsInertData[] = [
  620. 'market_customer_id' => $item->id,
  621. 'consultant_id' => $currentConsultantId,
  622. 'dept_id' => $currentDeptId,
  623. 'before_consultant_id' => $item->consultant_id,
  624. 'before_dept_id' => $item->dept_id,
  625. 'note' => $note,
  626. 'change_user_id' => $userId,
  627. 'created_at' => $now
  628. ];
  629. }
  630. }
  631. if ($customList->isEmpty()) {
  632. return json_fail('移交的客户信息不存在');
  633. }
  634. if (empty($logsInertData)) {
  635. return json_fail('移交记录不能为空');
  636. }
  637. $diffTime = self::DIFF_TIME;
  638. Db::beginTransaction();
  639. $result = false;
  640. try {
  641. foreach ($customList as $item) {
  642. if ($currentConsultantId != 0) {
  643. //移交至指定顾问
  644. //判断一下是否到了到访的过期时间,如果过期了就更新到访时间,没过期时间就不变
  645. if ($item->check_status == 2 && $item->current_status == 2) {
  646. $visitTime = $item->visit_time;
  647. $diff = strtotime($visitTime) + $diffTime - time();
  648. if ($diff <= 0) {
  649. $item->visit_time = time();
  650. }
  651. }
  652. } else {
  653. //移交至其他团队
  654. $item->visit_time = time() - self::DIFF_TIME;
  655. }
  656. $item->consultant_id = $currentConsultantId;
  657. $item->dept_id = $currentDeptId;
  658. $item->save();
  659. }
  660. $result = MarketCustomerLogs::insert($logsInertData);
  661. Db::commit();
  662. }catch (BusinessException|\Exception $e) {
  663. Db::rollBack();
  664. return json_fail($e->getMessage());
  665. }
  666. if ($result) {
  667. return json_success('移交成功');
  668. } else {
  669. return json_fail('移交失败');
  670. }
  671. }
  672. /**
  673. * Notes: 转移记录
  674. * User: yb
  675. * Date: 2024/8/7
  676. * Time: 15:33
  677. * @param Request $request
  678. */
  679. public static function moveLogs(Request $request)
  680. {
  681. $format = $request->get('format', 'normal');
  682. $limit = (int)$request->get('pageSize', $format === 'tree' ? 1000 : 10);
  683. $limit = $limit <= 0 ? 10 : $limit;
  684. $params = $request->get();
  685. $page = (int)$request->get('page');
  686. $page = $page > 0 ? $page : 1;
  687. $platform = 0;
  688. $where = [];
  689. $whereCustom = [];
  690. $whereCurrent = [];
  691. $whereBefore = [];
  692. $whereOpBack = [];
  693. $whereOpFront = [];
  694. if (!empty($params['market_customer_id'])) {
  695. $where[] = ['market_customer_id', '=', $params['market_customer_id']];
  696. }
  697. if (!empty($params['consultant_id'])) {
  698. $consultantIds = $params['consultant_id'];
  699. $where[] = [function($query) use ($consultantIds) {
  700. $query->orWhereIn('consultant_id', $consultantIds)->orWhereIn('before_consultant_id', $consultantIds);
  701. }];
  702. }
  703. if (!empty($params['custom'])) {
  704. //客户信息
  705. $custom = $params['custom'];
  706. $whereCustom[] = ['name', 'like', "%{$custom}%"];
  707. }
  708. if (!empty($params['current_consultant'])) {
  709. //当前员工信息
  710. $current = $params['current_consultant'];
  711. $whereCurrent[] = ['name', 'like', "%{$current}%"];
  712. }
  713. if (!empty($params['before_consultant'])) {
  714. //转移前员工信息
  715. $before = $params['before_consultant'];
  716. $whereBefore[] = ['name', 'like', "%{$before}%"];
  717. }
  718. if (!empty($params['platform'])) {
  719. $platform = $params['platform'];
  720. if ($platform == 1) {
  721. //后台
  722. $where[] = ['change_user_id', '<>', null];
  723. $where[] = ['change_user_id', '=', null];
  724. } else {
  725. //小程序
  726. $where[] = ['change_user_id', '=', null];
  727. $where[] = ['change_user_id', '<>', null];
  728. }
  729. }
  730. if (!empty($params['op_name'])) {
  731. $opName = $params['op_name'];
  732. if (!empty($platform)) {
  733. if ($platform == 1) {
  734. $whereOpBack[] = ['user_name', 'like', "%{$opName}%"];
  735. } else {
  736. $whereOpFront[] = ['name', 'like', "%{$opName}%"];
  737. }
  738. } else {
  739. $whereOpBack[] = [function($query) use ($opName) {
  740. $query->orWhere('user_name', 'like', "%{$opName}%");
  741. }];
  742. $whereOpFront[] = [function($query) use ($opName) {
  743. $query->orWhere('name', 'like', "%{$opName}%");
  744. }];
  745. }
  746. }
  747. if (!empty($params['created_at'])) {
  748. $createdDate = $params['created_at'];
  749. $createdDate[0] = strtotime($createdDate[0].' 00:00:00');
  750. $createdDate[1] = strtotime($createdDate[1].' 23:59:59');
  751. $where[] = [function($query) use ($createdDate) {
  752. $query->whereBetween('created_at', $createdDate);
  753. }];
  754. }
  755. $paginator = MarketCustomerLogs::with(['custom' => function($query) {
  756. $query->select('id', 'name', 'mobile');
  757. }, 'beforeMan' => function($query) {
  758. $query->select('id', 'name', 'mobile');
  759. }, 'currentMan' => function($query) {
  760. $query->select('id', 'name', 'mobile');
  761. }, 'beforeDept' => function($query) {
  762. $query->select('dept_id', 'dept_name');
  763. }, 'currentDept' => function($query) {
  764. $query->select('dept_id', 'dept_name');
  765. }])
  766. // ->whereHas('custom', function ($query) use ($whereCustom) {
  767. // $query->where($whereCustom);
  768. // })
  769. // ->whereHas('currentMan', function ($query) use ($whereCurrent) {
  770. // $query->where($whereCurrent);
  771. // })
  772. // ->whereHas('beforeMan', function ($query) use ($whereBefore) {
  773. // $query->where($whereBefore);
  774. // })
  775. ->where($where)
  776. ->orderBy('created_at', 'desc')
  777. ->paginate($limit, '*', 'page', $page);
  778. $total = $paginator->total();
  779. $items = $paginator->items();
  780. foreach ($items as &$item) {
  781. if (!empty($item->custom)) {
  782. $item->custom->mask_mobile = self::handlePhone($item->custom->mobile);
  783. }
  784. }
  785. $data = [
  786. 'total' => $total,
  787. 'rows' => $items
  788. ];
  789. return json_success('success', $data);
  790. }
  791. /**
  792. * Notes: 审核客户
  793. * User: yb
  794. * Date: 2024/8/16
  795. * Time: 11:21
  796. * @param $params
  797. */
  798. public static function checkCustom($params)
  799. {
  800. $adminId = JwtToken::getCurrentId();
  801. //查询客户是否已经存在
  802. $customId = $params['id'];
  803. $checkStatus = $params['check_status'];
  804. if (!in_array($checkStatus, [-1,2])) {
  805. return json_fail('状态值非法');
  806. }
  807. $info = MarketCustomer::firstWhere(['id' => $customId]);
  808. if (empty($info)) {
  809. return json_fail('客户不存在');
  810. }
  811. $status = $info->check_status;
  812. if ($status != 1) {
  813. return json_fail('客户不是待转到访状态');
  814. }
  815. $mobile = $info->mobile;
  816. if ($checkStatus == 2) {
  817. if (MarketCustomer::checkCustomExists($mobile)) {
  818. return json_fail('客户已经存在');
  819. }
  820. }
  821. $result = false;
  822. Db::beginTransaction();
  823. try {
  824. $info->check_status = $checkStatus;
  825. $info->current_status = $checkStatus;
  826. if ($checkStatus == -1) {
  827. //拒绝录入拒绝理由
  828. $info->check_note = $params['note'] ?? '无拒绝理由';
  829. }
  830. if ($checkStatus == 2) {
  831. //更新到访保护期时间
  832. $info->visit_time = time();
  833. }
  834. $info->consultant_id = $params['consultant_id'];
  835. $info->check_time = time();
  836. $info->check_admin_id = $adminId;
  837. $result = $info->save();
  838. if ($checkStatus == 2) {
  839. //将其他待审的相同手机号的改拒绝
  840. $where = [
  841. ['mobile' , '=', $mobile],
  842. ['check_status', '=', 1],
  843. ['id', '<>', $customId]
  844. ];
  845. MarketCustomer::where($where)->update(['check_time' => time(),'check_status' => -1, 'current_status' => -1,'check_note' => '客户已经被其他登记']);
  846. }
  847. Db::commit();
  848. }catch (BusinessException|\Exception $e){
  849. Db::rollBack();
  850. return json_fail($e->getMessage());
  851. }
  852. if ($result) {
  853. return json_success('操作成功');
  854. } else {
  855. return json_fail('操作失败');
  856. }
  857. }
  858. /**
  859. * Notes: 数据统计分析
  860. * User: yb
  861. * Date: 2024/8/17
  862. * Time: 11:27
  863. * @param $params
  864. */
  865. public static function statisticsIndex(Request $request)
  866. {
  867. $params = $request->get();
  868. $where = self::commonSearch($params);
  869. //客户总数
  870. $total = MarketCustomer::where($where)->count();
  871. //公池客户
  872. $pubTotal = MarketCustomer::where($where)->where([[function($query){
  873. $diffNums = self::DIFF_TIME;
  874. $query->orWhereRaw("((visit_time + {$diffNums}) - UNIX_TIMESTAMP() <= 0 AND current_status = 2 AND check_status = 2 AND belong_status = 1)")->whereOr('belong_status','<>', 1);
  875. }]])->count();
  876. //已报备
  877. $checkTotal = MarketCustomer::where($where)->where('check_status', 1)->count();
  878. //已到访
  879. $visitTotal = MarketCustomer::where($where)->where(
  880. [[function($query) {
  881. $diffNums = self::DIFF_TIME;
  882. $query->whereRaw("((visit_time + {$diffNums}) - UNIX_TIMESTAMP() > 0) AND current_status = 2 AND check_status = 2")->where('belong_status', 1);
  883. }]]
  884. )->count();
  885. //已来电
  886. $mobileTotal = MarketCustomer::where($where)->where([[function($query) {
  887. $query->where('check_status', '=', 2)->where('current_status', '=', 1);
  888. }]])->count();
  889. //已到访
  890. // $visitTotal = MarketCustomer::where($where)->where([[function($query) {
  891. // $query->where('check_status', '=', 2)->where('current_status', '=', 2);
  892. // }]])->count();
  893. //已缴费
  894. $payTotal = MarketCustomer::where($where)->where([[function($query) {
  895. $query->where('check_status', '=', 2)->where('current_status', '=', 3)->where('belong_status', 1);
  896. }]])->count();
  897. //已成交
  898. $dealTotal = MarketCustomer::where($where)->where([[function($query) {
  899. $query->where('check_status', '=', 2)->where('current_status', '=', 4)->where('belong_status', 1);
  900. }]])->count();
  901. //已缴费 + 已成交 / 客户总数
  902. //报备失败
  903. $failTotal = MarketCustomer::where($where)->where('current_status', -1)->count();
  904. $rant = 0;
  905. if ($total > 0) {
  906. $rant = ($payTotal + $dealTotal) / $total;
  907. }
  908. $rant = sprintf('%.2f', $rant);
  909. $data = [
  910. 'total' => $total,
  911. 'pub_total' => $pubTotal,
  912. 'check_total' => $checkTotal,
  913. 'report_total' => 0,
  914. 'mobile_total' => $mobileTotal,
  915. 'visit_total' => $visitTotal,
  916. 'pay_total' => $payTotal,
  917. 'deal_total' => $dealTotal,
  918. 'fail_total' => $failTotal,
  919. 'rant' => $rant,
  920. ];
  921. return json_success('请求成功', $data);
  922. }
  923. /**
  924. * Notes: 前12个月统计数据
  925. * User: yb
  926. * Date: 2024/8/21
  927. * Time: 15:56
  928. */
  929. public static function statisticsMonth()
  930. {
  931. $months = month_12();
  932. sort($months);
  933. $startDate = $months[0];
  934. $startDateTime = strtotime($startDate.'/01 00:00:00');
  935. $endDateTime = time();
  936. $where = [
  937. ['created_at', '>=', $startDateTime],
  938. ['created_at', '<=', $endDateTime]
  939. ];
  940. $currentTime = time();
  941. $diffNums = self::DIFF_TIME;
  942. $deptIds = TeamService::getIdsByUser();
  943. if (false === $deptIds) {
  944. //无权限
  945. $where[] = ['dept_id', '=', 0];
  946. } else if (is_array($deptIds)) {
  947. //指定团队下的权限
  948. if (!empty($params['dept_id'])) {
  949. $deptId = end($params['dept_id']);
  950. $deptIds = SysDept::where('dept_super_path','like', "%/{$deptId}/%")->where('dept_category', '=', TeamService::DEPT_CATEGORY)->pluck('dept_id')->toArray();
  951. }
  952. $where[] = [function($query) use ($deptIds) {
  953. $query->whereIn('dept_id', $deptIds);
  954. }];
  955. } else {
  956. if (!empty($params['dept_id'])) {
  957. $deptId = end($params['dept_id']);
  958. $deptIds = SysDept::where('dept_super_path','like', "%/{$deptId}/%")->where('dept_category', '=', TeamService::DEPT_CATEGORY)->pluck('dept_id')->toArray();
  959. $where[] = [function($query) use ($deptIds) {
  960. $query->whereIn('dept_id', $deptIds);
  961. }];
  962. }
  963. }
  964. $selectRaw = Db::raw("DATE_FORMAT(FROM_UNIXTIME(created_at), '%Y/%m') as date,count(*) as nums");
  965. $groupRaw = Db::raw("DATE_FORMAT(FROM_UNIXTIME(created_at), '%Y/%m')");
  966. $totalData = MarketCustomer::where($where)->selectRaw($selectRaw)->groupByRaw($groupRaw)->get();
  967. $payData = MarketCustomer::where($where)->where([['current_status', '=', 3], ['check_status', '=', 2]])->selectRaw($selectRaw)->groupByRaw($groupRaw)->get();
  968. $visitData = MarketCustomer::where($where)->where([['current_status', '=', 2], ['check_status', '=', 2]])->selectRaw($selectRaw)->groupByRaw($groupRaw)->get();
  969. $dealData = MarketCustomer::where($where)->where([['current_status', '=', 4], ['check_status', '=', 2]])->selectRaw($selectRaw)->groupByRaw($groupRaw)->get();
  970. $returnData = [
  971. 'total' => $totalData->pluck('nums','date'),
  972. 'pay' => $payData->pluck('nums','date'),
  973. 'visit' => $visitData->pluck('nums','date'),
  974. 'deal' => $dealData->pluck('nums','date'),
  975. 'date' => $months
  976. ];
  977. return json_success('请求成功', $returnData);
  978. }
  979. /**
  980. * Notes: 导出数据
  981. * User: yb
  982. * Date: 2024/8/17
  983. * Time: 13:01
  984. */
  985. public static function exportData(Request $request)
  986. {
  987. $currentTime = time();
  988. $diffNums = self::DIFF_TIME;
  989. $params = $request->get();
  990. $where = self::commonSearch($params);
  991. if (!empty($params['custom_ids'])) {
  992. $customIds = $params['custom_ids'];
  993. $where[] = [function($query) use ($customIds){
  994. $query->whereIn('id', $customIds);
  995. }];
  996. }
  997. $list = MarketCustomer::where($where)->orderBy('visit_time', 'desc')->get();
  998. if (!$list->isEmpty()) {
  999. $consultantKeys = [];
  1000. //查询顾问信息
  1001. $consultantList = Consultant::select(['id', 'name', 'mobile'])->get();
  1002. if (!$consultantList->isEmpty()) {
  1003. foreach ($consultantList->toArray() as $consultantItem) {
  1004. $consultantKeys[$consultantItem['id']] = $consultantItem;
  1005. }
  1006. }
  1007. $teamKeys = TeamService::getItemKeys();
  1008. $returnData = [];
  1009. $genderData = ['', '男', '女'];
  1010. $typeData = ['', '来电', '来访'];
  1011. $currentStatusData = [-1 => '无效客户', 1 => '已来电', 2 => '已到访', 3 => '已缴费', 4 => '已成交'];
  1012. foreach ($list as &$item) {
  1013. $visitTime = $item->visit_time;
  1014. $visitTimeStamp = strtotime($visitTime);
  1015. $diff = ($visitTimeStamp + $diffNums) - $currentTime;
  1016. $currentStatus = $item->current_status;//当前状态
  1017. $checkStatus = $item->check_status;//审核状态
  1018. if ($checkStatus == 1) {
  1019. $currentStatusText = '待审核';
  1020. }
  1021. if ($checkStatus == -1) {
  1022. $currentStatusText = '已失效';
  1023. }
  1024. if ($checkStatus == 2) {
  1025. //审核通过
  1026. if ($currentStatus > 1) {
  1027. $currentStatusText = $currentStatusData[$currentStatus] ?? '';
  1028. }
  1029. if ($currentStatus == 1) {
  1030. if ($diff > 0) {
  1031. $currentStatusText = $currentStatusData[$currentStatus] ?? '';
  1032. } else {
  1033. $currentStatusText = '已失效';
  1034. }
  1035. }
  1036. if ($currentStatus == -1) {
  1037. $currentStatusText = '无效客户';
  1038. }
  1039. }
  1040. $returnData[] = [
  1041. 'name' => $item->name,
  1042. 'mobile' => $item->mobile,
  1043. 'mask_mobile' => self::handlePhone($item->mobile),
  1044. 'gender' => $genderData[$item->gender] ?? '',
  1045. 'type' => $typeData[$item->type] ?? '',
  1046. 'consultant_name' => $consultantKeys[$item->consultant_id]['name'] ?? '',
  1047. 'consultant_mobile' => $consultantKeys[$item->consultant_id]['mobile'] ?? '',
  1048. 'team_name' => TeamService::getTeamName($teamKeys, $item->dept_id),
  1049. 'current_status' => $currentStatusText, //当前状态
  1050. 'visit_time' => $item->visit_time,
  1051. 'created_at' => date('Y-m-d H:i:s',strtotime($item->created_at))
  1052. ];
  1053. }
  1054. return json_success('请求成功', $returnData);
  1055. }
  1056. }
  1057. /**
  1058. * Notes: 对手机号加密处理
  1059. * User: yb
  1060. * Date: 2024/8/8
  1061. * Time: 15:41
  1062. * @param $val
  1063. * @return string|string[]
  1064. */
  1065. public static function handlePhone($val)
  1066. {
  1067. return substr_replace($val, '****', 3, 4);
  1068. }
  1069. /**
  1070. * Notes: 指定顾问
  1071. * User: yb
  1072. * Date: 2024/9/5
  1073. * Time: 12:52
  1074. * @param $params
  1075. */
  1076. public static function appoint($params)
  1077. {
  1078. if (empty($params['id'])) {
  1079. return json_fail('请选择客户');
  1080. }
  1081. if (empty($params['report_consultant_id'])) {
  1082. return json_fail('请选择指定顾问');
  1083. }
  1084. $userId = JwtToken::getCurrentId();
  1085. $relationUserId = $userId;
  1086. $customId = $params['id'];
  1087. $reportConsultantId = $params['report_consultant_id'];
  1088. $customInfo = MarketCustomer::firstWhere(['id' => $customId]);
  1089. if (empty($customInfo)) {
  1090. return json_fail('客户信息不存在');
  1091. }
  1092. $consultantInfo = Consultant::firstWhere(['id' => $reportConsultantId]);
  1093. if (empty($consultantInfo)) {
  1094. return json_fail('顾问信息不存在');
  1095. }
  1096. $currentDeptId = $consultantInfo->dept_id; //当前部门
  1097. $now = time();
  1098. $logData = [
  1099. 'market_customer_id' => $customId,
  1100. 'consultant_id' => $reportConsultantId,
  1101. 'dept_id' => $currentDeptId,
  1102. 'before_consultant_id' => $customInfo->report_consultant_id,
  1103. 'before_dept_id' => $customInfo->dept_id,
  1104. 'note' => $params['note'] ?? '判客指定报备顾问',
  1105. 'change_user_id' => $relationUserId,
  1106. 'change_consultant_id' => 0,
  1107. 'created_at' => $now
  1108. ];
  1109. Db::beginTransaction();
  1110. $result = false;
  1111. try {
  1112. $customInfo->report_consultant_id = $reportConsultantId;
  1113. $customInfo->dept_id = $currentDeptId;
  1114. $result = $customInfo->save();
  1115. MarketCustomerLogs::insert($logData);
  1116. Db::commit();
  1117. }catch (BusinessException|\Exception $e) {
  1118. Db::rollBack();
  1119. return json_fail($e->getMessage());
  1120. }
  1121. if ($result) {
  1122. return json_success('指定成功');
  1123. } else {
  1124. return json_fail('指定失败');
  1125. }
  1126. }
  1127. /**
  1128. * Notes: 导入客户
  1129. * User: yb
  1130. * Date: 2024/9/10
  1131. * Time: 10:30
  1132. * @param $params
  1133. */
  1134. public static function import($params)
  1135. {
  1136. if (empty($params['path'])) {
  1137. return json_fail('文件地址不能为空');
  1138. }
  1139. $path = 'public'.$params['path'];
  1140. if (is_file($path)) {
  1141. $teamKeys = [];
  1142. //查询顾问信息
  1143. $teamData = Db::table('consultant')
  1144. ->leftJoin('sys_dept', 'consultant.dept_id', '=', 'sys_dept.dept_id')
  1145. ->select(['consultant.id', 'consultant.name', 'sys_dept.dept_name', 'sys_dept.dept_id'])
  1146. ->whereNull('consultant.deleted_at')
  1147. ->get();
  1148. if (!($teamData->isEmpty())) {
  1149. foreach ($teamData as $item) {
  1150. $key = $item->name.'-'.$item->dept_name;
  1151. $teamKeys[$key] = [
  1152. 'consultant_id' => $item->id,
  1153. 'dept_id' => $item->dept_id,
  1154. 'name' => $item->name,
  1155. 'dept_name' => $item->dept_name
  1156. ];
  1157. }
  1158. }
  1159. $data = self::readExcel($path);
  1160. // $fields = ['到访时间', '客户姓名', '客户手机号', 'A类', 'B类', 'C类', 'D类', '健康顾问', '报备人', '团队'];
  1161. if (empty($data)) {
  1162. return json_fail('无可导入内容');
  1163. } else {
  1164. $sucNums = 0;
  1165. $errNums = 0;
  1166. $validate = '/^1\d{10}$/';
  1167. $errorData = [];
  1168. Db::beginTransaction();
  1169. try {
  1170. foreach ($data as $key => $val) {
  1171. 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;}
  1172. $line = '姓名:'.$val[1].' 第'.($key + 2).'行:';
  1173. $mobile = $val[2] ?? '';
  1174. $mobile = trim($mobile);
  1175. $error = [];
  1176. $msg = '';
  1177. if (empty($val[7]) && empty($val[8])) {
  1178. $msg = $line.'报备人和顾问必须存在其中之一';
  1179. $val[10] = '报备人和顾问必须存在其中之一';
  1180. // throw new \Exception($line.'报备人和顾问必须存在其中之一');
  1181. }
  1182. if (empty($val[9])) {
  1183. $msg = $line.'无团队信息';
  1184. $val[10] = '无团队信息';
  1185. // throw new \Exception($line.'无团队信息');
  1186. }
  1187. if ($val[0] == '1970-01-01 08:00:00') {
  1188. $msg = $line.'日期格式错误';
  1189. $val[10] = '日期格式错误';
  1190. // throw new \Exception($line.'日期格式错误');
  1191. }
  1192. if (empty($mobile)) {
  1193. $msg = $line.'手机号不能为空';
  1194. $val[10] = '手机号不能为空';
  1195. // throw new \Exception($line.'手机号不能为空');
  1196. }
  1197. if (!preg_match($validate, $mobile)) {
  1198. $msg = $line.'手机号格式非法';
  1199. $val[10] = '手机号格式非法';
  1200. // throw new \Exception($line.'手机号格式非法');
  1201. }
  1202. $consultantName = $val[7];
  1203. $reportName = $val[8];
  1204. $teamName = $val[9];
  1205. $consultantKey = $consultantName.'-'.$teamName;
  1206. $consultantId = $teamKeys[$consultantKey]['consultant_id'] ?? 0;
  1207. $reportKey = $reportName.'-'.$teamName;
  1208. $reportConsultantId = $teamKeys[$reportKey]['consultant_id'] ?? 0;
  1209. if ($consultantId <= 0 && $reportConsultantId <= 0) {
  1210. $msg = $line.'健康顾问或报备人都不存在';
  1211. $val[10] = '健康顾问或报备人都不存在';
  1212. // throw new \Exception($line.'健康顾问或报备人都不存在');
  1213. }
  1214. if ($consultantId > 0) {
  1215. $deptId = $teamKeys[$consultantKey]['dept_id'] ?? 0;
  1216. }
  1217. if ($reportConsultantId > 0) {
  1218. $deptId = $teamKeys[$reportKey]['dept_id'] ?? 0;
  1219. } else {
  1220. if ($consultantId > 0) {
  1221. $reportConsultantId = $consultantId;
  1222. }
  1223. }
  1224. if (empty($deptId)) {
  1225. $msg = $line.'健康顾问或报备人都不存在';
  1226. $val[10] = '健康顾问或报备人都不存在';
  1227. // throw new \Exception($line.'团队不存在');
  1228. }
  1229. if (MarketCustomer::checkCustomExists($val[2])) {
  1230. $msg = $line.'客户已转到访,无法二次录入';
  1231. $val[10] = '客户已转到访,无法二次录入';
  1232. // throw new \Exception($line.'客户已转到访,无法二次录入');
  1233. }
  1234. $result = false;
  1235. if (empty($msg)) {
  1236. //查看手机号是否存在
  1237. $insertData = [
  1238. 'name' => $val[1],
  1239. 'mobile' => $mobile,
  1240. 'level' => $level ?? null,
  1241. 'consultant_id' => $consultantId,
  1242. 'report_consultant_id' => $reportConsultantId,
  1243. 'create_consultant_id' => $reportConsultantId,
  1244. 'dept_id' => $deptId ?? 0,
  1245. 'belong_status' => 1,
  1246. 'current_status' => 2,
  1247. 'check_status' => 2,
  1248. 'check_note' => '导入的客户信息,无审核人员',
  1249. 'type' => 1,
  1250. 'visit_time' => strtotime($val[0]),
  1251. 'created_at' => strtotime($val[0])
  1252. ];
  1253. $result = Db::table('market_customer')->insert($insertData);
  1254. } else {
  1255. $val[11] = $line;
  1256. $errorData[] = $val;
  1257. }
  1258. if ($result) {
  1259. $sucNums++;
  1260. } else {
  1261. $errNums++;
  1262. }
  1263. }
  1264. Db::commit();
  1265. }catch (\Exception $e) {
  1266. Db::rollBack();
  1267. return json_fail($e->getMessage());
  1268. }
  1269. }
  1270. } else {
  1271. return json_fail('文件不存在');
  1272. }
  1273. $total = count($data);
  1274. return json_success("全部数据:{$total},成功:{$sucNums},失败:{$errNums}", ['data' => $errorData]);
  1275. }
  1276. /**
  1277. * Notes: 读取excel文件
  1278. * User: yb
  1279. * Date: 2024/9/10
  1280. * Time: 10:41
  1281. * @param $filePath
  1282. */
  1283. public static function readExcel($filePath)
  1284. {
  1285. set_time_limit(0);
  1286. ini_set('memory_limit', '1024M');
  1287. $ext = pathinfo($filePath, PATHINFO_EXTENSION);
  1288. if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
  1289. return json_fail('未知的导入文件类型');
  1290. }
  1291. if ($ext === 'csv') {
  1292. $file = fopen($filePath, 'r');
  1293. $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
  1294. $fp = fopen($filePath, "w");
  1295. $n = 0;
  1296. while ($line = fgets($file)) {
  1297. $line = rtrim($line, "\n\r\0");
  1298. $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
  1299. if ($encoding != 'utf-8') {
  1300. $line = mb_convert_encoding($line, 'utf-8', $encoding);
  1301. }
  1302. if ($n == 0 || preg_match('/^".*"$/', $line)) {
  1303. fwrite($fp, $line . "\n");
  1304. } else {
  1305. fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
  1306. }
  1307. $n++;
  1308. }
  1309. fclose($file) || fclose($fp);
  1310. $reader = new Csv();
  1311. } else if ($ext === 'xls') {
  1312. $reader = new Xls();
  1313. } else {
  1314. $reader = new Xlsx();
  1315. }
  1316. try {
  1317. if (!$PHPExcel = $reader->load($filePath)) {
  1318. return json_fail('未知的导入文件类型');
  1319. }
  1320. $currentSheet = $PHPExcel->getSheet(0); //读取文件中的第一个工作表
  1321. $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
  1322. $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
  1323. $maxColumnNumber = 10;
  1324. $insertData = [];
  1325. for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
  1326. $values = [];
  1327. for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
  1328. $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getFormattedValue();
  1329. if ($currentColumn == 1) {
  1330. $val = date('Y-m-d H:i:s', strtotime($val)); //时间
  1331. }
  1332. $values[] = is_null($val) ? '' : $val;
  1333. }
  1334. $insertData[] = $values;
  1335. }
  1336. }catch (\Exception $e) {
  1337. return json_fail($e->getMessage());
  1338. }
  1339. return $insertData;
  1340. }
  1341. }