fix: 规范数据库事物的使用,解决在swoole环境下可能会出现事物一直不被提交的问题

This commit is contained in:
xboard 2023-12-06 19:00:26 +08:00
parent 64cc2d79da
commit 1fcb6fa911
13 changed files with 293 additions and 251 deletions

View File

@ -64,17 +64,22 @@ class CheckCommission extends Command
->where('invite_user_id', '!=', NULL) ->where('invite_user_id', '!=', NULL)
->get(); ->get();
foreach ($orders as $order) { foreach ($orders as $order) {
DB::beginTransaction(); try{
if (!$this->payHandle($order->invite_user_id, $order)) { DB::beginTransaction();
if (!$this->payHandle($order->invite_user_id, $order)) {
DB::rollBack();
continue;
}
$order->commission_status = 2;
if (!$order->save()) {
DB::rollBack();
continue;
}
DB::commit();
} catch (\Exception $e){
DB::rollBack(); DB::rollBack();
continue; throw $e;
} }
$order->commission_status = 2;
if (!$order->save()) {
DB::rollBack();
continue;
}
DB::commit();
} }
} }

View File

@ -2,11 +2,12 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\Helpers\ApiResponse;
use Illuminate\Foundation\Bus\DispatchesJobs; use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests; use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController; use Illuminate\Routing\Controller as BaseController;
class Controller extends BaseController class Controller extends BaseController
{ {
use DispatchesJobs, ValidatesRequests; use DispatchesJobs, ValidatesRequests, ApiResponse;
} }

View File

@ -87,21 +87,26 @@ class CouponController extends Controller
$coupon['code'] = Helper::randomChar(8); $coupon['code'] = Helper::randomChar(8);
array_push($coupons, $coupon); array_push($coupons, $coupon);
} }
DB::beginTransaction(); try{
if (!Coupon::insert(array_map(function ($item) use ($coupon) { DB::beginTransaction();
// format data if (!Coupon::insert(array_map(function ($item) use ($coupon) {
if (isset($item['limit_plan_ids']) && is_array($item['limit_plan_ids'])) { // format data
$item['limit_plan_ids'] = json_encode($coupon['limit_plan_ids']); if (isset($item['limit_plan_ids']) && is_array($item['limit_plan_ids'])) {
$item['limit_plan_ids'] = json_encode($coupon['limit_plan_ids']);
}
if (isset($item['limit_period']) && is_array($item['limit_period'])) {
$item['limit_period'] = json_encode($coupon['limit_period']);
}
return $item;
}, $coupons))) {
throw new ApiException(500, '生成失败');
} }
if (isset($item['limit_period']) && is_array($item['limit_period'])) { DB::commit();
$item['limit_period'] = json_encode($coupon['limit_period']); }catch(\Exception $e){
}
return $item;
}, $coupons))) {
DB::rollBack(); DB::rollBack();
throw new ApiException(500, '生成失败'); throw $e;
} }
DB::commit();
$data = "名称,类型,金额或比例,开始时间,结束时间,可用次数,可用于订阅,券码,生成时间\r\n"; $data = "名称,类型,金额或比例,开始时间,结束时间,可用次数,可用于订阅,券码,生成时间\r\n";
foreach($coupons as $coupon) { foreach($coupons as $coupon) {
$type = ['', '金额', '比例'][$coupon['type']]; $type = ['', '金额', '比例'][$coupon['type']];

View File

@ -77,18 +77,18 @@ class KnowledgeController extends Controller
public function sort(KnowledgeSort $request) public function sort(KnowledgeSort $request)
{ {
DB::beginTransaction();
try { try {
DB::beginTransaction();
foreach ($request->input('knowledge_ids') as $k => $v) { foreach ($request->input('knowledge_ids') as $k => $v) {
$knowledge = Knowledge::find($v); $knowledge = Knowledge::find($v);
$knowledge->timestamps = false; $knowledge->timestamps = false;
$knowledge->update(['sort' => $k + 1]); $knowledge->update(['sort' => $k + 1]);
} }
DB::commit();
} catch (\Exception $e) { } catch (\Exception $e) {
DB::rollBack(); DB::rollBack();
throw new ApiException(500, '保存失败'); throw new ApiException(500, '保存失败');
} }
DB::commit();
return response([ return response([
'data' => true 'data' => true
]); ]);

View File

@ -156,34 +156,37 @@ class OrderController extends Controller
throw new ApiException(500, '该用户还有待支付的订单,无法分配'); throw new ApiException(500, '该用户还有待支付的订单,无法分配');
} }
DB::beginTransaction(); try {
$order = new Order(); DB::beginTransaction();
$orderService = new OrderService($order); $order = new Order();
$order->user_id = $user->id; $orderService = new OrderService($order);
$order->plan_id = $plan->id; $order->user_id = $user->id;
$order->period = $request->input('period'); $order->plan_id = $plan->id;
$order->trade_no = Helper::guid(); $order->period = $request->input('period');
$order->total_amount = $request->input('total_amount'); $order->trade_no = Helper::guid();
$order->total_amount = $request->input('total_amount');
if ($order->period === 'reset_price') { if ($order->period === 'reset_price') {
$order->type = 4; $order->type = 4;
} else if ($user->plan_id !== NULL && $order->plan_id !== $user->plan_id) { } else if ($user->plan_id !== NULL && $order->plan_id !== $user->plan_id) {
$order->type = 3; $order->type = 3;
} else if ($user->expired_at > time() && $order->plan_id == $user->plan_id) { } else if ($user->expired_at > time() && $order->plan_id == $user->plan_id) {
$order->type = 2; $order->type = 2;
} else { } else {
$order->type = 1; $order->type = 1;
}
$orderService->setInvite($user);
if (!$order->save()) {
throw new ApiException(500, '订单创建失败');
}
DB::commit();
}catch(\Exception $e){
DB::rollBack();
throw $e;
} }
$orderService->setInvite($user);
if (!$order->save()) {
DB::rollback();
throw new ApiException(500, '订单创建失败');
}
DB::commit();
return response([ return response([
'data' => $order->trade_no 'data' => $order->trade_no
]); ]);

View File

@ -118,14 +118,19 @@ class PaymentController extends Controller
'ids.required' => '参数有误', 'ids.required' => '参数有误',
'ids.array' => '参数有误' 'ids.array' => '参数有误'
]); ]);
DB::beginTransaction(); try{
foreach ($request->input('ids') as $k => $v) { DB::beginTransaction();
if (!Payment::find($v)->update(['sort' => $k + 1])) { foreach ($request->input('ids') as $k => $v) {
DB::rollBack(); if (!Payment::find($v)->update(['sort' => $k + 1])) {
throw new ApiException(500, '保存失败'); throw new ApiException(500, '保存失败');
}
} }
DB::commit();
}catch(\Exception $e){
DB::rollBack();
throw $e;
} }
DB::commit();
return response([ return response([
'data' => true 'data' => true
]); ]);

View File

@ -50,11 +50,11 @@ class PlanController extends Controller
]); ]);
} }
$plan->update($params); $plan->update($params);
DB::commit();
} catch (\Exception $e) { } catch (\Exception $e) {
DB::rollBack(); DB::rollBack();
throw new ApiException(500, '保存失败'); throw new ApiException(500, '保存失败');
} }
DB::commit();
return response([ return response([
'data' => true 'data' => true
]); ]);
@ -104,23 +104,24 @@ class PlanController extends Controller
throw new ApiException(500, '保存失败'); throw new ApiException(500, '保存失败');
} }
return response([ return $this->success();
'data' => true
]);
} }
public function sort(PlanSort $request) public function sort(PlanSort $request)
{ {
DB::beginTransaction();
foreach ($request->input('plan_ids') as $k => $v) { try{
if (!Plan::find($v)->update(['sort' => $k + 1])) { DB::beginTransaction();
DB::rollBack(); foreach ($request->input('plan_ids') as $k => $v) {
throw new ApiException(500, '保存失败'); if (!Plan::find($v)->update(['sort' => $k + 1])) {
throw new ApiException(500, '保存失败');
}
} }
DB::commit();
}catch (\Exception $e){
DB::rollBack();
throw $e;
} }
DB::commit(); return $this->success(true);
return response([
'data' => true
]);
} }
} }

View File

@ -28,19 +28,21 @@ class ManageController extends Controller
'hysteria', 'hysteria',
'vless' 'vless'
) ?? []; ) ?? [];
DB::beginTransaction(); try{
foreach ($params as $k => $v) { DB::beginTransaction();
$model = 'App\\Models\\Server' . ucfirst($k); foreach ($params as $k => $v) {
foreach($v as $id => $sort) { $model = 'App\\Models\\Server' . ucfirst($k);
if (!$model::find($id)->update(['sort' => $sort])) { foreach($v as $id => $sort) {
DB::rollBack(); if (!$model::find($id)->update(['sort' => $sort])) {
throw new ApiException(500, '保存失败'); throw new ApiException(500, '保存失败');
}
} }
} }
DB::commit();
}catch (\Exception $e){
DB::rollBack();
throw $e;
} }
DB::commit(); return $this->success(true);
return response([
'data' => true
]);
} }
} }

View File

@ -230,12 +230,16 @@ class UserController extends Controller
$user['password'] = password_hash($request->input('password') ?? $user['email'], PASSWORD_DEFAULT); $user['password'] = password_hash($request->input('password') ?? $user['email'], PASSWORD_DEFAULT);
array_push($users, $user); array_push($users, $user);
} }
DB::beginTransaction(); try{
if (!User::insert($users)) { DB::beginTransaction();
if (!User::insert($users)) {
throw new ApiException(500, '生成失败');
}
DB::commit();
}catch(\Exception $e){
DB::rollBack(); DB::rollBack();
throw new ApiException(500, '生成失败'); throw $e;
} }
DB::commit();
$data = "账号,密码,过期时间,UUID,创建时间,订阅地址\r\n"; $data = "账号,密码,过期时间,UUID,创建时间,订阅地址\r\n";
foreach($users as $user) { foreach($users as $user) {
$expireDate = $user['expired_at'] === NULL ? '长期有效' : date('Y-m-d H:i:s', $user['expired_at']); $expireDate = $user['expired_at'] === NULL ? '长期有效' : date('Y-m-d H:i:s', $user['expired_at']);

View File

@ -114,54 +114,54 @@ class OrderController extends Controller
throw new ApiException(500, __('This subscription has expired, please change to another subscription')); throw new ApiException(500, __('This subscription has expired, please change to another subscription'));
} }
DB::beginTransaction(); try{
$order = new Order(); DB::beginTransaction();
$orderService = new OrderService($order); $order = new Order();
$order->user_id = $request->user['id']; $orderService = new OrderService($order);
$order->plan_id = $plan->id; $order->user_id = $request->user['id'];
$order->period = $request->input('period'); $order->plan_id = $plan->id;
$order->trade_no = Helper::generateOrderNo(); $order->period = $request->input('period');
$order->total_amount = $plan[$request->input('period')]; $order->trade_no = Helper::generateOrderNo();
$order->total_amount = $plan[$request->input('period')];
if ($request->input('coupon_code')) { if ($request->input('coupon_code')) {
$couponService = new CouponService($request->input('coupon_code')); $couponService = new CouponService($request->input('coupon_code'));
if (!$couponService->use($order)) { if (!$couponService->use($order)) {
DB::rollBack(); throw new ApiException(500, __('Coupon failed'));
throw new ApiException(500, __('Coupon failed'));
}
$order->coupon_id = $couponService->getId();
}
$orderService->setVipDiscount($user);
$orderService->setOrderType($user);
$orderService->setInvite($user);
if ($user->balance && $order->total_amount > 0) {
$remainingBalance = $user->balance - $order->total_amount;
$userService = new UserService();
if ($remainingBalance > 0) {
if (!$userService->addBalance($order->user_id, - $order->total_amount)) {
DB::rollBack();
throw new ApiException(500, __('Insufficient balance'));
} }
$order->balance_amount = $order->total_amount; $order->coupon_id = $couponService->getId();
$order->total_amount = 0;
} else {
if (!$userService->addBalance($order->user_id, - $user->balance)) {
DB::rollBack();
throw new ApiException(500, __('Insufficient balance'));
}
$order->balance_amount = $user->balance;
$order->total_amount = $order->total_amount - $user->balance;
} }
}
if (!$order->save()) { $orderService->setVipDiscount($user);
DB::rollback(); $orderService->setOrderType($user);
throw new ApiException(500, __('Failed to create order')); $orderService->setInvite($user);
}
DB::commit(); if ($user->balance && $order->total_amount > 0) {
$remainingBalance = $user->balance - $order->total_amount;
$userService = new UserService();
if ($remainingBalance > 0) {
if (!$userService->addBalance($order->user_id, - $order->total_amount)) {
throw new ApiException(500, __('Insufficient balance'));
}
$order->balance_amount = $order->total_amount;
$order->total_amount = 0;
} else {
if (!$userService->addBalance($order->user_id, - $user->balance)) {
throw new ApiException(500, __('Insufficient balance'));
}
$order->balance_amount = $user->balance;
$order->total_amount = $order->total_amount - $user->balance;
}
}
if (!$order->save()) {
throw new ApiException(500, __('Failed to create order'));
}
DB::commit();
}catch (\Exception $e){
DB::rollBack();
throw $e;
}
return response([ return response([
'data' => $order->trade_no 'data' => $order->trade_no

View File

@ -48,30 +48,33 @@ class TicketController extends Controller
public function save(TicketSave $request) public function save(TicketSave $request)
{ {
DB::beginTransaction(); try{
if ((int)Ticket::where('status', 0)->where('user_id', $request->user['id'])->lockForUpdate()->count()) { DB::beginTransaction();
throw new ApiException(500, __('There are other unresolved tickets')); if ((int)Ticket::where('status', 0)->where('user_id', $request->user['id'])->lockForUpdate()->count()) {
throw new ApiException(500, __('There are other unresolved tickets'));
}
$ticket = Ticket::create(array_merge($request->only([
'subject',
'level'
]), [
'user_id' => $request->user['id']
]));
if (!$ticket) {
throw new ApiException(500, __('Failed to open ticket'));
}
$ticketMessage = TicketMessage::create([
'user_id' => $request->user['id'],
'ticket_id' => $ticket->id,
'message' => $request->input('message')
]);
if (!$ticketMessage) {
throw new ApiException(500, __('Failed to open ticket'));
}
DB::commit();
}catch(\Exception $e){
DB::rollBack();
throw $e;
} }
$ticket = Ticket::create(array_merge($request->only([
'subject',
'level'
]), [
'user_id' => $request->user['id']
]));
if (!$ticket) {
DB::rollback();
throw new ApiException(500, __('Failed to open ticket'));
}
$ticketMessage = TicketMessage::create([
'user_id' => $request->user['id'],
'ticket_id' => $ticket->id,
'message' => $request->input('message')
]);
if (!$ticketMessage) {
DB::rollback();
throw new ApiException(500, __('Failed to open ticket'));
}
DB::commit();
$this->sendNotify($ticket, $request->input('message')); $this->sendNotify($ticket, $request->input('message'));
return response([ return response([
'data' => true 'data' => true
@ -156,31 +159,34 @@ class TicketController extends Controller
if ($limit > ($user->commission_balance / 100)) { if ($limit > ($user->commission_balance / 100)) {
throw new ApiException(500, __('The current required minimum withdrawal commission is :limit', ['limit' => $limit])); throw new ApiException(500, __('The current required minimum withdrawal commission is :limit', ['limit' => $limit]));
} }
DB::beginTransaction(); try{
$subject = __('[Commission Withdrawal Request] This ticket is opened by the system'); DB::beginTransaction();
$ticket = Ticket::create([ $subject = __('[Commission Withdrawal Request] This ticket is opened by the system');
'subject' => $subject, $ticket = Ticket::create([
'level' => 2, 'subject' => $subject,
'user_id' => $request->user['id'] 'level' => 2,
]); 'user_id' => $request->user['id']
if (!$ticket) { ]);
DB::rollback(); if (!$ticket) {
throw new ApiException(500, __('Failed to open ticket')); throw new ApiException(500, __('Failed to open ticket'));
}
$message = sprintf("%s\r\n%s",
__('Withdrawal method') . "" . $request->input('withdraw_method'),
__('Withdrawal account') . "" . $request->input('withdraw_account')
);
$ticketMessage = TicketMessage::create([
'user_id' => $request->user['id'],
'ticket_id' => $ticket->id,
'message' => $message
]);
if (!$ticketMessage) {
throw new ApiException(500, __('Failed to open ticket'));
}
DB::commit();
}catch(\Exception $e){
DB::rollBack();
throw $e;
} }
$message = sprintf("%s\r\n%s",
__('Withdrawal method') . "" . $request->input('withdraw_method'),
__('Withdrawal account') . "" . $request->input('withdraw_account')
);
$ticketMessage = TicketMessage::create([
'user_id' => $request->user['id'],
'ticket_id' => $ticket->id,
'message' => $message
]);
if (!$ticketMessage) {
DB::rollback();
throw new ApiException(500, __('Failed to open ticket'));
}
DB::commit();
$this->sendNotify($ticket, $message); $this->sendNotify($ticket, $message);
return response([ return response([
'data' => true 'data' => true

View File

@ -36,53 +36,51 @@ class OrderService
if ($order->refund_amount) { if ($order->refund_amount) {
$this->user->balance = $this->user->balance + $order->refund_amount; $this->user->balance = $this->user->balance + $order->refund_amount;
} }
DB::beginTransaction(); try{
if ($order->surplus_order_ids) { DB::beginTransaction();
try { if ($order->surplus_order_ids) {
Order::whereIn('id', $order->surplus_order_ids)->update([ Order::whereIn('id', $order->surplus_order_ids)->update([
'status' => 4 'status' => 4
]); ]);
} catch (\Exception $e) {
DB::rollback();
throw new ApiException(500, '开通失败');
} }
} switch ((string)$order->period) {
switch ((string)$order->period) { case 'onetime_price':
case 'onetime_price': $this->buyByOneTime($plan);
$this->buyByOneTime($plan); break;
break; case 'reset_price':
case 'reset_price': $this->buyByResetTraffic();
$this->buyByResetTraffic(); break;
break; default:
default: $this->buyByPeriod($order, $plan);
$this->buyByPeriod($order, $plan); }
}
switch ((int)$order->type) { switch ((int)$order->type) {
case 1: case 1:
$this->openEvent(admin_setting('new_order_event_id', 0)); $this->openEvent(admin_setting('new_order_event_id', 0));
break; break;
case 2: case 2:
$this->openEvent(admin_setting('renew_order_event_id', 0)); $this->openEvent(admin_setting('renew_order_event_id', 0));
break; break;
case 3: case 3:
$this->openEvent(admin_setting('change_order_event_id', 0)); $this->openEvent(admin_setting('change_order_event_id', 0));
break; break;
} }
$this->setSpeedLimit($plan->speed_limit); $this->setSpeedLimit($plan->speed_limit);
if (!$this->user->save()) { if (!$this->user->save()) {
throw new \Exception('用户信息保存失败');
}
$order->status = 3;
if (!$order->save()) {
throw new \Exception('订单信息保存失败');
}
DB::commit();
}catch(\Exception $e){
DB::rollBack(); DB::rollBack();
\Log::error($e);
throw new ApiException(500, '开通失败'); throw new ApiException(500, '开通失败');
} }
$order->status = 3;
if (!$order->save()) {
DB::rollBack();
throw new ApiException(500, '开通失败');
}
DB::commit();
} }
@ -233,21 +231,25 @@ class OrderService
public function cancel():bool public function cancel():bool
{ {
$order = $this->order; $order = $this->order;
DB::beginTransaction(); try {
$order->status = 2; DB::beginTransaction();
if (!$order->save()) { $order->status = 2;
if (!$order->save()) {
throw new \Exception('Failed to save order status.');
}
if ($order->balance_amount) {
$userService = new UserService();
if (!$userService->addBalance($order->user_id, $order->balance_amount)) {
throw new \Exception('Failed to add balance.');
}
}
DB::commit();
return true;
}catch(\Exception $e){
DB::rollBack(); DB::rollBack();
\Log::error($e);
return false; return false;
} }
if ($order->balance_amount) {
$userService = new UserService();
if (!$userService->addBalance($order->user_id, $order->balance_amount)) {
DB::rollBack();
return false;
}
}
DB::commit();
return true;
} }
private function setSpeedLimit($speedLimit) private function setSpeedLimit($speedLimit)

View File

@ -13,23 +13,27 @@ use Illuminate\Support\Facades\DB;
class TicketService { class TicketService {
public function reply($ticket, $message, $userId) public function reply($ticket, $message, $userId)
{ {
DB::beginTransaction(); try{
$ticketMessage = TicketMessage::create([ DB::beginTransaction();
'user_id' => $userId, $ticketMessage = TicketMessage::create([
'ticket_id' => $ticket->id, 'user_id' => $userId,
'message' => $message 'ticket_id' => $ticket->id,
]); 'message' => $message
if ($userId !== $ticket->user_id) { ]);
$ticket->reply_status = 0; if ($userId !== $ticket->user_id) {
} else { $ticket->reply_status = 0;
$ticket->reply_status = 1; } else {
} $ticket->reply_status = 1;
if (!$ticketMessage || !$ticket->save()) { }
if (!$ticketMessage || !$ticket->save()) {
throw new \Exception();
}
DB::commit();
return $ticketMessage;
}catch(\Exception $e){
DB::rollback(); DB::rollback();
return false; return false;
} }
DB::commit();
return $ticketMessage;
} }
public function replyByAdmin($ticketId, $message, $userId):void public function replyByAdmin($ticketId, $message, $userId):void
@ -40,22 +44,26 @@ class TicketService {
throw new ApiException(500, '工单不存在'); throw new ApiException(500, '工单不存在');
} }
$ticket->status = 0; $ticket->status = 0;
DB::beginTransaction(); try{
$ticketMessage = TicketMessage::create([ DB::beginTransaction();
'user_id' => $userId, $ticketMessage = TicketMessage::create([
'ticket_id' => $ticket->id, 'user_id' => $userId,
'message' => $message 'ticket_id' => $ticket->id,
]); 'message' => $message
if ($userId !== $ticket->user_id) { ]);
$ticket->reply_status = 0; if ($userId !== $ticket->user_id) {
} else { $ticket->reply_status = 0;
$ticket->reply_status = 1; } else {
$ticket->reply_status = 1;
}
if (!$ticketMessage || !$ticket->save()) {
throw new ApiException(500, '工单回复失败');
}
DB::commit();
}catch(\Exception $e){
DB::rollBack();
throw $e;
} }
if (!$ticketMessage || !$ticket->save()) {
DB::rollback();
throw new ApiException(500, '工单回复失败');
}
DB::commit();
$this->sendEmailNotify($ticket, $ticketMessage); $this->sendEmailNotify($ticket, $ticketMessage);
} }