feat: place Order

This commit is contained in:
2025-02-05 17:56:32 +08:00
parent fd94db463e
commit fda042da54
14 changed files with 504 additions and 11 deletions

View File

@@ -0,0 +1,86 @@
<?php
declare(strict_types=1);
namespace App\Amqp\Consumer;
use App\Constants\Common\OrderCode;
use App\Lib\Log;
use App\Model\Order;
use Hyperf\Amqp\Message\ConsumerDelayedMessageTrait;
use Hyperf\Amqp\Message\ProducerDelayedMessageTrait;
use Hyperf\Amqp\Message\Type;
use Hyperf\Amqp\Result;
use Hyperf\Amqp\Annotation\Consumer;
use Hyperf\Amqp\Message\ConsumerMessage;
use Hyperf\Di\Annotation\Inject;
use PhpAmqpLib\Message\AMQPMessage;
#[Consumer(exchange: 'OrderCancel', routingKey: 'OrderCancel', queue: 'OrderCancel.delay', name: "CancelOrderConsumer", nums: 1)]
class CancelOrderConsumer extends ConsumerMessage
{
use ProducerDelayedMessageTrait,ConsumerDelayedMessageTrait;
/**
* @var Type|string 消息类型
*/
protected Type|string $type = Type::DIRECT;
/**
* @var Log $log
*/
#[Inject]
protected Log $log;
/**
* @var Order
*/
#[Inject]
protected Order $orderModel;
/**
* @var int
*/
private int $orderId;
/**
* @var int
*/
private int $orderType;
public function consumeMessage($data, AMQPMessage $message): Result
{
if (!$data['order_id'] || !$data['type']) {
$this->log->error('CancelOrderConsumer:error:NoData:'.json_encode($data));
return Result::ACK;
}
$this->orderId = (int)$data['order_id'];
$this->orderType = (int)$data['type'];
$orderInfo = match ($this->orderType) {
OrderCode::ORDER_TYPE_GOOD => $this->orderModel->getInfoById($this->orderId),
default => null,
};
if (empty($orderInfo)) {
$this->log->debug('CancelOrderConsumer:error:NoOrderData:'.json_encode($data));
return Result::ACK;
}
if ($orderInfo->status != OrderCode::WAIT_PAY) {
$this->log->debug('CancelOrderConsumer:error:orderStatusError:'.json_encode($orderInfo->toArray()));
return Result::ACK;
}
$orderInfo->status = OrderCode::CANCEL;
if (!$orderInfo->save()) {
$this->log->debug('CancelOrderConsumer:error:orderStatusSaveError:'.json_encode($orderInfo->toArray()));
return Result::ACK;
}
return Result::ACK;
}
}

View File

@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace App\Amqp\Consumer;
use Hyperf\Amqp\Message\Type;
use Hyperf\Amqp\Result;
use Hyperf\Amqp\Annotation\Consumer;
use Hyperf\Amqp\Message\ConsumerMessage;
use PhpAmqpLib\Message\AMQPMessage;
#[Consumer(exchange: 'OrderGoodStock', routingKey: 'OrderGoodStock', queue: 'OrderGoodStock.change', name: "OrderGoodStockConsumer", nums: 1)]
class OrderGoodStockConsumer extends ConsumerMessage
{
/**
* @var Type|string 消息类型
*/
protected Type|string $type = Type::DIRECT;
public function consumeMessage($data, AMQPMessage $message): Result
{
return Result::ACK;
}
}

View File

@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace App\Amqp\Consumer;
use Hyperf\Amqp\Message\Type;
use Hyperf\Amqp\Result;
use Hyperf\Amqp\Annotation\Consumer;
use Hyperf\Amqp\Message\ConsumerMessage;
use PhpAmqpLib\Message\AMQPMessage;
#[Consumer(exchange: 'RefundOrder', routingKey: 'RefundOrder', queue: 'RefundOrder.direct', name: "RefundOrderConsumer", nums: 1)]
class RefundOrderConsumer extends ConsumerMessage
{
/**
* @var Type|string 消息类型
*/
protected Type|string $type = Type::DIRECT;
public function consumeMessage($data, AMQPMessage $message): Result
{
return Result::ACK;
}
}

View File

@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace App\Amqp\Producer;
use Hyperf\Amqp\Annotation\Producer;
use Hyperf\Amqp\Message\ProducerDelayedMessageTrait;
use Hyperf\Amqp\Message\ProducerMessage;
use Hyperf\Amqp\Message\Type;
#[Producer(exchange: 'OrderCancel', routingKey: 'OrderCancel')]
class CancelOrderProducer extends ProducerMessage
{
use ProducerDelayedMessageTrait;
/**
* @var Type|string 消息类型
*/
protected Type|string $type = Type::DIRECT;
/**
* @param $data
*/
public function __construct($data)
{
/**
* $data string array => {"order_id":"orderId","type":"OrderCode::ORDER_TYPE_GOOD"}
*/
$this->payload = $data;
}
}

View File

@@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
namespace App\Amqp\Producer;
use Hyperf\Amqp\Annotation\Producer;
use Hyperf\Amqp\Message\ProducerMessage;
use Hyperf\Amqp\Message\Type;
#[Producer(exchange: 'OrderGoodStock', routingKey: 'OrderGoodStock')]
class OrderGoodStockProducer extends ProducerMessage
{
/**
* @var Type|string 消息类型
*/
protected Type|string $type = Type::DIRECT;
public function __construct($data)
{
/**
* $data string array => {"order_id":"orderId","type":"OrderCode::WAIT_PAY"}
*/
$this->payload = $data;
}
}

View File

@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace App\Amqp\Producer;
use Hyperf\Amqp\Annotation\Producer;
use Hyperf\Amqp\Message\ProducerMessage;
use Hyperf\Amqp\Message\Type;
#[Producer(exchange: 'RefundOrder', routingKey: 'RefundOrder')]
class RefundOrderProducer extends ProducerMessage
{
/**
* @var Type|string 消息类型
*/
protected Type|string $type = Type::DIRECT;
public function __construct($data)
{
$this->payload = $data;
}
}

View File

@@ -0,0 +1,45 @@
<?php
namespace App\Constants\Common;
class OrderCode
{
/**
* @var int 状态:1=未支付,11=未出,21=出餐,31=已出发,41=待取餐,51=完成,97=未完成退款,98=完成退款,99=取消
*/
CONST WAIT_PAY = 1; //待支付
CONST PAYED = 11; //已支付待出餐
CONST PLAN = 21; //出餐未出发
CONST DEPART = 31; //已出发
CONST ARRIVE = 41; // 已送达(待取餐)
CONST FINISH = 51; //已完成
const UNCOMPLETED_REFUND = 97; //未完成退款
CONST FINISH_REFUND = 98; //完成后退款
CONST CANCEL = 99; //取消
/**
* @var int 退款状态 1=未退款 2=已退款部分 3=全部退款
*/
CONST REFUND_NULL = 1; //未退款
CONST REFUND_SEGMENT = 2; //部分退款
CONST REFUND_ALL = 3; //全部退款
/**
* @var int 订单评价状态 1=未评价 2=部分评价 3=全部评价
*/
CONST ORDER_COMMENT_NULL = 1;
CONST ORDER_COMMENT_SEGMENT = 2;
CONST ORDER_COMMENT_FINISH = 3;
/**
* @var int 商品评价状态 1=未评价 2=已评价
*/
CONST GOOD_COMMENT_NULL = 1;
CONST GOOD_COMMENT_FINISH = 2;
/**
* @var int 订单类型 1=商品订单 2=充值订单
*/
const ORDER_TYPE_GOOD = 1;
const ORDER_TYPE_BALANCE = 2;
}

View File

@@ -5,8 +5,10 @@ namespace App\Constants;
class ConfigCode
{
const string TODAY_CUT_OFF_TIME_KEY = 'TodayCutOffTime';
const string ORDER_CANCEL_TIME_KEY = 'OrderCancelTime';
const array DEFAULT_VALUE = [
self::TODAY_CUT_OFF_TIME_KEY => '15:00:00'
self::TODAY_CUT_OFF_TIME_KEY => '15:00:00',
self::ORDER_CANCEL_TIME_KEY => 5,
];
}

View File

@@ -11,6 +11,8 @@ class DateUtil
public const MONTH = 2592000; // 月
public const YEAR = 311040000; // 年
public const MS = 1000;
/**
* 获取当前时间到今日结束的秒数
* @return int

66
app/Model/Order.php Normal file
View File

@@ -0,0 +1,66 @@
<?php
declare(strict_types=1);
namespace App\Model;
use Hyperf\Database\Model\Collection;
use Hyperf\DbConnection\Model\Model;
/**
* @property int $id
* @property string $order_sno
* @property int $user_id
* @property int $cycle_id
* @property int $site_id
* @property int $city_id
* @property int $coupon_id
* @property int $meal_copies
* @property int $optional_copies
* @property string $total_price
* @property string $actual_price
* @property string $discount_price
* @property int $status
* @property int $is_refund_all
* @property string $cancel_time
* @property string $set_out_time
* @property string $delivery_time
* @property string $take_food_time
* @property string $finish_time
* @property string $pay_time
* @property string $order_json
* @property string $create_time
* @property string $update_time
*/
class Order extends Model
{
/**
* The table associated with the model.
*/
protected ?string $table = 'order';
/**
* The attributes that are mass assignable.
*/
protected array $fillable = [];
protected array $guarded = [];
/**
* The attributes that should be cast to native types.
*/
protected array $casts = ['id' => 'integer', 'user_id' => 'integer', 'cycle_id' => 'integer', 'site_id' => 'integer', 'city_id' => 'integer', 'coupon_id' => 'integer', 'meal_copies' => 'integer', 'optional_copies' => 'integer', 'status' => 'integer', 'is_refund_all' => 'integer'];
const string CREATED_AT = 'create_time';
const string UPDATED_AT = 'update_time';
/**
* @param int $id
* @return Order|Order[]|Collection|\Hyperf\Database\Model\Model|null
*/
public function getInfoById(int $id): array|Order|Collection|\Hyperf\Database\Model\Model|null
{
return $this->find($id);
}
}

45
app/Model/OrderGood.php Normal file
View File

@@ -0,0 +1,45 @@
<?php
declare(strict_types=1);
namespace App\Model;
use Hyperf\DbConnection\Model\Model;
/**
* @property int $id
* @property int $order_id
* @property int $cycle_id
* @property int $sku_id
* @property int $spu_id
* @property int $user_id
* @property int $quantity
* @property string $unit_price
* @property int $is_comment
* @property int $copies
* @property int $type
* @property string $create_time
* @property string $update_time
*/
class OrderGood extends Model
{
/**
* The table associated with the model.
*/
protected ?string $table = 'order_goods';
/**
* The attributes that are mass assignable.
*/
protected array $fillable = [];
protected array $guarded = [];
/**
* The attributes that should be cast to native types.
*/
protected array $casts = ['id' => 'integer', 'order_id' => 'integer', 'cycle_id' => 'integer', 'sku_id' => 'integer', 'spu_id' => 'integer', 'user_id' => 'integer', 'quantity' => 'integer', 'is_comment' => 'integer', 'copies' => 'integer', 'type' => 'integer'];
const string CREATED_AT = 'create_time';
const string UPDATED_AT = 'update_time';
}

View File

@@ -81,6 +81,11 @@ abstract class BaseOrderService extends BaseService
*/
protected int $siteId;
/**
* @var int
*/
protected int $orderId;
/**
* 构造方法
* @throws ContainerExceptionInterface

View File

@@ -10,12 +10,25 @@ declare(strict_types=1);
namespace App\Service\Api\Order;
use App\Amqp\Producer\CancelOrderProducer;
use App\Constants\Common\GoodCode;
use App\Constants\Common\OrderCode;
use App\Constants\ConfigCode;
use App\Exception\ErrException;
use App\Extend\DateUtil;
use App\Model\Order;
use App\Model\OrderGood;
use Exception;
use Hyperf\Amqp\Producer;
use Hyperf\Context\ApplicationContext;
use Hyperf\DbConnection\Db;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
class PlaceOrderService extends BaseOrderService
{
/**
* 统一下单逻辑
* @return array
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
@@ -31,17 +44,108 @@ class PlaceOrderService extends BaseOrderService
$this->placeOrder();
$this->joinCancelDelayQueue();
return $this->return->success('success',$this->orderRes);
}
private function placeOrder()
/**
* 加入取消队列
* @return void
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
private function joinCancelDelayQueue(): void
{
foreach ($this->orderRes['good'] as $oneCopies)
{
foreach ($oneCopies['good_info'] as $one)
{
$message = new CancelOrderProducer([
'order_id' => $this->orderId,
'type' => OrderCode::ORDER_TYPE_GOOD
]);
$message->setDelayMs((int)$this->configCache->getConfigValue(ConfigCode::ORDER_CANCEL_TIME_KEY) * DateUtil::MINUTE * DateUtil::MS);
$producer = ApplicationContext::getContainer()->get(Producer::class);
$producer->produce($message);
}
}
/**
* 下单
* @return void
*/
private function placeOrder(): void
{
try {
Db::beginTransaction();
$this->insertOrder();
$this->insertOrderGoods();
Db::commit();
} catch (Exception $e){
Db::rollBack();
throw new ErrException($e->getMessage());
}
}
/**
* 插入订单商品
* @return void
* @throws Exception
*/
private function insertOrderGoods(): void
{
$copiesNum = 0;
$orderGoodInsertArr = [];
foreach ($this->orderRes['good'] as $oneCopies)
{
$copiesNum++;
foreach ($oneCopies['good_info'] as $one)
{
$orderGoodInsertArr[] = [
'order_id' => $this->orderId,
'cycle_id' => $this->cycleId,
'sku_id' => $one['id'],
'spu_id' => $one['spu_id'],
'user_id' => $this->userId,
'quantity' => $one['num'],
'unit_price' => $one['unit_price'],
'is_comment' => OrderCode::GOOD_COMMENT_NULL,
'copies' => $copiesNum,
'type' => $one['type'],
'create_time' => date('Y-m-d H:i:s'),
'update_time' => date('Y-m-d H:i:s'),
];
}
}
if (!(new OrderGood)->insert($orderGoodInsertArr)) throw new Exception('写入订单商品失败');
}
/**
* 插入订单
* @return void
* @throws Exception
*/
private function insertOrder(): void
{
$orderInsertModel = new Order();
$orderInsertModel->order_sno = '123';
$orderInsertModel->user_id = $this->userId;
$orderInsertModel->cycle_id = $this->cycleId;
$orderInsertModel->site_id = $this->siteId;
$orderInsertModel->city_id = $this->orderRes['site']['city_id'];
$orderInsertModel->coupon_id = $this->couponId;
$orderInsertModel->meal_copies = $this->orderRes['meal_copies'];
$orderInsertModel->optional_copies = $this->orderRes['optional_copies'];
$orderInsertModel->total_price = $this->orderRes['total_price'];
$orderInsertModel->actual_price = $this->orderRes['actual_price'];
$orderInsertModel->discount_price = $this->orderRes['favorable_sundry_price'] + $this->orderRes['favorable_good_price'];
$orderInsertModel->status = OrderCode::WAIT_PAY;
$orderInsertModel->is_refund_all = OrderCode::REFUND_NULL;
$orderInsertModel->order_json = json_encode($this->orderRes);
if (!$orderInsertModel->save()) throw new Exception('下单失败');
$this->orderId = $orderInsertModel->id;
}
}

View File

@@ -14,6 +14,7 @@ use App\Cache\Redis\Api\ApiRedisKey;
use App\Cache\Redis\Api\SiteCache;
use App\Cache\Redis\RedisCache;
use App\Constants\ApiCode;
use App\Constants\Common\GoodCode;
use App\Exception\ErrException;
use Hyperf\Di\Annotation\Inject;
use Psr\Container\ContainerExceptionInterface;
@@ -165,19 +166,21 @@ trait OrderTrait
$oneCopiesGoodInfo = [];
foreach ($oneCopies as $oneGood) {
if (empty($oneCopiesGoodInfo[$oneGood]))
{
if (empty($oneCopiesGoodInfo[$oneGood])) {
$oneCopiesGoodInfo[$oneGood] = [
'num' => 1,
'good_name' => '1',
'good_url' => '1',
'unit_price' => $this->skuArr[$oneGood]['price']
'unit_price' => $this->skuArr[$oneGood]['price'],
'type' => $this->skuArr[$oneGood]['type'],
];
} else {
$oneCopiesGoodInfo[$oneGood]['num'] += 1;
}
$oneCopiesTotalPrice = bcadd($oneCopiesTotalPrice, $this->skuArr[$oneGood]['price'],2);
if ($copiesType == 1 && $this->skuArr[$oneGood]['type'] == 2) {
if ($copiesType == 1 && $this->skuArr[$oneGood]['type'] == GoodCode::SPU_TYPE_MEAL) {
$copiesType = 2;
}
}