Order.php 13 KB

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