Order.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  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 'deliver';
  270. $filter['order_status'] = OrderStatusEnum::COMPLETED;
  271. $filter['is_comment'] = 0;
  272. break;
  273. case 'comment';
  274. $filter['is_comment'] = 0;
  275. $filter['order_status'] = OrderStatusEnum::COMPLETED;
  276. break;
  277. }
  278. // 当前用户ID
  279. $userId = UserService::getCurrentLoginUserId();
  280. // 查询数据
  281. return $this->where('user_id', '=', $userId)
  282. ->where('order_status', '<>', 20)
  283. ->where($filter)
  284. ->where('is_delete', '=', 0)
  285. ->count();
  286. }
  287. /**
  288. * 获取用户订单详情(含关联数据)
  289. * @param int $orderId 订单ID
  290. * @return Order|array|null
  291. * @throws BaseException
  292. * @throws \think\db\exception\DataNotFoundException
  293. * @throws \think\db\exception\DbException
  294. * @throws \think\db\exception\ModelNotFoundException
  295. */
  296. public static function getUserOrderDetail(int $orderId)
  297. {
  298. // 关联查询
  299. $with = [
  300. 'goods' => ['image', 'goods', 'refund'],
  301. 'address', 'express'
  302. ];
  303. // 查询订单记录
  304. $order = static::getDetail($orderId, $with);
  305. // 该订单是否允许申请售后
  306. $order['isAllowRefund'] = static::isAllowRefund($order);
  307. return $order;
  308. }
  309. /**
  310. * 获取用户订单详情(仅订单记录)
  311. * @param int $orderId
  312. * @param array $with
  313. * @return Order|array|null
  314. * @throws BaseException
  315. */
  316. public static function getDetail(int $orderId, $with = [])
  317. {
  318. // 查询订单记录
  319. $order = static::detail([
  320. 'order_id' => $orderId,
  321. 'user_id' => UserService::getCurrentLoginUserId(),
  322. ], $with);
  323. empty($order) && throwError('订单不存在');
  324. return $order;
  325. }
  326. /**
  327. * 当前订单是否允许申请售后
  328. * @param Order $order
  329. * @return bool
  330. * @throws \think\db\exception\DataNotFoundException
  331. * @throws \think\db\exception\DbException
  332. * @throws \think\db\exception\ModelNotFoundException
  333. */
  334. private static function isAllowRefund(self $order)
  335. {
  336. // 必须是已发货的订单
  337. if ($order['delivery_status'] != DeliveryStatusEnum::DELIVERED) {
  338. return false;
  339. }
  340. // 允许申请售后期限(天)
  341. $refundDays = SettingModel::getItem(SettingEnum::TRADE)['order']['refund_days'];
  342. // 不允许售后
  343. if ($refundDays == 0) {
  344. return false;
  345. }
  346. // 当前时间超出允许申请售后期限
  347. if (
  348. $order['receipt_status'] == ReceiptStatusEnum::RECEIVED
  349. && time() > ($order->getData('receipt_time') + ((int)$refundDays * 86400))
  350. ) {
  351. return false;
  352. }
  353. return true;
  354. }
  355. /**
  356. * 获取当前用户待处理的订单数量
  357. * @return array
  358. * @throws BaseException
  359. */
  360. public function getTodoCounts()
  361. {
  362. return [
  363. 'payment' => $this->getCount('payment'),
  364. 'deliver' => $this->getCount('deliver'),
  365. 'received' => $this->getCount('received')
  366. ];
  367. }
  368. /**
  369. * 设置错误信息
  370. * @param $error
  371. */
  372. protected function setError($error)
  373. {
  374. empty($this->error) && $this->error = $error;
  375. }
  376. /**
  377. * 是否存在错误
  378. * @return bool
  379. */
  380. public function hasError()
  381. {
  382. return !empty($this->error);
  383. }
  384. }