Files
hyperf_service/app/Service/Api/Driver/DeliverService.php
2025-04-01 14:44:31 +08:00

128 lines
3.6 KiB
PHP

<?php
/**
* This service file is part of item.
*
* @author ctexthuang
* @contact ctexthuang@qq.com
*/
declare(strict_types=1);
namespace App\Service\Api\Driver;
use App\Amqp\Producer\WxSubMessageProducer;
use App\Constants\Common\DriverCode;
use App\Constants\Common\OrderCode;
use App\Constants\Common\WxMiniCode;
use App\Exception\ErrException;
use App\Model\Order;
use Hyperf\Amqp\Producer;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use function Hyperf\Config\config;
class DeliverService extends BaseDriverService
{
/**
* @var Order
*/
#[Inject]
protected Order $orderModel;
/**
* @var int
*/
private int $siteId;
/**
* @return array
*/
public function handle(): array
{
$this->siteId = (int)$this->request->input('site_id');
$info = $this->driverStatusModel
->where('cycle_id',$this->cycleId)
->where('site_id',$this->siteId)
->where('driver_id',$this->adminInfo->id)
->first();
if (empty($info)) throw new ErrException('今日无该点位的送餐数据');
if ($info->status == DriverCode::DESTINATION) throw new ErrException('该点位已送达');
$orderList = $this->orderModel
->leftJoin('pickup_code','pickup_code.order_id','=','order.id')
->where('order.cycle_id',$this->cycleId)
->where('order.status',OrderCode::DEPART)
->where('order.site_id',$this->siteId)
->select(['order.user_id','order.id','pickup_code.pickup_code','order.order_sno'])
->get();
if ($orderList->isEmpty()) {
$orderList = [];
} else {
$orderList = $orderList->toArray();
}
Db::transaction(function () use ($info,$orderList) {
// $this->orderModel->whereIn('id', $orderIds)->update([
// 'status' => OrderCode::DEPART,
// 'set_out_time' => date('Y-m-d H:i:s'),
// ]);
$info->status = DriverCode::DESTINATION;
if (!$info->save()) throw new ErrException('送达失败-01');
if (!empty($orderList)){
$dateTime = date('Y-m-d H:i:s');
foreach (array_chunk(array_column($orderList,'id'), 500) as $chunk) {
$this->orderModel->whereIn('id', $chunk)->update([
'status' => OrderCode::ARRIVE,
'delivery_time' => $dateTime,
]);
}
}
});
$this->sendWxSubMessageMq($orderList);
return $this->return->success();
}
/**
* @var Producer
*/
#[Inject]
protected Producer $producer;
/**
* @param array $orderList
* @return void
*/
private function sendWxSubMessageMq(array $orderList): void
{
if (empty($orderList)) return;
$userIds = [];
foreach ($orderList as $oneOrder) {
if (in_array($oneOrder['user_id'], $userIds)) continue;
$msgData = [
'character_string19' => ['value' => $oneOrder['order_sno']],
'thing27' => ['value' => $oneOrder['pickup_code']],
'phrase16' => ['value' => '待取餐'],
'thing20' => ['value' => '您的午餐来了,早点吃饭哈,您的身体最重要'],
];
$message = new WxSubMessageProducer([
'type' => WxMiniCode::SEND_MSG_TYPE_DELIVER,
'user_id' => $oneOrder['user_id'],
'data' => $msgData,
'page' => null
]);
$this->producer->produce($message);
}
}
}