init: 1.0.0
This commit is contained in:
@@ -0,0 +1,41 @@
|
||||
package portal
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/ppanel-server/internal/svc"
|
||||
"github.com/perfect-panel/ppanel-server/internal/types"
|
||||
"github.com/perfect-panel/ppanel-server/pkg/logger"
|
||||
"github.com/perfect-panel/ppanel-server/pkg/tool"
|
||||
"github.com/perfect-panel/ppanel-server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type GetAvailablePaymentMethodsLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
func NewGetAvailablePaymentMethodsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetAvailablePaymentMethodsLogic {
|
||||
return &GetAvailablePaymentMethodsLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *GetAvailablePaymentMethodsLogic) GetAvailablePaymentMethods() (resp *types.GetAvailablePaymentMethodsResponse, err error) {
|
||||
data, err := l.svcCtx.PaymentModel.FindAvailableMethods(l.ctx)
|
||||
if err != nil {
|
||||
l.Errorw("[GetAvailablePaymentMethods] database error", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "GetAvailablePaymentMethods: %v", err.Error())
|
||||
}
|
||||
resp = &types.GetAvailablePaymentMethodsResponse{
|
||||
List: make([]types.PaymentMethod, 0),
|
||||
}
|
||||
|
||||
tool.DeepCopy(&resp.List, data)
|
||||
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package portal
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
|
||||
"github.com/perfect-panel/ppanel-server/internal/svc"
|
||||
"github.com/perfect-panel/ppanel-server/internal/types"
|
||||
"github.com/perfect-panel/ppanel-server/pkg/logger"
|
||||
"github.com/perfect-panel/ppanel-server/pkg/tool"
|
||||
"github.com/perfect-panel/ppanel-server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type GetSubscriptionLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// NewGetSubscriptionLogic Get Subscription
|
||||
func NewGetSubscriptionLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetSubscriptionLogic {
|
||||
return &GetSubscriptionLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *GetSubscriptionLogic) GetSubscription() (resp *types.GetSubscriptionResponse, err error) {
|
||||
resp = &types.GetSubscriptionResponse{
|
||||
List: make([]types.Subscribe, 0),
|
||||
}
|
||||
// Get the subscription list
|
||||
data, err := l.svcCtx.SubscribeModel.QuerySubscribeListByShow(l.ctx)
|
||||
if err != nil {
|
||||
l.Errorw("[Site GetSubscription]", logger.Field("err", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "get subscription list error: %v", err.Error())
|
||||
}
|
||||
list := make([]types.Subscribe, len(data))
|
||||
for i, item := range data {
|
||||
var sub types.Subscribe
|
||||
tool.DeepCopy(&sub, item)
|
||||
if item.Discount != "" {
|
||||
var discount []types.SubscribeDiscount
|
||||
_ = json.Unmarshal([]byte(item.Discount), &discount)
|
||||
sub.Discount = discount
|
||||
list[i] = sub
|
||||
}
|
||||
list[i] = sub
|
||||
}
|
||||
resp.List = list
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package portal
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
|
||||
"github.com/perfect-panel/ppanel-server/pkg/tool"
|
||||
|
||||
"github.com/perfect-panel/ppanel-server/internal/svc"
|
||||
"github.com/perfect-panel/ppanel-server/internal/types"
|
||||
"github.com/perfect-panel/ppanel-server/pkg/logger"
|
||||
"github.com/perfect-panel/ppanel-server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type PrePurchaseOrderLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// Pre Purchase Order
|
||||
func NewPrePurchaseOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PrePurchaseOrderLogic {
|
||||
return &PrePurchaseOrderLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *PrePurchaseOrderLogic) PrePurchaseOrder(req *types.PrePurchaseOrderRequest) (resp *types.PrePurchaseOrderResponse, err error) {
|
||||
// find subscribe plan
|
||||
sub, err := l.svcCtx.SubscribeModel.FindOne(l.ctx, req.SubscribeId)
|
||||
if err != nil {
|
||||
l.Errorw("[PreCreateOrder] Database query error", logger.Field("error", err.Error()), logger.Field("subscribe_id", req.SubscribeId))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find subscribe error: %v", err.Error())
|
||||
}
|
||||
var discount float64 = 1
|
||||
if sub.Discount != "" {
|
||||
var dis []types.SubscribeDiscount
|
||||
_ = json.Unmarshal([]byte(sub.Discount), &dis)
|
||||
discount = getDiscount(dis, req.Quantity)
|
||||
}
|
||||
price := sub.UnitPrice * req.Quantity
|
||||
amount := int64(float64(price) * discount)
|
||||
discountAmount := price - amount
|
||||
var coupon int64
|
||||
if req.Coupon != "" {
|
||||
couponInfo, err := l.svcCtx.CouponModel.FindOneByCode(l.ctx, req.Coupon)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.CouponNotExist), "coupon not found")
|
||||
}
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find coupon error: %v", err.Error())
|
||||
}
|
||||
if couponInfo.Count <= couponInfo.UsedCount {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.CouponInsufficientUsage), "coupon used")
|
||||
}
|
||||
subs := tool.StringToInt64Slice(couponInfo.Subscribe)
|
||||
|
||||
if len(subs) > 0 && !tool.Contains(subs, req.SubscribeId) {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.CouponNotApplicable), "coupon not match")
|
||||
}
|
||||
|
||||
coupon = calculateCoupon(amount, couponInfo)
|
||||
}
|
||||
amount -= coupon
|
||||
var feeAmount int64
|
||||
if req.Payment != 0 {
|
||||
payment, err := l.svcCtx.PaymentModel.FindOne(l.ctx, req.Payment)
|
||||
if err != nil {
|
||||
l.Logger.Error("[PreCreateOrder] Database query error", logger.Field("error", err.Error()), logger.Field("payment", req.Payment))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find payment method error: %v", err.Error())
|
||||
}
|
||||
// Calculate the handling fee
|
||||
if amount > 0 {
|
||||
feeAmount = calculateFee(amount, payment)
|
||||
}
|
||||
amount += feeAmount
|
||||
}
|
||||
|
||||
resp = &types.PrePurchaseOrderResponse{
|
||||
Price: price,
|
||||
Amount: amount,
|
||||
Discount: discountAmount,
|
||||
Coupon: req.Coupon,
|
||||
CouponDiscount: coupon,
|
||||
FeeAmount: feeAmount,
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,333 @@
|
||||
package portal
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strconv"
|
||||
|
||||
"github.com/perfect-panel/ppanel-server/pkg/constant"
|
||||
|
||||
paymentPlatform "github.com/perfect-panel/ppanel-server/pkg/payment"
|
||||
|
||||
"github.com/hibiken/asynq"
|
||||
"github.com/perfect-panel/ppanel-server/internal/model/user"
|
||||
queueType "github.com/perfect-panel/ppanel-server/queue/types"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/perfect-panel/ppanel-server/internal/model/order"
|
||||
"github.com/perfect-panel/ppanel-server/internal/model/payment"
|
||||
"github.com/perfect-panel/ppanel-server/internal/svc"
|
||||
"github.com/perfect-panel/ppanel-server/internal/types"
|
||||
"github.com/perfect-panel/ppanel-server/pkg/exchangeRate"
|
||||
"github.com/perfect-panel/ppanel-server/pkg/logger"
|
||||
"github.com/perfect-panel/ppanel-server/pkg/payment/alipay"
|
||||
"github.com/perfect-panel/ppanel-server/pkg/payment/epay"
|
||||
"github.com/perfect-panel/ppanel-server/pkg/payment/stripe"
|
||||
"github.com/perfect-panel/ppanel-server/pkg/tool"
|
||||
"github.com/perfect-panel/ppanel-server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type PurchaseCheckoutLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// NewPurchaseCheckoutLogic Purchase Checkout
|
||||
func NewPurchaseCheckoutLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PurchaseCheckoutLogic {
|
||||
return &PurchaseCheckoutLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *PurchaseCheckoutLogic) PurchaseCheckout(req *types.CheckoutOrderRequest) (resp *types.CheckoutOrderResponse, err error) {
|
||||
// Find order
|
||||
orderInfo, err := l.svcCtx.OrderModel.FindOneByOrderNo(l.ctx, req.OrderNo)
|
||||
if err != nil {
|
||||
l.Logger.Error("[PurchaseCheckout] Find order failed", logger.Field("error", err.Error()), logger.Field("orderNo", req.OrderNo))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.OrderNotExist), "order not exist: %v", req.OrderNo)
|
||||
}
|
||||
|
||||
if orderInfo.Status != 1 {
|
||||
l.Logger.Error("[PurchaseCheckout] Order status error", logger.Field("status", orderInfo.Status))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.OrderStatusError), "order status error: %v", orderInfo.Status)
|
||||
}
|
||||
|
||||
// find payment method
|
||||
paymentConfig, err := l.svcCtx.PaymentModel.FindOne(l.ctx, orderInfo.PaymentId)
|
||||
if err != nil {
|
||||
l.Logger.Error("[Purchase] Database query error", logger.Field("error", err.Error()), logger.Field("payment", orderInfo.Method))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find payment method error: %v", err.Error())
|
||||
}
|
||||
switch paymentPlatform.ParsePlatform(orderInfo.Method) {
|
||||
case paymentPlatform.EPay:
|
||||
url, err := l.epayPayment(paymentConfig, orderInfo, req.ReturnUrl)
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "epayPayment error: %v", err.Error())
|
||||
}
|
||||
resp = &types.CheckoutOrderResponse{
|
||||
CheckoutUrl: url,
|
||||
Type: "url",
|
||||
}
|
||||
case paymentPlatform.Stripe:
|
||||
stripePayment, err := l.stripePayment(paymentConfig.Config, orderInfo, "")
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "stripePayment error: %v", err.Error())
|
||||
}
|
||||
resp = &types.CheckoutOrderResponse{
|
||||
Type: "stripe",
|
||||
Stripe: stripePayment,
|
||||
}
|
||||
case paymentPlatform.AlipayF2F:
|
||||
url, err := l.alipayF2fPayment(paymentConfig, orderInfo)
|
||||
if err != nil {
|
||||
l.Errorw("[CheckoutOrderLogic] alipayF2fPayment error", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "alipayF2fPayment error: %v", err.Error())
|
||||
}
|
||||
resp = &types.CheckoutOrderResponse{
|
||||
Type: "qr",
|
||||
CheckoutUrl: url,
|
||||
}
|
||||
case paymentPlatform.Balance:
|
||||
if orderInfo.UserId == 0 {
|
||||
l.Errorw("[CheckoutOrderLogic] user not found", logger.Field("userId", orderInfo.UserId))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.UserNotExist), "user not found")
|
||||
}
|
||||
// find user
|
||||
userInfo, err := l.svcCtx.UserModel.FindOne(l.ctx, orderInfo.UserId)
|
||||
if err != nil {
|
||||
l.Errorw("[CheckoutOrderLogic] FindOne User error", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "FindOne error: %s", err.Error())
|
||||
}
|
||||
|
||||
// balance
|
||||
if err = l.balancePayment(userInfo, orderInfo); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp = &types.CheckoutOrderResponse{
|
||||
Type: "balance",
|
||||
}
|
||||
|
||||
default:
|
||||
l.Errorw("[CheckoutOrderLogic] payment method not found", logger.Field("method", orderInfo.Method))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "payment method not found")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// alipay f2f payment
|
||||
func (l *PurchaseCheckoutLogic) alipayF2fPayment(pay *payment.Payment, info *order.Order) (string, error) {
|
||||
f2FConfig := payment.AlipayF2FConfig{}
|
||||
if err := json.Unmarshal([]byte(pay.Config), &f2FConfig); err != nil {
|
||||
l.Errorw("[PurchaseCheckoutLogic] Unmarshal error", logger.Field("error", err.Error()))
|
||||
return "", errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "Unmarshal error: %s", err.Error())
|
||||
}
|
||||
notifyUrl := ""
|
||||
if pay.Domain != "" {
|
||||
notifyUrl = pay.Domain + "/v1/notify/" + pay.Platform + "/" + pay.Token
|
||||
} else {
|
||||
host, ok := l.ctx.Value(constant.CtxKeyRequestHost).(string)
|
||||
if !ok {
|
||||
host = l.svcCtx.Config.Host
|
||||
}
|
||||
notifyUrl = "https://" + host + "/v1/notify/" + pay.Platform + "/" + pay.Token
|
||||
}
|
||||
client := alipay.NewClient(alipay.Config{
|
||||
AppId: f2FConfig.AppId,
|
||||
PrivateKey: f2FConfig.PrivateKey,
|
||||
PublicKey: f2FConfig.PublicKey,
|
||||
InvoiceName: f2FConfig.InvoiceName,
|
||||
NotifyURL: notifyUrl,
|
||||
})
|
||||
// Calculate the amount with exchange rate
|
||||
amount, err := l.queryExchangeRate("CNY", info.Amount)
|
||||
if err != nil {
|
||||
l.Errorw("[CheckoutOrderLogic] queryExchangeRate error", logger.Field("error", err.Error()))
|
||||
return "", errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "queryExchangeRate error: %s", err.Error())
|
||||
}
|
||||
convertAmount := int64(amount * 100)
|
||||
// create payment
|
||||
QRCode, err := client.PreCreateTrade(l.ctx, alipay.Order{
|
||||
OrderNo: info.OrderNo,
|
||||
Amount: convertAmount,
|
||||
})
|
||||
if err != nil {
|
||||
l.Errorw("[CheckoutOrderLogic] PreCreateTrade error", logger.Field("error", err.Error()))
|
||||
return "", errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "PreCreateTrade error: %s", err.Error())
|
||||
}
|
||||
return QRCode, nil
|
||||
}
|
||||
|
||||
// Stripe Payment
|
||||
func (l *PurchaseCheckoutLogic) stripePayment(config string, info *order.Order, identifier string) (*types.StripePayment, error) {
|
||||
// stripe WeChat pay or stripe alipay
|
||||
stripeConfig := payment.StripeConfig{}
|
||||
if err := json.Unmarshal([]byte(config), &stripeConfig); err != nil {
|
||||
l.Errorw("[CheckoutOrderLogic] Unmarshal error", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "Unmarshal error: %s", err.Error())
|
||||
}
|
||||
client := stripe.NewClient(stripe.Config{
|
||||
SecretKey: stripeConfig.SecretKey,
|
||||
PublicKey: stripeConfig.PublicKey,
|
||||
WebhookSecret: stripeConfig.WebhookSecret,
|
||||
})
|
||||
// Calculate the amount with exchange rate
|
||||
amount, err := l.queryExchangeRate("CNY", info.Amount)
|
||||
if err != nil {
|
||||
l.Errorw("[CheckoutOrderLogic] queryExchangeRate error", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "queryExchangeRate error: %s", err.Error())
|
||||
}
|
||||
convertAmount := int64(amount * 100)
|
||||
// create payment
|
||||
result, err := client.CreatePaymentSheet(&stripe.Order{
|
||||
OrderNo: info.OrderNo,
|
||||
Subscribe: strconv.FormatInt(info.SubscribeId, 10),
|
||||
Amount: convertAmount,
|
||||
Currency: "cny",
|
||||
Payment: stripeConfig.Payment,
|
||||
},
|
||||
&stripe.User{
|
||||
Email: identifier,
|
||||
})
|
||||
if err != nil {
|
||||
l.Errorw("[CheckoutOrderLogic] CreatePaymentSheet error", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "CreatePaymentSheet error: %s", err.Error())
|
||||
}
|
||||
tradeNo := result.TradeNo
|
||||
stripePayment := &types.StripePayment{
|
||||
PublishableKey: stripeConfig.PublicKey,
|
||||
ClientSecret: result.ClientSecret,
|
||||
Method: stripeConfig.Payment,
|
||||
}
|
||||
// save payment
|
||||
info.TradeNo = tradeNo
|
||||
err = l.svcCtx.OrderModel.Update(l.ctx, info)
|
||||
if err != nil {
|
||||
l.Errorw("[CheckoutOrderLogic] Update error", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "Update error: %s", err.Error())
|
||||
}
|
||||
return stripePayment, nil
|
||||
}
|
||||
|
||||
func (l *PurchaseCheckoutLogic) epayPayment(config *payment.Payment, info *order.Order, returnUrl string) (string, error) {
|
||||
epayConfig := payment.EPayConfig{}
|
||||
if err := json.Unmarshal([]byte(config.Config), &epayConfig); err != nil {
|
||||
l.Errorw("[CheckoutOrderLogic] Unmarshal error", logger.Field("error", err.Error()))
|
||||
return "", errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "Unmarshal error: %s", err.Error())
|
||||
}
|
||||
client := epay.NewClient(epayConfig.Pid, epayConfig.Url, epayConfig.Key)
|
||||
// Calculate the amount with exchange rate
|
||||
amount, err := l.queryExchangeRate("CNY", info.Amount)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
notifyUrl := ""
|
||||
if config.Domain != "" {
|
||||
notifyUrl = config.Domain + "/v1/notify/" + config.Platform + "/" + config.Token
|
||||
} else {
|
||||
host, ok := l.ctx.Value(constant.CtxKeyRequestHost).(string)
|
||||
if !ok {
|
||||
host = l.svcCtx.Config.Host
|
||||
}
|
||||
notifyUrl = "https://" + host + "/v1/notify/" + config.Platform + "/" + config.Token
|
||||
}
|
||||
// create payment
|
||||
url := client.CreatePayUrl(epay.Order{
|
||||
Name: l.svcCtx.Config.Site.SiteName,
|
||||
Amount: amount,
|
||||
OrderNo: info.OrderNo,
|
||||
SignType: "MD5",
|
||||
NotifyUrl: notifyUrl,
|
||||
ReturnUrl: returnUrl,
|
||||
})
|
||||
return url, nil
|
||||
}
|
||||
|
||||
// Query exchange rate
|
||||
func (l *PurchaseCheckoutLogic) queryExchangeRate(to string, src int64) (amount float64, err error) {
|
||||
amount = float64(src) / float64(100)
|
||||
// query system currency
|
||||
currency, err := l.svcCtx.SystemModel.GetCurrencyConfig(l.ctx)
|
||||
if err != nil {
|
||||
l.Errorw("[CheckoutOrderLogic] GetCurrencyConfig error", logger.Field("error", err.Error()))
|
||||
return 0, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "GetCurrencyConfig error: %s", err.Error())
|
||||
}
|
||||
configs := struct {
|
||||
CurrencyUnit string
|
||||
CurrencySymbol string
|
||||
AccessKey string
|
||||
}{}
|
||||
tool.SystemConfigSliceReflectToStruct(currency, &configs)
|
||||
if configs.AccessKey == "" {
|
||||
return amount, nil
|
||||
}
|
||||
if configs.CurrencyUnit != to {
|
||||
// query exchange rate
|
||||
result, err := exchangeRate.GetExchangeRete(configs.CurrencyUnit, to, configs.AccessKey, 1)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
amount = result * amount
|
||||
}
|
||||
return amount, nil
|
||||
}
|
||||
|
||||
// Balance payment
|
||||
func (l *PurchaseCheckoutLogic) balancePayment(u *user.User, o *order.Order) error {
|
||||
var userInfo user.User
|
||||
err := l.svcCtx.UserModel.Transaction(l.ctx, func(db *gorm.DB) error {
|
||||
err := db.Model(&user.User{}).Where("id = ?", u.Id).First(&userInfo).Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if userInfo.Balance < o.Amount {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.InsufficientBalance), "Insufficient balance")
|
||||
}
|
||||
// deduct balance
|
||||
userInfo.Balance -= o.Amount
|
||||
err = l.svcCtx.UserModel.Update(l.ctx, &userInfo)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// create balance log
|
||||
balanceLog := &user.BalanceLog{
|
||||
Id: 0,
|
||||
UserId: u.Id,
|
||||
Amount: o.Amount,
|
||||
Type: 3,
|
||||
OrderId: o.Id,
|
||||
Balance: userInfo.Balance,
|
||||
}
|
||||
err = db.Create(balanceLog).Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return l.svcCtx.OrderModel.UpdateOrderStatus(l.ctx, o.OrderNo, 2)
|
||||
})
|
||||
if err != nil {
|
||||
l.Errorw("[CheckoutOrderLogic] Transaction error", logger.Field("error", err.Error()), logger.Field("orderNo", o.OrderNo))
|
||||
return err
|
||||
}
|
||||
// create activity order task
|
||||
payload := queueType.ForthwithActivateOrderPayload{
|
||||
OrderNo: o.OrderNo,
|
||||
}
|
||||
bytes, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
l.Errorw("[CheckoutOrderLogic] Marshal error", logger.Field("error", err.Error()))
|
||||
return err
|
||||
}
|
||||
|
||||
task := asynq.NewTask(queueType.ForthwithActivateOrder, bytes)
|
||||
_, err = l.svcCtx.Queue.EnqueueContext(l.ctx, task)
|
||||
if err != nil {
|
||||
l.Errorw("[CheckoutOrderLogic] Enqueue error", logger.Field("error", err.Error()))
|
||||
return err
|
||||
}
|
||||
l.Logger.Info("[CheckoutOrderLogic] Enqueue success", logger.Field("orderNo", o.OrderNo))
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
package portal
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/perfect-panel/ppanel-server/pkg/payment"
|
||||
|
||||
"github.com/perfect-panel/ppanel-server/pkg/constant"
|
||||
|
||||
"github.com/hibiken/asynq"
|
||||
"github.com/perfect-panel/ppanel-server/internal/model/order"
|
||||
"github.com/perfect-panel/ppanel-server/internal/svc"
|
||||
"github.com/perfect-panel/ppanel-server/internal/types"
|
||||
"github.com/perfect-panel/ppanel-server/pkg/logger"
|
||||
"github.com/perfect-panel/ppanel-server/pkg/tool"
|
||||
"github.com/perfect-panel/ppanel-server/pkg/xerr"
|
||||
queue "github.com/perfect-panel/ppanel-server/queue/types"
|
||||
"github.com/pkg/errors"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type PurchaseLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// NewPurchaseLogic Purchase subscription
|
||||
func NewPurchaseLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PurchaseLogic {
|
||||
return &PurchaseLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
const (
|
||||
CloseOrderTimeMinutes = 15
|
||||
)
|
||||
|
||||
func (l *PurchaseLogic) Purchase(req *types.PortalPurchaseRequest) (resp *types.PortalPurchaseResponse, err error) {
|
||||
// find user auth
|
||||
userAuth, err := l.svcCtx.UserModel.FindUserAuthMethodByOpenID(l.ctx, req.AuthType, req.Identifier)
|
||||
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find user auth error: %v", err.Error())
|
||||
}
|
||||
if userAuth.UserId != 0 {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.UserExist), "user already exists")
|
||||
}
|
||||
// find subscribe plan
|
||||
sub, err := l.svcCtx.SubscribeModel.FindOne(l.ctx, req.SubscribeId)
|
||||
if err != nil {
|
||||
l.Errorw("[Purchase] Database query error", logger.Field("error", err.Error()), logger.Field("subscribe_id", req.SubscribeId))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find subscribe error: %v", err.Error())
|
||||
}
|
||||
// check subscribe plan status
|
||||
if !*sub.Sell {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "subscribe not sell")
|
||||
}
|
||||
var discount float64 = 1
|
||||
if sub.Discount != "" {
|
||||
var dis []types.SubscribeDiscount
|
||||
_ = json.Unmarshal([]byte(sub.Discount), &dis)
|
||||
discount = getDiscount(dis, req.Quantity)
|
||||
}
|
||||
price := sub.UnitPrice * req.Quantity
|
||||
// discount amount
|
||||
amount := int64(float64(price) * discount)
|
||||
discountAmount := price - amount
|
||||
|
||||
var couponAmount int64 = 0
|
||||
// Calculate the coupon deduction
|
||||
if req.Coupon != "" {
|
||||
couponInfo, err := l.svcCtx.CouponModel.FindOneByCode(l.ctx, req.Coupon)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.CouponNotExist), "coupon not found")
|
||||
}
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find coupon error: %v", err.Error())
|
||||
}
|
||||
if couponInfo.Count <= couponInfo.UsedCount {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.CouponInsufficientUsage), "coupon used")
|
||||
}
|
||||
couponSub := tool.StringToInt64Slice(couponInfo.Subscribe)
|
||||
if len(couponSub) > 0 && !tool.Contains(couponSub, req.SubscribeId) {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.CouponNotApplicable), "coupon not match")
|
||||
}
|
||||
|
||||
couponAmount = calculateCoupon(amount, couponInfo)
|
||||
}
|
||||
// Calculate the handling fee
|
||||
amount -= couponAmount
|
||||
var deductionAmount int64
|
||||
// find payment method
|
||||
paymentConfig, err := l.svcCtx.PaymentModel.FindOne(l.ctx, req.Payment)
|
||||
if err != nil {
|
||||
l.Logger.Error("[Purchase] Database query error", logger.Field("error", err.Error()), logger.Field("payment", req.Payment))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.PaymentMethodNotFound), "find payment method error: %v", err.Error())
|
||||
}
|
||||
|
||||
if payment.ParsePlatform(paymentConfig.Platform) == payment.Balance {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.PaymentMethodNotFound), "balance error")
|
||||
}
|
||||
|
||||
var feeAmount int64
|
||||
// Calculate the handling fee
|
||||
if amount > 0 {
|
||||
feeAmount = calculateFee(amount, paymentConfig)
|
||||
}
|
||||
// create order
|
||||
orderInfo := &order.Order{
|
||||
OrderNo: tool.GenerateTradeNo(),
|
||||
Type: 1,
|
||||
Quantity: req.Quantity,
|
||||
Price: price,
|
||||
Amount: amount,
|
||||
Discount: discountAmount,
|
||||
GiftAmount: deductionAmount,
|
||||
Coupon: req.Coupon,
|
||||
CouponDiscount: couponAmount,
|
||||
PaymentId: req.Payment,
|
||||
Method: paymentConfig.Platform,
|
||||
FeeAmount: feeAmount,
|
||||
Status: 1,
|
||||
IsNew: true,
|
||||
SubscribeId: req.SubscribeId,
|
||||
}
|
||||
// save order
|
||||
err = l.svcCtx.DB.Transaction(func(tx *gorm.DB) error {
|
||||
// save guest order and user information
|
||||
tempOrder := constant.TemporaryOrderInfo{
|
||||
OrderNo: orderInfo.OrderNo,
|
||||
Identifier: req.Identifier,
|
||||
AuthType: req.AuthType,
|
||||
Password: req.Password,
|
||||
InviteCode: req.InviteCode,
|
||||
}
|
||||
if _, err = l.svcCtx.Redis.Set(l.ctx, fmt.Sprintf(constant.TempOrderCacheKey, orderInfo.OrderNo), tempOrder.Marshal(), CloseOrderTimeMinutes*time.Minute).Result(); err != nil {
|
||||
l.Errorw("[Purchase] Redis set error", logger.Field("error", err.Error()), logger.Field("order_no", orderInfo.OrderNo))
|
||||
return err
|
||||
}
|
||||
l.Infow("[Purchase] Guest order", logger.Field("order_no", orderInfo.OrderNo), logger.Field("identifier", req.Identifier))
|
||||
// save guest order
|
||||
if err := l.svcCtx.OrderModel.Insert(l.ctx, orderInfo, tx); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
l.Errorw("[Purchase] Database transaction error", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "transaction error: %v", err.Error())
|
||||
}
|
||||
// Deferred task
|
||||
payload := queue.DeferCloseOrderPayload{
|
||||
OrderNo: orderInfo.OrderNo,
|
||||
}
|
||||
val, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
l.Errorw("[CloseOrder Task] Marshal payload error", logger.Field("error", err.Error()), logger.Field("payload", payload))
|
||||
}
|
||||
task := asynq.NewTask(queue.DeferCloseOrder, val, asynq.MaxRetry(3))
|
||||
taskInfo, err := l.svcCtx.Queue.Enqueue(task, asynq.ProcessIn(CloseOrderTimeMinutes*time.Minute))
|
||||
if err != nil {
|
||||
l.Errorw("[CloseOrder Task] Enqueue task error", logger.Field("error", err.Error()), logger.Field("task", taskInfo))
|
||||
} else {
|
||||
l.Infow("[CloseOrder Task] Enqueue task success", logger.Field("TaskID", taskInfo.ID))
|
||||
}
|
||||
resp = &types.PortalPurchaseResponse{OrderNo: orderInfo.OrderNo}
|
||||
return resp, nil
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
package portal
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/perfect-panel/ppanel-server/internal/model/order"
|
||||
|
||||
"github.com/perfect-panel/ppanel-server/pkg/tool"
|
||||
|
||||
"github.com/perfect-panel/ppanel-server/internal/config"
|
||||
"github.com/perfect-panel/ppanel-server/internal/svc"
|
||||
"github.com/perfect-panel/ppanel-server/internal/types"
|
||||
"github.com/perfect-panel/ppanel-server/pkg/constant"
|
||||
"github.com/perfect-panel/ppanel-server/pkg/jwt"
|
||||
"github.com/perfect-panel/ppanel-server/pkg/logger"
|
||||
"github.com/perfect-panel/ppanel-server/pkg/uuidx"
|
||||
"github.com/perfect-panel/ppanel-server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type QueryPurchaseOrderLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// NewQueryPurchaseOrderLogic Query Purchase Order
|
||||
func NewQueryPurchaseOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryPurchaseOrderLogic {
|
||||
return &QueryPurchaseOrderLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
// Centralized error handler for database issues
|
||||
func wrapDatabaseError(err error) error {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "Database Query Error: %v", err.Error())
|
||||
}
|
||||
|
||||
func (l *QueryPurchaseOrderLogic) QueryPurchaseOrder(req *types.QueryPurchaseOrderRequest) (resp *types.QueryPurchaseOrderResponse, err error) {
|
||||
orderInfo, err := l.svcCtx.OrderModel.FindOneByOrderNo(l.ctx, req.OrderNo)
|
||||
if err != nil {
|
||||
return nil, wrapDatabaseError(err)
|
||||
}
|
||||
// Handle temporary orders if applicable
|
||||
var token string
|
||||
if orderInfo.Status == 2 || orderInfo.Status == 5 {
|
||||
if token, err = l.handleTemporaryOrder(orderInfo, req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
// Fetch subscription and payment information
|
||||
subscribeInfo, paymentInfo, err := l.fetchOrderDetails(orderInfo)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &types.QueryPurchaseOrderResponse{
|
||||
OrderNo: orderInfo.OrderNo,
|
||||
Subscribe: subscribeInfo,
|
||||
Quantity: orderInfo.Quantity,
|
||||
Price: orderInfo.Price,
|
||||
Amount: orderInfo.Amount,
|
||||
Discount: orderInfo.Discount,
|
||||
Coupon: orderInfo.Coupon,
|
||||
CouponDiscount: orderInfo.CouponDiscount,
|
||||
FeeAmount: orderInfo.FeeAmount,
|
||||
Payment: paymentInfo,
|
||||
Status: orderInfo.Status,
|
||||
CreatedAt: orderInfo.CreatedAt.UnixMilli(),
|
||||
Token: token,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// handleTemporaryOrder processes temporary order-related operations
|
||||
func (l *QueryPurchaseOrderLogic) handleTemporaryOrder(orderInfo *order.Order, req *types.QueryPurchaseOrderRequest) (string, error) {
|
||||
cacheKey := fmt.Sprintf(constant.TempOrderCacheKey, orderInfo.OrderNo)
|
||||
cacheValue, err := l.svcCtx.Redis.Get(l.ctx, cacheKey).Result()
|
||||
if err != nil {
|
||||
l.Errorw("Get TempOrderCacheKey Error", logger.Field("cacheKey", cacheKey), logger.Field("error", err.Error()))
|
||||
return "", errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "Get TempOrderCacheKey Error: %v", err.Error())
|
||||
}
|
||||
|
||||
var tempOrder constant.TemporaryOrderInfo
|
||||
if err := json.Unmarshal([]byte(cacheValue), &tempOrder); err != nil {
|
||||
l.Errorw("JSON Unmarshal Error", logger.Field("error", err.Error()), logger.Field("cacheValue", cacheValue))
|
||||
return "", errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "JSON Unmarshal Error: %v", err.Error())
|
||||
}
|
||||
if tempOrder.OrderNo != orderInfo.OrderNo {
|
||||
return "", errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "Order number mismatch")
|
||||
}
|
||||
|
||||
// Validate user and email
|
||||
if err := l.validateUserAndEmail(orderInfo, req.Identifier, req.Identifier); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// Generate session token
|
||||
return l.generateSessionToken(orderInfo.UserId)
|
||||
}
|
||||
|
||||
// validateUserAndEmail ensures the user and email are correct
|
||||
func (l *QueryPurchaseOrderLogic) validateUserAndEmail(orderInfo *order.Order, platform, openid string) error {
|
||||
userInfo, err := l.svcCtx.UserModel.FindOne(l.ctx, orderInfo.UserId)
|
||||
if err != nil {
|
||||
return wrapDatabaseError(err)
|
||||
}
|
||||
|
||||
authMethod, err := l.svcCtx.UserModel.FindUserAuthMethodByOpenID(l.ctx, platform, openid)
|
||||
if err != nil {
|
||||
return wrapDatabaseError(err)
|
||||
}
|
||||
if authMethod.UserId != userInfo.Id {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "Email verification failed")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// generateSessionToken creates a session token and stores it in Redis
|
||||
func (l *QueryPurchaseOrderLogic) generateSessionToken(userId int64) (string, error) {
|
||||
sessionId := uuidx.NewUUID().String()
|
||||
token, err := jwt.NewJwtToken(
|
||||
l.svcCtx.Config.JwtAuth.AccessSecret,
|
||||
time.Now().Unix(),
|
||||
l.svcCtx.Config.JwtAuth.AccessExpire,
|
||||
jwt.WithOption("UserId", userId),
|
||||
jwt.WithOption("SessionId", sessionId),
|
||||
)
|
||||
if err != nil {
|
||||
l.Errorw("Token Generation Error", logger.Field("error", err.Error()))
|
||||
return "", errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "Token generation error")
|
||||
}
|
||||
|
||||
cacheKey := fmt.Sprintf("%v:%v", config.SessionIdKey, sessionId)
|
||||
if err := l.svcCtx.Redis.Set(l.ctx, cacheKey, userId, time.Duration(l.svcCtx.Config.JwtAuth.AccessExpire)*time.Second).Err(); err != nil {
|
||||
return "", errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "Session storage error")
|
||||
}
|
||||
|
||||
return token, nil
|
||||
}
|
||||
|
||||
// fetchOrderDetails retrieves subscription and payment details
|
||||
func (l *QueryPurchaseOrderLogic) fetchOrderDetails(orderInfo *order.Order) (types.Subscribe, types.PaymentMethod, error) {
|
||||
sub, err := l.svcCtx.SubscribeModel.FindOne(l.ctx, orderInfo.SubscribeId)
|
||||
if err != nil {
|
||||
return types.Subscribe{}, types.PaymentMethod{}, wrapDatabaseError(err)
|
||||
}
|
||||
|
||||
var subscribeInfo types.Subscribe
|
||||
tool.DeepCopy(&subscribeInfo, sub)
|
||||
|
||||
payment, err := l.svcCtx.PaymentModel.FindOne(l.ctx, orderInfo.PaymentId)
|
||||
if err != nil {
|
||||
return types.Subscribe{}, types.PaymentMethod{}, wrapDatabaseError(err)
|
||||
}
|
||||
|
||||
var paymentInfo types.PaymentMethod
|
||||
tool.DeepCopy(&paymentInfo, payment)
|
||||
|
||||
return subscribeInfo, paymentInfo, nil
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package portal
|
||||
|
||||
import (
|
||||
"github.com/perfect-panel/ppanel-server/internal/model/coupon"
|
||||
"github.com/perfect-panel/ppanel-server/internal/model/payment"
|
||||
"github.com/perfect-panel/ppanel-server/internal/types"
|
||||
)
|
||||
|
||||
func getDiscount(discounts []types.SubscribeDiscount, inputMonths int64) float64 {
|
||||
var finalDiscount int64 = 100
|
||||
|
||||
for _, discount := range discounts {
|
||||
if inputMonths >= discount.Quantity && discount.Discount < finalDiscount {
|
||||
finalDiscount = discount.Discount
|
||||
}
|
||||
}
|
||||
return float64(finalDiscount) / float64(100)
|
||||
}
|
||||
|
||||
func calculateCoupon(amount int64, couponInfo *coupon.Coupon) int64 {
|
||||
if couponInfo.Type == 1 {
|
||||
return int64(float64(amount) * (float64(couponInfo.Discount) / float64(100)))
|
||||
} else {
|
||||
return min(couponInfo.Discount, amount)
|
||||
}
|
||||
}
|
||||
|
||||
func calculateFee(amount int64, config *payment.Payment) int64 {
|
||||
var fee float64
|
||||
switch config.FeeMode {
|
||||
case 0:
|
||||
return 0
|
||||
case 1:
|
||||
fee = float64(amount) * (float64(config.FeePercent) / float64(100))
|
||||
case 2:
|
||||
if amount > 0 {
|
||||
fee = float64(config.FeeAmount)
|
||||
}
|
||||
case 3:
|
||||
fee = float64(amount)*(float64(config.FeePercent)/float64(100)) + float64(config.FeeAmount)
|
||||
}
|
||||
return int64(fee)
|
||||
}
|
||||
Reference in New Issue
Block a user