OrderService.php 10 KB

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