AutomaticDispatch.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. <?php
  2. namespace app\common\command;
  3. use think\facade\Db;
  4. use think\facade\Log;
  5. use think\console\Input;
  6. use think\console\Output;
  7. use think\console\Command;
  8. use app\adminapi\service\WeCallService;
  9. use app\common\model\works\ServiceWork;
  10. use app\common\model\goods_time\GoodsTime;
  11. use app\common\model\master_worker\MasterWorker;
  12. use app\common\model\works\ServiceWorkAnomalous;
  13. use app\common\model\master_worker\MasterWorkerTeam;
  14. use app\common\model\works\ServiceWorkAllocateWorkerLog;
  15. use app\workerapi\logic\ServiceWorkerAllocateWorkerLogic;
  16. use app\common\model\master_worker\MasterWorkerServiceTime;
  17. class AutomaticDispatch extends Command
  18. {
  19. //地理时效评分占比
  20. protected $distanceRate = 0.25;
  21. //工程师权重评分占比
  22. protected $weightRate = 0.2;
  23. //工程师综合评分占比
  24. protected $comprehensiveRate = 0.55;
  25. //默认服务时长 180 分钟
  26. protected $defaultServiceTime = 180;
  27. //外呼客户列表
  28. protected $customerList = [];
  29. //服务类目
  30. protected $categoryType = [
  31. 1 => '安装',
  32. 2 => '维修',
  33. 3 => '清洗',
  34. ];
  35. protected function configure()
  36. {
  37. $this->setName('automatic_dispatch')
  38. ->setDescription('自动派单');
  39. }
  40. protected function execute(Input $input, Output $output)
  41. {
  42. //自动派单
  43. $this->autoDispatch();
  44. //执行外呼任务
  45. $h = date('H');
  46. if ($h >= 8 && $h <= 22) {
  47. $this->startTask();
  48. }
  49. //异常工单:上门时间超过两小时状态未变更已上门
  50. $this->workAnomalous();
  51. }
  52. /**
  53. * 异常工单:上门时间超过两小时状态未变更已上门
  54. */
  55. protected function workAnomalous()
  56. {
  57. $size = 100;
  58. $startTime = time() - 7200; // 当前时间减去7200秒(2小时)
  59. $list = ServiceWork::alias("a")
  60. ->leftJoin('service_work_anomalous b','a.id = b.work_id')
  61. ->where('a.work_status',3)
  62. ->where('a.service_status','<',2)
  63. ->where('a.refund_approval',0)
  64. ->where('a.work_pay_status',1)
  65. ->where('a.appointment_time','<=', $startTime)
  66. ->whereNull('b.id')
  67. ->field('a.id,a.appointment_time,b.id as anomalous_id')
  68. ->order('a.create_time','asc')
  69. ->limit($size)
  70. ->select()
  71. ->toArray();
  72. if (!$list) {
  73. return ;
  74. }
  75. foreach($list as $item) {
  76. try {
  77. ServiceWorkAnomalous::create([
  78. 'work_id' => $item['id'],
  79. 'reason_type' => 3,
  80. 'reason' => '上门时间超过两小时状态未变更已上门',
  81. ]);
  82. } catch (\Exception $e) {
  83. Log::write('异常工单:'.$e->getMessage());
  84. }
  85. }
  86. }
  87. /*
  88. * 自动派单总分100分
  89. 1、地理效率得分(distance score)25%
  90. 2、工程师权重「自定义是否有证」(weight score)20%
  91. 3、工程师综合服务分 55%
  92. */
  93. protected function autoDispatch()
  94. {
  95. $size = 100;
  96. $startTime = strtotime(date('Y-m-d 00:00:00'));
  97. $endTime = strtotime(date('Y-m-d 23:59:59'));
  98. $list = ServiceWork::where('work_status',0)
  99. ->where('service_status',0)
  100. ->where('refund_approval',0)
  101. ->where('work_pay_status',1)
  102. ->where('exec_num','<', 2)
  103. ->where('appointment_time','between', [$startTime, $endTime])
  104. ->field('id,category_type,goods_category_id,service_area_id,lon,lat,province,city,title,appointment_time,address,mobile,work_sn')
  105. ->order('create_time','asc')
  106. ->limit($size)
  107. ->select()
  108. ->toArray();
  109. if (!$list) {
  110. return ;
  111. }
  112. foreach($list as $item) {
  113. try {
  114. //优先平台工程师派单
  115. $res = $this->platformWorker($item);
  116. if ($res === false) {
  117. //门店负责人派单
  118. $res = $this->teamWorker($item);
  119. if ($res === false) {
  120. ServiceWork::where('id',$item['id'])
  121. ->update([
  122. 'exec_num' => 2,
  123. ]);
  124. ServiceWorkAnomalous::create([
  125. 'work_id' => $item['id'],
  126. 'reason_type' => 2,
  127. 'reason' => '自动派单:找不到工程师',
  128. ]);
  129. }
  130. }
  131. } catch (\Exception $e) {
  132. Log::write('自动派单异常:'.$e->getMessage());
  133. }
  134. }
  135. }
  136. /**
  137. * 执行外呼任务
  138. */
  139. protected function startTask() {
  140. if ($this->customerList) {
  141. $weCallService = new WeCallService();
  142. $res = $weCallService->importUser($this->customerList);
  143. if (isset($res['code']) && $res['code'] == 200) {
  144. $res = $weCallService->startTask();
  145. }
  146. }
  147. $this->customerList = [];
  148. }
  149. /**
  150. * 派单给平台工程师
  151. */
  152. protected function platformWorker($item) {
  153. // 定义地球半径(单位:米)
  154. $earthRadius = 6371000;
  155. // 定义 Haversine 公式计算距离的 SQL 片段
  156. $distanceCalculation = "{$earthRadius} * 2 * ASIN(SQRT(
  157. POWER(SIN((RADIANS({$item['lat']}) - RADIANS(a.lat)) / 2), 2) +
  158. COS(RADIANS({$item['lat']})) * COS(RADIANS(a.lat)) *
  159. POWER(SIN((RADIANS({$item['lon']}) - RADIANS(a.lon)) / 2), 2)
  160. ))";
  161. // 计算距离的字段定义
  162. $real_distance = Db::raw("{$distanceCalculation} AS real_distance");
  163. // 获取符合条件的工程师
  164. $worker = MasterWorker::alias('a')
  165. ->leftJoin('master_worker_score b', 'a.id = b.worker_id')
  166. ->where([
  167. ['is_disable', '=', 0],
  168. ['work_status', '=', 0],
  169. ['accept_order_status', '=', 1],
  170. ['city', '=', $item['city']],
  171. ['service_area_id', '=', $item['service_area_id']],
  172. ['tenant_id', '=', 0]
  173. ])
  174. ->distinct('a.id')
  175. ->whereRaw('FIND_IN_SET(' . $item['goods_category_id'] . ', a.category_ids)')
  176. ->whereRaw("{$distanceCalculation} <= a.distance")
  177. ->field([
  178. 'a.id',
  179. 'a.tenant_id',
  180. 'a.distance',
  181. 'a.lon',
  182. 'a.lat',
  183. 'a.worker_number',
  184. 'a.real_name',
  185. 'a.mobile',
  186. 'a.is_wecall',
  187. 'b.comprehensive_score',
  188. 'b.weight_score',
  189. $real_distance
  190. ])
  191. ->orderRaw('(b.comprehensive_score + b.weight_score) desc')
  192. ->limit(100)
  193. ->select()
  194. ->toArray();
  195. //echo MasterWorker::getLastSql();die;
  196. $queue = [];
  197. foreach($worker as $key => $value) {
  198. //过滤已接过此单的师傅
  199. $exists = ServiceWorkAllocateWorkerLog::where('work_id', $item['id'])->where('master_worker_id',$value['id'])->count();
  200. if ($exists) {
  201. continue;
  202. }
  203. //计算地理效率得分
  204. $realDistance = bcdiv($value['real_distance'],1000,2);
  205. $travelTime = $realDistance * 2;//预计每公里行驶2分钟
  206. $distanceScore = 100 - ($travelTime * 1.5) - ($realDistance * 5);
  207. $distanceScore = bcadd($distanceScore, 0, 2);
  208. $tmpDistanceRate = bcmul($distanceScore, $this->distanceRate, 2);
  209. $tmpRate = 0;
  210. $value['travelTime'] = $travelTime;
  211. $value['comprehensive_score'] = isset($value['comprehensive_score']) ? $value['comprehensive_score'] : 0;
  212. $value['weight_score'] = isset($value['weight_score']) ? $value['weight_score'] : 0;
  213. $tmpRate = bcmul($value['comprehensive_score'], $this->comprehensiveRate, 2) + bcmul($value['weight_score'], $this->weightRate, 2);
  214. $tmpRate = bcadd($tmpRate, $tmpDistanceRate,2);
  215. $tmpKey = isset($queue[$tmpRate]) ? bcadd($tmpRate, $key / 100,2) : $tmpRate;//防止键名重复
  216. $queue[$tmpKey] = $value;
  217. }
  218. //按照工程师的总分值倒序排序
  219. krsort($queue);
  220. foreach($queue as $worker) {
  221. $serviceTime = MasterWorkerServiceTime::where('master_worker_id',$worker['id'])->where('goods_category_id',$item['goods_category_id'])->value('service_time');
  222. if (empty($serviceTime)) {
  223. $serviceTime = GoodsTime::whereRaw('FIND_IN_SET('.$item['goods_category_id'].', goods_category_ids)')->value('service_time');
  224. $serviceTime = $serviceTime ?? $this->defaultServiceTime;//默认服务时长
  225. }
  226. //预约开始时间和结束时间
  227. $appointment_time = is_numeric($item['appointment_time']) ? $item['appointment_time'] : strtotime($item['appointment_time']);
  228. $estimated_finish_time = $appointment_time + $serviceTime * 60 + $worker['travelTime'] * 60;
  229. //校验客户的预约时间是否在工程师的空挡期内
  230. $count = ServiceWork::where([
  231. ['master_worker_id','=',$worker['id']],
  232. ['work_status','>=',1],
  233. ['work_status','<=',5],
  234. ['service_status','<',4]
  235. ])
  236. ->where(function ($query) use ($appointment_time,$estimated_finish_time) {
  237. $query->where('appointment_time', 'between',[$appointment_time, $estimated_finish_time])
  238. ->whereOr('estimated_finish_time', 'between', [$appointment_time, $estimated_finish_time]);
  239. })
  240. ->count();
  241. if ($count == 0) {
  242. $operaLog = '系统自动派单于'.date('Y-m-d H:i:s',time()).'分配了工程师'.'编号['.$worker['worker_number'].']'.$worker['real_name'];
  243. $res = $this->allocateWorker($item,$worker['id'],$worker['tenant_id'],$operaLog,$estimated_finish_time);
  244. if ($res === true && $worker['is_wecall'] == 1) {
  245. $this->customerList[] = [
  246. 'phone' => $worker['mobile'],
  247. 'properties' => [
  248. '订单号' => substr($item['work_sn'], -4),
  249. // '详细地址'=>$item['address'],
  250. // '服务类型'=> isset($this->categoryType[$item['category_type']]) ? $this->categoryType[$item['category_type']] : '',
  251. // '客户手机号'=>$item['mobile']
  252. ]
  253. ];
  254. return true;
  255. }
  256. }
  257. }
  258. return false;
  259. }
  260. /**
  261. * 派单给门店负责人
  262. */
  263. protected function teamWorker($item) {
  264. // 地球半径,单位:米
  265. $earthRadius = 6371000;
  266. // 定义 Haversine 公式计算距离的 SQL 片段
  267. $distanceCalculation = "{$earthRadius} * 2 * ASIN(SQRT(
  268. POWER(SIN((RADIANS({$item['lat']}) - RADIANS(lat)) / 2), 2) +
  269. COS(RADIANS({$item['lat']})) * COS(RADIANS(lat)) *
  270. POWER(SIN((RADIANS({$item['lon']}) - RADIANS(lon)) / 2), 2)
  271. ))";
  272. // 计算距离的字段定义
  273. $real_distance = Db::raw("{$distanceCalculation} AS real_distance");
  274. // 判断预约时间是上午还是下午
  275. $isAm = date("H", strtotime($item['appointment_time'])) < 12 ? 1 : 0;
  276. // 根据上午或下午构建查询条件
  277. $whereRaw = $isAm ? 'am_order < am_limit' : 'pm_order < pm_limit';
  278. // 获取符合条件的工程师团队
  279. $worker = MasterWorkerTeam::where([
  280. ['accept_order_status', '=', 1],
  281. ['city', '=', $item['city']],
  282. ['service_area_id', '=', $item['service_area_id']],
  283. ])
  284. ->whereRaw($whereRaw)
  285. ->whereRaw('FIND_IN_SET(' . $item['goods_category_id'] . ', goods_category_ids)')
  286. // 使用 Haversine 公式替换 ST_Distance_Sphere 函数进行距离筛选
  287. ->whereRaw("{$distanceCalculation} <= distance")
  288. ->field([
  289. 'id',
  290. 'lon',
  291. 'lat',
  292. 'distance',
  293. 'tenant_id',
  294. 'team_name',
  295. 'master_worker_id',
  296. 'am_order',
  297. 'am_limit',
  298. 'pm_order',
  299. 'pm_limit',
  300. 'min_order',
  301. 'comprehensive_score',
  302. $real_distance
  303. ])
  304. ->order('comprehensive_score', 'desc')
  305. ->limit(100)
  306. ->select()
  307. ->toArray();
  308. //echo MasterWorkerTeam::getLastSql();die;
  309. $minQueue = [];
  310. $queue = [];
  311. foreach($worker as $key => $value) {
  312. //过滤已接过此单的师傅
  313. $exists = ServiceWorkAllocateWorkerLog::where('work_id', $item['id'])->where('master_worker_id',$value['master_worker_id'])->count();
  314. if ($exists) {
  315. continue;
  316. }
  317. if ($value['am_order'] + $value['pm_order'] < $value['min_order']) {
  318. $minQueue[] = $value;
  319. } else {
  320. $queue[] = $value;
  321. }
  322. }
  323. $queue = array_merge($minQueue,$queue);
  324. //优先给接单数量不足最低接单数的团队派单,其次再给服务评分高的派单
  325. foreach($queue as $worker) {
  326. $operaLog = '系统自动派单于'.date('Y-m-d H:i:s',time()).'分配了团队ID['.$worker['id'].']'.$worker['team_name'];
  327. $res = $this->allocateWorker($item, $worker['master_worker_id'], $worker['tenant_id'], $operaLog);
  328. if ($res === true) {
  329. $updateData = $isAm == 1 ? ['am_order' => Db::raw('am_order + 1')] : ['pm_order' => Db::raw('pm_order + 1')];
  330. MasterWorkerTeam::where('id',$worker['id'])->update($updateData);
  331. $this->customerList[] = [
  332. 'phone' => MasterWorker::where('id',$worker['master_worker_id'])->value('mobile'),
  333. 'properties' => [
  334. '订单号' => substr($item['work_sn'], -4),
  335. // '详细地址'=>$item['address'],
  336. // '服务类型'=> isset($this->categoryType[$item['category_type']]) ? $this->categoryType[$item['category_type']] : '',
  337. // '客户手机号'=>$item['mobile']
  338. ]
  339. ];
  340. return true;
  341. }
  342. }
  343. return false;
  344. }
  345. /**
  346. * 分配工程师
  347. */
  348. protected function allocateWorker($workDetail, $masterWorkerId, $tenant_id,$operaLog, $estimated_finish_time=0)
  349. {
  350. Db::startTrans();
  351. try {
  352. ServiceWork::where('id',$workDetail['id'])->update([
  353. 'master_worker_id'=>$masterWorkerId,
  354. 'tenant_id' => $tenant_id,
  355. 'work_status'=>1,
  356. 'estimated_finish_time' => $estimated_finish_time,
  357. 'dispatch_time'=>time(),
  358. 'exec_num' => Db::raw('exec_num + 1'),
  359. ]);
  360. MasterWorker::setWorktotal('inc',$masterWorkerId);
  361. $work_log = [
  362. 'work_id'=>$workDetail['id'],
  363. 'master_worker_id'=>$masterWorkerId,
  364. 'type' => 0,
  365. 'opera_log'=> $operaLog
  366. ];
  367. ServiceWorkerAllocateWorkerLogic::add($work_log);
  368. Db::commit();
  369. } catch (\Exception $e) {
  370. Db::rollback();
  371. Log::write('自动派单分配工程师异常:'.$e->getMessage());
  372. return false;
  373. }
  374. // 工程师派单通知【给工程师的通知】【公众号通知,不发短信】
  375. $res = event('Notice', [
  376. 'scene_id' => 113,
  377. 'params' => [
  378. 'user_id' => $masterWorkerId,
  379. 'order_id' => $workDetail['id'],
  380. 'thing9' => $workDetail['title'],
  381. 'time7' => $workDetail['appointment_time'],
  382. 'thing8' => (iconv_strlen($workDetail['address'])>15)?(mb_substr($workDetail['address'],0,15,'UTF-8').'...'):$workDetail['address'],
  383. 'phone_number6' => asteriskString($workDetail['mobile']),
  384. ]
  385. ]);
  386. return true;
  387. }
  388. }