Order.php 13 KB

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