Order.php 13 KB

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