| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200 |
- <?php
- namespace app\common\command;
- use think\facade\Db;
- use think\facade\Log;
- use think\console\Input;
- use think\console\Output;
- use think\console\Command;
- use app\common\model\works\ServiceWork;
- use app\common\model\goods_time\GoodsTime;
- use app\common\model\master_worker\MasterWorker;
- use app\common\model\works\ServiceWorkAllocateWorkerLog;
- use app\workerapi\logic\ServiceWorkerAllocateWorkerLogic;
- use app\common\model\master_worker\MasterWorkerServiceTime;
- class AutomaticDispatch extends Command
- {
- protected $defaultServiceTime = 300; //默认服务时长 300 分钟
- protected function configure()
- {
- $this->setName('automatic_dispatch')
- ->setDescription('自动派单');
- }
- protected function execute(Input $input, Output $output)
- {
- $this->autoDispatch();
- }
- /*
- * 自动派单总分100分
- 1、地理效率得分(distance score)25%
- 2、工程师权重「自定义是否有证」(weight score)20%
- 3、工程师综合服务分 55%
- */
- protected function autoDispatch()
- {
- $size = 30;
- $distanceRate = 0.25;
- $weightRate = 0.2;
- $comprehensiveRate = 0.55;
- // 获取当前时间的前五分钟时间戳
- $fiveMinutesAgo = time() - 300; // 300 秒 = 5 分钟
- while(true) {
- $list = ServiceWork::where('work_status',0)
- ->where(function ($query) use ($fiveMinutesAgo) {
- $query->where('exec_time', 0)->whereOr('exec_time', '<', $fiveMinutesAgo);
- })
- ->where('create_time','>', strtotime("-1 days"))
- ->field('id,category_type,goods_category_id,lon,lat,province,city,title,appointment_time,address,mobile')
- ->limit($size)
- ->select()
- ->toArray();
- if (!$list) {
- sleep(5);
- }
- $isExec = 0;
-
- foreach($list as $item) {
- try {
- // 获取符合条件的工程师
- $worker = MasterWorker::alias('a')->leftJoin('master_worker_score b','a.id = b.worker_id')
- ->where([
- ['is_disable','=',0],
- ['work_status','=',0],
- ['accept_order_status','=',0],
- ['city','=',$item['city']],
- ])
- ->whereRaw('FIND_IN_SET('.$item['goods_category_id'].', a.category_ids)')
- ->field('a.id,a.distance,a.lon,a.lat,a.worker_number,a.real_name,b.comprehensive_score,b.weight_score')
- ->orderRaw('(b.comprehensive_score + b.weight_score) desc')
- ->limit(100)
- ->select()
- ->toArray();
- $queue = [];
- foreach($worker as $value) {
- //过滤已接过此单的师傅
- $exists = ServiceWorkAllocateWorkerLog::where('work_id', $item['id'])->where('master_worker_id',$value['id'])->count();
- if ($exists) {
- continue;
- }
-
- if ( $value['distance'] > 0) {
- //校验客户的地址是否在工程师的接单区域内
- $realDistance = haversineDistance($item['lat'],$item['lon'], $value['lat'],$value['lon'],$value['distance']);
- if ($realDistance > $value['distance']) {
- continue;
- }
- }
- //计算地理效率得分
- $realDistance = ceil($realDistance / 1000);
- $travelTime = $realDistance * 2;//预计每公里行驶2分钟
-
- $distanceScore = 100 - ($travelTime * 1.5) - ($realDistance * 5);
- $distanceScore = bcadd($distanceScore, 0, 2);
- $tmpDistanceRate = bcmul($distanceScore, $distanceRate, 2);
- $tmpRate = 0;
- $value['travelTime'] = $travelTime;
- $value['comprehensive_score'] = isset($value['comprehensive_score']) ? $value['comprehensive_score'] : 0;
- $value['weight_score'] = isset($value['weight_score']) ? $value['weight_score'] : 0;
- $tmpRate = bcmul($value['comprehensive_score'], $comprehensiveRate, 2) + bcmul($value['weight_score'], $weightRate, 2);
- $tmpRate = bcadd($tmpRate, $tmpDistanceRate,2);
- $queue[$tmpRate."_".$value['id']] = $value;
-
- }
- //按照工程师的总分值倒序排序
- krsort($queue);
- foreach($queue as $worker) {
- $serviceTime = MasterWorkerServiceTime::where('master_worker_id',$worker['id'])->where('goods_category_id',$item['goods_category_id'])->value('service_time');
- if (empty($serviceTime)) {
- $serviceTime = GoodsTime::whereRaw('FIND_IN_SET('.$item['goods_category_id'].', goods_category_ids)')->value('service_time');
- $serviceTime = $serviceTime ?? $this->defaultServiceTime;//默认服务时长
- }
- //预约开始时间和结束时间
- $appointment_time = is_numeric($item['appointment_time']) ? $item['appointment_time'] : strtotime($item['appointment_time']);
- $estimated_finish_time = $appointment_time + $serviceTime * 60 + $worker['travelTime'] * 60;
- //校验客户的预约时间是否在工程师的空挡期内
- $count = ServiceWork::where([
- ['master_worker_id','=',$worker['id']],
- ['work_status','>=',1],
- ['work_status','<=',5],
- ])
- ->where(function ($query) use ($appointment_time,$estimated_finish_time) {
- $query->where('appointment_time', 'between',[$appointment_time, $estimated_finish_time])
- ->whereOr('estimated_finish_time', 'between', [$appointment_time, $estimated_finish_time]);
- })
- ->count();
- if ($count == 0) {
- $res = $this->allocateWorker($item,$worker,$estimated_finish_time);
- if ($res === true) {
- $isExec = 1;
- }
- break;
- }
- }
- } catch (\Exception $e) {
- Log::write('自动派单异常:'.$e->getMessage());
- sleep(5);
- }
- if ($isExec == 0) {
- ServiceWork::where('id',$item['id'])->update([
- 'exec_time' => time(),
- ]);
- }
- }
-
- }
- }
- /**
- * 分配工程师
- */
- protected function allocateWorker($workDetail, $worker, $estimated_finish_time)
- {
- Db::startTrans();
- try {
- ServiceWork::where('id',$workDetail['id'])->update([
- 'master_worker_id'=>$worker['id'],
- 'work_status'=>1,
- 'estimated_finish_time' => $estimated_finish_time,
- 'dispatch_time'=>time(),
- 'exec_time' => time(),
- ]);
- MasterWorker::setWorktotal('inc',$worker['id']);
- $work_log = [
- 'work_id'=>$workDetail['id'],
- 'master_worker_id'=>$worker['id'],
- 'type' => 0,
- 'opera_log'=>'系统自动派单于'.date('Y-m-d H:i:s',time()).'分配了工程师'.'编号['.$worker['worker_number'].']'.$worker['real_name']
- ];
- ServiceWorkerAllocateWorkerLogic::add($work_log);
- Db::commit();
- } catch (\Exception $e) {
- Db::rollback();
- Log::write('自动派单分配工程师异常:'.$e->getMessage());
- return false;
- }
- // 工程师派单通知【给工程师的通知】【公众号通知,不发短信】
- $res = event('Notice', [
- 'scene_id' => 113,
- 'params' => [
- 'user_id' => $worker['id'],
- 'order_id' => $workDetail['id'],
- 'thing9' => $workDetail['title'],
- 'time7' => $workDetail['appointment_time'],
- 'thing8' => (iconv_strlen($workDetail['address'])>15)?(mb_substr($workDetail['address'],0,15,'UTF-8').'...'):$workDetail['address'],
- 'phone_number6' => asteriskString($workDetail['mobile']),
- ]
- ]);
- return true;
- }
- }
|