PresellOrderRepository.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2024 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. namespace app\common\repositories\store\order;
  12. use app\common\dao\store\order\PresellOrderDao;
  13. use app\common\model\store\order\PresellOrder;
  14. use app\common\model\user\User;
  15. use app\common\repositories\BaseRepository;
  16. use app\common\repositories\store\product\ProductPresellSkuRepository;
  17. use app\common\repositories\store\product\ProductRepository;
  18. use app\common\repositories\system\merchant\FinancialRecordRepository;
  19. use app\common\repositories\system\merchant\MerchantRepository;
  20. use app\common\repositories\user\UserBillRepository;
  21. use app\common\repositories\user\UserMerchantRepository;
  22. use app\common\repositories\user\UserRepository;
  23. use app\common\repositories\wechat\WechatUserRepository;
  24. use crmeb\jobs\UserBrokerageLevelJob;
  25. use crmeb\services\AlipayService;
  26. use crmeb\services\CombinePayService;
  27. use crmeb\services\MiniProgramService;
  28. use crmeb\services\PayService;
  29. use crmeb\services\WechatService;
  30. use think\Exception;
  31. use think\exception\ValidateException;
  32. use think\facade\Cache;
  33. use think\facade\Db;
  34. use think\facade\Log;
  35. use think\facade\Queue;
  36. /**
  37. * Class PresellOrderRepository
  38. * @package app\common\repositories\store\order
  39. * @author xaboy
  40. * @day 2020/10/27
  41. * @mixin PresellOrderDao
  42. */
  43. class PresellOrderRepository extends BaseRepository
  44. {
  45. public function __construct(PresellOrderDao $dao)
  46. {
  47. $this->dao = $dao;
  48. }
  49. /**
  50. * 创建订单
  51. *
  52. * 本函数用于创建一个新的订单。它通过收集用户ID、订单ID、价格以及订单的开始和结束时间,
  53. * 来构造订单的基本信息。此外,它还会为预售价订单生成一个新的订单号。
  54. *
  55. * @param int $uid 用户ID。标识订单所属的用户。
  56. * @param string $orderId 订单ID。用于唯一标识订单。
  57. * @param float $price 订单价格。表示订单的总金额。
  58. * @param int $final_start_time 订单开始时间。表示订单的有效起始时间。
  59. * @param int $final_end_time 订单结束时间。表示订单的有效结束时间。
  60. * @return bool|object 返回创建的订单对象或false,如果创建失败。
  61. */
  62. public function createOrder($uid, $orderId, $price, $final_start_time, $final_end_time)
  63. {
  64. // 通过DAO层创建订单,传入包括用户ID、订单ID、开始时间、结束时间、价格以及预售价订单号等信息。
  65. return $this->dao->create([
  66. 'uid' => $uid,
  67. 'order_id' => $orderId,
  68. 'final_start_time' => $final_start_time,
  69. 'final_end_time' => $final_end_time,
  70. 'pay_price' => $price,
  71. 'presell_order_sn' => app()->make(StoreOrderRepository::class)->getNewOrderId(StoreOrderRepository::TYPE_SN_PRESELL)
  72. ]);
  73. }
  74. /**
  75. * 处理预售订单的支付逻辑。
  76. *
  77. * 根据支付方式的不同,选择不同的支付处理方式。支持余额支付以及微信、支付宝等第三方支付。
  78. * 对于移动端支付,会根据支付类型添加App后缀以区分支付渠道。
  79. * 在支付前,会触发一个事件,允许其他功能模块在支付前进行额外的操作或校验。
  80. * 根据支付类型和系统配置,选择使用合并支付服务或普通支付服务来生成支付配置。
  81. *
  82. * @param string $type 支付方式,可以是余额(balance)、微信(weixin)、支付宝(alipay)等。
  83. * @param User $user 进行支付的用户对象。
  84. * @param PresellOrder $order 预售订单对象。
  85. * @param string $return_url 支付宝支付时的回调URL,可选。
  86. * @param bool $isApp 是否为APP支付,用于区分微信支付的普通支付和APP支付。
  87. * @return array 返回包含支付配置和订单ID的信息。
  88. */
  89. public function pay($type, User $user, PresellOrder $order, $return_url = '', $isApp = false)
  90. {
  91. // 如果是余额支付,则直接调用余额支付方法
  92. if ($type === 'balance') {
  93. return $this->payBalance($user, $order);
  94. }
  95. // 如果是微信或支付宝支付,并且是APP支付,则在支付方式后添加App后缀
  96. if (in_array($type, ['weixin', 'alipay'], true) && $isApp) {
  97. $type .= 'App';
  98. }
  99. // 在支付前触发一个事件,允许其他功能模块进行额外的操作或校验
  100. event('order.presell.pay.before', compact('order', 'type', 'isApp'));
  101. // 根据支付类型和系统配置,选择使用合并支付服务或普通支付服务
  102. if (in_array($type, ['weixin', 'weixinApp', 'routine', 'h5', 'weixinQr'], true) && systemConfig('open_wx_combine')) {
  103. $service = new CombinePayService($type, $order->getCombinePayParams());
  104. } else {
  105. $service = new PayService($type, $order->getPayParams($type === 'alipay' ? $return_url : ''), 'presell');
  106. }
  107. // 生成支付配置
  108. $config = $service->pay($user);
  109. // 返回支付配置和订单ID,供前端进行支付操作
  110. return app('json')->status($type, $config + ['order_id' => $order['presell_order_id']]);
  111. }
  112. /**
  113. * 使用余额支付预售价订单。
  114. *
  115. * 此方法处理用户使用余额支付预售价订单的流程。它首先检查余额支付是否已开启,然后确保用户余额充足。
  116. * 如果条件满足,它将在数据库事务中执行支付操作,包括更新用户余额、记录账单和标记订单为支付成功。
  117. *
  118. * @param User $user 当前进行支付的用户对象。
  119. * @param PresellOrder $order 需要支付的预售价订单对象。
  120. * @throws ValidateException 如果支付方式未开启或用户余额不足,则抛出验证异常。
  121. * @return json 返回支付成功的响应。
  122. */
  123. public function payBalance(User $user, PresellOrder $order)
  124. {
  125. // 检查余额支付是否开启,如果没有开启则抛出异常。
  126. if (!systemConfig('yue_pay_status'))
  127. throw new ValidateException('未开启余额支付');
  128. // 检查用户余额是否足够支付订单,如果不足则抛出异常。
  129. if ($user['now_money'] < $order['pay_price'])
  130. throw new ValidateException('余额不足,请更换支付方式');
  131. // 使用数据库事务来确保支付操作的原子性。
  132. Db::transaction(function () use ($user, $order) {
  133. // 更新用户的余额,并保存更改。
  134. $user->now_money = bcsub($user->now_money, $order['pay_price'], 2);
  135. $user->save();
  136. // 创建用户账单记录,记录用户余额的减少。
  137. $userBillRepository = app()->make(UserBillRepository::class);
  138. $userBillRepository->decBill($user['uid'], 'now_money', 'presell', [
  139. 'link_id' => $order['presell_order_id'],
  140. 'status' => 1,
  141. 'title' => '支付预售尾款',
  142. 'number' => $order['pay_price'],
  143. 'mark' => '余额支付支付' . floatval($order['pay_price']) . '元购买商品',
  144. 'balance' => $user->now_money
  145. ]);
  146. // 标记订单为支付成功。
  147. $this->paySuccess($order);
  148. });
  149. // 返回支付成功的响应。
  150. return app('json')->status('success', '余额支付成功', ['order_id' => $order['presell_order_id']]);
  151. }
  152. /**
  153. * 处理预售订单支付成功后的业务逻辑。
  154. *
  155. * @param PresellOrder $order 预售订单对象
  156. * @param int $is_combine 是否为合并支付,0表示正常支付,1表示合并支付
  157. * @param array $subOrders 子订单数组,包含交易号等信息
  158. *
  159. * 此函数在支付成功后,更新订单状态,记录支付信息,并处理相关的财务记录。
  160. * 同时,它还处理了订单相关的佣金计算和分佣逻辑。
  161. */
  162. public function paySuccess(PresellOrder $order, $is_combine = 0, array $subOrders = [])
  163. {
  164. Db::transaction(function () use ($is_combine, $order, $subOrders) {
  165. $time = date('Y-m-d H:i:s');
  166. $order->paid = 1;
  167. $order->pay_time = $time;
  168. if (isset($subOrders[$order->presell_order_sn])) {
  169. $order->transaction_id = $subOrders[$order->presell_order_sn]['transaction_id'];
  170. }
  171. $order->is_combine = $is_combine;
  172. $order->order->status = 0;
  173. $storeOrderRepository = app()->make(StoreOrderRepository::class);
  174. if ($order->order->order_type == 1) {
  175. $order->order->verify_code = $storeOrderRepository->verifyCode();
  176. }
  177. if (empty($order->order_sn)) {
  178. $order->order_sn = $storeOrderRepository->getOrderSn($order->order_id);
  179. }
  180. $order->order->save();
  181. $order->save();
  182. //订单记录
  183. $statusRepository = app()->make(StoreOrderStatusRepository::class);
  184. $orderStatus = [
  185. 'order_id' => $order->order_id,
  186. 'order_sn' => $order->order_sn,
  187. 'type' => $statusRepository::TYPE_ORDER,
  188. 'change_message' => '订单尾款支付成功',
  189. 'change_type' => $statusRepository::ORDER_STATUS_PRESELL,
  190. ];
  191. $i = 1;
  192. $finance = [];
  193. $final_price = $order->order->pay_price;
  194. $order_price = $order->pay_price;
  195. $pay_price = bcadd($order_price, $final_price, 2);
  196. $sn = app()->make(FinancialRecordRepository::class)->getSn();
  197. $finance[] = [
  198. 'order_id' => $order->order_id,
  199. 'order_sn' => $order->presell_order_sn,
  200. 'user_info' => $order->user->nickname,
  201. 'user_id' => $order->uid,
  202. 'financial_type' => 'presell',
  203. 'financial_pm' => 1,
  204. 'type' => 2,
  205. 'number' => $order->pay_price,
  206. 'mer_id' => $order->mer_id,
  207. 'financial_record_sn' => $sn . ($i++),
  208. 'pay_type' => $order->pay_type,
  209. ];
  210. $finance[] = [
  211. 'order_id' => $order->order->order_id,
  212. 'order_sn' => $order->order->order_sn,
  213. 'user_info' => $order->user->nickname,
  214. 'user_id' => $order->uid,
  215. 'financial_type' => 'mer_presell',
  216. 'financial_pm' => 1,
  217. 'type' => 0,
  218. 'number' => $pay_price,
  219. 'mer_id' => $order->mer_id,
  220. 'financial_record_sn' => $sn . ($i++),
  221. 'pay_type' => $order->pay_type,
  222. ];
  223. // $pay_price = bcsub($pay_price, bcadd($order->order['extension_one'], $order->order['extension_two'], 3), 2);
  224. if (isset($order->order->orderProduct[0]['cart_info']['presell_extension_one']) && $order->order->orderProduct[0]['cart_info']['presell_extension_one'] > 0) {
  225. $order_price = bcsub($order_price, $order->order->orderProduct[0]['cart_info']['presell_extension_one'], 2);
  226. }
  227. if (isset($order->order->orderProduct[0]['cart_info']['presell_extension_two']) && $order->order->orderProduct[0]['cart_info']['presell_extension_two'] > 0) {
  228. $order_price = bcsub($order_price, $order->order->orderProduct[0]['cart_info']['presell_extension_two'], 2);
  229. }
  230. if (isset($order->order->orderProduct[0]['cart_info']['final_extension_one']) && $order->order->orderProduct[0]['cart_info']['final_extension_one'] > 0) {
  231. $final_price = bcsub($final_price, $order->order->orderProduct[0]['cart_info']['final_extension_one'], 2);
  232. }
  233. if (isset($order->order->orderProduct[0]['cart_info']['final_extension_two']) && $order->order->orderProduct[0]['cart_info']['final_extension_two'] > 0) {
  234. $final_price = bcsub($final_price, $order->order->orderProduct[0]['cart_info']['final_extension_two'], 2);
  235. }
  236. if ($order->order['extension_one'] > 0) {
  237. $finance[] = [
  238. 'order_id' => $order->order->order_id,
  239. 'order_sn' => $order->order->order_sn,
  240. 'user_info' => $order->user->nickname,
  241. 'user_id' => $order->uid,
  242. 'financial_type' => 'brokerage_one',
  243. 'financial_pm' => 0,
  244. 'type' => 1,
  245. 'number' => $order->order['extension_one'],
  246. 'mer_id' => $order->mer_id,
  247. 'financial_record_sn' => $sn . ($i++),
  248. 'pay_type' => $order->pay_type,
  249. ];
  250. }
  251. if ($order->order['extension_two'] > 0) {
  252. $finance[] = [
  253. 'order_id' => $order->order->order_id,
  254. 'order_sn' => $order->order->order_sn,
  255. 'user_info' => $order->user->nickname,
  256. 'user_id' => $order->uid,
  257. 'financial_type' => 'brokerage_two',
  258. 'financial_pm' => 0,
  259. 'type' => 1,
  260. 'number' => $order->order['extension_two'],
  261. 'mer_id' => $order->mer_id,
  262. 'financial_record_sn' => $sn . ($i++),
  263. 'pay_type' => $order->pay_type,
  264. ];
  265. }
  266. if ($order->order->commission_rate > 0) {
  267. $commission_rate = ($order->order->commission_rate / 100);
  268. $finalRatePrice = bcmul($final_price, $commission_rate, 2);
  269. $orderRatePrice = bcmul($order_price, $commission_rate, 2);
  270. $ratePrice = bcadd($finalRatePrice, $orderRatePrice, 2);
  271. $finance[] = [
  272. 'order_id' => $order->order->order_id,
  273. 'order_sn' => $order->order->order_sn,
  274. 'user_info' => $order->user->nickname,
  275. 'user_id' => $order->uid,
  276. 'financial_type' => 'presell_charge',
  277. 'financial_pm' => 1,
  278. 'type' => 1,
  279. 'number' => $ratePrice,
  280. 'mer_id' => $order->mer_id,
  281. 'financial_record_sn' => $sn . ($i++),
  282. 'pay_type' => $order->pay_type,
  283. ];
  284. // $pay_price = bcsub($pay_price, $ratePrice, 2);
  285. $order_price = bcsub($order_price, $orderRatePrice, 2);
  286. $final_price = bcsub($final_price, $finalRatePrice, 2);
  287. }
  288. $finance[] = [
  289. 'order_id' => $order->order->order_id,
  290. 'order_sn' => $order->order->order_sn,
  291. 'user_info' => $order->user->nickname,
  292. 'user_id' => $order->uid,
  293. 'financial_type' => 'presell_true',
  294. 'financial_pm' => 1,
  295. 'type' => 2,
  296. 'number' => bcadd($order_price, $final_price, 2),
  297. 'mer_id' => $order->mer_id,
  298. 'financial_record_sn' => $sn . ($i++),
  299. 'pay_type' => $order->pay_type,
  300. ];
  301. if (!$is_combine && $order->pay_type != 7) {
  302. app()->make(MerchantRepository::class)->addLockMoney($order->mer_id, 'presell', $order->presell_order_id, !$order->order->groupOrder->is_combine ? bcadd($order_price, $final_price, 2) : $order_price);
  303. // app()->make(MerchantRepository::class)->addMoney($order->mer_id, !$order->order->groupOrder->is_combine ? bcadd($order_price, $final_price, 2) : $order_price);
  304. } else if (!$order->order->groupOrder->is_combine && $order->pay_type != 7) {
  305. app()->make(MerchantRepository::class)->addLockMoney($order->mer_id, 'presell', $order->presell_order_id, $final_price);
  306. // app()->make(MerchantRepository::class)->addMoney($order->mer_id, $final_price);
  307. }
  308. if ($is_combine) {
  309. $storeOrderProfitsharingRepository = app()->make(StoreOrderProfitsharingRepository::class);
  310. $storeOrderProfitsharingRepository->create([
  311. 'profitsharing_sn' => $storeOrderProfitsharingRepository->getOrderSn(),
  312. 'order_id' => $order->order->order_id,
  313. 'mer_id' => $order->mer_id,
  314. 'transaction_id' => $order->transaction_id ?? '',
  315. 'profitsharing_price' => $order->pay_price,
  316. 'profitsharing_mer_price' => $order_price,
  317. 'type' => $storeOrderProfitsharingRepository::PROFITSHARING_TYPE_PRESELL,
  318. ]);
  319. }
  320. app()->make(UserRepository::class)->update($order->uid, [
  321. 'pay_price' => Db::raw('pay_price+' . $order->pay_price),
  322. ]);
  323. app()->make(ProductPresellSkuRepository::class)->incCount($order->order->orderProduct[0]['activity_id'], $order->order->orderProduct[0]['product_sku'], 'two_pay');
  324. app()->make(UserMerchantRepository::class)->updatePayTime($order->uid, $order->mer_id, $order->pay_price, false);
  325. app()->make(FinancialRecordRepository::class)->insertAll($finance);
  326. $statusRepository->createUserLog($orderStatus);
  327. });
  328. if ($order->user->spread_uid) {
  329. Queue::push(UserBrokerageLevelJob::class, ['uid' => $order->user->spread_uid, 'type' => 'spread_money', 'inc' => $order->pay_price]);
  330. }
  331. Queue::push(UserBrokerageLevelJob::class, ['uid' => $order->uid, 'type' => 'pay_money', 'inc' => $order->pay_price]);
  332. event('order.presll.paySuccess', compact('order'));
  333. }
  334. /**
  335. * 取消预售订单
  336. * 当预售订单超过支付时间未支付时,调用此函数进行订单取消操作。
  337. * 主要包括以下几个步骤:
  338. * 1. 根据预售订单ID查询订单信息,确认订单未支付。
  339. * 2. 更新订单状态为关闭,并对相关商品库存进行回滚。
  340. * 3. 如果订单有关联的预付分账信息,处理预付分账的退款及记录。
  341. * 4. 生成相关的财务记录。
  342. * 5. 触发相关的事件,供其他系统监听并执行相应的操作。
  343. *
  344. * @param int $id 预售订单ID
  345. */
  346. public function cancel($id)
  347. {
  348. $order = $this->dao->getWhere(['presell_order_id' => $id, 'paid' => 0]);
  349. if (!$order) return;
  350. //订单记录
  351. $statusRepository = app()->make(StoreOrderStatusRepository::class);
  352. $orderStatus = [
  353. 'order_id' => $order->order_id,
  354. 'order_sn' => $order->order_sn,
  355. 'type' => $statusRepository::TYPE_ORDER,
  356. 'change_message' => '预售订单超时支付自动关闭',
  357. 'change_type' => $statusRepository::ORDER_STATUS_PRESELL_CLOSE,
  358. ];
  359. event('order.presll.fail.before', compact('order'));
  360. $productRepository = app()->make(ProductRepository::class);
  361. Db::transaction(function () use ($productRepository, $order, $orderStatus,$statusRepository) {
  362. $statusRepository->createSysLog($orderStatus);
  363. $order->order->status = 11;
  364. $order->status = 0;
  365. $order->save();
  366. $order->order->save();
  367. foreach ($order->order->orderProduct as $cart) {
  368. try{
  369. $productRepository->orderProductIncStock($order->order, $cart);
  370. }catch (Exception $e) {}
  371. }
  372. if ($order->order->firstProfitsharing && $order->order->firstProfitsharing->profitsharing_price > 0) {
  373. $make = app()->make(FinancialRecordRepository::class);
  374. $sn = $make->getSn();
  375. $financial = [[
  376. 'order_id' => $order->order->order_id,
  377. 'order_sn' => $order->order->order_sn,
  378. 'user_info' => $order->user->nickname,
  379. 'user_id' => $order->uid,
  380. 'financial_type' => 'presell_charge',
  381. 'financial_pm' => 1,
  382. 'type' => 1,
  383. 'number' => bcsub($order->order->firstProfitsharing->profitsharing_price, $order->order->firstProfitsharing->profitsharing_mer_price, 2),
  384. 'mer_id' => $order->mer_id,
  385. 'financial_record_sn' => $sn . '0'
  386. ], [
  387. 'order_id' => $order->order->order_id,
  388. 'order_sn' => $order->order->order_sn,
  389. 'user_info' => $order->user->nickname,
  390. 'user_id' => $order->uid,
  391. 'financial_type' => 'mer_presell',
  392. 'financial_pm' => 1,
  393. 'type' => 0,
  394. 'number' => $order->order->firstProfitsharing->profitsharing_mer_pric,
  395. 'mer_id' => $order->mer_id,
  396. 'financial_record_sn' => $sn . '1'
  397. ], [
  398. 'order_id' => $order->order->order_id,
  399. 'order_sn' => $order->order->order_sn,
  400. 'user_info' => $order->user->nickname,
  401. 'user_id' => $order->uid,
  402. 'financial_type' => 'presell_true',
  403. 'financial_pm' => 1,
  404. 'type' => 2,
  405. 'number' => $order->order->firstProfitsharing->profitsharing_mer_price,
  406. 'mer_id' => $order->mer_id,
  407. 'financial_record_sn' => $sn . '2'
  408. ]];
  409. $make->insertAll($financial);
  410. try {
  411. app()->make(StoreOrderProfitsharingRepository::class)->profitsharing($order->order->firstProfitsharing);
  412. } catch (\Exception $e) {
  413. Log::info('预售定金分账失败' . $order->order_id . $e->getMessage());
  414. }
  415. }
  416. });
  417. event('order.presll.fail', compact('order'));
  418. }
  419. }