OrderService.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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):void
  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. $isCommission = false;
  128. switch ((int)$user->commission_type) {
  129. case 0:
  130. $commissionFirstTime = (int)config('v2board.commission_first_time_enable', 1);
  131. $isCommission = (!$commissionFirstTime || ($commissionFirstTime && !$this->haveValidOrder($user)));
  132. break;
  133. case 1:
  134. $isCommission = true;
  135. break;
  136. case 2:
  137. $isCommission = !$this->haveValidOrder($user);
  138. break;
  139. }
  140. if ($isCommission) {
  141. $inviter = User::find($user->invite_user_id);
  142. if ($inviter && $inviter->commission_rate) {
  143. $order->commission_balance = $order->total_amount * ($inviter->commission_rate / 100);
  144. } else {
  145. $order->commission_balance = $order->total_amount * (config('v2board.invite_commission', 10) / 100);
  146. }
  147. }
  148. }
  149. }
  150. private function haveValidOrder(User $user)
  151. {
  152. return Order::where('user_id', $user->id)
  153. ->whereNotIn('status', [0, 2])
  154. ->first();
  155. }
  156. private function getSurplusValue(User $user, Order $order)
  157. {
  158. if ($user->expired_at === NULL) {
  159. $this->getSurplusValueByOneTime($user, $order);
  160. } else {
  161. $this->getSurplusValueByCycle($user, $order);
  162. }
  163. }
  164. private function getSurplusValueByOneTime(User $user, Order $order)
  165. {
  166. $plan = Plan::find($user->plan_id);
  167. $trafficUnitPrice = $plan->onetime_price / $plan->transfer_enable;
  168. if ($user->discount && $trafficUnitPrice) {
  169. $trafficUnitPrice = $trafficUnitPrice - ($trafficUnitPrice * $user->discount / 100);
  170. }
  171. $notUsedTraffic = $plan->transfer_enable - (($user->u + $user->d) / 1073741824);
  172. $result = $trafficUnitPrice * $notUsedTraffic;
  173. $orderModel = Order::where('user_id', $user->id)->where('cycle', '!=', 'reset_price')->where('status', 3);
  174. $order->surplus_amount = $result > 0 ? $result : 0;
  175. $order->surplus_order_ids = json_encode(array_column($orderModel->get()->toArray(), 'id'));
  176. }
  177. private function orderIsUsed(Order $order):bool
  178. {
  179. $month = self::STR_TO_TIME[$order->cycle];
  180. $orderExpireDay = strtotime('+' . $month . ' month', $order->created_at->timestamp);
  181. if ($orderExpireDay < time()) return true;
  182. return false;
  183. }
  184. private function getSurplusValueByCycle(User $user, Order $order)
  185. {
  186. $orderModel = Order::where('user_id', $user->id)
  187. ->where('cycle', '!=', 'reset_price')
  188. ->where('status', 3);
  189. $orders = $orderModel->get();
  190. $orderSurplusMonth = 0;
  191. $orderSurplusAmount = 0;
  192. $userSurplusMonth = ($user->expired_at - time()) / 2678400;
  193. foreach ($orders as $k => $item) {
  194. // 兼容历史余留问题
  195. if ($item->cycle === 'onetime_price') continue;
  196. if ($this->orderIsUsed($item)) continue;
  197. $orderSurplusMonth = $orderSurplusMonth + self::STR_TO_TIME[$item->cycle];
  198. $orderSurplusAmount = $orderSurplusAmount + ($item['total_amount'] + $item['balance_amount'] + $item['surplus_amount'] - $item['refund_amount']);
  199. }
  200. if (!$orderSurplusMonth || !$orderSurplusAmount) return;
  201. $monthUnitPrice = $orderSurplusAmount / $orderSurplusMonth;
  202. // 如果用户过期月大于订单过期月
  203. if ($userSurplusMonth > $orderSurplusMonth) {
  204. $orderSurplusAmount = $orderSurplusMonth * $monthUnitPrice;
  205. } else {
  206. $orderSurplusAmount = $userSurplusMonth * $monthUnitPrice;
  207. }
  208. if (!$orderSurplusAmount) {
  209. return;
  210. }
  211. $order->surplus_amount = $orderSurplusAmount > 0 ? $orderSurplusAmount : 0;
  212. $order->surplus_order_ids = json_encode(array_column($orders->toArray(), 'id'));
  213. }
  214. public function success(string $callbackNo)
  215. {
  216. $order = $this->order;
  217. if ($order->status !== 0) {
  218. return true;
  219. }
  220. $order->status = 1;
  221. $order->callback_no = $callbackNo;
  222. return $order->save();
  223. }
  224. private function buyByResetTraffic()
  225. {
  226. $this->user->u = 0;
  227. $this->user->d = 0;
  228. }
  229. private function buyByCycle(Order $order, Plan $plan)
  230. {
  231. // change plan process
  232. if ((int)$order->type === 3) {
  233. $this->user->expired_at = time();
  234. }
  235. $this->user->transfer_enable = $plan->transfer_enable * 1073741824;
  236. // 从一次性转换到循环
  237. if ($this->user->expired_at === NULL) $this->buyByResetTraffic();
  238. // 新购
  239. if ($order->type === 1) $this->buyByResetTraffic();
  240. $this->user->plan_id = $plan->id;
  241. $this->user->group_id = $plan->group_id;
  242. $this->user->expired_at = $this->getTime($order->cycle, $this->user->expired_at);
  243. }
  244. private function buyByOneTime(Plan $plan)
  245. {
  246. $this->buyByResetTraffic();
  247. $this->user->transfer_enable = $plan->transfer_enable * 1073741824;
  248. $this->user->plan_id = $plan->id;
  249. $this->user->group_id = $plan->group_id;
  250. $this->user->expired_at = NULL;
  251. }
  252. private function getTime($str, $timestamp)
  253. {
  254. if ($timestamp < time()) {
  255. $timestamp = time();
  256. }
  257. switch ($str) {
  258. case 'month_price':
  259. return strtotime('+1 month', $timestamp);
  260. case 'quarter_price':
  261. return strtotime('+3 month', $timestamp);
  262. case 'half_year_price':
  263. return strtotime('+6 month', $timestamp);
  264. case 'year_price':
  265. return strtotime('+12 month', $timestamp);
  266. case 'two_year_price':
  267. return strtotime('+24 month', $timestamp);
  268. case 'three_year_price':
  269. return strtotime('+36 month', $timestamp);
  270. }
  271. }
  272. private function openEvent($eventId)
  273. {
  274. switch ((int) $eventId) {
  275. case 0:
  276. break;
  277. case 1:
  278. $this->buyByResetTraffic();
  279. break;
  280. }
  281. }
  282. }