OrderService.php 11 KB

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