Browse Source

fix:订单trait类

super-yimizi 2 months ago
parent
commit
1634ebd0bc

+ 14 - 17
application/api/controller/Order.php

@@ -132,22 +132,18 @@ class Order extends Base
     {
     {
         // 验证请求参数
         // 验证请求参数
         $validate = new \app\api\validate\Order();
         $validate = new \app\api\validate\Order();
-        $params = ['order_sn' => $this->request->param('order_sn')];
+        $orderId = $this->request->get('orderId');
+        $params = ['orderId' => $orderId];
         if (!$validate->scene('detail')->check($params)) {
         if (!$validate->scene('detail')->check($params)) {
             $this->error($validate->getError());
             $this->error($validate->getError());
         }
         }
-        
-        $order_sn = $this->request->param('order_sn');
-        $order = OrderModel::getDetail($order_sn, $this->auth->id);
+        $order = OrderService::getDetail($orderId, $this->auth->id);
         if (empty($order)) {
         if (empty($order)) {
             $this->error('未找到订单');
             $this->error('未找到订单');
         }
         }
-        if (OrderModel::isExpired($order_sn)) {
-            $this->error("订单已经失效");
-        }
-        $order->append(['status_text']);
-        $order->hidden(explode(',', 'method,transactionid,updatetime,deletetime'));
-        $order->expiretime = $order->expiretime - time();
+        // $order->append(['status_text']);
+        // $order->hidden(explode(',', 'method,transactionid,updatetime,deletetime'));
+        // $order->expiretime = $order->expiretime - time();
         $this->success('', $order);
         $this->success('', $order);
     }
     }
 
 
@@ -184,12 +180,13 @@ class Order extends Base
     {
     {
         // 验证请求参数
         // 验证请求参数
         $validate = new \app\api\validate\Order();
         $validate = new \app\api\validate\Order();
-        if (!$validate->scene('cancel')->check($this->request->post())) {
+        $orderId = $this->request->post('orderId');
+        $params = ['orderId' => $orderId];
+        if (!$validate->scene('cancel')->check($params)) {
             $this->error($validate->getError());
             $this->error($validate->getError());
-        }
+        }        
         
         
-        $order_sn = $this->request->post('order_sn');
-        $order = OrderModel::getByOrderSn($order_sn);
+        $order = OrderService::getByOrderId($orderId);
         if (empty($order)) {
         if (empty($order)) {
             $this->error('订单不存在');
             $this->error('订单不存在');
         }
         }
@@ -200,12 +197,12 @@ class Order extends Base
             $this->error('订单已失效!');
             $this->error('订单已失效!');
         }
         }
         //可以取消
         //可以取消
-        if (!$order->paystate && !$order->orderstate) {
+        if ($order->canCancelHandle()) {
             // 启动事务
             // 启动事务
             Db::startTrans();
             Db::startTrans();
             try {
             try {
-                $order->orderstate = 1;
-                $order->canceltime = time();
+                $order->order_status = OrderEnum::STATUS_CANCEL;
+                $order->cancel_time = time();
                 $order->save();
                 $order->save();
                 foreach ($order->order_goods as $item) {
                 foreach ($order->order_goods as $item) {
                     $sku = $item->sku;
                     $sku = $item->sku;

+ 7 - 3
application/api/validate/Order.php

@@ -33,6 +33,7 @@ class Order extends Validate
         
         
         // 订单操作相关
         // 订单操作相关
         'order_sn'        => 'require|alphaNum',
         'order_sn'        => 'require|alphaNum',
+        'orderId'        => 'require|integer|gt:0',
         'paytype'         => 'require|in:alipay,wechat,unionpay,balance',
         'paytype'         => 'require|in:alipay,wechat,unionpay,balance',
         'method'          => 'require|in:web,wap,app,miniapp,mp,mini',
         'method'          => 'require|in:web,wap,app,miniapp,mp,mini',
         
         
@@ -82,6 +83,9 @@ class Order extends Validate
         // 订单操作相关
         // 订单操作相关
         'order_sn.require'      => '订单号不能为空',
         'order_sn.require'      => '订单号不能为空',
         'order_sn.alphaNum'     => '订单号格式错误',
         'order_sn.alphaNum'     => '订单号格式错误',
+        'orderId.require'       => '订单ID不能为空',
+        'orderId.integer'       => '订单ID必须是整数',
+        'orderId.gt'            => '订单ID必须大于0',
         'paytype.require'       => '支付方式不能为空',
         'paytype.require'       => '支付方式不能为空',
         'paytype.in'            => '支付方式不支持',
         'paytype.in'            => '支付方式不支持',
         'method.require'        => '支付方法不能为空',
         'method.require'        => '支付方法不能为空',
@@ -106,11 +110,11 @@ class Order extends Validate
         // 计算订单(支持购物车和商品规格两种模式)
         // 计算订单(支持购物车和商品规格两种模式)
         'calculate'         => ['address_id', 'user_coupon_id', 'calculate_data'],
         'calculate'         => ['address_id', 'user_coupon_id', 'calculate_data'],
         // 订单详情、确认收货、查询物流
         // 订单详情、确认收货、查询物流
-        'detail'            => ['order_sn'],
+        'detail'            => ['orderId'],
         // 取消订单
         // 取消订单
-        'cancel'            => ['order_sn'],
+        'cancel'            => ['orderId'],
         // 订单支付
         // 订单支付
-        'pay'               => ['order_sn', 'paytype', 'method'],
+        'pay'               => ['orderId', 'paytype', 'method'],
         // 订单列表
         // 订单列表
         'lists'             => ['page', 'pageSize', 'status', 'keywords', 'start_time', 'end_time', 'time_range'],
         'lists'             => ['page', 'pageSize', 'status', 'keywords', 'start_time', 'end_time', 'time_range'],
     ];
     ];

+ 56 - 0
application/common/Service/OrderService.php

@@ -518,4 +518,60 @@ class OrderService
     }
     }
 
 
 
 
+     /**
+     * 
+     * @ 订单信息
+     * @param $orderId
+     * @param $userId
+     * @return array|false|\PDOStatement|string|Model
+     */
+    public static function getDetail($orderId, $userId)
+    {
+        return Order::with(['orderGoods'])
+        ->where('id', $orderId)
+        ->where('user_id', $userId)->find();
+    }
+
+      
+
+    /**
+     * 判断订单是否失效
+     * @param $order_sn
+     * @return bool
+     */
+    public static function isExpired($orderSn)
+    {
+        $orderInfo = self::getByOrderSn($orderSn);
+        //订单过期
+        if (!$orderInfo['orderstate'] && !$orderInfo['paystate'] && time() > $orderInfo['expiretime']) {
+            // 启动事务
+            Db::startTrans();
+            try {
+                $orderInfo->save(['orderstate' => 2]);
+                //库存恢复
+                OrderGoods::setGoodsStocksInc($orderInfo->order_sn);
+                //恢复优惠券
+                UserCoupon::resetUserCoupon($orderInfo->user_coupon_id, $orderInfo->order_sn);
+                // 提交事务
+                Db::commit();
+            } catch (\Exception $e) {
+                // 回滚事务
+                Db::rollback();
+            }
+            return true;
+        }
+        return false;
+    }
+
+    public static function getByOrderSn($orderSn)
+    {
+        return Order::where('order_sn', $orderSn)->find();
+    }
+    public static function getByOrderId($orderId)
+    {
+        return Order::where('id', $orderId)->find();
+    }
+
+
+
 } 
 } 

+ 131 - 0
application/common/Traits/OrderStatusTrait.php

@@ -0,0 +1,131 @@
+<?php
+
+namespace app\common\Traits;
+
+use app\common\Enum\OrderEnum;
+use Exception;
+// 移除 think\helper\Str,使用原生PHP函数
+use ReflectionClass;
+
+/**
+ * Trait OrderStatusTrait
+ * @package App\Models\Order
+ * @method bool canCancelHandle()
+ * @method bool canDeleteHandle()
+ * @method bool canPayHandle()
+ * @method bool canCommentHandle()
+ * @method bool canConfirmHandle()
+ * @method bool canRefundHandle()
+ * @method bool canRebuyHandle()
+ * @method bool canAftersaleHandle()
+ * @method bool isCreateStatus()
+ * @method bool isPayStatus()
+ * @method bool isShipStatus()
+ * @method bool isConfirmStatus()
+ * @method bool isCancelStatus()
+ * @method bool isAutoCancelStatus()
+ * @method bool isRefundStatus()
+ * @method bool isRefundConfirmStatus()
+ * @method bool isAutoConfirmStatus()
+ */
+trait OrderStatusTrait
+{
+    private $canHandleMap = [
+        // 取消操作
+        'cancel' => [
+            OrderEnum::STATUS_CREATE
+        ],
+        // 删除操作
+        'delete' => [
+            OrderEnum::STATUS_CANCEL,
+            OrderEnum::STATUS_AUTO_CANCEL,
+            OrderEnum::STATUS_ADMIN_CANCEL,
+            OrderEnum::STATUS_REFUND_CONFIRM,
+            OrderEnum::STATUS_CONFIRM,
+            OrderEnum::STATUS_AUTO_CONFIRM
+        ],
+        // 支付操作
+        'pay' => [
+            OrderEnum::STATUS_CREATE
+        ],
+        // 发货
+        'ship' => [
+            OrderEnum::STATUS_PAY
+        ],
+        // 评论操作
+        'comment' => [
+            OrderEnum::STATUS_CONFIRM,
+            OrderEnum::STATUS_AUTO_CONFIRM
+        ],
+        // 确认收货操作
+        'confirm' => [OrderEnum::STATUS_SHIP],
+        // 取消订单并退款操作
+        'refund' => [OrderEnum::STATUS_PAY],
+        // 再次购买
+        'rebuy' => [
+            OrderEnum::STATUS_CONFIRM,
+            OrderEnum::STATUS_AUTO_CONFIRM
+        ],
+        // 售后操作
+        'aftersale' => [
+            OrderEnum::STATUS_CONFIRM,
+            OrderEnum::STATUS_AUTO_CONFIRM
+        ],
+        // 同意退款
+        'agreerefund' => [
+            OrderEnum::STATUS_REFUND
+        ],
+    ];
+
+    public function __call($name, $arguments)
+    {
+        // 检查是否是can*Handle格式的方法
+        $canHandleMatches = [];
+        if (preg_match('/^can(.+)Handle$/', $name, $canHandleMatches)) {
+            if (is_null($this->order_status)) {
+                throw new Exception("order status is null when call method[$name]!");
+            }
+            $key = strtolower($canHandleMatches[1]);
+            return in_array($this->order_status, $this->canHandleMap[$key] ?? []);
+        } 
+        
+        // 检查是否是is*Status格式的方法
+        $statusMatches = [];
+        if (preg_match('/^is(.+)Status$/', $name, $statusMatches)) {
+            if (is_null($this->order_status)) {
+                throw new Exception("order status is null when call method[$name]!");
+            }
+            // 将驼峰转为下划线并转大写,然后加上STATUS_前缀
+            $statusName = strtoupper(preg_replace('/([a-z])([A-Z])/', '$1_$2', $statusMatches[1]));
+            $constantName = 'STATUS_' . $statusName;
+            $status = (new ReflectionClass(OrderEnum::class))->getConstant($constantName);
+            return $this->order_status == $status;
+        }
+        
+        return parent::__call($name, $arguments);
+    }
+
+    public function getCanHandelOptions()
+    {
+        return [
+            'cancel' => $this->canCancelHandle(),
+            'delete' => $this->canDeleteHandle(),
+            'pay' => $this->canPayHandle(),
+            'comment' => $this->canCommentHandle(),
+            'confirm' => $this->canConfirmHandle(),
+            'refund' => $this->canRefundHandle(),
+            'rebuy' => $this->canRebuyHandle(),
+            'aftersale' => $this->canAftersaleHandle(),
+        ];
+    }
+
+    public function isHadPaid()
+    {
+        return !in_array($this->order_status, [
+            OrderEnum::STATUS_CREATE,
+            OrderEnum::STATUS_ADMIN_CANCEL,
+            OrderEnum::STATUS_AUTO_CANCEL,
+            OrderEnum::STATUS_CANCEL
+        ]);
+    }
+}

+ 5 - 43
application/common/model/Order.php

@@ -7,16 +7,18 @@ use think\Exception;
 use think\Model;
 use think\Model;
 use Yansongda\Pay\Exceptions\GatewayException;
 use Yansongda\Pay\Exceptions\GatewayException;
 use addons\epay\library\Service;
 use addons\epay\library\Service;
-use addons\shop\model\OrderAction;
-use addons\shop\model\TemplateMsg;
+use app\common\model\OrderAction;
+use app\common\model\TemplateMsg;
 use traits\model\SoftDelete;
 use traits\model\SoftDelete;
 use app\common\Enum\OrderEnum;
 use app\common\Enum\OrderEnum;
+use app\common\Traits\OrderStatusTrait;
 /**
 /**
  * 模型
  * 模型
  */
  */
 class Order extends Model
 class Order extends Model
 {
 {
     use SoftDelete;
     use SoftDelete;
+    use OrderStatusTrait;
 
 
     // 表名
     // 表名
     protected $name = 'shop_order';
     protected $name = 'shop_order';
@@ -77,47 +79,7 @@ class Order extends Model
         return max(0, $data['expiretime'] - time());
         return max(0, $data['expiretime'] - time());
     }
     }
     
     
-    /**
-     * @ DateTime 2021-05-31
-     * @ 订单信息
-     * @param $order_sn
-     * @param $user_id
-     * @return array|false|\PDOStatement|string|Model
-     */
-    public static function getDetail($order_sn, $user_id)
-    {
-        return self::with(['orderGoods'])->where('order_sn', $order_sn)->where('user_id', $user_id)->find();
-    }
-
-    /**
-     * 判断订单是否失效
-     * @param $order_sn
-     * @return bool
-     */
-    public static function isExpired($order_sn)
-    {
-        $orderInfo = Order::getByOrderSn($order_sn);
-        //订单过期
-        if (!$orderInfo['orderstate'] && !$orderInfo['paystate'] && time() > $orderInfo['expiretime']) {
-            // 启动事务
-            Db::startTrans();
-            try {
-                $orderInfo->save(['orderstate' => 2]);
-                //库存恢复
-                OrderGoods::setGoodsStocksInc($orderInfo->order_sn);
-                //恢复优惠券
-                UserCoupon::resetUserCoupon($orderInfo->user_coupon_id, $orderInfo->order_sn);
-                // 提交事务
-                Db::commit();
-            } catch (\Exception $e) {
-                // 回滚事务
-                Db::rollback();
-            }
-            return true;
-        }
-        return false;
-    }
-
+ 
 
 
     /**
     /**
      * @ 支付
      * @ 支付

+ 56 - 0
application/common/service/OrderService.php

@@ -518,4 +518,60 @@ class OrderService
     }
     }
 
 
 
 
+     /**
+     * 
+     * @ 订单信息
+     * @param $orderId
+     * @param $userId
+     * @return array|false|\PDOStatement|string|Model
+     */
+    public static function getDetail($orderId, $userId)
+    {
+        return Order::with(['orderGoods'])
+        ->where('id', $orderId)
+        ->where('user_id', $userId)->find();
+    }
+
+      
+
+    /**
+     * 判断订单是否失效
+     * @param $order_sn
+     * @return bool
+     */
+    public static function isExpired($orderSn)
+    {
+        $orderInfo = self::getByOrderSn($orderSn);
+        //订单过期
+        if (!$orderInfo['orderstate'] && !$orderInfo['paystate'] && time() > $orderInfo['expiretime']) {
+            // 启动事务
+            Db::startTrans();
+            try {
+                $orderInfo->save(['orderstate' => 2]);
+                //库存恢复
+                OrderGoods::setGoodsStocksInc($orderInfo->order_sn);
+                //恢复优惠券
+                UserCoupon::resetUserCoupon($orderInfo->user_coupon_id, $orderInfo->order_sn);
+                // 提交事务
+                Db::commit();
+            } catch (\Exception $e) {
+                // 回滚事务
+                Db::rollback();
+            }
+            return true;
+        }
+        return false;
+    }
+
+    public static function getByOrderSn($orderSn)
+    {
+        return Order::where('order_sn', $orderSn)->find();
+    }
+    public static function getByOrderId($orderId)
+    {
+        return Order::where('id', $orderId)->find();
+    }
+
+
+
 } 
 }