Order.php 13 KB

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