Order.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2017~2021 https://www.yiovo.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
  8. // +----------------------------------------------------------------------
  9. // | Author: 萤火科技 <admin@yiovo.com>
  10. // +----------------------------------------------------------------------
  11. declare (strict_types=1);
  12. namespace app\api\model;
  13. use app\api\model\{Goods as GoodsModel, OrderRefund as OrderRefundModel, Setting as SettingModel};
  14. use app\api\service\{User as UserService, Payment as PaymentService};
  15. use app\api\service\order\{PaySuccess as OrderPaySuccesService, source\Factory as OrderSourceFactory};
  16. use app\common\model\Order as OrderModel;
  17. use app\common\service\{Order as OrderService, order\Complete as OrderCompleteService};
  18. use app\common\enum\{
  19. Setting as SettingEnum,
  20. OrderType as OrderTypeEnum,
  21. order\PayType as OrderPayTypeEnum,
  22. order\PayStatus as PayStatusEnum,
  23. order\OrderStatus as OrderStatusEnum,
  24. // order\DeliveryType as DeliveryTypeEnum,
  25. order\ReceiptStatus as ReceiptStatusEnum,
  26. order\DeliveryStatus as DeliveryStatusEnum
  27. };
  28. use app\common\library\helper;
  29. use cores\exception\BaseException;
  30. /**
  31. * 订单模型
  32. * Class Order
  33. * @package app\api\model
  34. */
  35. class Order extends OrderModel
  36. {
  37. /**
  38. * 隐藏字段
  39. * @var array
  40. */
  41. protected $hidden = [
  42. 'store_id',
  43. 'update_time'
  44. ];
  45. // 信息提示
  46. private $message = '';
  47. /**
  48. * 待支付订单详情
  49. * @param string $orderNo 订单号
  50. * @return null|static
  51. */
  52. public static function getPayDetail(string $orderNo): ?Order
  53. {
  54. return self::detail(['order_no' => $orderNo, 'pay_status' => PayStatusEnum::PENDING, 'is_delete' => 0], ['goods', 'user']);
  55. }
  56. /**
  57. * 订单支付事件
  58. * @param int $payType
  59. * @return bool
  60. */
  61. public function onPay(int $payType = OrderPayTypeEnum::WECHAT): bool
  62. {
  63. // 判断订单状态
  64. $orderSource = OrderSourceFactory::getFactory($this['order_source']);
  65. if (!$orderSource->checkOrderStatusOnPay($this)) {
  66. $this->error = $orderSource->getError();
  67. return false;
  68. }
  69. // 余额支付
  70. if ($payType == OrderPayTypeEnum::BALANCE) {
  71. return $this->onPaymentByBalance($this['order_no']);
  72. }
  73. return true;
  74. }
  75. /**
  76. * 构建支付请求的参数
  77. * @param self $order 订单信息
  78. * @param int $payType 订单支付方式
  79. * @return array
  80. * @throws BaseException
  81. * @throws \think\db\exception\DataNotFoundException
  82. * @throws \think\db\exception\DbException
  83. * @throws \think\db\exception\ModelNotFoundException
  84. */
  85. public function onOrderPayment(self $order, int $payType): array
  86. {
  87. if ($payType == OrderPayTypeEnum::WECHAT) {
  88. return $this->onPaymentByWechat($order);
  89. }
  90. return [];
  91. }
  92. /**
  93. * 构建微信支付请求
  94. * @param self $order 订单详情
  95. * @return array
  96. * @throws BaseException
  97. * @throws \think\db\exception\DataNotFoundException
  98. * @throws \think\db\exception\DbException
  99. * @throws \think\db\exception\ModelNotFoundException
  100. */
  101. protected function onPaymentByWechat(self $order): array
  102. {
  103. return PaymentService::wechat(
  104. $order['order_id'],
  105. $order['order_no'],
  106. $order['pay_price'],
  107. OrderTypeEnum::ORDER
  108. );
  109. }
  110. /**
  111. * 立即购买:获取订单商品列表
  112. * @param int $goodsId 商品ID
  113. * @param string $goodsSkuId 商品SKU
  114. * @param int $goodsNum 购买数量
  115. * @return mixed
  116. * @throws BaseException
  117. */
  118. public function getOrderGoodsListByNow(int $goodsId, string $goodsSkuId, int $goodsNum)
  119. {
  120. // 获取商品列表
  121. $model = new GoodsModel;
  122. $goodsList = $model->isGoodsGradeMoney(false)->getListByIdsFromApi([$goodsId]);
  123. if ($goodsList->isEmpty()) {
  124. throwError('未找到商品信息');
  125. }
  126. // 隐藏冗余的属性
  127. $goodsList->hidden(GoodsModel::getHidden(['content', 'goods_images', 'images']));
  128. foreach ($goodsList as &$item) {
  129. // 商品sku信息
  130. $goodsInfo['skuInfo'] = GoodsModel::getSkuInfo($item, $goodsSkuId, false);
  131. // 商品封面 (优先sku封面)
  132. $item['goods_image'] = $item['skuInfo']['goods_image'] ?: $item['goods_image'];
  133. // 商品单价
  134. $item['goods_price'] = $item['skuInfo']['goods_price'];
  135. // 商品购买数量
  136. $item['total_num'] = $goodsNum;
  137. // 商品SKU索引
  138. $item['goods_sku_id'] = $item['skuInfo']['goods_sku_id'];
  139. // 商品购买总金额
  140. $item['total_price'] = helper::bcmul($item['goods_price'], $goodsNum);
  141. }
  142. return $goodsList;
  143. }
  144. /**
  145. * 余额支付标记订单已支付
  146. * @param string $orderNo 订单号
  147. * @return bool
  148. */
  149. public function onPaymentByBalance(string $orderNo): bool
  150. {
  151. // 获取订单详情
  152. $service = new OrderPaySuccesService($orderNo);
  153. // 发起余额支付
  154. $status = $service->onPaySuccess(OrderPayTypeEnum::BALANCE);
  155. if (!$status) {
  156. $this->error = $service->getError();
  157. }
  158. return $status;
  159. }
  160. /**
  161. * 获取用户订单列表
  162. * @param string $type 订单类型 (all全部 payment待付款 received待发货 deliver待收货 comment待评价)
  163. * @return \think\Paginator
  164. * @throws \think\db\exception\DbException
  165. * @throws BaseException
  166. */
  167. public function getList(string $type = 'all'): \think\Paginator
  168. {
  169. // 筛选条件
  170. $filter = [];
  171. // 订单数据类型
  172. switch ($type) {
  173. case 'all':
  174. break;
  175. case 'payment':
  176. $filter['pay_status'] = PayStatusEnum::PENDING;
  177. $filter['order_status'] = OrderStatusEnum::NORMAL;
  178. break;
  179. case 'delivery':
  180. $filter['pay_status'] = PayStatusEnum::SUCCESS;
  181. $filter['delivery_status'] = DeliveryStatusEnum::NOT_DELIVERED;
  182. $filter['order_status'] = OrderStatusEnum::NORMAL;
  183. break;
  184. case 'received':
  185. $filter['pay_status'] = PayStatusEnum::SUCCESS;
  186. $filter['delivery_status'] = DeliveryStatusEnum::DELIVERED;
  187. $filter['receipt_status'] = ReceiptStatusEnum::NOT_RECEIVED;
  188. $filter['order_status'] = OrderStatusEnum::NORMAL;
  189. break;
  190. case 'comment':
  191. $filter['is_comment'] = 0;
  192. $filter['order_status'] = OrderStatusEnum::COMPLETED;
  193. break;
  194. }
  195. // 当前用户ID
  196. $userId = UserService::getCurrentLoginUserId();
  197. // 查询列表数据
  198. return $this->with(['goods.image'])
  199. ->where($filter)
  200. ->where('user_id', '=', $userId)
  201. ->where('is_delete', '=', 0)
  202. ->order(['create_time' => 'desc'])
  203. ->paginate(15);
  204. }
  205. /**
  206. * 取消订单
  207. * @return bool|mixed
  208. */
  209. public function cancel()
  210. {
  211. if ($this['delivery_status'] == DeliveryStatusEnum::DELIVERED) {
  212. $this->error = '已发货订单不可取消';
  213. return false;
  214. }
  215. // 订单是否已支付
  216. $isPay = $this['pay_status'] == PayStatusEnum::SUCCESS;
  217. // 提示信息
  218. $this->message = $isPay ? '订单已申请取消,需等待后台审核' : '订单已取消成功';
  219. // 订单取消事件
  220. return $this->transaction(function () use ($isPay) {
  221. // 订单取消事件
  222. $isPay == false && OrderService::cancelEvent($this);
  223. // 更新订单状态: 已付款的订单设置为"待取消", 等待后台审核
  224. return $this->save(['order_status' => $isPay ? OrderStatusEnum::APPLY_CANCEL : OrderStatusEnum::CANCELLED]);
  225. });
  226. }
  227. /**
  228. * 确认收货
  229. * @return bool|mixed
  230. */
  231. public function receipt()
  232. {
  233. // 验证订单是否合法
  234. // 条件1: 订单必须已发货
  235. // 条件2: 订单必须未收货
  236. if ($this['delivery_status'] != 20 || $this['receipt_status'] != 10) {
  237. $this->error = '该订单不合法';
  238. return false;
  239. }
  240. return $this->transaction(function () {
  241. // 更新订单状态
  242. $status = $this->save([
  243. 'receipt_status' => 20,
  244. 'receipt_time' => time(),
  245. 'order_status' => 30
  246. ]);
  247. // 执行订单完成后的操作
  248. $OrderCompleteService = new OrderCompleteService();
  249. $OrderCompleteService->complete([$this], static::$storeId);
  250. return $status;
  251. });
  252. }
  253. /**
  254. * 获取当前用户订单数量
  255. * @param string $type 订单类型 (all全部 payment待付款 received待发货 deliver待收货 comment待评价)
  256. * @return int
  257. * @throws BaseException
  258. */
  259. public function getCount(string $type = 'all'): int
  260. {
  261. // 筛选条件
  262. $filter = [];
  263. // 订单数据类型
  264. switch ($type) {
  265. case 'all':
  266. break;
  267. case 'payment':
  268. $filter['pay_status'] = PayStatusEnum::PENDING;
  269. break;
  270. case 'received':
  271. $filter['pay_status'] = PayStatusEnum::SUCCESS;
  272. $filter['delivery_status'] = DeliveryStatusEnum::DELIVERED;
  273. $filter['receipt_status'] = ReceiptStatusEnum::NOT_RECEIVED;
  274. break;
  275. case 'delivery':
  276. $filter['pay_status'] = PayStatusEnum::SUCCESS;
  277. $filter['delivery_status'] = DeliveryStatusEnum::NOT_DELIVERED;
  278. $filter['order_status'] = OrderStatusEnum::NORMAL;
  279. break;
  280. case 'comment':
  281. $filter['is_comment'] = 0;
  282. $filter['order_status'] = OrderStatusEnum::COMPLETED;
  283. break;
  284. }
  285. // 当前用户ID
  286. $userId = UserService::getCurrentLoginUserId();
  287. // 查询数据
  288. return $this->where('user_id', '=', $userId)
  289. ->where('order_status', '<>', 20)
  290. ->where($filter)
  291. ->where('is_delete', '=', 0)
  292. ->count();
  293. }
  294. /**
  295. * 获取用户订单详情(含关联数据)
  296. * @param int $orderId 订单ID
  297. * @return Order|array|null
  298. * @throws BaseException
  299. * @throws \think\db\exception\DataNotFoundException
  300. * @throws \think\db\exception\DbException
  301. * @throws \think\db\exception\ModelNotFoundException
  302. */
  303. public static function getUserOrderDetail(int $orderId)
  304. {
  305. // 关联查询
  306. $with = [
  307. 'goods' => ['image', 'goods', 'refund'],
  308. 'address', 'express'
  309. ];
  310. // 查询订单记录
  311. $order = static::getDetail($orderId, $with);
  312. // 该订单是否允许申请售后
  313. $order['isAllowRefund'] = static::isAllowRefund($order);
  314. return $order;
  315. }
  316. /**
  317. * 获取用户订单详情(仅订单记录)
  318. * @param int $orderId
  319. * @param array $with
  320. * @return Order|array|null
  321. * @throws BaseException
  322. */
  323. public static function getDetail(int $orderId, array $with = [])
  324. {
  325. // 查询订单记录
  326. $order = static::detail([
  327. 'order_id' => $orderId,
  328. 'user_id' => UserService::getCurrentLoginUserId(),
  329. ], $with);
  330. empty($order) && throwError('订单不存在');
  331. return $order;
  332. }
  333. /**
  334. * 获取当前用户待处理的订单数量
  335. * @return array
  336. * @throws BaseException
  337. */
  338. public function getTodoCounts(): array
  339. {
  340. return [
  341. 'payment' => $this->getCount('payment'), // 待付款的订单
  342. 'delivery' => $this->getCount('delivery'), // 待发货的订单
  343. 'received' => $this->getCount('received'), // 待收货的订单
  344. 'refund' => OrderRefundModel::getCountByUnderway(), // 进行中的售后单
  345. ];
  346. }
  347. // 返回提示信息
  348. public function getMessage(): string
  349. {
  350. return $this->message;
  351. }
  352. /**
  353. * 当前订单是否允许申请售后
  354. * @param Order $order
  355. * @return bool
  356. * @throws \think\db\exception\DataNotFoundException
  357. * @throws \think\db\exception\DbException
  358. * @throws \think\db\exception\ModelNotFoundException
  359. */
  360. private static function isAllowRefund(self $order): bool
  361. {
  362. // 必须是已发货的订单
  363. if ($order['delivery_status'] != DeliveryStatusEnum::DELIVERED) {
  364. return false;
  365. }
  366. // 允许申请售后期限(天)
  367. $refundDays = SettingModel::getItem(SettingEnum::TRADE)['order']['refund_days'];
  368. // 不允许售后
  369. if ($refundDays == 0) {
  370. return false;
  371. }
  372. // 当前时间超出允许申请售后期限
  373. if (
  374. $order['receipt_status'] == ReceiptStatusEnum::RECEIVED
  375. && time() > ($order->getData('receipt_time') + ((int)$refundDays * 86400))
  376. ) {
  377. return false;
  378. }
  379. return true;
  380. }
  381. }