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)
->get();
foreach ($orders as $order) {
DB::beginTransaction();
if (!$this->payHandle($order->invite_user_id, $order)) {
try{
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();
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;
use App\Helpers\ApiResponse;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as 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);
array_push($coupons, $coupon);
}
DB::beginTransaction();
if (!Coupon::insert(array_map(function ($item) use ($coupon) {
// format data
if (isset($item['limit_plan_ids']) && is_array($item['limit_plan_ids'])) {
$item['limit_plan_ids'] = json_encode($coupon['limit_plan_ids']);
try{
DB::beginTransaction();
if (!Coupon::insert(array_map(function ($item) use ($coupon) {
// format data
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'])) {
$item['limit_period'] = json_encode($coupon['limit_period']);
}
return $item;
}, $coupons))) {
DB::commit();
}catch(\Exception $e){
DB::rollBack();
throw new ApiException(500, '生成失败');
throw $e;
}
DB::commit();
$data = "名称,类型,金额或比例,开始时间,结束时间,可用次数,可用于订阅,券码,生成时间\r\n";
foreach($coupons as $coupon) {
$type = ['', '金额', '比例'][$coupon['type']];

View File

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

View File

@ -156,34 +156,37 @@ class OrderController extends Controller
throw new ApiException(500, '该用户还有待支付的订单,无法分配');
}
DB::beginTransaction();
$order = new Order();
$orderService = new OrderService($order);
$order->user_id = $user->id;
$order->plan_id = $plan->id;
$order->period = $request->input('period');
$order->trade_no = Helper::guid();
$order->total_amount = $request->input('total_amount');
try {
DB::beginTransaction();
$order = new Order();
$orderService = new OrderService($order);
$order->user_id = $user->id;
$order->plan_id = $plan->id;
$order->period = $request->input('period');
$order->trade_no = Helper::guid();
$order->total_amount = $request->input('total_amount');
if ($order->period === 'reset_price') {
$order->type = 4;
} else if ($user->plan_id !== NULL && $order->plan_id !== $user->plan_id) {
$order->type = 3;
} else if ($user->expired_at > time() && $order->plan_id == $user->plan_id) {
$order->type = 2;
} else {
$order->type = 1;
if ($order->period === 'reset_price') {
$order->type = 4;
} else if ($user->plan_id !== NULL && $order->plan_id !== $user->plan_id) {
$order->type = 3;
} else if ($user->expired_at > time() && $order->plan_id == $user->plan_id) {
$order->type = 2;
} else {
$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([
'data' => $order->trade_no
]);

View File

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

View File

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

View File

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

View File

@ -230,12 +230,16 @@ class UserController extends Controller
$user['password'] = password_hash($request->input('password') ?? $user['email'], PASSWORD_DEFAULT);
array_push($users, $user);
}
DB::beginTransaction();
if (!User::insert($users)) {
try{
DB::beginTransaction();
if (!User::insert($users)) {
throw new ApiException(500, '生成失败');
}
DB::commit();
}catch(\Exception $e){
DB::rollBack();
throw new ApiException(500, '生成失败');
throw $e;
}
DB::commit();
$data = "账号,密码,过期时间,UUID,创建时间,订阅地址\r\n";
foreach($users as $user) {
$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'));
}
DB::beginTransaction();
$order = new Order();
$orderService = new OrderService($order);
$order->user_id = $request->user['id'];
$order->plan_id = $plan->id;
$order->period = $request->input('period');
$order->trade_no = Helper::generateOrderNo();
$order->total_amount = $plan[$request->input('period')];
try{
DB::beginTransaction();
$order = new Order();
$orderService = new OrderService($order);
$order->user_id = $request->user['id'];
$order->plan_id = $plan->id;
$order->period = $request->input('period');
$order->trade_no = Helper::generateOrderNo();
$order->total_amount = $plan[$request->input('period')];
if ($request->input('coupon_code')) {
$couponService = new CouponService($request->input('coupon_code'));
if (!$couponService->use($order)) {
DB::rollBack();
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'));
if ($request->input('coupon_code')) {
$couponService = new CouponService($request->input('coupon_code'));
if (!$couponService->use($order)) {
throw new ApiException(500, __('Coupon failed'));
}
$order->balance_amount = $order->total_amount;
$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;
$order->coupon_id = $couponService->getId();
}
}
if (!$order->save()) {
DB::rollback();
throw new ApiException(500, __('Failed to create order'));
}
$orderService->setVipDiscount($user);
$orderService->setOrderType($user);
$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([
'data' => $order->trade_no

View File

@ -48,30 +48,33 @@ class TicketController extends Controller
public function save(TicketSave $request)
{
DB::beginTransaction();
if ((int)Ticket::where('status', 0)->where('user_id', $request->user['id'])->lockForUpdate()->count()) {
throw new ApiException(500, __('There are other unresolved tickets'));
try{
DB::beginTransaction();
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'));
return response([
'data' => true
@ -156,31 +159,34 @@ class TicketController extends Controller
if ($limit > ($user->commission_balance / 100)) {
throw new ApiException(500, __('The current required minimum withdrawal commission is :limit', ['limit' => $limit]));
}
DB::beginTransaction();
$subject = __('[Commission Withdrawal Request] This ticket is opened by the system');
$ticket = Ticket::create([
'subject' => $subject,
'level' => 2,
'user_id' => $request->user['id']
]);
if (!$ticket) {
DB::rollback();
throw new ApiException(500, __('Failed to open ticket'));
try{
DB::beginTransaction();
$subject = __('[Commission Withdrawal Request] This ticket is opened by the system');
$ticket = Ticket::create([
'subject' => $subject,
'level' => 2,
'user_id' => $request->user['id']
]);
if (!$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);
return response([
'data' => true

View File

@ -36,53 +36,51 @@ class OrderService
if ($order->refund_amount) {
$this->user->balance = $this->user->balance + $order->refund_amount;
}
DB::beginTransaction();
if ($order->surplus_order_ids) {
try {
try{
DB::beginTransaction();
if ($order->surplus_order_ids) {
Order::whereIn('id', $order->surplus_order_ids)->update([
'status' => 4
]);
} catch (\Exception $e) {
DB::rollback();
throw new ApiException(500, '开通失败');
}
}
switch ((string)$order->period) {
case 'onetime_price':
$this->buyByOneTime($plan);
break;
case 'reset_price':
$this->buyByResetTraffic();
break;
default:
$this->buyByPeriod($order, $plan);
}
switch ((string)$order->period) {
case 'onetime_price':
$this->buyByOneTime($plan);
break;
case 'reset_price':
$this->buyByResetTraffic();
break;
default:
$this->buyByPeriod($order, $plan);
}
switch ((int)$order->type) {
case 1:
$this->openEvent(admin_setting('new_order_event_id', 0));
break;
case 2:
$this->openEvent(admin_setting('renew_order_event_id', 0));
break;
case 3:
$this->openEvent(admin_setting('change_order_event_id', 0));
break;
}
switch ((int)$order->type) {
case 1:
$this->openEvent(admin_setting('new_order_event_id', 0));
break;
case 2:
$this->openEvent(admin_setting('renew_order_event_id', 0));
break;
case 3:
$this->openEvent(admin_setting('change_order_event_id', 0));
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();
\Log::error($e);
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
{
$order = $this->order;
DB::beginTransaction();
$order->status = 2;
if (!$order->save()) {
try {
DB::beginTransaction();
$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();
\Log::error($e);
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)

View File

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