重构: 手续费改为百分比/固定二选一,清理旧 Skin/Order/ShipLog 演示链路
手续费: - 新增 fee_type 字段(rate/fixed),百分比与固定金额二选一,不再叠加 - calculateServiceFee 按 fee_type 分支计算 - 商户创建/更新校验 fee_type,订单落库快照 fee_type - 前端表单改为下拉选择手续费类型,动态显示对应输入框 - 测试拆为 TestFeeRate + TestFeeFixed 清理旧链路: - 删除旧 Skin/Order/ShipLog 模型及 OrderService/SkinService - Dashboard 迁移到 FulfillmentService - 上游 /api/open/v1 改为基于 FulfillmentOrder 实现,接口契约不变 - 推送留痕改用 AuditLog,不再建 ShipLog 表 - 删除前端 Skins/Orders/ShipLogs/Distributors 页面及路由、菜单、API、类型 - 新增迁移 003: 添加 fee_type 列并 DROP 旧表
This commit is contained in:
@@ -2,9 +2,6 @@ package service
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"time"
|
||||
|
||||
"affiliate_dash/internal/model"
|
||||
"affiliate_dash/internal/pkg/jwt"
|
||||
@@ -63,9 +60,8 @@ func (s *AuthService) Register(username, password, nickname string) (*model.User
|
||||
Username: username,
|
||||
PasswordHash: string(hash),
|
||||
Nickname: nickname,
|
||||
Role: model.RoleDistributor,
|
||||
Role: model.RoleMerchant,
|
||||
Status: 1,
|
||||
InviteCode: generateInviteCode(),
|
||||
}
|
||||
if user.Nickname == "" {
|
||||
user.Nickname = username
|
||||
@@ -116,7 +112,6 @@ func (s *AuthService) EnsureAdmin() error {
|
||||
Nickname: "管理员",
|
||||
Role: model.RoleAdmin,
|
||||
Status: 1,
|
||||
InviteCode: "ADMIN001",
|
||||
}
|
||||
if err := s.db.Create(admin).Error; err != nil {
|
||||
return err
|
||||
@@ -126,8 +121,3 @@ func (s *AuthService) EnsureAdmin() error {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func generateInviteCode() string {
|
||||
r := rand.New(rand.NewSource(time.Now().UnixNano()))
|
||||
return fmt.Sprintf("D%06d", r.Intn(1000000))
|
||||
}
|
||||
|
||||
@@ -79,6 +79,13 @@ func (s *FulfillmentService) CreateOrder(in CreateFulfillmentOrderInput) (*Creat
|
||||
return err
|
||||
}
|
||||
|
||||
var merchant model.Merchant
|
||||
if err := tx.Where("id = ? AND status = ?", in.MerchantID, model.MerchantStatusActive).First(&merchant).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return errors.New("商户不存在或已禁用")
|
||||
}
|
||||
return err
|
||||
}
|
||||
var product model.MerchantProduct
|
||||
if err := tx.Preload("Product").Clauses(clause.Locking{Strength: "UPDATE"}).
|
||||
Where("merchant_id = ? AND sku = ? AND status = ?", in.MerchantID, in.SKU, model.ProductStatusActive).
|
||||
@@ -97,7 +104,15 @@ func (s *FulfillmentService) CreateOrder(in CreateFulfillmentOrderInput) (*Creat
|
||||
if product.PriceAmount > 0 && in.Quantity > math.MaxInt64/product.PriceAmount {
|
||||
return errors.New("订单金额超出范围")
|
||||
}
|
||||
totalAmount := product.PriceAmount * in.Quantity
|
||||
baseAmount := product.PriceAmount * in.Quantity
|
||||
serviceFee, err := calculateServiceFee(baseAmount, merchant.FeeType, merchant.FeeRateBP, merchant.FeeFixedAmount)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if serviceFee > math.MaxInt64-baseAmount {
|
||||
return errors.New("订单金额超出范围")
|
||||
}
|
||||
totalAmount := baseAmount + serviceFee
|
||||
|
||||
var wallet model.WalletAccount
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
|
||||
@@ -120,6 +135,11 @@ func (s *FulfillmentService) CreateOrder(in CreateFulfillmentOrderInput) (*Creat
|
||||
ProductSKU: product.SKU,
|
||||
ProductName: fallbackName(product.DisplayName, product.Product.Name),
|
||||
Quantity: in.Quantity,
|
||||
BaseAmount: baseAmount,
|
||||
FeeType: merchant.FeeType,
|
||||
FeeRateBP: merchant.FeeRateBP,
|
||||
FeeFixedAmount: merchant.FeeFixedAmount,
|
||||
ServiceFeeAmount: serviceFee,
|
||||
Amount: totalAmount,
|
||||
Currency: product.Currency,
|
||||
PaymentStatus: model.PaymentStatusPaid,
|
||||
@@ -141,7 +161,7 @@ func (s *FulfillmentService) CreateOrder(in CreateFulfillmentOrderInput) (*Creat
|
||||
ReferenceType: "fulfillment_order",
|
||||
ReferenceNo: order.OrderNo,
|
||||
IdempotencyKey: &idempotencyKey,
|
||||
Note: "开放接口下单扣款",
|
||||
Note: "开放接口下单扣款(含平台手续费)",
|
||||
}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -493,6 +513,31 @@ func newFulfillmentOrderNo() string {
|
||||
return "FO" + time.Now().UTC().Format("20060102150405") + strings.ReplaceAll(uuid.NewString()[:12], "-", "")
|
||||
}
|
||||
|
||||
// calculateServiceFee 按"百分比或固定"二选一计算手续费:
|
||||
// - feeType=rate:按 baseAmount * feeRateBP / 10000 计算
|
||||
// - feeType=fixed:直接取 feeFixedAmount
|
||||
//
|
||||
// 二者互斥,不会叠加。
|
||||
func calculateServiceFee(baseAmount int64, feeType string, feeRateBP, feeFixedAmount int64) (int64, error) {
|
||||
if baseAmount < 0 || feeRateBP < 0 || feeFixedAmount < 0 {
|
||||
return 0, errors.New("订单金额或手续费配置无效")
|
||||
}
|
||||
switch feeType {
|
||||
case model.FeeTypeFixed:
|
||||
return feeFixedAmount, nil
|
||||
case model.FeeTypeRate, "":
|
||||
if feeRateBP > 10000 {
|
||||
return 0, errors.New("手续费比例不能超过 10000 BP")
|
||||
}
|
||||
if feeRateBP > 0 && baseAmount > math.MaxInt64/feeRateBP {
|
||||
return 0, errors.New("手续费金额超出范围")
|
||||
}
|
||||
return baseAmount * feeRateBP / 10000, nil
|
||||
default:
|
||||
return 0, errors.New("无效的手续费类型")
|
||||
}
|
||||
}
|
||||
|
||||
func CanFulfill(order *model.FulfillmentOrder) (bool, string) {
|
||||
if order.PaymentStatus != model.PaymentStatusPaid {
|
||||
return false, "订单未支付或已退款"
|
||||
@@ -518,8 +563,11 @@ func orderCallbackData(order *model.FulfillmentOrder) map[string]interface{} {
|
||||
"client_order_no": order.ClientOrderNo,
|
||||
"product_sku": order.ProductSKU,
|
||||
"quantity": order.Quantity,
|
||||
"base_amount": order.BaseAmount,
|
||||
"fee_type": order.FeeType,
|
||||
"service_fee_amount": order.ServiceFeeAmount,
|
||||
"amount": order.Amount,
|
||||
"currency": order.Currency,
|
||||
"currency": order.Currency,
|
||||
"payment_status": order.PaymentStatus,
|
||||
"fulfillment_status": order.FulfillmentStatus,
|
||||
"can_fulfill": canFulfill,
|
||||
@@ -528,3 +576,358 @@ func orderCallbackData(order *model.FulfillmentOrder) map[string]interface{} {
|
||||
"failure_reason": order.FailureReason,
|
||||
}
|
||||
}
|
||||
|
||||
// ----- 仪表盘统计 -----
|
||||
|
||||
// DashboardStats 仪表盘聚合指标。
|
||||
type DashboardStats struct {
|
||||
ProductCount int64 `json:"product_count"`
|
||||
MerchantCount int64 `json:"merchant_count"`
|
||||
OrderCount int64 `json:"order_count"`
|
||||
TotalSales float64 `json:"total_sales"`
|
||||
TotalFees float64 `json:"total_fees"`
|
||||
PendingOrderCount int64 `json:"pending_order_count"`
|
||||
}
|
||||
|
||||
// Dashboard 汇总商户维度的商品、商户、订单与金额统计。
|
||||
func (s *FulfillmentService) Dashboard(merchantID uint, isPlatformAdmin bool) (*DashboardStats, error) {
|
||||
stats := &DashboardStats{}
|
||||
s.db.Model(&model.MerchantProduct{}).Where("merchant_id = ?", merchantID).Count(&stats.ProductCount)
|
||||
if isPlatformAdmin {
|
||||
s.db.Model(&model.Merchant{}).Where("status = ?", model.MerchantStatusActive).Count(&stats.MerchantCount)
|
||||
} else {
|
||||
stats.MerchantCount = 1
|
||||
}
|
||||
s.db.Model(&model.FulfillmentOrder{}).Where("merchant_id = ?", merchantID).Count(&stats.OrderCount)
|
||||
s.db.Model(&model.FulfillmentOrder{}).
|
||||
Where("merchant_id = ? AND fulfillment_status = ?", merchantID, model.FulfillmentStatusPending).
|
||||
Count(&stats.PendingOrderCount)
|
||||
s.db.Model(&model.FulfillmentOrder{}).
|
||||
Where("merchant_id = ?", merchantID).
|
||||
Where("payment_status = ?", model.PaymentStatusPaid).
|
||||
Select("COALESCE(SUM(amount),0) / 100.0").Scan(&stats.TotalSales)
|
||||
s.db.Model(&model.FulfillmentOrder{}).
|
||||
Where("merchant_id = ?", merchantID).
|
||||
Where("payment_status = ?", model.PaymentStatusPaid).
|
||||
Select("COALESCE(SUM(service_fee_amount),0) / 100.0").Scan(&stats.TotalFees)
|
||||
return stats, nil
|
||||
}
|
||||
|
||||
// ----- 上游 SourceOpen 接口(基于 FulfillmentOrder)-----
|
||||
|
||||
// OpenOrderQuery 开放接口订单查询结果。
|
||||
type OpenOrderQuery struct {
|
||||
OrderNo string `json:"order_no"`
|
||||
Status string `json:"status"`
|
||||
CanShip bool `json:"can_ship"`
|
||||
CannotShipReason string `json:"cannot_ship_reason,omitempty"`
|
||||
Product *OpenOrderProduct `json:"product,omitempty"`
|
||||
BuyerName string `json:"buyer_name"`
|
||||
Amount float64 `json:"amount"`
|
||||
ProviderOrderNo string `json:"provider_order_no,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
ShippedAt *time.Time `json:"shipped_at"`
|
||||
ShipFailReason string `json:"ship_fail_reason,omitempty"`
|
||||
GameChannel string `json:"game_channel,omitempty"`
|
||||
GameUID string `json:"game_uid,omitempty"`
|
||||
RoleName string `json:"role_name,omitempty"`
|
||||
PayScore int `json:"pay_score,omitempty"`
|
||||
}
|
||||
|
||||
// OpenOrderProduct 开放接口返回的商品快照。
|
||||
type OpenOrderProduct struct {
|
||||
Name string `json:"name"`
|
||||
SKU string `json:"sku"`
|
||||
Game string `json:"game"`
|
||||
}
|
||||
|
||||
// ShipNotifyInput 上游发货结果推送。
|
||||
type ShipNotifyInput struct {
|
||||
OrderNo string
|
||||
ShipStatus string // success / failed / processing
|
||||
ProviderOrderNo string
|
||||
ShippedAt *time.Time
|
||||
FailReason string
|
||||
RawPayload string
|
||||
GameChannel *string
|
||||
GameUID *string
|
||||
RoleName *string
|
||||
PayScore *int
|
||||
}
|
||||
|
||||
// ShipNotifyResult 上游推送处理结果。
|
||||
type ShipNotifyResult struct {
|
||||
OrderNo string `json:"order_no"`
|
||||
Status string `json:"status"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
// GetByOrderNo 按订单号查询(不限定商户,供上游 SourceOpen 使用)。
|
||||
func (s *FulfillmentService) GetByOrderNo(orderNo string) (*model.FulfillmentOrder, error) {
|
||||
var order model.FulfillmentOrder
|
||||
err := s.db.Preload("MerchantProduct.Product").Where("order_no = ?", orderNo).First(&order).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, errors.New("订单不存在")
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &order, nil
|
||||
}
|
||||
|
||||
// QueryOpenOrder 供上游查询:商品信息 + 是否可发货。
|
||||
func (s *FulfillmentService) QueryOpenOrder(orderNo string) (*OpenOrderQuery, error) {
|
||||
if orderNo == "" {
|
||||
return nil, errors.New("订单号不能为空")
|
||||
}
|
||||
order, err := s.GetByOrderNo(orderNo)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
canShip, reason := CanFulfill(order)
|
||||
out := &OpenOrderQuery{
|
||||
OrderNo: order.OrderNo,
|
||||
Status: fulfillmentStatusToLegacyStatus(order.FulfillmentStatus),
|
||||
CanShip: canShip,
|
||||
CannotShipReason: reason,
|
||||
BuyerName: order.BuyerReference,
|
||||
Amount: float64(order.Amount) / 100.0,
|
||||
ProviderOrderNo: order.ProviderOrderNo,
|
||||
CreatedAt: order.CreatedAt,
|
||||
ShippedAt: order.DeliveredAt,
|
||||
ShipFailReason: order.FailureReason,
|
||||
}
|
||||
if order.MerchantProduct != nil {
|
||||
game := ""
|
||||
if order.MerchantProduct.Product != nil {
|
||||
game = order.MerchantProduct.Product.Category
|
||||
}
|
||||
out.Product = &OpenOrderProduct{
|
||||
Name: order.ProductName,
|
||||
SKU: order.ProductSKU,
|
||||
Game: game,
|
||||
}
|
||||
}
|
||||
// 新模型无独立的游戏字段列,从 RequestData / ResultData JSON 中还原。
|
||||
extractGameFields(order.RequestData, out)
|
||||
extractGameFields(order.ResultData, out)
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// HandleShipNotify 处理上游发货结果推送(幂等),基于 FulfillmentOrder。
|
||||
func (s *FulfillmentService) HandleShipNotify(in ShipNotifyInput) (*ShipNotifyResult, error) {
|
||||
if in.OrderNo == "" {
|
||||
return nil, errors.New("订单号不能为空")
|
||||
}
|
||||
var nextStatus string
|
||||
switch in.ShipStatus {
|
||||
case "success":
|
||||
nextStatus = model.FulfillmentStatusSucceeded
|
||||
case "failed":
|
||||
nextStatus = model.FulfillmentStatusFailed
|
||||
case "processing":
|
||||
nextStatus = model.FulfillmentStatusProcessing
|
||||
default:
|
||||
return nil, errors.New("无效的 ship_status,仅支持 success/failed/processing")
|
||||
}
|
||||
|
||||
order, err := s.GetByOrderNo(in.OrderNo)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 已履约成功:success 推送幂等成功
|
||||
if order.FulfillmentStatus == model.FulfillmentStatusSucceeded && in.ShipStatus == "success" {
|
||||
_ = s.writeShipNotifyAudit(order, in, order.FulfillmentStatus, "订单已履约成功,幂等忽略")
|
||||
return &ShipNotifyResult{
|
||||
OrderNo: order.OrderNo,
|
||||
Status: fulfillmentStatusToLegacyStatus(order.FulfillmentStatus),
|
||||
Message: "订单已交付,幂等成功",
|
||||
}, nil
|
||||
}
|
||||
|
||||
// 已取消不允许再推
|
||||
if order.FulfillmentStatus == model.FulfillmentStatusCancelled {
|
||||
_ = s.writeShipNotifyAudit(order, in, order.FulfillmentStatus, "订单已取消,拒绝更新")
|
||||
return nil, errors.New("订单已取消,无法更新发货状态")
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
shippedAt := in.ShippedAt
|
||||
if shippedAt == nil && in.ShipStatus == "success" {
|
||||
shippedAt = &now
|
||||
}
|
||||
|
||||
updates := map[string]interface{}{
|
||||
"fulfillment_status": nextStatus,
|
||||
}
|
||||
var msg string
|
||||
switch in.ShipStatus {
|
||||
case "success":
|
||||
// 仅 pending / failed / processing 可转为 succeeded
|
||||
if order.FulfillmentStatus != model.FulfillmentStatusPending &&
|
||||
order.FulfillmentStatus != model.FulfillmentStatusFailed &&
|
||||
order.FulfillmentStatus != model.FulfillmentStatusProcessing {
|
||||
_ = s.writeShipNotifyAudit(order, in, order.FulfillmentStatus, "当前状态不允许标记发货成功")
|
||||
return nil, fmt.Errorf("当前状态 %s 不允许标记发货成功", order.FulfillmentStatus)
|
||||
}
|
||||
updates["delivered_at"] = shippedAt
|
||||
updates["failure_reason"] = ""
|
||||
if in.ProviderOrderNo != "" {
|
||||
updates["provider_order_no"] = in.ProviderOrderNo
|
||||
}
|
||||
msg = "发货成功,订单已交付"
|
||||
case "failed":
|
||||
if order.FulfillmentStatus == model.FulfillmentStatusSucceeded {
|
||||
_ = s.writeShipNotifyAudit(order, in, order.FulfillmentStatus, "订单已交付,忽略失败推送")
|
||||
return nil, errors.New("订单已交付,不能标记发货失败")
|
||||
}
|
||||
updates["failure_reason"] = in.FailReason
|
||||
if in.ProviderOrderNo != "" {
|
||||
updates["provider_order_no"] = in.ProviderOrderNo
|
||||
}
|
||||
msg = "已记录发货失败"
|
||||
case "processing":
|
||||
if order.FulfillmentStatus == model.FulfillmentStatusSucceeded {
|
||||
_ = s.writeShipNotifyAudit(order, in, order.FulfillmentStatus, "订单已交付,忽略发货中推送")
|
||||
return &ShipNotifyResult{
|
||||
OrderNo: order.OrderNo,
|
||||
Status: fulfillmentStatusToLegacyStatus(order.FulfillmentStatus),
|
||||
Message: "订单已交付,忽略 processing",
|
||||
}, nil
|
||||
}
|
||||
if order.FulfillmentStatus != model.FulfillmentStatusPending &&
|
||||
order.FulfillmentStatus != model.FulfillmentStatusFailed &&
|
||||
order.FulfillmentStatus != model.FulfillmentStatusProcessing {
|
||||
_ = s.writeShipNotifyAudit(order, in, order.FulfillmentStatus, "当前状态不允许进入发货中")
|
||||
return nil, fmt.Errorf("当前状态 %s 不允许进入发货中", order.FulfillmentStatus)
|
||||
}
|
||||
if in.ProviderOrderNo != "" {
|
||||
updates["provider_order_no"] = in.ProviderOrderNo
|
||||
}
|
||||
msg = "订单已标记为发货中"
|
||||
}
|
||||
|
||||
// 游戏相关字段与推送结果合并写入 ResultData,便于后续查询还原(新模型无独立列)。
|
||||
updates["result_data"] = buildShipNotifyResultData(order.ResultData, in, shippedAt)
|
||||
|
||||
if err := s.db.Model(&model.FulfillmentOrder{}).Where("id = ?", order.ID).Updates(updates).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_ = s.writeShipNotifyAudit(order, in, nextStatus, msg)
|
||||
|
||||
return &ShipNotifyResult{
|
||||
OrderNo: order.OrderNo,
|
||||
Status: fulfillmentStatusToLegacyStatus(nextStatus),
|
||||
Message: msg,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// writeShipNotifyAudit 将上游推送留痕写入 AuditLog(替代旧的 ShipLog 表)。
|
||||
func (s *FulfillmentService) writeShipNotifyAudit(order *model.FulfillmentOrder, in ShipNotifyInput, resultStatus, message string) error {
|
||||
metadata := map[string]interface{}{
|
||||
"ship_status": in.ShipStatus,
|
||||
"provider_order_no": in.ProviderOrderNo,
|
||||
"fail_reason": in.FailReason,
|
||||
"result_status": resultStatus,
|
||||
"message": message,
|
||||
"payload": in.RawPayload,
|
||||
}
|
||||
return writeAudit(s.db, &order.MerchantID, nil, nil, "ship.notify", "fulfillment_order", order.OrderNo, metadata)
|
||||
}
|
||||
|
||||
// buildShipNotifyResultData 把推送结果与游戏字段合并进 ResultData JSON。
|
||||
func buildShipNotifyResultData(existing string, in ShipNotifyInput, shippedAt *time.Time) string {
|
||||
m := map[string]interface{}{}
|
||||
if existing != "" && json.Valid([]byte(existing)) {
|
||||
_ = json.Unmarshal([]byte(existing), &m)
|
||||
}
|
||||
m["ship_status"] = in.ShipStatus
|
||||
if in.ProviderOrderNo != "" {
|
||||
m["provider_order_no"] = in.ProviderOrderNo
|
||||
}
|
||||
if in.FailReason != "" {
|
||||
m["fail_reason"] = in.FailReason
|
||||
}
|
||||
if shippedAt != nil {
|
||||
m["shipped_at"] = shippedAt.Format(time.RFC3339)
|
||||
}
|
||||
if in.GameChannel != nil {
|
||||
m["game_channel"] = *in.GameChannel
|
||||
}
|
||||
if in.GameUID != nil {
|
||||
m["game_uid"] = *in.GameUID
|
||||
}
|
||||
if in.RoleName != nil {
|
||||
m["role_name"] = *in.RoleName
|
||||
}
|
||||
if in.PayScore != nil {
|
||||
m["pay_score"] = *in.PayScore
|
||||
}
|
||||
raw, err := json.Marshal(m)
|
||||
if err != nil {
|
||||
return existing
|
||||
}
|
||||
return string(raw)
|
||||
}
|
||||
|
||||
// extractGameFields 从 JSON 文本中还原游戏相关字段(仅填充当前为空的字段)。
|
||||
func extractGameFields(raw string, out *OpenOrderQuery) {
|
||||
if raw == "" || !json.Valid([]byte(raw)) {
|
||||
return
|
||||
}
|
||||
var m map[string]interface{}
|
||||
if err := json.Unmarshal([]byte(raw), &m); err != nil {
|
||||
return
|
||||
}
|
||||
if out.GameChannel == "" {
|
||||
if v, ok := m["game_channel"].(string); ok {
|
||||
out.GameChannel = v
|
||||
}
|
||||
}
|
||||
if out.GameUID == "" {
|
||||
if v, ok := m["game_uid"].(string); ok {
|
||||
out.GameUID = v
|
||||
}
|
||||
}
|
||||
if out.RoleName == "" {
|
||||
if v, ok := m["role_name"].(string); ok {
|
||||
out.RoleName = v
|
||||
}
|
||||
}
|
||||
if out.PayScore == 0 {
|
||||
if v, ok := toInt(m["pay_score"]); ok {
|
||||
out.PayScore = v
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func toInt(v interface{}) (int, bool) {
|
||||
switch n := v.(type) {
|
||||
case float64:
|
||||
return int(n), true
|
||||
case int:
|
||||
return n, true
|
||||
case int64:
|
||||
return int(n), true
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
|
||||
// fulfillmentStatusToLegacyStatus 将新的履约状态映射为上游兼容的旧状态字符串。
|
||||
func fulfillmentStatusToLegacyStatus(status string) string {
|
||||
switch status {
|
||||
case model.FulfillmentStatusPending:
|
||||
return "paid"
|
||||
case model.FulfillmentStatusProcessing:
|
||||
return "delivering"
|
||||
case model.FulfillmentStatusSucceeded:
|
||||
return "delivered"
|
||||
case model.FulfillmentStatusFailed:
|
||||
return "ship_failed"
|
||||
case model.FulfillmentStatusCancelled:
|
||||
return "cancelled"
|
||||
default:
|
||||
return status
|
||||
}
|
||||
}
|
||||
|
||||
@@ -117,6 +117,80 @@ func TestFulfillmentCreateOrderDebitsWalletAndIsIdempotent(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestFulfillmentCreateOrderAppliesMerchantFeeRate(t *testing.T) {
|
||||
db := newServiceTestDB(t)
|
||||
merchantID, product := seedFulfillmentMerchant(t, db, "merchant-fee-rate", 1000, 5, 200)
|
||||
if err := db.Model(&model.Merchant{}).Where("id = ?", merchantID).Updates(map[string]interface{}{
|
||||
"fee_type": model.FeeTypeRate,
|
||||
"fee_rate_bp": int64(250),
|
||||
}).Error; err != nil {
|
||||
t.Fatalf("update merchant fee: %v", err)
|
||||
}
|
||||
svc := NewFulfillmentService(db, nil)
|
||||
|
||||
created, err := svc.CreateOrder(CreateFulfillmentOrderInput{
|
||||
MerchantID: merchantID,
|
||||
APIClientID: 21,
|
||||
ClientOrderNo: "client-fee-rate",
|
||||
SKU: product.SKU,
|
||||
Quantity: 2,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("create order: %v", err)
|
||||
}
|
||||
// baseAmount = 200 * 2 = 400; rate 250BP = 400 * 250 / 10000 = 10; total = 410
|
||||
if created.Order.BaseAmount != 400 || created.Order.ServiceFeeAmount != 10 || created.Order.Amount != 410 {
|
||||
t.Fatalf("unexpected rate fee snapshot: %+v", created.Order)
|
||||
}
|
||||
if created.Order.FeeType != model.FeeTypeRate || created.Order.FeeRateBP != 250 {
|
||||
t.Fatalf("unexpected rate fee config snapshot: %+v", created.Order)
|
||||
}
|
||||
var wallet model.WalletAccount
|
||||
if err := db.Where("merchant_id = ?", merchantID).First(&wallet).Error; err != nil {
|
||||
t.Fatalf("query wallet: %v", err)
|
||||
}
|
||||
if wallet.AvailableBalance != 590 {
|
||||
t.Fatalf("wallet should debit total amount, got %d", wallet.AvailableBalance)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFulfillmentCreateOrderAppliesMerchantFeeFixed(t *testing.T) {
|
||||
db := newServiceTestDB(t)
|
||||
merchantID, product := seedFulfillmentMerchant(t, db, "merchant-fee-fixed", 1000, 5, 200)
|
||||
if err := db.Model(&model.Merchant{}).Where("id = ?", merchantID).Updates(map[string]interface{}{
|
||||
"fee_type": model.FeeTypeFixed,
|
||||
"fee_fixed_amount": int64(30),
|
||||
}).Error; err != nil {
|
||||
t.Fatalf("update merchant fee: %v", err)
|
||||
}
|
||||
svc := NewFulfillmentService(db, nil)
|
||||
|
||||
created, err := svc.CreateOrder(CreateFulfillmentOrderInput{
|
||||
MerchantID: merchantID,
|
||||
APIClientID: 22,
|
||||
ClientOrderNo: "client-fee-fixed",
|
||||
SKU: product.SKU,
|
||||
Quantity: 2,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("create order: %v", err)
|
||||
}
|
||||
// baseAmount = 400; fixed fee = 30; total = 430
|
||||
if created.Order.BaseAmount != 400 || created.Order.ServiceFeeAmount != 30 || created.Order.Amount != 430 {
|
||||
t.Fatalf("unexpected fixed fee snapshot: %+v", created.Order)
|
||||
}
|
||||
if created.Order.FeeType != model.FeeTypeFixed || created.Order.FeeFixedAmount != 30 {
|
||||
t.Fatalf("unexpected fixed fee config snapshot: %+v", created.Order)
|
||||
}
|
||||
var wallet model.WalletAccount
|
||||
if err := db.Where("merchant_id = ?", merchantID).First(&wallet).Error; err != nil {
|
||||
t.Fatalf("query wallet: %v", err)
|
||||
}
|
||||
if wallet.AvailableBalance != 570 {
|
||||
t.Fatalf("wallet should debit total amount, got %d", wallet.AvailableBalance)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFulfillmentCancelRefundsOnceAndRestoresStock(t *testing.T) {
|
||||
db := newServiceTestDB(t)
|
||||
merchantID, product := seedFulfillmentMerchant(t, db, "merchant-b", 1000, 2, 300)
|
||||
|
||||
@@ -1,58 +1,11 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"affiliate_dash/internal/model"
|
||||
)
|
||||
|
||||
func TestLegacyOrderCreateRejectsDistributorOutsideMerchant(t *testing.T) {
|
||||
db := newServiceTestDB(t)
|
||||
merchant := model.Merchant{Code: "legacy-merchant", Name: "旧后台商户", Status: model.MerchantStatusActive}
|
||||
if err := db.Create(&merchant).Error; err != nil {
|
||||
t.Fatalf("create merchant: %v", err)
|
||||
}
|
||||
inside := model.User{Username: "inside", PasswordHash: "hash", Role: model.RoleDistributor, Status: 1, InviteCode: "INSIDE"}
|
||||
outside := model.User{Username: "outside", PasswordHash: "hash", Role: model.RoleDistributor, Status: 1, InviteCode: "OUTSIDE"}
|
||||
if err := db.Create(&inside).Error; err != nil {
|
||||
t.Fatalf("create inside user: %v", err)
|
||||
}
|
||||
if err := db.Create(&outside).Error; err != nil {
|
||||
t.Fatalf("create outside user: %v", err)
|
||||
}
|
||||
if err := db.Create(&model.MerchantMember{
|
||||
MerchantID: merchant.ID,
|
||||
UserID: inside.ID,
|
||||
Role: model.MemberRoleOperator,
|
||||
Status: 1,
|
||||
}).Error; err != nil {
|
||||
t.Fatalf("create member: %v", err)
|
||||
}
|
||||
skin := model.Skin{
|
||||
MerchantID: merchant.ID,
|
||||
Name: "旧皮肤",
|
||||
SKU: "legacy-skin",
|
||||
Price: 10,
|
||||
Stock: -1,
|
||||
Status: 1,
|
||||
}
|
||||
if err := db.Create(&skin).Error; err != nil {
|
||||
t.Fatalf("create skin: %v", err)
|
||||
}
|
||||
|
||||
_, err := NewOrderService(db).Create(CreateOrderInput{
|
||||
MerchantID: merchant.ID,
|
||||
SkinID: skin.ID,
|
||||
DistributorID: outside.ID,
|
||||
BuyerName: "买家",
|
||||
Status: model.OrderStatusPaid,
|
||||
})
|
||||
if err == nil || !strings.Contains(err.Error(), "不属于当前商户") {
|
||||
t.Fatalf("expected tenant boundary error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserListFiltersByMerchantMembership(t *testing.T) {
|
||||
db := newServiceTestDB(t)
|
||||
merchantA := model.Merchant{Code: "user-merchant-a", Name: "商户 A", Status: model.MerchantStatusActive}
|
||||
@@ -63,8 +16,8 @@ func TestUserListFiltersByMerchantMembership(t *testing.T) {
|
||||
if err := db.Create(&merchantB).Error; err != nil {
|
||||
t.Fatalf("create merchant b: %v", err)
|
||||
}
|
||||
userA := model.User{Username: "user-a", PasswordHash: "hash", Role: model.RoleDistributor, Status: 1, InviteCode: "USERA"}
|
||||
userB := model.User{Username: "user-b", PasswordHash: "hash", Role: model.RoleDistributor, Status: 1, InviteCode: "USERB"}
|
||||
userA := model.User{Username: "user-a", PasswordHash: "hash", Role: model.RoleMerchant, Status: 1}
|
||||
userB := model.User{Username: "user-b", PasswordHash: "hash", Role: model.RoleMerchant, Status: 1}
|
||||
if err := db.Create(&userA).Error; err != nil {
|
||||
t.Fatalf("create user a: %v", err)
|
||||
}
|
||||
@@ -83,7 +36,7 @@ func TestUserListFiltersByMerchantMembership(t *testing.T) {
|
||||
MerchantID: merchantA.ID,
|
||||
Page: 1,
|
||||
Size: 20,
|
||||
Role: model.RoleDistributor,
|
||||
Role: model.RoleMerchant,
|
||||
Status: &active,
|
||||
})
|
||||
if err != nil {
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
|
||||
"affiliate_dash/internal/model"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
@@ -28,38 +29,60 @@ func NewMerchantService(db *gorm.DB, codec *SecretCodec, tenant *TenantService)
|
||||
}
|
||||
|
||||
type CreateMerchantInput struct {
|
||||
Code string
|
||||
Name string
|
||||
ContactName string
|
||||
ContactInfo string
|
||||
OwnerUserID uint
|
||||
Code string
|
||||
Name string
|
||||
ContactName string
|
||||
ContactInfo string
|
||||
OwnerUserID uint
|
||||
OwnerUsername string
|
||||
OwnerPassword string
|
||||
OwnerNickname string
|
||||
Features string
|
||||
FeeType string
|
||||
FeeRateBP int64
|
||||
FeeFixedAmount int64
|
||||
}
|
||||
|
||||
func (s *MerchantService) CreateMerchant(in CreateMerchantInput, actorUserID uint) (*model.Merchant, error) {
|
||||
in.Code = strings.ToLower(strings.TrimSpace(in.Code))
|
||||
in.Name = strings.TrimSpace(in.Name)
|
||||
in.Features = NormalizeMerchantFeatures(in.Features)
|
||||
if !merchantCodePattern.MatchString(in.Code) {
|
||||
return nil, errors.New("商户编码需为 3-64 位小写字母、数字或连字符")
|
||||
}
|
||||
if in.Name == "" {
|
||||
return nil, errors.New("商户名称不能为空")
|
||||
}
|
||||
if in.OwnerUserID == 0 {
|
||||
if in.OwnerUserID == 0 && strings.TrimSpace(in.OwnerUsername) == "" {
|
||||
return nil, errors.New("商户负责人不能为空")
|
||||
}
|
||||
if in.FeeRateBP < 0 || in.FeeRateBP > 10000 {
|
||||
return nil, errors.New("手续费比例需在 0-10000 BP 之间")
|
||||
}
|
||||
if in.FeeFixedAmount < 0 {
|
||||
return nil, errors.New("固定手续费不能小于零")
|
||||
}
|
||||
feeType := in.FeeType
|
||||
if feeType == "" {
|
||||
feeType = model.FeeTypeRate
|
||||
}
|
||||
if feeType != model.FeeTypeRate && feeType != model.FeeTypeFixed {
|
||||
return nil, errors.New("手续费类型仅支持 rate 或 fixed")
|
||||
}
|
||||
merchant := &model.Merchant{
|
||||
Code: in.Code,
|
||||
Name: in.Name,
|
||||
Status: model.MerchantStatusActive,
|
||||
ContactName: in.ContactName,
|
||||
ContactInfo: in.ContactInfo,
|
||||
Code: in.Code,
|
||||
Name: in.Name,
|
||||
Status: model.MerchantStatusActive,
|
||||
ContactName: in.ContactName,
|
||||
ContactInfo: in.ContactInfo,
|
||||
Features: in.Features,
|
||||
FeeType: feeType,
|
||||
FeeRateBP: in.FeeRateBP,
|
||||
FeeFixedAmount: in.FeeFixedAmount,
|
||||
}
|
||||
err := s.db.Transaction(func(tx *gorm.DB) error {
|
||||
var owner model.User
|
||||
if err := tx.First(&owner, in.OwnerUserID).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return errors.New("商户负责人不存在")
|
||||
}
|
||||
owner, err := s.resolveOrCreateOwner(tx, in)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if owner.Status != 1 {
|
||||
@@ -88,6 +111,121 @@ func (s *MerchantService) CreateMerchant(in CreateMerchantInput, actorUserID uin
|
||||
return merchant, nil
|
||||
}
|
||||
|
||||
func (s *MerchantService) resolveOrCreateOwner(tx *gorm.DB, in CreateMerchantInput) (*model.User, error) {
|
||||
if in.OwnerUserID != 0 {
|
||||
var owner model.User
|
||||
if err := tx.First(&owner, in.OwnerUserID).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, errors.New("商户负责人不存在")
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &owner, nil
|
||||
}
|
||||
username := strings.TrimSpace(in.OwnerUsername)
|
||||
password := strings.TrimSpace(in.OwnerPassword)
|
||||
nickname := strings.TrimSpace(in.OwnerNickname)
|
||||
if username == "" || len(username) < 3 {
|
||||
return nil, errors.New("负责人用户名至少 3 位")
|
||||
}
|
||||
if len(password) < 6 {
|
||||
return nil, errors.New("负责人密码至少 6 位")
|
||||
}
|
||||
if nickname == "" {
|
||||
nickname = username
|
||||
}
|
||||
var count int64
|
||||
if err := tx.Model(&model.User{}).Where("username = ?", username).Count(&count).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if count > 0 {
|
||||
return nil, errors.New("负责人用户名已存在")
|
||||
}
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
owner := &model.User{
|
||||
Username: username,
|
||||
PasswordHash: string(hash),
|
||||
Nickname: nickname,
|
||||
Role: model.RoleMerchant,
|
||||
Status: 1,
|
||||
}
|
||||
if err := tx.Create(owner).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return owner, nil
|
||||
}
|
||||
|
||||
type UpdateMerchantSettingsInput struct {
|
||||
Name *string
|
||||
Status *string
|
||||
ContactName *string
|
||||
ContactInfo *string
|
||||
Features *string
|
||||
FeeType *string
|
||||
FeeRateBP *int64
|
||||
FeeFixedAmount *int64
|
||||
}
|
||||
|
||||
func (s *MerchantService) UpdateMerchantSettings(merchantID uint, in UpdateMerchantSettingsInput, actorUserID uint) error {
|
||||
updates := map[string]interface{}{}
|
||||
if in.Name != nil {
|
||||
name := strings.TrimSpace(*in.Name)
|
||||
if name == "" {
|
||||
return errors.New("商户名称不能为空")
|
||||
}
|
||||
updates["name"] = name
|
||||
}
|
||||
if in.Status != nil {
|
||||
if *in.Status != model.MerchantStatusActive && *in.Status != model.MerchantStatusDisabled {
|
||||
return errors.New("无效的商户状态")
|
||||
}
|
||||
updates["status"] = *in.Status
|
||||
}
|
||||
if in.ContactName != nil {
|
||||
updates["contact_name"] = strings.TrimSpace(*in.ContactName)
|
||||
}
|
||||
if in.ContactInfo != nil {
|
||||
updates["contact_info"] = strings.TrimSpace(*in.ContactInfo)
|
||||
}
|
||||
if in.Features != nil {
|
||||
updates["features"] = NormalizeMerchantFeatures(*in.Features)
|
||||
}
|
||||
if in.FeeRateBP != nil {
|
||||
if *in.FeeRateBP < 0 || *in.FeeRateBP > 10000 {
|
||||
return errors.New("手续费比例需在 0-10000 BP 之间")
|
||||
}
|
||||
updates["fee_rate_bp"] = *in.FeeRateBP
|
||||
}
|
||||
if in.FeeFixedAmount != nil {
|
||||
if *in.FeeFixedAmount < 0 {
|
||||
return errors.New("固定手续费不能小于零")
|
||||
}
|
||||
updates["fee_fixed_amount"] = *in.FeeFixedAmount
|
||||
}
|
||||
if in.FeeType != nil {
|
||||
if *in.FeeType != model.FeeTypeRate && *in.FeeType != model.FeeTypeFixed {
|
||||
return errors.New("手续费类型仅支持 rate 或 fixed")
|
||||
}
|
||||
updates["fee_type"] = *in.FeeType
|
||||
}
|
||||
if len(updates) == 0 {
|
||||
return errors.New("没有可更新字段")
|
||||
}
|
||||
return s.db.Transaction(func(tx *gorm.DB) error {
|
||||
result := tx.Model(&model.Merchant{}).Where("id = ?", merchantID).Updates(updates)
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
}
|
||||
if result.RowsAffected == 0 {
|
||||
return errors.New("商户不存在")
|
||||
}
|
||||
return writeAudit(tx, &merchantID, &actorUserID, nil, "merchant.settings.update", "merchant", fmt.Sprint(merchantID), updates)
|
||||
})
|
||||
}
|
||||
|
||||
func (s *MerchantService) ListMerchants(page, size int) ([]model.Merchant, int64, error) {
|
||||
page, size = normalizePage(page, size)
|
||||
tx := s.db.Model(&model.Merchant{})
|
||||
|
||||
@@ -1,480 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"affiliate_dash/internal/model"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type OrderService struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewOrderService(db *gorm.DB) *OrderService {
|
||||
return &OrderService{db: db}
|
||||
}
|
||||
|
||||
type OrderListQuery struct {
|
||||
MerchantID uint
|
||||
Page int
|
||||
Size int
|
||||
Status string
|
||||
DistributorID *uint
|
||||
}
|
||||
|
||||
type CreateOrderInput struct {
|
||||
MerchantID uint
|
||||
SkinID uint
|
||||
DistributorID uint
|
||||
BuyerName string
|
||||
Remark string
|
||||
// Status 可选:pending(默认)/ paid(联调测试可直接创建可发货订单)
|
||||
Status string
|
||||
}
|
||||
|
||||
func (s *OrderService) List(q OrderListQuery) ([]model.Order, int64, error) {
|
||||
if q.Page < 1 {
|
||||
q.Page = 1
|
||||
}
|
||||
if q.Size < 1 || q.Size > 100 {
|
||||
q.Size = 20
|
||||
}
|
||||
tx := s.db.Model(&model.Order{})
|
||||
if q.MerchantID != 0 {
|
||||
tx = tx.Where("merchant_id = ?", q.MerchantID)
|
||||
}
|
||||
if q.Status != "" {
|
||||
tx = tx.Where("status = ?", q.Status)
|
||||
}
|
||||
if q.DistributorID != nil {
|
||||
tx = tx.Where("distributor_id = ?", *q.DistributorID)
|
||||
}
|
||||
var total int64
|
||||
if err := tx.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
var list []model.Order
|
||||
err := tx.Preload("Skin").Preload("Distributor").
|
||||
Order("id DESC").
|
||||
Offset((q.Page - 1) * q.Size).Limit(q.Size).
|
||||
Find(&list).Error
|
||||
return list, total, err
|
||||
}
|
||||
|
||||
func (s *OrderService) Create(in CreateOrderInput) (*model.Order, error) {
|
||||
var skin model.Skin
|
||||
if in.MerchantID == 0 {
|
||||
return nil, errors.New("商户不能为空")
|
||||
}
|
||||
if err := s.db.Where("id = ? AND merchant_id = ?", in.SkinID, in.MerchantID).First(&skin).Error; err != nil {
|
||||
return nil, errors.New("皮肤不存在")
|
||||
}
|
||||
if skin.Status != 1 {
|
||||
return nil, errors.New("皮肤已下架")
|
||||
}
|
||||
if skin.Stock == 0 {
|
||||
return nil, errors.New("库存不足")
|
||||
}
|
||||
var memberCount int64
|
||||
if err := s.db.Model(&model.MerchantMember{}).
|
||||
Where("merchant_id = ? AND user_id = ? AND status = ?", in.MerchantID, in.DistributorID, 1).
|
||||
Count(&memberCount).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if memberCount == 0 {
|
||||
return nil, errors.New("分销商不属于当前商户")
|
||||
}
|
||||
|
||||
status := model.OrderStatusPending
|
||||
switch in.Status {
|
||||
case model.OrderStatusPending,
|
||||
model.OrderStatusPaid,
|
||||
model.OrderStatusDelivering,
|
||||
model.OrderStatusDelivered,
|
||||
model.OrderStatusShipFailed,
|
||||
model.OrderStatusCancelled:
|
||||
status = in.Status
|
||||
case "":
|
||||
// default pending
|
||||
default:
|
||||
return nil, errors.New("无效的订单状态")
|
||||
}
|
||||
|
||||
order := &model.Order{
|
||||
MerchantID: in.MerchantID,
|
||||
OrderNo: generateOrderNo(),
|
||||
SkinID: in.SkinID,
|
||||
DistributorID: in.DistributorID,
|
||||
BuyerName: in.BuyerName,
|
||||
Amount: skin.Price,
|
||||
CommissionAmt: skin.Price * skin.Commission,
|
||||
Status: status,
|
||||
Remark: in.Remark,
|
||||
}
|
||||
|
||||
err := s.db.Transaction(func(tx *gorm.DB) error {
|
||||
if skin.Stock > 0 {
|
||||
res := tx.Model(&model.Skin{}).
|
||||
Where("id = ? AND stock > 0", skin.ID).
|
||||
Update("stock", gorm.Expr("stock - 1"))
|
||||
if res.Error != nil {
|
||||
return res.Error
|
||||
}
|
||||
if res.RowsAffected == 0 {
|
||||
return errors.New("库存不足")
|
||||
}
|
||||
}
|
||||
return tx.Create(order).Error
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// 带回商品信息,方便前端展示 sku / 订单号联调
|
||||
_ = s.db.Preload("Skin").First(order, order.ID).Error
|
||||
return order, nil
|
||||
}
|
||||
|
||||
func (s *OrderService) UpdateStatus(merchantID, id uint, status string) error {
|
||||
allowed := map[string]bool{
|
||||
model.OrderStatusPending: true,
|
||||
model.OrderStatusPaid: true,
|
||||
model.OrderStatusDelivering: true,
|
||||
model.OrderStatusDelivered: true,
|
||||
model.OrderStatusShipFailed: true,
|
||||
model.OrderStatusCancelled: true,
|
||||
}
|
||||
if !allowed[status] {
|
||||
return errors.New("无效的订单状态")
|
||||
}
|
||||
res := s.db.Model(&model.Order{}).Where("id = ? AND merchant_id = ?", id, merchantID).Update("status", status)
|
||||
if res.Error != nil {
|
||||
return res.Error
|
||||
}
|
||||
if res.RowsAffected == 0 {
|
||||
return errors.New("订单不存在")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ----- 开放接口:皮肤源头对接 -----
|
||||
|
||||
// OpenOrderQuery 开放接口订单查询结果
|
||||
type OpenOrderQuery struct {
|
||||
OrderNo string `json:"order_no"`
|
||||
Status string `json:"status"`
|
||||
CanShip bool `json:"can_ship"`
|
||||
CannotShipReason string `json:"cannot_ship_reason,omitempty"`
|
||||
Product *OpenOrderProduct `json:"product,omitempty"`
|
||||
BuyerName string `json:"buyer_name"`
|
||||
Amount float64 `json:"amount"`
|
||||
ProviderOrderNo string `json:"provider_order_no,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
ShippedAt *time.Time `json:"shipped_at"`
|
||||
ShipFailReason string `json:"ship_fail_reason,omitempty"`
|
||||
GameChannel string `json:"game_channel,omitempty"`
|
||||
GameUID string `json:"game_uid,omitempty"`
|
||||
RoleName string `json:"role_name,omitempty"`
|
||||
PayScore int `json:"pay_score,omitempty"`
|
||||
}
|
||||
|
||||
type OpenOrderProduct struct {
|
||||
Name string `json:"name"`
|
||||
SKU string `json:"sku"`
|
||||
Game string `json:"game"`
|
||||
}
|
||||
|
||||
// ShipNotifyInput 上游发货结果推送
|
||||
type ShipNotifyInput struct {
|
||||
OrderNo string
|
||||
ShipStatus string // success / failed / processing
|
||||
ProviderOrderNo string
|
||||
ShippedAt *time.Time
|
||||
FailReason string
|
||||
RawPayload string
|
||||
GameChannel *string
|
||||
GameUID *string
|
||||
RoleName *string
|
||||
PayScore *int
|
||||
}
|
||||
|
||||
type ShipNotifyResult struct {
|
||||
OrderNo string `json:"order_no"`
|
||||
Status string `json:"status"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
func (s *OrderService) GetByOrderNo(orderNo string) (*model.Order, error) {
|
||||
var order model.Order
|
||||
err := s.db.Preload("Skin").Where("order_no = ?", orderNo).First(&order).Error
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, errors.New("订单不存在")
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &order, nil
|
||||
}
|
||||
|
||||
// QueryOpenOrder 供上游查询:商品信息 + 是否可发货
|
||||
func (s *OrderService) QueryOpenOrder(orderNo string) (*OpenOrderQuery, error) {
|
||||
if orderNo == "" {
|
||||
return nil, errors.New("订单号不能为空")
|
||||
}
|
||||
order, err := s.GetByOrderNo(orderNo)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
canShip, reason := evaluateCanShip(order)
|
||||
out := &OpenOrderQuery{
|
||||
OrderNo: order.OrderNo,
|
||||
Status: order.Status,
|
||||
CanShip: canShip,
|
||||
CannotShipReason: reason,
|
||||
BuyerName: order.BuyerName,
|
||||
Amount: order.Amount,
|
||||
ProviderOrderNo: order.ProviderOrderNo,
|
||||
CreatedAt: order.CreatedAt,
|
||||
ShippedAt: order.ShippedAt,
|
||||
ShipFailReason: order.ShipFailReason,
|
||||
GameChannel: order.GameChannel,
|
||||
GameUID: order.GameUID,
|
||||
RoleName: order.RoleName,
|
||||
PayScore: order.PayScore,
|
||||
}
|
||||
if order.Skin != nil {
|
||||
out.Product = &OpenOrderProduct{
|
||||
Name: order.Skin.Name,
|
||||
SKU: order.Skin.SKU,
|
||||
Game: order.Skin.Game,
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func evaluateCanShip(order *model.Order) (bool, string) {
|
||||
switch order.Status {
|
||||
case model.OrderStatusPaid, model.OrderStatusShipFailed:
|
||||
return true, ""
|
||||
case model.OrderStatusPending:
|
||||
return false, "订单未支付"
|
||||
case model.OrderStatusDelivering:
|
||||
return false, "订单发货中"
|
||||
case model.OrderStatusDelivered:
|
||||
return false, "订单已发货完成"
|
||||
case model.OrderStatusCancelled:
|
||||
return false, "订单已取消"
|
||||
default:
|
||||
return false, "当前状态不可发货: " + order.Status
|
||||
}
|
||||
}
|
||||
|
||||
// HandleShipNotify 处理上游发货结果推送(幂等)
|
||||
func (s *OrderService) HandleShipNotify(in ShipNotifyInput) (*ShipNotifyResult, error) {
|
||||
if in.OrderNo == "" {
|
||||
return nil, errors.New("订单号不能为空")
|
||||
}
|
||||
switch in.ShipStatus {
|
||||
case model.ShipNotifySuccess, model.ShipNotifyFailed, model.ShipNotifyProcessing:
|
||||
default:
|
||||
return nil, errors.New("无效的 ship_status,仅支持 success/failed/processing")
|
||||
}
|
||||
|
||||
order, err := s.GetByOrderNo(in.OrderNo)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 已交付:success 推送幂等成功
|
||||
if order.Status == model.OrderStatusDelivered && in.ShipStatus == model.ShipNotifySuccess {
|
||||
_ = s.appendShipLog(order, in, order.Status, "订单已是已交付状态,幂等忽略")
|
||||
return &ShipNotifyResult{
|
||||
OrderNo: order.OrderNo,
|
||||
Status: order.Status,
|
||||
Message: "订单已交付,幂等成功",
|
||||
}, nil
|
||||
}
|
||||
|
||||
// 已取消不允许再推成功
|
||||
if order.Status == model.OrderStatusCancelled {
|
||||
_ = s.appendShipLog(order, in, order.Status, "订单已取消,拒绝更新")
|
||||
return nil, errors.New("订单已取消,无法更新发货状态")
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
shippedAt := in.ShippedAt
|
||||
if shippedAt == nil && in.ShipStatus == model.ShipNotifySuccess {
|
||||
shippedAt = &now
|
||||
}
|
||||
|
||||
updates := map[string]interface{}{}
|
||||
var nextStatus string
|
||||
var msg string
|
||||
|
||||
switch in.ShipStatus {
|
||||
case model.ShipNotifySuccess:
|
||||
// 仅 paid / ship_failed / delivering 可转为 delivered
|
||||
if order.Status != model.OrderStatusPaid &&
|
||||
order.Status != model.OrderStatusShipFailed &&
|
||||
order.Status != model.OrderStatusDelivering {
|
||||
_ = s.appendShipLog(order, in, order.Status, "当前状态不允许标记发货成功")
|
||||
return nil, fmt.Errorf("当前状态 %s 不允许标记发货成功", order.Status)
|
||||
}
|
||||
nextStatus = model.OrderStatusDelivered
|
||||
updates["status"] = nextStatus
|
||||
updates["shipped_at"] = shippedAt
|
||||
updates["ship_fail_reason"] = ""
|
||||
if in.ProviderOrderNo != "" {
|
||||
updates["provider_order_no"] = in.ProviderOrderNo
|
||||
}
|
||||
msg = "发货成功,订单已交付"
|
||||
case model.ShipNotifyFailed:
|
||||
if order.Status == model.OrderStatusDelivered {
|
||||
_ = s.appendShipLog(order, in, order.Status, "订单已交付,忽略失败推送")
|
||||
return nil, errors.New("订单已交付,不能标记发货失败")
|
||||
}
|
||||
nextStatus = model.OrderStatusShipFailed
|
||||
updates["status"] = nextStatus
|
||||
updates["ship_fail_reason"] = in.FailReason
|
||||
if in.ProviderOrderNo != "" {
|
||||
updates["provider_order_no"] = in.ProviderOrderNo
|
||||
}
|
||||
msg = "已记录发货失败"
|
||||
case model.ShipNotifyProcessing:
|
||||
if order.Status == model.OrderStatusDelivered {
|
||||
_ = s.appendShipLog(order, in, order.Status, "订单已交付,忽略发货中推送")
|
||||
return &ShipNotifyResult{
|
||||
OrderNo: order.OrderNo,
|
||||
Status: order.Status,
|
||||
Message: "订单已交付,忽略 processing",
|
||||
}, nil
|
||||
}
|
||||
if order.Status != model.OrderStatusPaid &&
|
||||
order.Status != model.OrderStatusShipFailed &&
|
||||
order.Status != model.OrderStatusDelivering {
|
||||
_ = s.appendShipLog(order, in, order.Status, "当前状态不允许进入发货中")
|
||||
return nil, fmt.Errorf("当前状态 %s 不允许进入发货中", order.Status)
|
||||
}
|
||||
nextStatus = model.OrderStatusDelivering
|
||||
updates["status"] = nextStatus
|
||||
if in.ProviderOrderNo != "" {
|
||||
updates["provider_order_no"] = in.ProviderOrderNo
|
||||
}
|
||||
msg = "订单已标记为发货中"
|
||||
}
|
||||
|
||||
if in.GameChannel != nil {
|
||||
updates["game_channel"] = *in.GameChannel
|
||||
}
|
||||
if in.GameUID != nil {
|
||||
updates["game_uid"] = *in.GameUID
|
||||
}
|
||||
if in.RoleName != nil {
|
||||
updates["role_name"] = *in.RoleName
|
||||
}
|
||||
if in.PayScore != nil {
|
||||
updates["pay_score"] = *in.PayScore
|
||||
}
|
||||
|
||||
if err := s.db.Model(&model.Order{}).Where("id = ?", order.ID).Updates(updates).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_ = s.appendShipLog(order, in, nextStatus, msg)
|
||||
|
||||
return &ShipNotifyResult{
|
||||
OrderNo: order.OrderNo,
|
||||
Status: nextStatus,
|
||||
Message: msg,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *OrderService) appendShipLog(order *model.Order, in ShipNotifyInput, resultStatus, message string) error {
|
||||
payload := in.RawPayload
|
||||
if payload == "" {
|
||||
b, _ := json.Marshal(in)
|
||||
payload = string(b)
|
||||
}
|
||||
log := &model.ShipLog{
|
||||
MerchantID: order.MerchantID,
|
||||
OrderNo: order.OrderNo,
|
||||
OrderID: order.ID,
|
||||
ShipStatus: in.ShipStatus,
|
||||
ProviderOrderNo: in.ProviderOrderNo,
|
||||
FailReason: in.FailReason,
|
||||
Payload: payload,
|
||||
ResultStatus: resultStatus,
|
||||
Message: message,
|
||||
}
|
||||
return s.db.Create(log).Error
|
||||
}
|
||||
|
||||
type ShipLogListQuery struct {
|
||||
MerchantID uint
|
||||
Page int
|
||||
Size int
|
||||
OrderNo string
|
||||
ShipStatus string
|
||||
}
|
||||
|
||||
func (s *OrderService) ListShipLogs(q ShipLogListQuery) ([]model.ShipLog, int64, error) {
|
||||
if q.Page < 1 {
|
||||
q.Page = 1
|
||||
}
|
||||
if q.Size < 1 || q.Size > 100 {
|
||||
q.Size = 20
|
||||
}
|
||||
tx := s.db.Model(&model.ShipLog{})
|
||||
if q.MerchantID != 0 {
|
||||
tx = tx.Where("merchant_id = ?", q.MerchantID)
|
||||
}
|
||||
if q.OrderNo != "" {
|
||||
tx = tx.Where("order_no LIKE ?", "%"+q.OrderNo+"%")
|
||||
}
|
||||
if q.ShipStatus != "" {
|
||||
tx = tx.Where("ship_status = ?", q.ShipStatus)
|
||||
}
|
||||
var total int64
|
||||
if err := tx.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
var list []model.ShipLog
|
||||
err := tx.Order("id DESC").Offset((q.Page - 1) * q.Size).Limit(q.Size).Find(&list).Error
|
||||
return list, total, err
|
||||
}
|
||||
|
||||
type DashboardStats struct {
|
||||
SkinCount int64 `json:"skin_count"`
|
||||
DistributorCount int64 `json:"distributor_count"`
|
||||
OrderCount int64 `json:"order_count"`
|
||||
TotalSales float64 `json:"total_sales"`
|
||||
TotalCommission float64 `json:"total_commission"`
|
||||
PendingOrderCount int64 `json:"pending_order_count"`
|
||||
}
|
||||
|
||||
func (s *OrderService) Dashboard(merchantID uint) (*DashboardStats, error) {
|
||||
stats := &DashboardStats{}
|
||||
s.db.Model(&model.Skin{}).Where("merchant_id = ?", merchantID).Count(&stats.SkinCount)
|
||||
s.db.Model(&model.User{}).
|
||||
Joins("JOIN merchant_members ON merchant_members.user_id = users.id").
|
||||
Where("merchant_members.merchant_id = ? AND users.role = ?", merchantID, model.RoleDistributor).
|
||||
Count(&stats.DistributorCount)
|
||||
s.db.Model(&model.Order{}).Where("merchant_id = ?", merchantID).Count(&stats.OrderCount)
|
||||
s.db.Model(&model.Order{}).Where("merchant_id = ? AND status = ?", merchantID, model.OrderStatusPending).Count(&stats.PendingOrderCount)
|
||||
s.db.Model(&model.Order{}).
|
||||
Where("merchant_id = ?", merchantID).
|
||||
Where("status IN ?", []string{model.OrderStatusPaid, model.OrderStatusDelivered}).
|
||||
Select("COALESCE(SUM(amount),0)").Scan(&stats.TotalSales)
|
||||
s.db.Model(&model.Order{}).
|
||||
Where("merchant_id = ?", merchantID).
|
||||
Where("status IN ?", []string{model.OrderStatusPaid, model.OrderStatusDelivered}).
|
||||
Select("COALESCE(SUM(commission_amt),0)").Scan(&stats.TotalCommission)
|
||||
return stats, nil
|
||||
}
|
||||
|
||||
func generateOrderNo() string {
|
||||
return fmt.Sprintf("O%s%04d", time.Now().Format("20060102150405"), time.Now().Nanosecond()%10000)
|
||||
}
|
||||
@@ -1,179 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"affiliate_dash/internal/model"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type SkinService struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewSkinService(db *gorm.DB) *SkinService {
|
||||
return &SkinService{db: db}
|
||||
}
|
||||
|
||||
type SkinListQuery struct {
|
||||
MerchantID uint
|
||||
Page int
|
||||
Size int
|
||||
Keyword string
|
||||
Game string
|
||||
Category string
|
||||
Status *int
|
||||
}
|
||||
|
||||
func (s *SkinService) List(q SkinListQuery) ([]model.Skin, int64, error) {
|
||||
if q.Page < 1 {
|
||||
q.Page = 1
|
||||
}
|
||||
if q.Size < 1 || q.Size > 100 {
|
||||
q.Size = 20
|
||||
}
|
||||
tx := s.db.Model(&model.Skin{})
|
||||
if q.MerchantID != 0 {
|
||||
tx = tx.Where("merchant_id = ?", q.MerchantID)
|
||||
}
|
||||
if q.Keyword != "" {
|
||||
like := "%" + q.Keyword + "%"
|
||||
tx = tx.Where("name LIKE ? OR sku LIKE ?", like, like)
|
||||
}
|
||||
if q.Game != "" {
|
||||
tx = tx.Where("game = ?", q.Game)
|
||||
}
|
||||
if q.Category != "" {
|
||||
tx = tx.Where("category = ?", q.Category)
|
||||
}
|
||||
if q.Status != nil {
|
||||
tx = tx.Where("status = ?", *q.Status)
|
||||
}
|
||||
var total int64
|
||||
if err := tx.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
var list []model.Skin
|
||||
err := tx.Order("id DESC").Offset((q.Page - 1) * q.Size).Limit(q.Size).Find(&list).Error
|
||||
return list, total, err
|
||||
}
|
||||
|
||||
func (s *SkinService) Get(merchantID, id uint) (*model.Skin, error) {
|
||||
var skin model.Skin
|
||||
tx := s.db.Where("id = ?", id)
|
||||
if merchantID != 0 {
|
||||
tx = tx.Where("merchant_id = ?", merchantID)
|
||||
}
|
||||
if err := tx.First(&skin).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, errors.New("皮肤不存在")
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &skin, nil
|
||||
}
|
||||
|
||||
func (s *SkinService) Create(skin *model.Skin) error {
|
||||
return s.db.Create(skin).Error
|
||||
}
|
||||
|
||||
func (s *SkinService) Update(merchantID, id uint, updates map[string]interface{}) error {
|
||||
res := s.db.Model(&model.Skin{}).Where("id = ? AND merchant_id = ?", id, merchantID).Updates(updates)
|
||||
if res.Error != nil {
|
||||
return res.Error
|
||||
}
|
||||
if res.RowsAffected == 0 {
|
||||
return errors.New("皮肤不存在")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *SkinService) Delete(merchantID, id uint) error {
|
||||
res := s.db.Where("merchant_id = ?", merchantID).Delete(&model.Skin{}, id)
|
||||
if res.Error != nil {
|
||||
return res.Error
|
||||
}
|
||||
if res.RowsAffected == 0 {
|
||||
return errors.New("皮肤不存在")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SeedCatalog 按 sku 幂等导入商品目录(已存在则跳过)
|
||||
func (s *SkinService) SeedCatalog() error {
|
||||
var merchant model.Merchant
|
||||
if err := s.db.Where("code = ?", "self-operated").First(&merchant).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
// 清理早期无 sku 的演示数据,避免唯一索引冲突
|
||||
_ = s.db.Where("merchant_id = ? AND (sku = ? OR sku IS NULL)", merchant.ID, "").Delete(&model.Skin{}).Error
|
||||
|
||||
for _, item := range peaceEliteCatalog {
|
||||
var existing model.Skin
|
||||
err := s.db.Where("merchant_id = ? AND sku = ?", merchant.ID, item.SKU).First(&existing).Error
|
||||
if err == nil {
|
||||
// 已存在:仅同步默认佣金为 0(不改价格等业务字段)
|
||||
if existing.Commission != 0 {
|
||||
_ = s.db.Model(&existing).Update("commission", 0).Error
|
||||
}
|
||||
continue
|
||||
}
|
||||
if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return err
|
||||
}
|
||||
skin := model.Skin{
|
||||
MerchantID: merchant.ID,
|
||||
Name: item.Name,
|
||||
SKU: item.SKU,
|
||||
Game: "和平精英",
|
||||
Category: item.Category,
|
||||
Price: 0,
|
||||
CostPrice: 0,
|
||||
Commission: 0,
|
||||
Stock: -1,
|
||||
Status: 1,
|
||||
}
|
||||
if err := s.db.Create(&skin).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type catalogItem struct {
|
||||
Name string
|
||||
SKU string
|
||||
Category string
|
||||
}
|
||||
|
||||
// 和平精英商品目录(中文名保持原样,英文名为固定 sku)
|
||||
var peaceEliteCatalog = []catalogItem{
|
||||
{Name: "套装-Alan Walker", SKU: "suit_alan_walker", Category: "套装"},
|
||||
{Name: "套装-暗影哥特", SKU: "suit_shadow_gothic", Category: "套装"},
|
||||
{Name: "黑色高级特训官上衣", SKU: "top_black_elite_trainer", Category: "上衣"},
|
||||
{Name: "M416-仓鼠灰灰", SKU: "m416_hamster_gray", Category: "枪械"},
|
||||
{Name: "萌熊伴侣背包", SKU: "bag_cute_bear", Category: "背包"},
|
||||
{Name: "套装-双彩绵绵", SKU: "suit_dual_fluffy", Category: "套装"},
|
||||
{Name: "套装-糯粉咩咩", SKU: "suit_pink_sheep", Category: "套装"},
|
||||
{Name: "套装-恋恋初桃", SKU: "suit_first_peach", Category: "套装"},
|
||||
{Name: "套装-浪漫天命", SKU: "suit_romantic_destiny", Category: "套装"},
|
||||
{Name: "西部牛仔大礼包", SKU: "pack_western_cowboy", Category: "礼包"},
|
||||
{Name: "烟雾弹-糯粉咩咩", SKU: "smoke_pink_sheep", Category: "投掷物"},
|
||||
{Name: "破片手榴弹-糯粉咩咩", SKU: "frag_pink_sheep", Category: "投掷物"},
|
||||
{Name: "套装-仓鼠灰灰", SKU: "suit_hamster_gray", Category: "套装"},
|
||||
{Name: "套装-萌熊伴侣", SKU: "suit_cute_bear", Category: "套装"},
|
||||
{Name: "糯粉咩咩背包", SKU: "bag_pink_sheep", Category: "背包"},
|
||||
{Name: "糯粉咩咩头盔", SKU: "helmet_pink_sheep", Category: "头盔"},
|
||||
{Name: "仓鼠灰灰背包", SKU: "bag_hamster_gray", Category: "背包"},
|
||||
{Name: "仓鼠灰灰头盔", SKU: "helmet_hamster_gray", Category: "头盔"},
|
||||
{Name: "套装-西部谜踪", SKU: "suit_western_mystery", Category: "套装"},
|
||||
{Name: "国宝胖达头盔", SKU: "helmet_panda_treasure", Category: "头盔"},
|
||||
{Name: "套装-胖达圆圆", SKU: "suit_panda_round", Category: "套装"},
|
||||
{Name: "套装-胖达团团", SKU: "suit_panda_tuan", Category: "套装"},
|
||||
{Name: "熔岩游骑兵礼包", SKU: "pack_lava_ranger", Category: "礼包"},
|
||||
{Name: "套装-狂沙舞者", SKU: "suit_sand_dancer", Category: "套装"},
|
||||
{Name: "星际漫游服装礼包", SKU: "pack_star_roam_outfit", Category: "礼包"},
|
||||
{Name: "星际漫游枪械礼包", SKU: "pack_star_roam_weapon", Category: "礼包"},
|
||||
{Name: "套装-绵云熊熊", SKU: "suit_cloud_bear", Category: "套装"},
|
||||
}
|
||||
@@ -118,3 +118,46 @@ func HasAnyScope(scopes string, wanted ...string) bool {
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func NormalizeMerchantFeatures(features string) string {
|
||||
set := ParseScopes(features)
|
||||
if len(set) == 0 {
|
||||
set = ParseScopes(model.DefaultMerchantFeatures)
|
||||
}
|
||||
valid := map[string]struct{}{
|
||||
model.MerchantFeatureProducts: {},
|
||||
model.MerchantFeatureOrders: {},
|
||||
model.MerchantFeatureWallet: {},
|
||||
model.MerchantFeatureAPI: {},
|
||||
model.MerchantFeatureCallbacks: {},
|
||||
}
|
||||
ordered := []string{
|
||||
model.MerchantFeatureProducts,
|
||||
model.MerchantFeatureOrders,
|
||||
model.MerchantFeatureWallet,
|
||||
model.MerchantFeatureAPI,
|
||||
model.MerchantFeatureCallbacks,
|
||||
}
|
||||
out := make([]string, 0, len(ordered))
|
||||
for _, feature := range ordered {
|
||||
if _, ok := set[feature]; ok {
|
||||
if _, allowed := valid[feature]; allowed {
|
||||
out = append(out, feature)
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(out) == 0 {
|
||||
return model.DefaultMerchantFeatures
|
||||
}
|
||||
return strings.Join(out, ",")
|
||||
}
|
||||
|
||||
func MerchantHasFeature(features string, wanted ...string) bool {
|
||||
set := ParseScopes(features)
|
||||
for _, feature := range wanted {
|
||||
if _, ok := set[feature]; ok {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -58,14 +58,17 @@ func (s *UserService) List(q UserListQuery) ([]model.User, int64, error) {
|
||||
return list, total, err
|
||||
}
|
||||
|
||||
func (s *UserService) Create(username, password, nickname, role string, parentID *uint, merchantID uint) (*model.User, error) {
|
||||
func (s *UserService) Create(username, password, nickname, role string, merchantID uint) (*model.User, error) {
|
||||
var count int64
|
||||
s.db.Model(&model.User{}).Where("username = ?", username).Count(&count)
|
||||
if count > 0 {
|
||||
return nil, errors.New("用户名已存在")
|
||||
}
|
||||
if role == "" {
|
||||
role = model.RoleDistributor
|
||||
role = model.RoleMerchant
|
||||
}
|
||||
if role != model.RoleAdmin && role != model.RoleMerchant {
|
||||
return nil, errors.New("无效的账号角色")
|
||||
}
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
@@ -77,8 +80,6 @@ func (s *UserService) Create(username, password, nickname, role string, parentID
|
||||
Nickname: nickname,
|
||||
Role: role,
|
||||
Status: 1,
|
||||
InviteCode: generateInviteCode(),
|
||||
ParentID: parentID,
|
||||
}
|
||||
if user.Nickname == "" {
|
||||
user.Nickname = username
|
||||
|
||||
Reference in New Issue
Block a user