Order.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  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. $model = new GoodsModel;
  122. $goodsList = $model->getListByIdsFromApi([$goodsId]);
  123. if ($goodsList->isEmpty()) {
  124. throwError('未找到商品信息');
  125. }
  126. foreach ($goodsList as &$item) {
  127. // 商品sku信息
  128. $item['skuInfo'] = GoodsSkuModel::detail($item['goods_id'], $goodsSkuId);
  129. // 商品单价
  130. $item['goods_price'] = $item['skuInfo']['goods_price'];
  131. // 商品购买数量
  132. $item['total_num'] = $goodsNum;
  133. // 商品SKU索引
  134. $item['goods_sku_id'] = $item['skuInfo']['goods_sku_id'];
  135. // 商品购买总金额
  136. $item['total_price'] = helper::bcmul($item['goods_price'], $goodsNum);
  137. }
  138. return $goodsList;
  139. }
  140. /**
  141. * 余额支付标记订单已支付
  142. * @param string $orderNo 订单号
  143. * @return bool
  144. */
  145. public function onPaymentByBalance(string $orderNo)
  146. {
  147. // 获取订单详情
  148. $service = new OrderPaySuccesService($orderNo);
  149. // 发起余额支付
  150. $status = $service->onPaySuccess(OrderPayTypeEnum::BALANCE);
  151. if (!$status) {
  152. $this->error = $service->getError();
  153. }
  154. return $status;
  155. }
  156. /**
  157. * 获取用户订单列表
  158. * @param string $type 订单类型 (all全部 payment待付款 received待发货 deliver待收货 comment待评价)
  159. * @return \think\Paginator
  160. * @throws BaseException
  161. * @throws \think\db\exception\DbException
  162. */
  163. public function getList($type = 'all')
  164. {
  165. // 筛选条件
  166. $filter = [];
  167. // 订单数据类型
  168. switch ($type) {
  169. case 'all':
  170. break;
  171. case 'payment';
  172. $filter['pay_status'] = PayStatusEnum::PENDING;
  173. $filter['order_status'] = OrderStatusEnum::NORMAL;
  174. break;
  175. case 'delivery';
  176. $filter['pay_status'] = PayStatusEnum::SUCCESS;
  177. $filter['delivery_status'] = DeliveryStatusEnum::NOT_DELIVERED;
  178. $filter['order_status'] = OrderStatusEnum::NORMAL;
  179. break;
  180. case 'received';
  181. $filter['pay_status'] = PayStatusEnum::SUCCESS;
  182. $filter['delivery_status'] = DeliveryStatusEnum::DELIVERED;
  183. $filter['receipt_status'] = ReceiptStatusEnum::NOT_RECEIVED;
  184. $filter['order_status'] = OrderStatusEnum::NORMAL;
  185. break;
  186. case 'comment';
  187. $filter['is_comment'] = 0;
  188. $filter['order_status'] = OrderStatusEnum::COMPLETED;
  189. break;
  190. }
  191. // 当前用户ID
  192. $userId = UserService::getCurrentLoginUserId();
  193. // 查询列表数据
  194. return $this->with(['goods.image'])
  195. ->where($filter)
  196. ->where('user_id', '=', $userId)
  197. ->where('is_delete', '=', 0)
  198. ->order(['create_time' => 'desc'])
  199. ->paginate(15);
  200. }
  201. /**
  202. * 取消订单
  203. * @return bool|mixed
  204. */
  205. public function cancel()
  206. {
  207. if ($this['delivery_status'] == DeliveryStatusEnum::DELIVERED) {
  208. $this->error = '已发货订单不可取消';
  209. return false;
  210. }
  211. // 订单取消事件
  212. return $this->transaction(function () {
  213. // 订单是否已支付
  214. $isPay = $this['pay_status'] == PayStatusEnum::SUCCESS;
  215. // 订单取消事件
  216. $isPay == false && OrderService::cancelEvent($this);
  217. // 更新订单状态: 已付款的订单设置为"待取消", 等待后台审核
  218. return $this->save(['order_status' => $isPay ? OrderStatusEnum::APPLY_CANCEL : OrderStatusEnum::CANCELLED]);
  219. });
  220. }
  221. /**
  222. * 确认收货
  223. * @return bool|mixed
  224. */
  225. public function receipt()
  226. {
  227. // 验证订单是否合法
  228. // 条件1: 订单必须已发货
  229. // 条件2: 订单必须未收货
  230. if ($this['delivery_status'] != 20 || $this['receipt_status'] != 10) {
  231. $this->error = '该订单不合法';
  232. return false;
  233. }
  234. return $this->transaction(function () {
  235. // 更新订单状态
  236. $status = $this->save([
  237. 'receipt_status' => 20,
  238. 'receipt_time' => time(),
  239. 'order_status' => 30
  240. ]);
  241. // 执行订单完成后的操作
  242. $OrderCompleteService = new OrderCompleteService(OrderTypeEnum::ORDER);
  243. $OrderCompleteService->complete([$this], static::$storeId);
  244. return $status;
  245. });
  246. }
  247. /**
  248. * 获取当前用户订单数量
  249. * @param string $type 订单类型 (all全部 payment待付款 received待发货 deliver待收货 comment待评价)
  250. * @return int
  251. * @throws BaseException
  252. */
  253. public function getCount($type = 'all')
  254. {
  255. // 筛选条件
  256. $filter = [];
  257. // 订单数据类型
  258. switch ($type) {
  259. case 'all':
  260. break;
  261. case 'payment';
  262. $filter['pay_status'] = PayStatusEnum::PENDING;
  263. break;
  264. case 'received';
  265. $filter['pay_status'] = PayStatusEnum::SUCCESS;
  266. $filter['delivery_status'] = DeliveryStatusEnum::DELIVERED;
  267. $filter['receipt_status'] = ReceiptStatusEnum::NOT_RECEIVED;
  268. break;
  269. case 'delivery';
  270. $filter['pay_status'] = PayStatusEnum::SUCCESS;
  271. $filter['delivery_status'] = DeliveryStatusEnum::NOT_DELIVERED;
  272. $filter['order_status'] = OrderStatusEnum::NORMAL;
  273. break;
  274. case 'comment';
  275. $filter['is_comment'] = 0;
  276. $filter['order_status'] = OrderStatusEnum::COMPLETED;
  277. break;
  278. }
  279. // 当前用户ID
  280. $userId = UserService::getCurrentLoginUserId();
  281. // 查询数据
  282. return $this->where('user_id', '=', $userId)
  283. ->where('order_status', '<>', 20)
  284. ->where($filter)
  285. ->where('is_delete', '=', 0)
  286. ->count();
  287. }
  288. /**
  289. * 获取用户订单详情(含关联数据)
  290. * @param int $orderId 订单ID
  291. * @return Order|array|null
  292. * @throws BaseException
  293. * @throws \think\db\exception\DataNotFoundException
  294. * @throws \think\db\exception\DbException
  295. * @throws \think\db\exception\ModelNotFoundException
  296. */
  297. public static function getUserOrderDetail(int $orderId)
  298. {
  299. // 关联查询
  300. $with = [
  301. 'goods' => ['image', 'goods', 'refund'],
  302. 'address', 'express'
  303. ];
  304. // 查询订单记录
  305. $order = static::getDetail($orderId, $with);
  306. // 该订单是否允许申请售后
  307. $order['isAllowRefund'] = static::isAllowRefund($order);
  308. return $order;
  309. }
  310. /**
  311. * 获取用户订单详情(仅订单记录)
  312. * @param int $orderId
  313. * @param array $with
  314. * @return Order|array|null
  315. * @throws BaseException
  316. */
  317. public static function getDetail(int $orderId, $with = [])
  318. {
  319. // 查询订单记录
  320. $order = static::detail([
  321. 'order_id' => $orderId,
  322. 'user_id' => UserService::getCurrentLoginUserId(),
  323. ], $with);
  324. empty($order) && throwError('订单不存在');
  325. return $order;
  326. }
  327. /**
  328. * 当前订单是否允许申请售后
  329. * @param Order $order
  330. * @return bool
  331. * @throws \think\db\exception\DataNotFoundException
  332. * @throws \think\db\exception\DbException
  333. * @throws \think\db\exception\ModelNotFoundException
  334. */
  335. private static function isAllowRefund(self $order)
  336. {
  337. // 必须是已发货的订单
  338. if ($order['delivery_status'] != DeliveryStatusEnum::DELIVERED) {
  339. return false;
  340. }
  341. // 允许申请售后期限(天)
  342. $refundDays = SettingModel::getItem(SettingEnum::TRADE)['order']['refund_days'];
  343. // 不允许售后
  344. if ($refundDays == 0) {
  345. return false;
  346. }
  347. // 当前时间超出允许申请售后期限
  348. if (
  349. $order['receipt_status'] == ReceiptStatusEnum::RECEIVED
  350. && time() > ($order->getData('receipt_time') + ((int)$refundDays * 86400))
  351. ) {
  352. return false;
  353. }
  354. return true;
  355. }
  356. /**
  357. * 获取当前用户待处理的订单数量
  358. * @return array
  359. * @throws BaseException
  360. */
  361. public function getTodoCounts()
  362. {
  363. return [
  364. 'payment' => $this->getCount('payment'),
  365. 'delivery' => $this->getCount('delivery'),
  366. 'received' => $this->getCount('received')
  367. ];
  368. }
  369. /**
  370. * 设置错误信息
  371. * @param $error
  372. */
  373. protected function setError($error)
  374. {
  375. empty($this->error) && $this->error = $error;
  376. }
  377. /**
  378. * 是否存在错误
  379. * @return bool
  380. */
  381. public function hasError()
  382. {
  383. return !empty($this->error);
  384. }
  385. }