CustomService.php 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383
  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. $errorData = [];
  1172. Db::beginTransaction();
  1173. try {
  1174. foreach ($data as $key => $val) {
  1175. 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;}
  1176. $line = '姓名:'.$val[1].' 第'.($key + 2).'行:';
  1177. $mobile = $val[2] ?? '';
  1178. $mobile = trim($mobile);
  1179. $error = [];
  1180. $msg = '';
  1181. if (empty($val[7]) && empty($val[8])) {
  1182. $msg = $line.'报备人和顾问必须存在其中之一';
  1183. throw new \Exception($line.'报备人和顾问必须存在其中之一');
  1184. }
  1185. if (empty($val[9])) {
  1186. $msg = $line.'无团队信息';
  1187. throw new \Exception($line.'无团队信息');
  1188. }
  1189. if ($val[0] == '1970-01-01 08:00:00') {
  1190. $msg = $line.'日期格式错误';
  1191. // throw new \Exception($line.'日期格式错误');
  1192. }
  1193. if (empty($mobile)) {
  1194. $msg = $line.'手机号不能为空';
  1195. // throw new \Exception($line.'手机号不能为空');
  1196. }
  1197. if (!preg_match($validate, $mobile)) {
  1198. $msg = $line.'手机号格式非法';
  1199. // throw new \Exception($line.'手机号格式非法');
  1200. }
  1201. $consultantName = $val[7];
  1202. $reportName = $val[8];
  1203. $teamName = $val[9];
  1204. $consultantKey = $consultantName.'-'.$teamName;
  1205. $consultantId = $teamKeys[$consultantKey]['consultant_id'] ?? 0;
  1206. $reportKey = $reportName.'-'.$teamName;
  1207. $reportConsultantId = $teamKeys[$reportKey]['consultant_id'] ?? 0;
  1208. if ($consultantId <= 0 && $reportConsultantId <= 0) {
  1209. $msg = $line.'健康顾问或报备人都不存在';
  1210. // throw new \Exception($line.'健康顾问或报备人都不存在');
  1211. }
  1212. if ($consultantId > 0) {
  1213. $deptId = $teamKeys[$consultantKey]['dept_id'] ?? 0;
  1214. }
  1215. if ($reportConsultantId > 0) {
  1216. $deptId = $teamKeys[$reportKey]['dept_id'] ?? 0;
  1217. } else {
  1218. if ($consultantId > 0) {
  1219. $reportConsultantId = $consultantId;
  1220. }
  1221. }
  1222. if (empty($deptId)) {
  1223. $msg = $line.'健康顾问或报备人都不存在';
  1224. // throw new \Exception($line.'团队不存在');
  1225. }
  1226. if (MarketCustomer::checkCustomExists($val[2])) {
  1227. $msg = $line.'客户已转到访,无法二次录入';
  1228. // throw new \Exception($line.'客户已转到访,无法二次录入');
  1229. }
  1230. //查看手机号是否存在
  1231. $insertData = [
  1232. 'name' => $val[1],
  1233. 'mobile' => $mobile,
  1234. 'level' => $level ?? null,
  1235. 'consultant_id' => $consultantId,
  1236. 'report_consultant_id' => $reportConsultantId,
  1237. 'create_consultant_id' => $reportConsultantId,
  1238. 'dept_id' => $deptId,
  1239. 'belong_status' => 1,
  1240. 'current_status' => 2,
  1241. 'check_status' => 2,
  1242. 'check_note' => '导入的客户信息,无审核人员',
  1243. 'type' => 1,
  1244. 'visit_time' => strtotime('2024-08-31 00:00:00'),
  1245. 'created_at' => strtotime('2024-08-31 00:00:00')
  1246. ];
  1247. $result = false;
  1248. if (empty($msg)) {
  1249. $result = Db::table('market_customer')->insert($insertData);
  1250. } else {
  1251. $errorData[] = [
  1252. 'msg' => $msg,
  1253. 'val' => $val
  1254. ];
  1255. }
  1256. if ($result) {
  1257. $sucNums++;
  1258. } else {
  1259. $errNums++;
  1260. }
  1261. }
  1262. Db::commit();
  1263. }catch (\Exception $e) {
  1264. Db::rollBack();
  1265. return json_fail($e->getMessage());
  1266. }
  1267. }
  1268. } else {
  1269. return json_fail('文件不存在');
  1270. }
  1271. $total = count($data);
  1272. return json_success("全部数据:{$total},成功:{$sucNums},失败:{$errNums}", ['data' => $errorData]);
  1273. }
  1274. /**
  1275. * Notes: 读取excel文件
  1276. * User: yb
  1277. * Date: 2024/9/10
  1278. * Time: 10:41
  1279. * @param $filePath
  1280. */
  1281. public static function readExcel($filePath)
  1282. {
  1283. set_time_limit(0);
  1284. ini_set('memory_limit', '1024M');
  1285. $ext = pathinfo($filePath, PATHINFO_EXTENSION);
  1286. if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
  1287. return json_fail('未知的导入文件类型');
  1288. }
  1289. if ($ext === 'csv') {
  1290. $file = fopen($filePath, 'r');
  1291. $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
  1292. $fp = fopen($filePath, "w");
  1293. $n = 0;
  1294. while ($line = fgets($file)) {
  1295. $line = rtrim($line, "\n\r\0");
  1296. $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
  1297. if ($encoding != 'utf-8') {
  1298. $line = mb_convert_encoding($line, 'utf-8', $encoding);
  1299. }
  1300. if ($n == 0 || preg_match('/^".*"$/', $line)) {
  1301. fwrite($fp, $line . "\n");
  1302. } else {
  1303. fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
  1304. }
  1305. $n++;
  1306. }
  1307. fclose($file) || fclose($fp);
  1308. $reader = new Csv();
  1309. } else if ($ext === 'xls') {
  1310. $reader = new Xls();
  1311. } else {
  1312. $reader = new Xlsx();
  1313. }
  1314. try {
  1315. if (!$PHPExcel = $reader->load($filePath)) {
  1316. return json_fail('未知的导入文件类型');
  1317. }
  1318. $currentSheet = $PHPExcel->getSheet(0); //读取文件中的第一个工作表
  1319. $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
  1320. $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
  1321. $maxColumnNumber = 10;
  1322. $insertData = [];
  1323. for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
  1324. $values = [];
  1325. for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
  1326. $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getFormattedValue();
  1327. if ($currentColumn == 1) {
  1328. $val = date('Y-m-d H:i:s', strtotime($val)); //时间
  1329. }
  1330. $values[] = is_null($val) ? '' : $val;
  1331. }
  1332. $insertData[] = $values;
  1333. }
  1334. }catch (\Exception $e) {
  1335. return json_fail($e->getMessage());
  1336. }
  1337. return $insertData;
  1338. }
  1339. }