AutomaticDispatch.php 15 KB

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