CustomService.php 58 KB

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