CustomService.php 57 KB

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