OrderService.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. <?php
  2. namespace App\Services;
  3. use App\Jobs\OrderHandleJob;
  4. use App\Models\Order;
  5. use App\Models\Plan;
  6. use App\Models\User;
  7. use Illuminate\Support\Facades\DB;
  8. class OrderService
  9. {
  10. CONST STR_TO_TIME = [
  11. 'month_price' => 1,
  12. 'quarter_price' => 3,
  13. 'half_year_price' => 6,
  14. 'year_price' => 12,
  15. 'two_year_price' => 24,
  16. 'three_year_price' => 36
  17. ];
  18. public $order;
  19. public $user;
  20. public function __construct(Order $order)
  21. {
  22. $this->order = $order;
  23. }
  24. public function open()
  25. {
  26. $order = $this->order;
  27. $this->user = User::find($order->user_id);
  28. $plan = Plan::find($order->plan_id);
  29. if ($order->refund_amount) {
  30. $this->user->balance = $this->user->balance + $order->refund_amount;
  31. }
  32. DB::beginTransaction();
  33. if ($order->surplus_order_ids) {
  34. try {
  35. Order::whereIn('id', $order->surplus_order_ids)->update([
  36. 'status' => 4
  37. ]);
  38. } catch (\Exception $e) {
  39. DB::rollback();
  40. abort(500, '开通失败');
  41. }
  42. }
  43. switch ((string)$order->period) {
  44. case 'onetime_price':
  45. $this->buyByOneTime($plan);
  46. break;
  47. case 'reset_price':
  48. $this->buyByResetTraffic();
  49. break;
  50. default:
  51. $this->buyByPeriod($order, $plan);
  52. }
  53. switch ((int)$order->type) {
  54. case 1:
  55. $this->openEvent(config('v2board.new_order_event_id', 0));
  56. break;
  57. case 2:
  58. $this->openEvent(config('v2board.renew_order_event_id', 0));
  59. break;
  60. case 3:
  61. $this->openEvent(config('v2board.change_order_event_id', 0));
  62. break;
  63. }
  64. if (!$this->user->save()) {
  65. DB::rollBack();
  66. abort(500, '开通失败');
  67. }
  68. $order->status = 3;
  69. if (!$order->save()) {
  70. DB::rollBack();
  71. abort(500, '开通失败');
  72. }
  73. DB::commit();
  74. }
  75. public function setOrderType(User $user)
  76. {
  77. $order = $this->order;
  78. if ($order->period === 'reset_price') {
  79. $order->type = 4;
  80. } else if ($user->plan_id !== NULL && $order->plan_id !== $user->plan_id && ($user->expired_at > time() || $user->expired_at === NULL)) {
  81. if (!(int)config('v2board.plan_change_enable', 1)) abort(500, '目前不允许更改订阅,请联系客服或提交工单操作');
  82. $order->type = 3;
  83. if ((int)config('v2board.surplus_enable', 1)) $this->getSurplusValue($user, $order);
  84. if ($order->surplus_amount >= $order->total_amount) {
  85. $order->refund_amount = $order->surplus_amount - $order->total_amount;
  86. $order->total_amount = 0;
  87. } else {
  88. $order->total_amount = $order->total_amount - $order->surplus_amount;
  89. }
  90. } else if ($user->expired_at > time() && $order->plan_id == $user->plan_id) { // 用户订阅未过期且购买订阅与当前订阅相同 === 续费
  91. $order->type = 2;
  92. } else { // 新购
  93. $order->type = 1;
  94. }
  95. }
  96. public function setVipDiscount(User $user)
  97. {
  98. $order = $this->order;
  99. if ($user->discount) {
  100. $order->discount_amount = $order->discount_amount + ($order->total_amount * ($user->discount / 100));
  101. }
  102. $order->total_amount = $order->total_amount - $order->discount_amount;
  103. }
  104. public function setInvite(User $user):void
  105. {
  106. $order = $this->order;
  107. if ($user->invite_user_id && ($order->total_amount <= 0)) return;
  108. $order->invite_user_id = $user->invite_user_id;
  109. $inviter = User::find($user->invite_user_id);
  110. if (!$inviter) return;
  111. $isCommission = false;
  112. switch ((int)$inviter->commission_type) {
  113. case 0:
  114. $commissionFirstTime = (int)config('v2board.commission_first_time_enable', 1);
  115. $isCommission = (!$commissionFirstTime || ($commissionFirstTime && !$this->haveValidOrder($user)));
  116. break;
  117. case 1:
  118. $isCommission = true;
  119. break;
  120. case 2:
  121. $isCommission = !$this->haveValidOrder($user);
  122. break;
  123. }
  124. if (!$isCommission) return;
  125. if ($inviter && $inviter->commission_rate) {
  126. $order->commission_balance = $order->total_amount * ($inviter->commission_rate / 100);
  127. } else {
  128. $order->commission_balance = $order->total_amount * (config('v2board.invite_commission', 10) / 100);
  129. }
  130. }
  131. private function haveValidOrder(User $user)
  132. {
  133. return Order::where('user_id', $user->id)
  134. ->whereNotIn('status', [0, 2])
  135. ->first();
  136. }
  137. private function getSurplusValue(User $user, Order $order)
  138. {
  139. if ($user->expired_at === NULL) {
  140. $this->getSurplusValueByOneTime($user, $order);
  141. } else {
  142. $this->getSurplusValueByPeriod($user, $order);
  143. }
  144. }
  145. private function getSurplusValueByOneTime(User $user, Order $order)
  146. {
  147. $lastOneTimeOrder = Order::where('user_id', $user->id)
  148. ->where('period', 'onetime_price')
  149. ->where('status', 3)
  150. ->orderBy('id', 'DESC')
  151. ->first();
  152. if (!$lastOneTimeOrder) return;
  153. $plan = Plan::find($lastOneTimeOrder->plan_id);
  154. if (!$plan) return;
  155. $trafficUnitPrice = $plan->onetime_price / $plan->transfer_enable;
  156. if ($user->discount && $trafficUnitPrice) {
  157. $trafficUnitPrice = $trafficUnitPrice - ($trafficUnitPrice * $user->discount / 100);
  158. }
  159. $notUsedTraffic = $plan->transfer_enable - (($user->u + $user->d) / 1073741824);
  160. $result = $trafficUnitPrice * $notUsedTraffic;
  161. $orderModel = Order::where('user_id', $user->id)->where('period', '!=', 'reset_price')->where('status', 3);
  162. $order->surplus_amount = $result > 0 ? $result : 0;
  163. $order->surplus_order_ids = array_column($orderModel->get()->toArray(), 'id');
  164. }
  165. private function orderIsUsed(Order $order):bool
  166. {
  167. $month = self::STR_TO_TIME[$order->period];
  168. $orderExpireDay = strtotime('+' . $month . ' month', $order->created_at);
  169. if ($orderExpireDay < time()) return true;
  170. return false;
  171. }
  172. private function getSurplusValueByPeriod(User $user, Order $order)
  173. {
  174. $orderModel = Order::where('user_id', $user->id)
  175. ->where('period', '!=', 'reset_price')
  176. ->where('status', 3);
  177. $orders = $orderModel->get();
  178. $orderSurplusMonth = 0;
  179. $orderSurplusAmount = 0;
  180. $userSurplusMonth = ($user->expired_at - time()) / 2678400;
  181. foreach ($orders as $k => $item) {
  182. // 兼容历史余留问题
  183. if ($item->period === 'onetime_price') continue;
  184. if ($this->orderIsUsed($item)) continue;
  185. $orderSurplusMonth = $orderSurplusMonth + self::STR_TO_TIME[$item->period];
  186. $orderSurplusAmount = $orderSurplusAmount + ($item['total_amount'] + $item['balance_amount'] + $item['surplus_amount'] - $item['refund_amount']);
  187. }
  188. if (!$orderSurplusMonth || !$orderSurplusAmount) return;
  189. $monthUnitPrice = $orderSurplusAmount / $orderSurplusMonth;
  190. // 如果用户过期月大于订单过期月
  191. if ($userSurplusMonth > $orderSurplusMonth) {
  192. $orderSurplusAmount = $orderSurplusMonth * $monthUnitPrice;
  193. } else {
  194. $orderSurplusAmount = $userSurplusMonth * $monthUnitPrice;
  195. }
  196. if (!$orderSurplusAmount) {
  197. return;
  198. }
  199. $order->surplus_amount = $orderSurplusAmount > 0 ? $orderSurplusAmount : 0;
  200. $order->surplus_order_ids = array_column($orders->toArray(), 'id');
  201. }
  202. public function paid(string $callbackNo)
  203. {
  204. $order = $this->order;
  205. if ($order->status !== 0) return true;
  206. $order->status = 1;
  207. $order->paid_at = time();
  208. $order->callback_no = $callbackNo;
  209. if (!$order->save()) return false;
  210. OrderHandleJob::dispatch($order->trade_no);
  211. return true;
  212. }
  213. public function cancel():bool
  214. {
  215. $order = $this->order;
  216. DB::beginTransaction();
  217. $order->status = 2;
  218. if (!$order->save()) {
  219. DB::rollBack();
  220. return false;
  221. }
  222. if ($order->balance_amount) {
  223. $userService = new UserService();
  224. if (!$userService->addBalance($order->user_id, $order->balance_amount)) {
  225. DB::rollBack();
  226. return false;
  227. }
  228. }
  229. DB::commit();
  230. return true;
  231. }
  232. private function buyByResetTraffic()
  233. {
  234. $this->user->u = 0;
  235. $this->user->d = 0;
  236. }
  237. private function buyByPeriod(Order $order, Plan $plan)
  238. {
  239. // change plan process
  240. if ((int)$order->type === 3) {
  241. $this->user->expired_at = time();
  242. }
  243. $this->user->transfer_enable = $plan->transfer_enable * 1073741824;
  244. // 从一次性转换到循环
  245. if ($this->user->expired_at === NULL) $this->buyByResetTraffic();
  246. // 新购
  247. if ($order->type === 1) $this->buyByResetTraffic();
  248. $this->user->plan_id = $plan->id;
  249. $this->user->group_id = $plan->group_id;
  250. $this->user->expired_at = $this->getTime($order->period, $this->user->expired_at);
  251. }
  252. private function buyByOneTime(Plan $plan)
  253. {
  254. $this->buyByResetTraffic();
  255. $this->user->transfer_enable = $plan->transfer_enable * 1073741824;
  256. $this->user->plan_id = $plan->id;
  257. $this->user->group_id = $plan->group_id;
  258. $this->user->expired_at = NULL;
  259. }
  260. private function getTime($str, $timestamp)
  261. {
  262. if ($timestamp < time()) {
  263. $timestamp = time();
  264. }
  265. switch ($str) {
  266. case 'month_price':
  267. return strtotime('+1 month', $timestamp);
  268. case 'quarter_price':
  269. return strtotime('+3 month', $timestamp);
  270. case 'half_year_price':
  271. return strtotime('+6 month', $timestamp);
  272. case 'year_price':
  273. return strtotime('+12 month', $timestamp);
  274. case 'two_year_price':
  275. return strtotime('+24 month', $timestamp);
  276. case 'three_year_price':
  277. return strtotime('+36 month', $timestamp);
  278. }
  279. }
  280. private function openEvent($eventId)
  281. {
  282. switch ((int) $eventId) {
  283. case 0:
  284. break;
  285. case 1:
  286. $this->buyByResetTraffic();
  287. break;
  288. }
  289. }
  290. }