CustomService.php 55 KB

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