AutomaticDispatch.php 15 KB

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