OrderService.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  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', $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 setOrderType(User $user)
  75. {
  76. $order = $this->order;
  77. if ($order->cycle === 'reset_price') {
  78. $order->type = 4;
  79. } else if ($user->plan_id !== NULL && $order->plan_id !== $user->plan_id && ($user->expired_at > time() || $user->expired_at === NULL)) {
  80. if (!(int)config('v2board.plan_change_enable', 1)) abort(500, '目前不允许更改订阅,请联系客服或提交工单操作');
  81. $order->type = 3;
  82. if ((int)config('v2board.surplus_enable', 1)) $this->getSurplusValue($user, $order);
  83. if ($order->surplus_amount >= $order->total_amount) {
  84. $order->refund_amount = $order->surplus_amount - $order->total_amount;
  85. $order->total_amount = 0;
  86. } else {
  87. $order->total_amount = $order->total_amount - $order->surplus_amount;
  88. }
  89. } else if ($user->expired_at > time() && $order->plan_id == $user->plan_id) { // 用户订阅未过期且购买订阅与当前订阅相同 === 续费
  90. $order->type = 2;
  91. } else { // 新购
  92. $order->type = 1;
  93. }
  94. }
  95. public function setVipDiscount(User $user)
  96. {
  97. $order = $this->order;
  98. if ($user->discount) {
  99. $order->discount_amount = $order->discount_amount + ($order->total_amount * ($user->discount / 100));
  100. }
  101. $order->total_amount = $order->total_amount - $order->discount_amount;
  102. }
  103. public function setInvite(User $user):void
  104. {
  105. $order = $this->order;
  106. if ($user->invite_user_id && $order->total_amount > 0) {
  107. $order->invite_user_id = $user->invite_user_id;
  108. $isCommission = false;
  109. switch ((int)$user->commission_type) {
  110. case 0:
  111. $commissionFirstTime = (int)config('v2board.commission_first_time_enable', 1);
  112. $isCommission = (!$commissionFirstTime || ($commissionFirstTime && !$this->haveValidOrder($user)));
  113. break;
  114. case 1:
  115. $isCommission = true;
  116. break;
  117. case 2:
  118. $isCommission = !$this->haveValidOrder($user);
  119. break;
  120. }
  121. if ($isCommission) {
  122. $inviter = User::find($user->invite_user_id);
  123. if ($inviter && $inviter->commission_rate) {
  124. $order->commission_balance = $order->total_amount * ($inviter->commission_rate / 100);
  125. } else {
  126. $order->commission_balance = $order->total_amount * (config('v2board.invite_commission', 10) / 100);
  127. }
  128. }
  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->getSurplusValueByCycle($user, $order);
  143. }
  144. }
  145. private function getSurplusValueByOneTime(User $user, Order $order)
  146. {
  147. $plan = Plan::find($user->plan_id);
  148. $trafficUnitPrice = $plan->onetime_price / $plan->transfer_enable;
  149. if ($user->discount && $trafficUnitPrice) {
  150. $trafficUnitPrice = $trafficUnitPrice - ($trafficUnitPrice * $user->discount / 100);
  151. }
  152. $notUsedTraffic = $plan->transfer_enable - (($user->u + $user->d) / 1073741824);
  153. $result = $trafficUnitPrice * $notUsedTraffic;
  154. $orderModel = Order::where('user_id', $user->id)->where('cycle', '!=', 'reset_price')->where('status', 3);
  155. $order->surplus_amount = $result > 0 ? $result : 0;
  156. $order->surplus_order_ids = array_column($orderModel->get()->toArray(), 'id');
  157. }
  158. private function orderIsUsed(Order $order):bool
  159. {
  160. $month = self::STR_TO_TIME[$order->cycle];
  161. $orderExpireDay = strtotime('+' . $month . ' month', $order->created_at);
  162. if ($orderExpireDay < time()) return true;
  163. return false;
  164. }
  165. private function getSurplusValueByCycle(User $user, Order $order)
  166. {
  167. $orderModel = Order::where('user_id', $user->id)
  168. ->where('cycle', '!=', 'reset_price')
  169. ->where('status', 3);
  170. $orders = $orderModel->get();
  171. $orderSurplusMonth = 0;
  172. $orderSurplusAmount = 0;
  173. $userSurplusMonth = ($user->expired_at - time()) / 2678400;
  174. foreach ($orders as $k => $item) {
  175. // 兼容历史余留问题
  176. if ($item->cycle === 'onetime_price') continue;
  177. if ($this->orderIsUsed($item)) continue;
  178. $orderSurplusMonth = $orderSurplusMonth + self::STR_TO_TIME[$item->cycle];
  179. $orderSurplusAmount = $orderSurplusAmount + ($item['total_amount'] + $item['balance_amount'] + $item['surplus_amount'] - $item['refund_amount']);
  180. }
  181. if (!$orderSurplusMonth || !$orderSurplusAmount) return;
  182. $monthUnitPrice = $orderSurplusAmount / $orderSurplusMonth;
  183. // 如果用户过期月大于订单过期月
  184. if ($userSurplusMonth > $orderSurplusMonth) {
  185. $orderSurplusAmount = $orderSurplusMonth * $monthUnitPrice;
  186. } else {
  187. $orderSurplusAmount = $userSurplusMonth * $monthUnitPrice;
  188. }
  189. if (!$orderSurplusAmount) {
  190. return;
  191. }
  192. $order->surplus_amount = $orderSurplusAmount > 0 ? $orderSurplusAmount : 0;
  193. $order->surplus_order_ids = array_column($orders->toArray(), 'id');
  194. }
  195. public function paid(string $callbackNo)
  196. {
  197. $order = $this->order;
  198. if ($order->status !== 0) return true;
  199. $order->status = 1;
  200. $order->paid_at = time();
  201. $order->callback_no = $callbackNo;
  202. return $order->save();
  203. }
  204. public function cancel():bool
  205. {
  206. $order = $this->order;
  207. DB::beginTransaction();
  208. $order->status = 2;
  209. if (!$order->save()) {
  210. DB::rollBack();
  211. return false;
  212. }
  213. if ($order->balance_amount) {
  214. $userService = new UserService();
  215. if (!$userService->addBalance($order->user_id, $order->balance_amount)) {
  216. DB::rollBack();
  217. return false;
  218. }
  219. }
  220. DB::commit();
  221. return true;
  222. }
  223. private function buyByResetTraffic()
  224. {
  225. $this->user->u = 0;
  226. $this->user->d = 0;
  227. }
  228. private function buyByCycle(Order $order, Plan $plan)
  229. {
  230. // change plan process
  231. if ((int)$order->type === 3) {
  232. $this->user->expired_at = time();
  233. }
  234. $this->user->transfer_enable = $plan->transfer_enable * 1073741824;
  235. // 从一次性转换到循环
  236. if ($this->user->expired_at === NULL) $this->buyByResetTraffic();
  237. // 新购
  238. if ($order->type === 1) $this->buyByResetTraffic();
  239. $this->user->plan_id = $plan->id;
  240. $this->user->group_id = $plan->group_id;
  241. $this->user->expired_at = $this->getTime($order->cycle, $this->user->expired_at);
  242. }
  243. private function buyByOneTime(Plan $plan)
  244. {
  245. $this->buyByResetTraffic();
  246. $this->user->transfer_enable = $plan->transfer_enable * 1073741824;
  247. $this->user->plan_id = $plan->id;
  248. $this->user->group_id = $plan->group_id;
  249. $this->user->expired_at = NULL;
  250. }
  251. private function getTime($str, $timestamp)
  252. {
  253. if ($timestamp < time()) {
  254. $timestamp = time();
  255. }
  256. switch ($str) {
  257. case 'month_price':
  258. return strtotime('+1 month', $timestamp);
  259. case 'quarter_price':
  260. return strtotime('+3 month', $timestamp);
  261. case 'half_year_price':
  262. return strtotime('+6 month', $timestamp);
  263. case 'year_price':
  264. return strtotime('+12 month', $timestamp);
  265. case 'two_year_price':
  266. return strtotime('+24 month', $timestamp);
  267. case 'three_year_price':
  268. return strtotime('+36 month', $timestamp);
  269. }
  270. }
  271. private function openEvent($eventId)
  272. {
  273. switch ((int) $eventId) {
  274. case 0:
  275. break;
  276. case 1:
  277. $this->buyByResetTraffic();
  278. break;
  279. }
  280. }
  281. }