package user import ( "context" logicCommon "github.com/perfect-panel/server/internal/logic/common" "github.com/perfect-panel/server/internal/model/log" usermodel "github.com/perfect-panel/server/internal/model/user" "github.com/perfect-panel/server/internal/svc" "github.com/perfect-panel/server/internal/types" "github.com/perfect-panel/server/pkg/constant" "github.com/perfect-panel/server/pkg/logger" "github.com/perfect-panel/server/pkg/xerr" "github.com/pkg/errors" "gorm.io/gorm" ) type CancelWithdrawalLogic struct { logger.Logger ctx context.Context svcCtx *svc.ServiceContext } func NewCancelWithdrawalLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CancelWithdrawalLogic { return &CancelWithdrawalLogic{ Logger: logger.WithContext(ctx), ctx: ctx, svcCtx: svcCtx, } } func (l *CancelWithdrawalLogic) CancelWithdrawal(req *types.CancelWithdrawalRequest) error { u, ok := l.ctx.Value(constant.CtxKeyUser).(*usermodel.User) if !ok { l.Error("current user is not found in context") return errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "Invalid Access") } return l.svcCtx.DB.WithContext(l.ctx).Transaction(func(tx *gorm.DB) error { withdrawal, err := logicCommon.LoadPendingWithdrawalForUpdate(l.ctx, tx, req.WithdrawalId) if err != nil { if err.Error() == "withdrawal status invalid" { return errors.Wrapf(xerr.NewErrCode(xerr.WithdrawalStatusInvalid), "withdrawal %d already processed", req.WithdrawalId) } return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "load withdrawal failed: %v", err) } if withdrawal.UserId != u.Id { return errors.Wrapf(xerr.NewErrCode(xerr.WithdrawalCancelForbidden), "cannot cancel other user's withdrawal %d", req.WithdrawalId) } if err := tx.Model(&usermodel.Withdrawal{}). Where("id = ? AND status = ?", req.WithdrawalId, constant.WithdrawalStatusPending). Updates(map[string]interface{}{"status": constant.WithdrawalStatusCancelled}).Error; err != nil { return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "cancel withdrawal failed: %v", err) } if err := l.svcCtx.UserModel.UpdateCommission(l.ctx, u.Id, withdrawal.Amount, tx); err != nil { return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "refund commission failed: %v", err) } if err := logicCommon.WriteCommissionLog(tx, u.Id, log.CommissionTypeWithdrawCancel, withdrawal.Amount, ""); err != nil { return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "write commission log failed: %v", err) } return nil }) }