fix(listing): 外部上传归属分销站点
This commit is contained in:
@@ -277,9 +277,10 @@ type ExternalUploadInventory struct {
|
||||
}
|
||||
|
||||
type ExternalUploadMeta struct {
|
||||
IP string
|
||||
UserAgent string
|
||||
RawPayload []byte
|
||||
IP string
|
||||
UserAgent string
|
||||
RawPayload []byte
|
||||
DistributionSiteCode string
|
||||
}
|
||||
|
||||
type ExternalUploadResult struct {
|
||||
|
||||
@@ -56,12 +56,13 @@ func (s *Service) ImportExternalUpload(ctx context.Context, req ExternalUploadRe
|
||||
}
|
||||
parsedPayload, _ := json.Marshal(item)
|
||||
dto, err := s.repo.CreateFromExternalUpload(ctx, externalUploadCreate{
|
||||
UploaderName: uploaderName,
|
||||
SourceChannel: sourceChannel,
|
||||
ClientUploadTime: clientUploadTime,
|
||||
ClientIP: meta.IP,
|
||||
RawPayload: meta.RawPayload,
|
||||
ParsedPayload: parsedPayload,
|
||||
UploaderName: uploaderName,
|
||||
SourceChannel: sourceChannel,
|
||||
DistributionSiteCode: meta.DistributionSiteCode,
|
||||
ClientUploadTime: clientUploadTime,
|
||||
ClientIP: meta.IP,
|
||||
RawPayload: meta.RawPayload,
|
||||
ParsedPayload: parsedPayload,
|
||||
}, createReq)
|
||||
if err != nil {
|
||||
if len(items) == 1 {
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/sitecode"
|
||||
"hfb_sys/backend/pkg/response"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -39,9 +40,10 @@ func (h *Handler) ImportExternalUpload(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
result, err := h.service.ImportExternalUpload(c.Request.Context(), req, ExternalUploadMeta{
|
||||
IP: c.ClientIP(),
|
||||
UserAgent: c.GetHeader("User-Agent"),
|
||||
RawPayload: raw,
|
||||
IP: c.ClientIP(),
|
||||
UserAgent: c.GetHeader("User-Agent"),
|
||||
RawPayload: raw,
|
||||
DistributionSiteCode: sitecode.FromRequest(c),
|
||||
})
|
||||
if err != nil {
|
||||
writeListingError(c, err)
|
||||
|
||||
@@ -1,17 +1,81 @@
|
||||
package listing
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/model"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func TestImportExternalUploadUsesDistributionSiteHeader(t *testing.T) {
|
||||
db := database.NewTestDB()
|
||||
if err := database.MigrateListingLifecycleTestSchema(db); err != nil {
|
||||
t.Fatalf("failed to migrate test db: %v", err)
|
||||
}
|
||||
if err := database.AutoMigrateIfMissing(db, &model.AdminUser{}, &model.ListingUpload{}, &model.DistributionSite{}); err != nil {
|
||||
t.Fatalf("failed to migrate upload tables: %v", err)
|
||||
}
|
||||
site := model.DistributionSite{
|
||||
SiteCode: "gz_dist",
|
||||
SiteName: "天域商行",
|
||||
Domain: "tysh.hao858.com",
|
||||
Status: "active",
|
||||
DisplayAccountEnabled: true,
|
||||
}
|
||||
if err := db.Create(&site).Error; err != nil {
|
||||
t.Fatalf("failed to create distribution site: %v", err)
|
||||
}
|
||||
if err := db.Create(&model.AdminUser{
|
||||
Username: "tianyu-http",
|
||||
PasswordHash: "hash",
|
||||
Nickname: "天域上传客服",
|
||||
Status: "active",
|
||||
}).Error; err != nil {
|
||||
t.Fatalf("failed to create admin: %v", err)
|
||||
}
|
||||
|
||||
body, err := json.Marshal(ExternalUploadRequest{
|
||||
UploaderName: "tianyu-http",
|
||||
SourceChannel: "淘宝",
|
||||
Data: json.RawMessage(validExternalUploadDataJSON()),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("marshal request: %v", err)
|
||||
}
|
||||
|
||||
gin.SetMode(gin.TestMode)
|
||||
engine := gin.New()
|
||||
handler := NewHandler(NewService(NewRepository(db, nil), nil), nil)
|
||||
engine.POST("/api/open/listing-uploads", handler.ImportExternalUpload)
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/open/listing-uploads", bytes.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("X-Distribution-Site-Code", "gz_dist")
|
||||
recorder := httptest.NewRecorder()
|
||||
engine.ServeHTTP(recorder, req)
|
||||
|
||||
if recorder.Code != http.StatusCreated {
|
||||
t.Fatalf("status = %d, body = %s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
var stored model.RentalListing
|
||||
if err := db.Order("id DESC").First(&stored).Error; err != nil {
|
||||
t.Fatalf("failed to find listing: %v", err)
|
||||
}
|
||||
if stored.DistributionSiteID == nil || *stored.DistributionSiteID != site.ID {
|
||||
t.Fatalf("distribution_site_id = %v, want %d", stored.DistributionSiteID, site.ID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyExternalUploadSignature(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
body := []byte(`{"data":{"loginMethod":"QQ账号密码"}}`)
|
||||
|
||||
@@ -164,17 +164,22 @@ func (r *Repository) ensureCreateCooldown(tx *gorm.DB, ownerID uint64, cooldown
|
||||
}
|
||||
|
||||
type externalUploadCreate struct {
|
||||
UploaderName string
|
||||
SourceChannel string
|
||||
ClientUploadTime *time.Time
|
||||
ClientIP string
|
||||
RawPayload []byte
|
||||
ParsedPayload []byte
|
||||
UploaderName string
|
||||
SourceChannel string
|
||||
DistributionSiteCode string
|
||||
ClientUploadTime *time.Time
|
||||
ClientIP string
|
||||
RawPayload []byte
|
||||
ParsedPayload []byte
|
||||
}
|
||||
|
||||
func (r *Repository) CreateFromExternalUpload(ctx context.Context, upload externalUploadCreate, req CreateRequest) (*ListingDTO, error) {
|
||||
var dto *ListingDTO
|
||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
site, distributionSiteID, err := resolveExternalUploadSite(tx, upload.DistributionSiteCode)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
listingNo, err := r.nextListingNo(tx, time.Now())
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -183,7 +188,7 @@ func (r *Repository) CreateFromExternalUpload(ctx context.Context, upload extern
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
owner, err := r.ensureUploadOwnerUser(tx, admin)
|
||||
owner, err := r.ensureUploadOwnerUser(tx, admin, distributionSiteID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -214,22 +219,33 @@ func (r *Repository) CreateFromExternalUpload(ctx context.Context, upload extern
|
||||
}
|
||||
priceCent := normalizedListingPriceCent(req)
|
||||
listing := model.RentalListing{
|
||||
SourceTenantID: owner.TenantID,
|
||||
ListingNo: listingNo,
|
||||
AccountID: account.ID,
|
||||
OwnerID: owner.ID,
|
||||
PriceCent: priceCent,
|
||||
DepositAmountCent: req.DepositAmountCent,
|
||||
Status: "draft",
|
||||
ReviewStatus: "pending",
|
||||
HandoffMode: "platform",
|
||||
SettlementMode: "platform_managed",
|
||||
ManagedAdminID: &admin.ID,
|
||||
SourceChannel: upload.SourceChannel,
|
||||
SourceTenantID: owner.TenantID,
|
||||
ListingNo: listingNo,
|
||||
AccountID: account.ID,
|
||||
OwnerID: owner.ID,
|
||||
PriceCent: priceCent,
|
||||
DepositAmountCent: req.DepositAmountCent,
|
||||
Status: "draft",
|
||||
ReviewStatus: "pending",
|
||||
HandoffMode: "platform",
|
||||
SettlementMode: "platform_managed",
|
||||
ManagedAdminID: &admin.ID,
|
||||
DistributionSiteID: distributionSiteID,
|
||||
SourceChannel: upload.SourceChannel,
|
||||
}
|
||||
if err := tx.Create(&listing).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if distributionSiteID != nil {
|
||||
if err := tx.Create(&model.DistributionSiteAccount{
|
||||
SiteID: *distributionSiteID,
|
||||
AccountID: account.ID,
|
||||
ListingID: listing.ID,
|
||||
DisplayStatus: "enabled",
|
||||
}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
var conversationID uint64
|
||||
if r.chatCreator != nil {
|
||||
convID, err := r.chatCreator.EnsureListingConversation(tx, listing, admin.ID)
|
||||
@@ -257,12 +273,32 @@ func (r *Repository) CreateFromExternalUpload(ctx context.Context, upload extern
|
||||
return err
|
||||
}
|
||||
dto = toDTO(account, listing)
|
||||
if distributionSiteID != nil {
|
||||
dto.DistributionSiteID = distributionSiteID
|
||||
dto.DistributionSiteCode = site.SiteCode
|
||||
dto.DistributionSiteName = site.SiteName
|
||||
}
|
||||
dto.ListingGroupConversationID = conversationID
|
||||
return nil
|
||||
})
|
||||
return dto, err
|
||||
}
|
||||
|
||||
func resolveExternalUploadSite(tx *gorm.DB, siteCode string) (*model.DistributionSite, *uint64, error) {
|
||||
siteCode = strings.TrimSpace(siteCode)
|
||||
if siteCode == "" {
|
||||
return nil, nil, nil
|
||||
}
|
||||
var site model.DistributionSite
|
||||
if err := tx.Where("site_code = ? AND status = ?", siteCode, "active").First(&site).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil, ErrDistributionSiteInvalid
|
||||
}
|
||||
return nil, nil, err
|
||||
}
|
||||
return &site, &site.ID, nil
|
||||
}
|
||||
|
||||
func (r *Repository) Update(ctx context.Context, ownerID uint64, listingID uint64, req UpdateRequest, reviewRequired bool) (*ListingDTO, error) {
|
||||
var dto *ListingDTO
|
||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
@@ -383,7 +419,7 @@ func (r *Repository) findActiveUploadAdmin(tx *gorm.DB, uploaderName string) (*m
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Repository) ensureUploadOwnerUser(tx *gorm.DB, admin *model.AdminUser) (*model.User, error) {
|
||||
func (r *Repository) ensureUploadOwnerUser(tx *gorm.DB, admin *model.AdminUser, distributionSiteID *uint64) (*model.User, error) {
|
||||
phone := fmt.Sprintf("admin:%d", admin.ID)
|
||||
nickname := strings.TrimSpace(admin.Nickname)
|
||||
if nickname == "" {
|
||||
@@ -391,7 +427,11 @@ func (r *Repository) ensureUploadOwnerUser(tx *gorm.DB, admin *model.AdminUser)
|
||||
}
|
||||
var user model.User
|
||||
tenantID := userTenantID(tx.Statement.Context, tx, 0)
|
||||
userQuery := tx.Where("phone = ?", phone)
|
||||
siteID := uint64(0)
|
||||
if distributionSiteID != nil {
|
||||
siteID = *distributionSiteID
|
||||
}
|
||||
userQuery := tx.Where("phone = ? AND distribution_site_id = ?", phone, siteID)
|
||||
if tenantID > 0 {
|
||||
userQuery = userQuery.Where("tenant_id = ?", tenantID)
|
||||
}
|
||||
@@ -414,13 +454,14 @@ func (r *Repository) ensureUploadOwnerUser(tx *gorm.DB, admin *model.AdminUser)
|
||||
return nil, err
|
||||
}
|
||||
user = model.User{
|
||||
TenantID: tenantID,
|
||||
Phone: phone,
|
||||
Nickname: nickname,
|
||||
RealnameStatus: "verified",
|
||||
RiskStatus: "normal",
|
||||
CreditScore: 100,
|
||||
Status: "active",
|
||||
TenantID: tenantID,
|
||||
DistributionSiteID: siteID,
|
||||
Phone: phone,
|
||||
Nickname: nickname,
|
||||
RealnameStatus: "verified",
|
||||
RiskStatus: "normal",
|
||||
CreditScore: 100,
|
||||
Status: "active",
|
||||
}
|
||||
if err := tx.Create(&user).Error; err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -426,6 +426,79 @@ func TestImportExternalUploadStoresSourceChannel(t *testing.T) {
|
||||
if upload.SourceChannel != "淘宝" {
|
||||
t.Fatalf("source channel = %q, want 淘宝", upload.SourceChannel)
|
||||
}
|
||||
var listing model.RentalListing
|
||||
if err := db.First(&listing, resp.ListingID).Error; err != nil {
|
||||
t.Fatalf("failed to find listing: %v", err)
|
||||
}
|
||||
if listing.DistributionSiteID != nil {
|
||||
t.Fatalf("main-site upload distribution_site_id = %v, want nil", listing.DistributionSiteID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestImportExternalUploadStoresDistributionSite(t *testing.T) {
|
||||
db := database.NewTestDB()
|
||||
if err := database.MigrateListingLifecycleTestSchema(db); err != nil {
|
||||
t.Fatalf("failed to migrate test db: %v", err)
|
||||
}
|
||||
if err := database.AutoMigrateIfMissing(db, &model.AdminUser{}, &model.ListingUpload{}, &model.DistributionSite{}); err != nil {
|
||||
t.Fatalf("failed to migrate upload tables: %v", err)
|
||||
}
|
||||
site := model.DistributionSite{
|
||||
SiteCode: "gz_dist",
|
||||
SiteName: "天域商行",
|
||||
Domain: "tysh.hao858.com",
|
||||
Status: "active",
|
||||
DisplayAccountEnabled: true,
|
||||
}
|
||||
if err := db.Create(&site).Error; err != nil {
|
||||
t.Fatalf("failed to create distribution site: %v", err)
|
||||
}
|
||||
admin := model.AdminUser{
|
||||
Username: "tianyu-cs",
|
||||
PasswordHash: "hash",
|
||||
Nickname: "天域客服",
|
||||
Status: "active",
|
||||
}
|
||||
if err := db.Create(&admin).Error; err != nil {
|
||||
t.Fatalf("failed to create admin: %v", err)
|
||||
}
|
||||
|
||||
service := NewService(NewRepository(db, nil), nil)
|
||||
resp, err := service.ImportExternalUpload(t.Context(), ExternalUploadRequest{
|
||||
UploaderName: "tianyu-cs",
|
||||
SourceChannel: "微信",
|
||||
Data: json.RawMessage(validExternalUploadDataJSON()),
|
||||
}, ExternalUploadMeta{DistributionSiteCode: "gz_dist"})
|
||||
if err != nil {
|
||||
t.Fatalf("ImportExternalUpload() error = %v", err)
|
||||
}
|
||||
|
||||
var listing model.RentalListing
|
||||
if err := db.First(&listing, resp.ListingID).Error; err != nil {
|
||||
t.Fatalf("failed to find listing: %v", err)
|
||||
}
|
||||
if listing.DistributionSiteID == nil || *listing.DistributionSiteID != site.ID {
|
||||
t.Fatalf("distribution_site_id = %v, want %d", listing.DistributionSiteID, site.ID)
|
||||
}
|
||||
if listing.SourceChannel != "微信" {
|
||||
t.Fatalf("source channel = %q, want 微信", listing.SourceChannel)
|
||||
}
|
||||
|
||||
var owner model.User
|
||||
if err := db.First(&owner, listing.OwnerID).Error; err != nil {
|
||||
t.Fatalf("failed to find upload owner: %v", err)
|
||||
}
|
||||
if owner.DistributionSiteID != site.ID {
|
||||
t.Fatalf("owner distribution_site_id = %d, want %d", owner.DistributionSiteID, site.ID)
|
||||
}
|
||||
|
||||
var shelf model.DistributionSiteAccount
|
||||
if err := db.Where("site_id = ? AND listing_id = ?", site.ID, listing.ID).First(&shelf).Error; err != nil {
|
||||
t.Fatalf("failed to find distribution shelf: %v", err)
|
||||
}
|
||||
if shelf.DisplayStatus != "enabled" {
|
||||
t.Fatalf("shelf display status = %q, want enabled", shelf.DisplayStatus)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListPendingReviewIncludesSourceChannel(t *testing.T) {
|
||||
|
||||
+1
-1
@@ -86,7 +86,7 @@ API 规划以 [项目计划](project-plan.md) 第 10 章为准。
|
||||
|
||||
说明:`POST /api/listings` 和 `PUT /api/listings/{id}` 支持 `screenshot_urls` 数组,用于保存号主上传的账号资产截图地址。`GET /api/admin/listings` 支持按 `owner_id`、`status`、`review_status` 和 `limit` 查询商品。`GET /api/admin/wallet/ledger` 支持按 `user_id`、`order_id`、`biz_type` 和 `limit` 查询最近资金流水。`GET /api/admin/audit-logs` 支持按 `actor_id`、`action`、`biz_type` 和 `limit` 查询最近审计日志。`/api/admin/*` 当前已使用独立后台登录,后续接入 RBAC 和 Casbin 权限后再按角色收紧访问控制。
|
||||
|
||||
开放上传说明:`POST /api/open/listing-uploads` 不需要登录鉴权,用于接收外部软件上传的账号资料。请求体包含 `uploadTime`、`uploaderName` 和 `data`,默认按单条账号对象处理,也兼容少量数组。后端会按 `uploaderName` 优先匹配 `admin_users.username`,未匹配时再匹配唯一 `nickname`,只使用 `status = active` 的后台用户;匹配成功后自动创建/复用对应的客服代发布普通用户,生成 `draft` + `pending` 的待审核商品,并使用 `/api/listings/default-upload-screenshot` 作为默认账号截图。上传原始内容和转换结果记录在 `listing_uploads` 表中。
|
||||
开放上传说明:`POST /api/open/listing-uploads` 不需要登录鉴权,用于接收外部软件上传的账号资料。请求体包含 `uploadTime`、`uploaderName` 和 `data`,默认按单条账号对象处理,也兼容少量数组。后端会按 `uploaderName` 优先匹配 `admin_users.username`,未匹配时再匹配唯一 `nickname`,只使用 `status = active` 的后台用户;匹配成功后自动创建/复用对应的客服代发布普通用户,生成 `draft` + `pending` 的待审核商品,并使用 `/api/listings/default-upload-screenshot` 作为默认账号截图。上传原始内容和转换结果记录在 `listing_uploads` 表中。请求可通过分销站域名或 `X-Distribution-Site-Code` 头指定历史分销站点;指定成功后,上传用户、商品和站点货架会一并归属该分销站,天域商行使用 `gz_dist`。
|
||||
|
||||
文件上传说明:`POST /api/files/upload` 使用 `multipart/form-data`,文件字段名为 `file`,可选 `scene` 为 `listing`、`handoff`、`dispute`、`realname`、`avatar`;当前允许 10MB 内的 JPG、PNG、WebP 和 PDF。返回的 `url` 为后端代理访问地址。后台查看私有文件使用 `GET /api/admin/files/object?key=...`。
|
||||
|
||||
|
||||
Reference in New Issue
Block a user