Compare commits
6
Commits
97948e2ca6
...
3ec7febb8c
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3ec7febb8c | ||
|
|
7640dd43ac | ||
|
|
663d7e1e9f | ||
|
|
04c3369e6d | ||
|
|
e692790aa7 | ||
|
|
8c12d1d448 |
+4
-7
@@ -4,14 +4,11 @@ FRONTEND_PORT=15173
|
||||
# Caddy 对外端口:生产部署需域名绑定 80/443;本机与其他站点共存时可覆盖
|
||||
# HTTP_PORT=80
|
||||
# HTTPS_PORT=443
|
||||
# JWT_SECRET 用于签发后台登录 Token;泄露 = 任何人都能伪造管理员身份。
|
||||
# 生成方式:openssl rand -hex 48
|
||||
# JWT_SECRET 应用主密钥(用于签发后台登录 Token 与敏感数据加密)。
|
||||
# 生成方式:openssl rand -hex 32
|
||||
JWT_SECRET=your_very_secure_jwt_secret_here_change_me_in_production
|
||||
# DATA_ENCRYPTION_KEY 用于加密落库的 API Client / 回调密钥,必须与 JWT_SECRET 独立,
|
||||
# 留空会回退到 JWT_SECRET(启动时会打印安全告警)。生成方式:openssl rand -hex 32
|
||||
# 更换该密钥会导致存量密文无法解密,需先执行:go run ./cmd/reencrypt_secrets
|
||||
# 详见 docs/密钥轮换说明.md
|
||||
DATA_ENCRYPTION_KEY=your_32_plus_char_data_encryption_key_change_me
|
||||
# DATA_ENCRYPTION_KEY 可选,未设置时默认由 JWT_SECRET 派生(推荐保持单主密钥极简架构)。
|
||||
# DATA_ENCRYPTION_KEY=
|
||||
# 仅用于空数据库的首次启动;已有管理员账号时不会被覆盖。
|
||||
POSTGRES_USER=affiliate
|
||||
POSTGRES_PASSWORD=affiliate_dev_password
|
||||
|
||||
@@ -101,8 +101,8 @@ make docker-down # 停止并移除
|
||||
| `PORT` | 后端端口 | `18080` |
|
||||
| `FRONTEND_PORT` | 前端开发端口 | `15173` |
|
||||
| `HTTP_PORT` / `HTTPS_PORT` | Caddy 对外 HTTP/HTTPS 端口 | `80` / `443` |
|
||||
| `JWT_SECRET` | JWT 签名密钥 | 开发默认值 |
|
||||
| `DATA_ENCRYPTION_KEY` | 加密落库的 API/回调密钥;留空会回退到 `JWT_SECRET` 并在启动日志告警 | 回退到 `JWT_SECRET` |
|
||||
| `JWT_SECRET` | 应用主密钥(JWT 签名与敏感数据加密共用) | 开发默认值 |
|
||||
| `DATA_ENCRYPTION_KEY` | 敏感数据加密独立密钥(可选;未设置时默认由 `JWT_SECRET` 派生) | 回退到 `JWT_SECRET` |
|
||||
| `DATABASE_URL` | PostgreSQL 连接串 | 本地开发默认值 |
|
||||
| `DOCKER_DATABASE_URL` | Docker 后端容器内 PostgreSQL 连接串,通常无需设置 | Compose 内置默认值 |
|
||||
| `POSTGRES_PORT` | PostgreSQL 映射到宿主机的端口 | `15432` |
|
||||
@@ -120,9 +120,7 @@ make docker-down # 停止并移除
|
||||
| `FULFILLMENT_PROCESSING_TIMEOUT_MINUTES` | 发货中订单自动标记失败的超时分钟数,<=0 关闭 | `30` |
|
||||
| `FULFILLMENT_TIMEOUT_SCAN_INTERVAL_SECONDS` | 发货超时巡检间隔秒数 | `60` |
|
||||
|
||||
> **安全提示**:`JWT_SECRET` 与 `DATA_ENCRYPTION_KEY` 必须各自生成随机值(`openssl rand -hex 48` / `openssl rand -hex 32`),
|
||||
> 不能沿用 `.env.example` 中的示例值,也不能两者相同。服务启动时会自动体检并打印
|
||||
> `[CONFIG] 安全告警: ...`。轮换方法见 [`docs/密钥轮换说明.md`](docs/密钥轮换说明.md)。
|
||||
> **安全提示**:生产环境请将 `JWT_SECRET` 配置为随机值(如 `openssl rand -hex 32`),不要使用示例值。
|
||||
|
||||
## 开放接口(皮肤源头对接)
|
||||
|
||||
@@ -191,13 +189,29 @@ POST /api/open/v1/orders/ship-notify
|
||||
|
||||
管理员登录后可访问商品管理、订单管理、用户管理、发货日志等功能。后台默认地址 `/`。
|
||||
|
||||
### 订单管理有两个入口,不要混淆
|
||||
|
||||
平台管理员同时拥有「平台视角」与「商户视角」两套订单入口,它们的数据范围**不同**:
|
||||
|
||||
| 入口 | 接口 | 数据范围 | 是否受商户上下文影响 |
|
||||
|------|------|----------|----------------------|
|
||||
| 下游订单(全部商户) | `GET /api/platform/orders` | 全部下游商户 | 否 |
|
||||
| 发货订单(当前商户) | `GET /api/merchant/orders` | 仅当前商户 | 是,取决于 `X-Merchant-ID` |
|
||||
|
||||
首页 Dashboard 对管理员是**平台口径**(跨商户聚合)。如果只看「发货订单」,需要先知道
|
||||
自己当前处在哪个商户上下文里,否则会出现「首页 37 单、订单页 29 单」这种看起来像 bug 的差异——
|
||||
实际上订单页只显示了自营商户这一家。
|
||||
|
||||
商户上下文的来源是前端 `localStorage.merchant_id`,只会在「平台商户」页点「成员」时被写入。
|
||||
顶栏会常驻显示「当前商户:xxx」,点旁边的「退出商户视角」即可回到默认商户(自营商户)。
|
||||
需要看某个下游商户的订单时,用「下游订单」页的商户筛选即可,不必切换上下文。
|
||||
|
||||
## 目录结构
|
||||
|
||||
```
|
||||
├── backend/
|
||||
│ ├── cmd/
|
||||
│ │ ├── server/ # 服务入口
|
||||
│ │ ├── reencrypt_secrets/ # 密钥轮换:重加密落库密文
|
||||
│ │ ├── cache_images/ # 商品图本地缓存工具
|
||||
│ │ └── sync_product_images/ # 商品图同步工具
|
||||
│ └── internal/
|
||||
|
||||
@@ -1,91 +0,0 @@
|
||||
// Command reencrypt_secrets 在轮换 DATA_ENCRYPTION_KEY 时,
|
||||
// 把存量以密文落库的 API Client / 回调密钥从旧密钥重新加密为新密钥。
|
||||
//
|
||||
// 典型用法:
|
||||
//
|
||||
// OLD_DATA_ENCRYPTION_KEY=<旧密钥> go run ./cmd/reencrypt_secrets # 预演
|
||||
// OLD_DATA_ENCRYPTION_KEY=<旧密钥> go run ./cmd/reencrypt_secrets -apply # 真正写库
|
||||
//
|
||||
// 详见 docs/密钥轮换说明.md
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
|
||||
"affiliate_dash/internal/config"
|
||||
"affiliate_dash/internal/service"
|
||||
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
)
|
||||
|
||||
func main() {
|
||||
apply := flag.Bool("apply", false, "真正写库;不加该参数时只做预演(dry-run),不修改任何数据")
|
||||
flag.Parse()
|
||||
|
||||
cfg := config.Load()
|
||||
|
||||
newKey := cfg.DataEncryptionKey
|
||||
// 兼容两种历史配置:显式配置过 DATA_ENCRYPTION_KEY,或曾经回退到 JWT_SECRET。
|
||||
oldKey := os.Getenv("OLD_DATA_ENCRYPTION_KEY")
|
||||
if oldKey == "" {
|
||||
oldKey = os.Getenv("OLD_JWT_SECRET")
|
||||
}
|
||||
|
||||
if oldKey == "" {
|
||||
log.Fatal("缺少旧密钥:请用 OLD_DATA_ENCRYPTION_KEY(或旧 JWT_SECRET)环境变量提供轮换前的密钥")
|
||||
}
|
||||
if oldKey == newKey {
|
||||
log.Fatal("新旧密钥相同,无需轮换")
|
||||
}
|
||||
|
||||
oldCodec, err := service.NewSecretCodec(oldKey)
|
||||
if err != nil {
|
||||
log.Fatalf("初始化旧密钥编解码器失败: %v", err)
|
||||
}
|
||||
newCodec, err := service.NewSecretCodec(newKey)
|
||||
if err != nil {
|
||||
log.Fatalf("初始化新密钥编解码器失败: %v", err)
|
||||
}
|
||||
|
||||
db, err := gorm.Open(postgres.Open(cfg.DatabaseURL), &gorm.Config{
|
||||
Logger: logger.Default.LogMode(logger.Silent),
|
||||
})
|
||||
if err != nil {
|
||||
log.Fatalf("连接数据库失败: %v", err)
|
||||
}
|
||||
sqlDB, err := db.DB()
|
||||
if err != nil {
|
||||
log.Fatalf("获取数据库连接失败: %v", err)
|
||||
}
|
||||
defer sqlDB.Close()
|
||||
|
||||
mode := "预演(dry-run)"
|
||||
if *apply {
|
||||
mode = "写入(apply)"
|
||||
}
|
||||
fmt.Printf("密钥轮换模式: %s\n\n", mode)
|
||||
|
||||
results, err := service.ReencryptSecrets(db, oldCodec, newCodec, *apply)
|
||||
if err != nil {
|
||||
log.Fatalf("重加密失败: %v", err)
|
||||
}
|
||||
|
||||
for _, r := range results {
|
||||
fmt.Printf("%-24s 扫描=%d 重加密=%d 已是新密钥=%d 失败=%d\n",
|
||||
r.Table, r.Report.Scanned, r.Report.Reencrypted, r.Report.AlreadyNewKey, r.Report.Failed)
|
||||
}
|
||||
|
||||
if failed := service.TotalFailed(results); failed > 0 {
|
||||
log.Fatalf("有 %d 行新旧密钥都无法解密,请先排查数据来源,未做任何破坏性操作", failed)
|
||||
}
|
||||
if !*apply {
|
||||
fmt.Println("\n预演完成,未修改任何数据。确认无误后加 -apply 执行写入。")
|
||||
return
|
||||
}
|
||||
fmt.Println("\n重加密完成。请确认业务正常后再移除旧密钥。")
|
||||
}
|
||||
@@ -105,26 +105,13 @@ func Load() *Config {
|
||||
}
|
||||
|
||||
// 仓库 .env.example 中的占位密钥。这些值对所有人公开,一旦被带到真实部署,
|
||||
// JWT 可被伪造、落库密文可被解密,因此启动时必须显式告警。
|
||||
const (
|
||||
exampleJWTSecret = "your_very_secure_jwt_secret_here_change_me_in_production"
|
||||
exampleDataKey = "your_32_plus_char_data_encryption_key_change_me"
|
||||
)
|
||||
const exampleJWTSecret = "your_very_secure_jwt_secret_here_change_me_in_production"
|
||||
|
||||
// SecurityWarnings 返回启动时的密钥配置风险清单;返回空切片表示配置正常。
|
||||
// 刻意只告警不阻断:升级过程直接 fatal 会让存量部署起不来,风险由运维可见性兜住。
|
||||
// SecurityWarnings 返回启动时的配置风险清单;返回空切片表示配置正常。
|
||||
func (c *Config) SecurityWarnings() []string {
|
||||
var warnings []string
|
||||
if c.JWTSecret == exampleJWTSecret {
|
||||
warnings = append(warnings, "JWT_SECRET 仍是 .env.example 里的示例值,任何见过仓库的人都能伪造管理员 Token")
|
||||
}
|
||||
if os.Getenv("DATA_ENCRYPTION_KEY") == "" {
|
||||
warnings = append(warnings, "DATA_ENCRYPTION_KEY 未显式设置,已回退到 JWT_SECRET;请设置独立密钥,更换后需用 cmd/reencrypt_secrets 重加密历史密文")
|
||||
} else if c.DataEncryptionKey == exampleDataKey {
|
||||
warnings = append(warnings, "DATA_ENCRYPTION_KEY 仍是 .env.example 里的示例值,落库的 API/回调密钥可被解密")
|
||||
}
|
||||
if c.DataEncryptionKey == c.JWTSecret {
|
||||
warnings = append(warnings, "DATA_ENCRYPTION_KEY 与 JWT_SECRET 相同,建议分离以便独立轮换")
|
||||
warnings = append(warnings, "JWT_SECRET 仍是 .env.example 里的示例值,建议生成生产随机密钥以防 Token 伪造")
|
||||
}
|
||||
if c.Mode == "release" && c.OpenAPIDebug {
|
||||
warnings = append(warnings, "GIN_MODE=release 下开启了 OPEN_API_DEBUG,开放接口报文详情会持续写盘")
|
||||
|
||||
@@ -18,42 +18,25 @@ func containsWarning(warnings []string, fragment string) bool {
|
||||
func TestSecurityWarnings(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
dataKeyEnv string
|
||||
cfg Config
|
||||
wantWarning string // 期望命中的告警片段;为空表示期望无任何告警
|
||||
}{
|
||||
{
|
||||
name: "示例 JWT_SECRET 必须告警",
|
||||
dataKeyEnv: "a-real-data-key",
|
||||
cfg: Config{JWTSecret: exampleJWTSecret, DataEncryptionKey: "a-real-data-key", Mode: "debug"},
|
||||
cfg: Config{JWTSecret: exampleJWTSecret, Mode: "debug"},
|
||||
wantWarning: "JWT_SECRET",
|
||||
},
|
||||
{
|
||||
name: "未显式设置 DATA_ENCRYPTION_KEY 时提示回退 JWT_SECRET",
|
||||
dataKeyEnv: "",
|
||||
cfg: Config{JWTSecret: "a-real-jwt-secret", DataEncryptionKey: "a-real-jwt-secret", Mode: "debug"},
|
||||
wantWarning: "DATA_ENCRYPTION_KEY 未显式设置",
|
||||
},
|
||||
{
|
||||
name: "示例 DATA_ENCRYPTION_KEY 必须告警",
|
||||
dataKeyEnv: exampleDataKey,
|
||||
cfg: Config{JWTSecret: "a-real-jwt-secret", DataEncryptionKey: exampleDataKey, Mode: "debug"},
|
||||
wantWarning: "DATA_ENCRYPTION_KEY 仍是",
|
||||
},
|
||||
{
|
||||
name: "release 模式开启 OPEN_API_DEBUG 必须告警",
|
||||
dataKeyEnv: "a-real-data-key",
|
||||
cfg: Config{JWTSecret: "a-real-jwt-secret", DataEncryptionKey: "a-real-data-key", Mode: "release", OpenAPIDebug: true},
|
||||
cfg: Config{JWTSecret: "a-real-jwt-secret", Mode: "release", OpenAPIDebug: true},
|
||||
wantWarning: "OPEN_API_DEBUG",
|
||||
},
|
||||
{
|
||||
name: "健康配置不应产生任何告警",
|
||||
dataKeyEnv: "a-real-data-key",
|
||||
name: "健康配置不应产生任何告警",
|
||||
cfg: Config{
|
||||
JWTSecret: "a-real-jwt-secret",
|
||||
DataEncryptionKey: "a-real-data-key",
|
||||
Mode: "release",
|
||||
OpenAPIDebug: false,
|
||||
JWTSecret: "a-real-jwt-secret",
|
||||
Mode: "release",
|
||||
OpenAPIDebug: false,
|
||||
},
|
||||
wantWarning: "",
|
||||
},
|
||||
@@ -61,7 +44,6 @@ func TestSecurityWarnings(t *testing.T) {
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Setenv("DATA_ENCRYPTION_KEY", tc.dataKeyEnv)
|
||||
warnings := tc.cfg.SecurityWarnings()
|
||||
|
||||
if tc.wantWarning == "" {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"affiliate_dash/internal/middleware"
|
||||
@@ -25,6 +26,37 @@ func (h *MerchantHandler) ListOrders(c *gin.Context) {
|
||||
response.Page(c, list, total, page, size)
|
||||
}
|
||||
|
||||
// ListPlatformOrders GET /api/platform/orders
|
||||
//
|
||||
// 平台管理员跨商户查看下游订单。merchant_id 查询参数可选:不传表示全部商户。
|
||||
// 与商户侧 /api/merchant/orders 是两条独立路径——商户侧仍强制单商户隔离,
|
||||
// 这里不依赖 X-Merchant-ID,因此管理员遗留的商户上下文不会影响本接口。
|
||||
func (h *MerchantHandler) ListPlatformOrders(c *gin.Context) {
|
||||
page, size := pageParams(c)
|
||||
|
||||
var merchantID *uint
|
||||
if raw := strings.TrimSpace(c.Query("merchant_id")); raw != "" {
|
||||
id, err := strconv.ParseUint(raw, 10, 64)
|
||||
if err != nil || id == 0 {
|
||||
response.BadRequest(c, "商户 ID 无效")
|
||||
return
|
||||
}
|
||||
value := uint(id)
|
||||
merchantID = &value
|
||||
}
|
||||
|
||||
list, total, err := h.fulfillmentSvc.ListPlatformOrders(merchantID, page, size, c.Query("order_status"), c.Query("order_source"), c.Query("keyword"))
|
||||
if err != nil {
|
||||
if err.Error() == "无效的订单来源" || err.Error() == "无效的订单状态" {
|
||||
response.BadRequest(c, err.Error())
|
||||
return
|
||||
}
|
||||
response.ServerError(c, err.Error())
|
||||
return
|
||||
}
|
||||
response.Page(c, list, total, page, size)
|
||||
}
|
||||
|
||||
type merchantManualOrderReq struct {
|
||||
ClientOrderNo string `json:"client_order_no" binding:"required,max=96"`
|
||||
SKU string `json:"sku" binding:"required,max=96"`
|
||||
|
||||
@@ -20,6 +20,19 @@ func (h *MerchantHandler) ListPlatformMerchants(c *gin.Context) {
|
||||
response.Page(c, list, total, page, size)
|
||||
}
|
||||
|
||||
// ListMerchantOptions GET /api/platform/merchant-options
|
||||
//
|
||||
// 返回全部启用商户的精简列表,供筛选下拉使用。分页接口的 size 上限是 100,
|
||||
// 下拉需要「全部」,因此单开一个不分页的轻量接口。
|
||||
func (h *MerchantHandler) ListMerchantOptions(c *gin.Context) {
|
||||
options, err := h.merchantSvc.ListMerchantOptions()
|
||||
if err != nil {
|
||||
response.ServerError(c, err.Error())
|
||||
return
|
||||
}
|
||||
response.OK(c, options)
|
||||
}
|
||||
|
||||
type createMerchantReq struct {
|
||||
Code string `json:"code" binding:"required"`
|
||||
Name string `json:"name" binding:"required"`
|
||||
|
||||
@@ -246,6 +246,9 @@ type FulfillmentOrder struct {
|
||||
DeliveryLinkGeneratedAt *time.Time `json:"delivery_link_generated_at"`
|
||||
|
||||
MerchantProduct *MerchantProduct `gorm:"foreignKey:MerchantProductID" json:"merchant_product,omitempty"`
|
||||
// Merchant 仅在平台侧跨商户查询时 Preload;商户侧响应里为 nil,被 omitempty 省略,
|
||||
// 因此该字段不改变既有接口结构。
|
||||
Merchant *Merchant `gorm:"foreignKey:MerchantID" json:"merchant,omitempty"`
|
||||
}
|
||||
|
||||
// CallbackSubscription 为商户提供独立、可禁用的事件订阅。
|
||||
|
||||
@@ -222,6 +222,62 @@ func Setup(h *Handlers) *gin.Engine {
|
||||
clientOpen.GET("/wallet", middleware.RequireMerchantFeature(h.OpenDB, model.MerchantFeatureWallet), middleware.RequireAPIScope("wallet:read"), h.Open.GetWallet)
|
||||
}
|
||||
|
||||
// 平台管理端:只依赖 JWT 与角色,刻意不挂 Tenant。
|
||||
// 平台接口本身跨商户,一旦让它们解析 X-Merchant-ID,管理员哪怕只是残留一个已禁用
|
||||
// 商户的上下文,Tenant 就会对全部请求返回 403,整个管理端都会被锁死。
|
||||
platform := api.Group("")
|
||||
platform.Use(middleware.Auth(h.JWT))
|
||||
platform.Use(middleware.RequireRole(model.RoleAdmin))
|
||||
{
|
||||
platform.GET("/platform/admins", h.User.ListPlatformAdmins)
|
||||
platform.GET("/platform/merchant-accounts", h.User.ListMerchantAccountGroups)
|
||||
platform.DELETE("/platform/merchant-accounts/:id", h.User.DeleteMerchantAccount)
|
||||
platform.POST("/platform/admins", h.User.CreatePlatformAdmin)
|
||||
platform.PATCH("/platform/admins/:id", h.User.UpdatePlatformAdmin)
|
||||
platform.DELETE("/platform/admins/:id", h.User.DeletePlatformAdmin)
|
||||
platform.GET("/platform/merchants", h.Merchant.ListPlatformMerchants)
|
||||
// 不分页的精简商户列表,供筛选下拉使用(分页接口的 size 上限是 100)
|
||||
platform.GET("/platform/merchant-options", h.Merchant.ListMerchantOptions)
|
||||
// 跨商户订单视图:商户后台的 /api/merchant/orders 强制单商户隔离,
|
||||
// 超管需要一条平台视角入口来查看全部下游订单。
|
||||
platform.GET("/platform/orders", h.Merchant.ListPlatformOrders)
|
||||
platform.POST("/platform/merchants", h.Merchant.CreateMerchant)
|
||||
platform.PATCH("/platform/merchants/:id", h.Merchant.UpdateMerchantSettings)
|
||||
platform.POST("/platform/merchants/:id/members", h.Merchant.AddPlatformMerchantMember)
|
||||
platform.GET("/platform/product-catalog", h.Merchant.ListProductCatalog)
|
||||
platform.GET("/platform/merchants/:id/products", h.Merchant.ListMerchantProductsByAdmin)
|
||||
platform.PATCH("/platform/merchants/:id/products/:pid", h.Merchant.AdminUpdateMerchantProduct)
|
||||
platform.POST("/platform/merchants/:id/products/assign", h.Merchant.AssignProducts)
|
||||
platform.GET("/platform/merchants/:id/wallet", h.Merchant.AdminGetWallet)
|
||||
platform.GET("/platform/merchants/:id/account", h.Merchant.AdminGetMerchantAccount)
|
||||
platform.PATCH("/platform/merchants/:id/account", h.Merchant.AdminUpdateMerchantAccount)
|
||||
platform.GET("/platform/merchants/:id/wallet/ledger", h.Merchant.AdminListWalletLedger)
|
||||
platform.POST("/platform/merchants/:id/wallet/adjust", h.Merchant.AdminAdjustWallet)
|
||||
platform.GET("/platform/recharge/applications", h.Recharge.AdminListApplications)
|
||||
platform.POST("/platform/recharge/applications/:id/review", h.Recharge.AdminReviewApplication)
|
||||
|
||||
// 乐玩平台商品拉取、同步与履约路由配置
|
||||
if h.PlatformLewan != nil {
|
||||
platform.GET("/platform/lewan/products", h.PlatformLewan.ListLewanProducts)
|
||||
platform.POST("/platform/lewan/sync-catalog", h.PlatformLewan.SyncLewanProduct)
|
||||
platform.POST("/platform/lewan/batch-sync-catalog", h.PlatformLewan.BatchSyncLewanProducts)
|
||||
platform.PUT("/platform/products/:id/routing", h.PlatformLewan.UpdateProductRouting)
|
||||
}
|
||||
|
||||
// Rock平台 (0666.pro) 自动发货与库存风控管理
|
||||
if h.Rock != nil {
|
||||
platform.GET("/platform/rock/config", h.Rock.GetConfig)
|
||||
platform.PUT("/platform/rock/config", h.Rock.UpdateConfig)
|
||||
platform.POST("/platform/rock/test-conn", h.Rock.TestConnection)
|
||||
platform.GET("/platform/rock/stats", h.Rock.GetStats)
|
||||
platform.POST("/platform/rock/purchase", h.Rock.PurchaseTokens)
|
||||
platform.GET("/platform/rock/tokens", h.Rock.ListTokens)
|
||||
platform.POST("/platform/rock/tokens/:id/expected-uid", h.Rock.CorrectTokenUID)
|
||||
platform.POST("/platform/rock/tokens/:id/reset", h.Rock.ResetToken)
|
||||
platform.POST("/platform/rock/tokens/:id/release", h.Rock.ReleaseToken)
|
||||
}
|
||||
}
|
||||
|
||||
auth := api.Group("")
|
||||
auth.Use(middleware.Auth(h.JWT))
|
||||
auth.Use(middleware.Tenant(h.Tenant))
|
||||
@@ -273,54 +329,6 @@ func Setup(h *Handlers) *gin.Engine {
|
||||
merchant.PATCH("/roles/:id", middleware.RequireMerchantPermissions(h.Tenant, model.PermissionMembersManage), h.Merchant.UpdateRole)
|
||||
}
|
||||
|
||||
// 平台管理员 / 发货记录 / 平台商户(仅管理员)
|
||||
admin := auth.Group("")
|
||||
admin.Use(middleware.RequireRole(model.RoleAdmin))
|
||||
{
|
||||
admin.GET("/platform/admins", h.User.ListPlatformAdmins)
|
||||
admin.GET("/platform/merchant-accounts", h.User.ListMerchantAccountGroups)
|
||||
admin.DELETE("/platform/merchant-accounts/:id", h.User.DeleteMerchantAccount)
|
||||
admin.POST("/platform/admins", h.User.CreatePlatformAdmin)
|
||||
admin.PATCH("/platform/admins/:id", h.User.UpdatePlatformAdmin)
|
||||
admin.DELETE("/platform/admins/:id", h.User.DeletePlatformAdmin)
|
||||
admin.GET("/platform/merchants", h.Merchant.ListPlatformMerchants)
|
||||
admin.POST("/platform/merchants", h.Merchant.CreateMerchant)
|
||||
admin.PATCH("/platform/merchants/:id", h.Merchant.UpdateMerchantSettings)
|
||||
admin.POST("/platform/merchants/:id/members", h.Merchant.AddPlatformMerchantMember)
|
||||
admin.GET("/platform/product-catalog", h.Merchant.ListProductCatalog)
|
||||
admin.GET("/platform/merchants/:id/products", h.Merchant.ListMerchantProductsByAdmin)
|
||||
admin.PATCH("/platform/merchants/:id/products/:pid", h.Merchant.AdminUpdateMerchantProduct)
|
||||
admin.POST("/platform/merchants/:id/products/assign", h.Merchant.AssignProducts)
|
||||
admin.GET("/platform/merchants/:id/wallet", h.Merchant.AdminGetWallet)
|
||||
admin.GET("/platform/merchants/:id/account", h.Merchant.AdminGetMerchantAccount)
|
||||
admin.PATCH("/platform/merchants/:id/account", h.Merchant.AdminUpdateMerchantAccount)
|
||||
admin.GET("/platform/merchants/:id/wallet/ledger", h.Merchant.AdminListWalletLedger)
|
||||
admin.POST("/platform/merchants/:id/wallet/adjust", h.Merchant.AdminAdjustWallet)
|
||||
admin.GET("/platform/recharge/applications", h.Recharge.AdminListApplications)
|
||||
admin.POST("/platform/recharge/applications/:id/review", h.Recharge.AdminReviewApplication)
|
||||
|
||||
// 乐玩平台商品拉取、同步与履约路由配置
|
||||
if h.PlatformLewan != nil {
|
||||
admin.GET("/platform/lewan/products", h.PlatformLewan.ListLewanProducts)
|
||||
admin.POST("/platform/lewan/sync-catalog", h.PlatformLewan.SyncLewanProduct)
|
||||
admin.POST("/platform/lewan/batch-sync-catalog", h.PlatformLewan.BatchSyncLewanProducts)
|
||||
admin.PUT("/platform/products/:id/routing", h.PlatformLewan.UpdateProductRouting)
|
||||
}
|
||||
|
||||
// Rock平台 (0666.pro) 自动发货与库存风控管理
|
||||
if h.Rock != nil {
|
||||
admin.GET("/platform/rock/config", h.Rock.GetConfig)
|
||||
admin.PUT("/platform/rock/config", h.Rock.UpdateConfig)
|
||||
admin.POST("/platform/rock/test-conn", h.Rock.TestConnection)
|
||||
admin.GET("/platform/rock/stats", h.Rock.GetStats)
|
||||
admin.POST("/platform/rock/purchase", h.Rock.PurchaseTokens)
|
||||
admin.GET("/platform/rock/tokens", h.Rock.ListTokens)
|
||||
admin.POST("/platform/rock/tokens/:id/expected-uid", h.Rock.CorrectTokenUID)
|
||||
admin.POST("/platform/rock/tokens/:id/reset", h.Rock.ResetToken)
|
||||
admin.POST("/platform/rock/tokens/:id/release", h.Rock.ReleaseToken)
|
||||
}
|
||||
}
|
||||
|
||||
auth.POST("/upload", h.Recharge.Upload)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"testing"
|
||||
|
||||
"affiliate_dash/internal/handler"
|
||||
"affiliate_dash/internal/model"
|
||||
"affiliate_dash/internal/pkg/applog"
|
||||
"affiliate_dash/internal/pkg/jwt"
|
||||
"affiliate_dash/internal/pkg/openlog"
|
||||
@@ -17,15 +18,18 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func TestSetupDoesNotPanic(t *testing.T) {
|
||||
// newTestRouter 构建一个接好全部依赖的测试路由。
|
||||
func newTestRouter(t *testing.T) (*gin.Engine, *jwt.Manager) {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
db := testdb.New(t)
|
||||
codec, err := service.NewSecretCodec("test-master-key")
|
||||
if err != nil {
|
||||
t.Fatalf("codec: %v", err)
|
||||
}
|
||||
jm := jwt.NewManager("test-jwt")
|
||||
tenantSvc := service.NewTenantService(db)
|
||||
authSvc := service.NewAuthService(db, jwt.NewManager("test-jwt"), tenantSvc)
|
||||
authSvc := service.NewAuthService(db, jm, tenantSvc)
|
||||
userSvc := service.NewUserService(db, tenantSvc)
|
||||
callbackSvc := service.NewCallbackService(db, codec)
|
||||
fulfillmentSvc := service.NewFulfillmentService(db, callbackSvc)
|
||||
@@ -33,12 +37,7 @@ func TestSetupDoesNotPanic(t *testing.T) {
|
||||
rechargeSvc := service.NewRechargeService(db, fulfillmentSvc, "")
|
||||
deliverySvc := service.NewDeliveryService(fulfillmentSvc, "", "", "", "", 0)
|
||||
|
||||
defer func() {
|
||||
if recovered := recover(); recovered != nil {
|
||||
t.Fatalf("setup should not panic: %v", recovered)
|
||||
}
|
||||
}()
|
||||
_ = Setup(&Handlers{
|
||||
engine := Setup(&Handlers{
|
||||
Auth: handler.NewAuthHandler(authSvc),
|
||||
Dashboard: handler.NewDashboardHandler(fulfillmentSvc),
|
||||
User: handler.NewUserHandler(userSvc),
|
||||
@@ -46,7 +45,7 @@ func TestSetupDoesNotPanic(t *testing.T) {
|
||||
SourceOpen: handler.NewOpenHandler(fulfillmentSvc),
|
||||
Merchant: handler.NewMerchantHandler(merchantSvc, fulfillmentSvc, callbackSvc, deliverySvc, rechargeSvc),
|
||||
Recharge: handler.NewRechargeHandler(rechargeSvc),
|
||||
JWT: jwt.NewManager("test-jwt"),
|
||||
JWT: jm,
|
||||
Tenant: tenantSvc,
|
||||
OpenDB: db,
|
||||
SecretCodec: codec,
|
||||
@@ -54,6 +53,72 @@ func TestSetupDoesNotPanic(t *testing.T) {
|
||||
OpenAPISecret: "source-secret",
|
||||
OpenSignSkew: 300,
|
||||
})
|
||||
return engine, jm
|
||||
}
|
||||
|
||||
func TestSetupDoesNotPanic(t *testing.T) {
|
||||
defer func() {
|
||||
if recovered := recover(); recovered != nil {
|
||||
t.Fatalf("setup should not panic: %v", recovered)
|
||||
}
|
||||
}()
|
||||
_, _ = newTestRouter(t)
|
||||
}
|
||||
|
||||
// TestPlatformRoutesIgnoreStaleMerchantContext 卡住一个会把整个管理端锁死的场景:
|
||||
// 平台路由一旦挂上 Tenant,管理员 localStorage 里残留一个已不存在/已禁用的商户 ID 时,
|
||||
// 所有 /api/platform/* 请求都会被 403,连"去改回来"的页面都打不开。
|
||||
// 因此平台分组只挂 Auth + RequireRole,不解析商户上下文。
|
||||
func TestPlatformRoutesIgnoreStaleMerchantContext(t *testing.T) {
|
||||
engine, jm := newTestRouter(t)
|
||||
token, err := jm.Generate(1, "admin", model.RoleAdmin)
|
||||
if err != nil {
|
||||
t.Fatalf("generate token: %v", err)
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
merchantHeader string
|
||||
}{
|
||||
{name: "无商户上下文", merchantHeader: ""},
|
||||
{name: "残留不存在的商户", merchantHeader: "999999"},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
req := httptest.NewRequest("GET", "/api/platform/merchants", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
if tc.merchantHeader != "" {
|
||||
req.Header.Set("X-Merchant-ID", tc.merchantHeader)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
engine.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != 200 {
|
||||
t.Fatalf("平台路由必须不受残留商户上下文影响,期望 200,实际 %d:%s", w.Code, w.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestMerchantRoutesStillRejectStaleContext 反向卡住商户侧:
|
||||
// 摘掉 Tenant 只针对平台分组,商户后台仍必须校验商户上下文。
|
||||
func TestMerchantRoutesStillRejectStaleContext(t *testing.T) {
|
||||
engine, jm := newTestRouter(t)
|
||||
token, err := jm.Generate(1, "admin", model.RoleAdmin)
|
||||
if err != nil {
|
||||
t.Fatalf("generate token: %v", err)
|
||||
}
|
||||
|
||||
req := httptest.NewRequest("GET", "/api/merchant", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
req.Header.Set("X-Merchant-ID", "999999")
|
||||
w := httptest.NewRecorder()
|
||||
engine.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != 403 {
|
||||
t.Fatalf("商户路由必须拒绝无效商户上下文,期望 403,实际 %d:%s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsPollingEndpoint(t *testing.T) {
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"affiliate_dash/internal/model"
|
||||
)
|
||||
|
||||
// seedPlatformOrders 为两个商户各造若干订单,用于平台侧跨商户查询测试。
|
||||
func seedPlatformOrders(t *testing.T) (*FulfillmentService, uint, uint) {
|
||||
t.Helper()
|
||||
db := newServiceTestDB(t)
|
||||
svc := NewFulfillmentService(db, nil)
|
||||
|
||||
merchantA, productA := seedFulfillmentMerchant(t, db, "pf-merchant-a", 0, -1, 100)
|
||||
merchantB, productB := seedFulfillmentMerchant(t, db, "pf-merchant-b", 0, -1, 100)
|
||||
|
||||
orders := []model.FulfillmentOrder{
|
||||
{MerchantID: merchantA, OrderNo: "A-1", ClientOrderNo: "A-C1", MerchantProductID: productA.ID, ProductSKU: productA.SKU, ProductName: "商品A", Amount: 100, OrderStatus: model.OrderStatusPaid, OrderSource: model.OrderSourceAPI},
|
||||
{MerchantID: merchantA, OrderNo: "A-2", ClientOrderNo: "A-C2", MerchantProductID: productA.ID, ProductSKU: productA.SKU, ProductName: "商品A", Amount: 100, OrderStatus: model.OrderStatusDelivered, OrderSource: model.OrderSourceManual},
|
||||
{MerchantID: merchantB, OrderNo: "B-1", ClientOrderNo: "B-C1", MerchantProductID: productB.ID, ProductSKU: productB.SKU, ProductName: "商品B", Amount: 200, OrderStatus: model.OrderStatusPaid, OrderSource: model.OrderSourceAPI},
|
||||
}
|
||||
for i := range orders {
|
||||
if err := db.Create(&orders[i]).Error; err != nil {
|
||||
t.Fatalf("create order: %v", err)
|
||||
}
|
||||
}
|
||||
return svc, merchantA, merchantB
|
||||
}
|
||||
|
||||
// TestListPlatformOrdersSpansMerchants 是本次修复的核心断言:
|
||||
// 平台视角必须能同时看到全部商户的订单,并带出订单所属商户。
|
||||
func TestListPlatformOrdersSpansMerchants(t *testing.T) {
|
||||
svc, merchantA, merchantB := seedPlatformOrders(t)
|
||||
|
||||
list, total, err := svc.ListPlatformOrders(nil, 1, 20, "", "", "")
|
||||
if err != nil {
|
||||
t.Fatalf("平台侧跨商户查询失败: %v", err)
|
||||
}
|
||||
if total != 3 || len(list) != 3 {
|
||||
t.Fatalf("期望 3 单(A 2 单 + B 1 单),实际 total=%d len=%d", total, len(list))
|
||||
}
|
||||
|
||||
seen := map[uint]int{}
|
||||
for _, order := range list {
|
||||
seen[order.MerchantID]++
|
||||
// 跨商户列表必须能说明每单属于哪个商户,否则管理员无法分辨。
|
||||
if order.Merchant == nil {
|
||||
t.Fatalf("订单 %s 未预加载商户信息", order.OrderNo)
|
||||
}
|
||||
}
|
||||
if seen[merchantA] != 2 || seen[merchantB] != 1 {
|
||||
t.Fatalf("商户分布不符:%v", seen)
|
||||
}
|
||||
}
|
||||
|
||||
// TestListPlatformOrdersFiltersByMerchant 指定 merchant_id 时只返回该商户。
|
||||
func TestListPlatformOrdersFiltersByMerchant(t *testing.T) {
|
||||
svc, merchantA, _ := seedPlatformOrders(t)
|
||||
|
||||
list, total, err := svc.ListPlatformOrders(&merchantA, 1, 20, "", "", "")
|
||||
if err != nil {
|
||||
t.Fatalf("按商户筛选失败: %v", err)
|
||||
}
|
||||
if total != 2 || len(list) != 2 {
|
||||
t.Fatalf("期望商户 A 的 2 单,实际 total=%d len=%d", total, len(list))
|
||||
}
|
||||
for _, order := range list {
|
||||
if order.MerchantID != merchantA {
|
||||
t.Fatalf("出现了其他商户的订单:merchant_id=%d", order.MerchantID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestListPlatformOrdersAppliesFilters 平台侧同样要支持状态/来源/关键字筛选与非法值校验。
|
||||
func TestListPlatformOrdersAppliesFilters(t *testing.T) {
|
||||
svc, _, _ := seedPlatformOrders(t)
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
status string
|
||||
source string
|
||||
keyword string
|
||||
wantTotal int64
|
||||
wantErrText string
|
||||
}{
|
||||
{name: "按状态筛选", status: model.OrderStatusPaid, wantTotal: 2},
|
||||
{name: "按来源筛选", source: model.OrderSourceManual, wantTotal: 1},
|
||||
{name: "按订单号关键字", keyword: "B-", wantTotal: 1},
|
||||
{name: "按商户单号关键字", keyword: "A-C", wantTotal: 2},
|
||||
{name: "非法状态", status: "not-a-status", wantErrText: "无效的订单状态"},
|
||||
{name: "非法来源", source: "not-a-source", wantErrText: "无效的订单来源"},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
list, total, err := svc.ListPlatformOrders(nil, 1, 20, tc.status, tc.source, tc.keyword)
|
||||
if tc.wantErrText != "" {
|
||||
if err == nil || err.Error() != tc.wantErrText {
|
||||
t.Fatalf("期望错误 %q,实际 %v", tc.wantErrText, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("查询失败: %v", err)
|
||||
}
|
||||
if total != tc.wantTotal || int64(len(list)) != tc.wantTotal {
|
||||
t.Fatalf("期望 %d 单,实际 total=%d len=%d", tc.wantTotal, total, len(list))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestListOrdersStillIsolatesSingleMerchant 卡住商户侧隔离语义:
|
||||
// 这次修复新增了平台侧路径,但绝不能顺手放宽商户侧的可见范围。
|
||||
// 同时商户侧响应不应带上 Merchant(保持既有接口结构不变)。
|
||||
func TestListOrdersStillIsolatesSingleMerchant(t *testing.T) {
|
||||
svc, merchantA, _ := seedPlatformOrders(t)
|
||||
|
||||
list, total, err := svc.ListOrders(merchantA, 1, 20, "", "", "")
|
||||
if err != nil {
|
||||
t.Fatalf("商户侧查询失败: %v", err)
|
||||
}
|
||||
if total != 2 || len(list) != 2 {
|
||||
t.Fatalf("商户侧必须只看到自己的 2 单,实际 total=%d len=%d", total, len(list))
|
||||
}
|
||||
for _, order := range list {
|
||||
if order.MerchantID != merchantA {
|
||||
t.Fatalf("商户侧串到了其他商户的订单:merchant_id=%d", order.MerchantID)
|
||||
}
|
||||
if order.Merchant != nil {
|
||||
t.Fatal("商户侧不应预加载 Merchant,否则会改变既有响应结构")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -24,38 +24,86 @@ func (s *FulfillmentService) GetOrder(merchantID uint, orderNo string) (*model.F
|
||||
return &order, nil
|
||||
}
|
||||
|
||||
func (s *FulfillmentService) ListOrders(merchantID uint, page, size int, orderStatus, orderSource, keyword string) ([]model.FulfillmentOrder, int64, error) {
|
||||
page, size = normalizePage(page, size)
|
||||
tx := s.db.Model(&model.FulfillmentOrder{}).Where("merchant_id = ?", merchantID)
|
||||
if orderStatus != "" {
|
||||
switch orderStatus {
|
||||
// orderFilters 是商户侧与平台侧共用的订单筛选条件。
|
||||
// 集中在一处校验,避免以后新增筛选项时只改了一边。
|
||||
type orderFilters struct {
|
||||
// merchantID 为 nil 表示不限商户(仅平台侧使用);指向 0 时仍会按 merchant_id=0 过滤,
|
||||
// 以保持 ListOrders 的原有语义不变。
|
||||
merchantID *uint
|
||||
orderStatus string
|
||||
orderSource string
|
||||
keyword string
|
||||
}
|
||||
|
||||
func (f orderFilters) apply(tx *gorm.DB) (*gorm.DB, error) {
|
||||
if f.merchantID != nil {
|
||||
tx = tx.Where("merchant_id = ?", *f.merchantID)
|
||||
}
|
||||
if f.orderStatus != "" {
|
||||
switch f.orderStatus {
|
||||
case model.OrderStatusPaid, model.OrderStatusDelivering, model.OrderStatusDelivered, model.OrderStatusShipFailed, model.OrderStatusCancelled:
|
||||
default:
|
||||
return nil, 0, errors.New("无效的订单状态")
|
||||
return nil, errors.New("无效的订单状态")
|
||||
}
|
||||
tx = tx.Where("order_status = ?", orderStatus)
|
||||
tx = tx.Where("order_status = ?", f.orderStatus)
|
||||
}
|
||||
if orderSource != "" {
|
||||
switch orderSource {
|
||||
if f.orderSource != "" {
|
||||
switch f.orderSource {
|
||||
case model.OrderSourceAPI, model.OrderSourceManual, model.OrderSourceTest:
|
||||
tx = tx.Where("order_source = ?", orderSource)
|
||||
tx = tx.Where("order_source = ?", f.orderSource)
|
||||
default:
|
||||
return nil, 0, errors.New("无效的订单来源")
|
||||
return nil, errors.New("无效的订单来源")
|
||||
}
|
||||
}
|
||||
if keyword = strings.TrimSpace(keyword); keyword != "" {
|
||||
if keyword := strings.TrimSpace(f.keyword); keyword != "" {
|
||||
like := "%" + keyword + "%"
|
||||
tx = tx.Where("order_no LIKE ? OR client_order_no LIKE ?", like, like)
|
||||
}
|
||||
return tx, nil
|
||||
}
|
||||
|
||||
func (s *FulfillmentService) listOrders(f orderFilters, page, size int, withMerchant bool) ([]model.FulfillmentOrder, int64, error) {
|
||||
page, size = normalizePage(page, size)
|
||||
tx, err := f.apply(s.db.Model(&model.FulfillmentOrder{}))
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
var total int64
|
||||
if err := tx.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
query := tx.Preload("MerchantProduct.Product")
|
||||
if withMerchant {
|
||||
// 平台侧跨商户列表需要展示订单属于哪个商户。
|
||||
query = query.Preload("Merchant")
|
||||
}
|
||||
var orders []model.FulfillmentOrder
|
||||
err := tx.Preload("MerchantProduct.Product").Order("id DESC").Offset((page - 1) * size).Limit(size).Find(&orders).Error
|
||||
err = query.Order("id DESC").Offset((page - 1) * size).Limit(size).Find(&orders).Error
|
||||
return orders, total, err
|
||||
}
|
||||
|
||||
// ListOrders 商户后台订单列表,强制按单个商户隔离。
|
||||
func (s *FulfillmentService) ListOrders(merchantID uint, page, size int, orderStatus, orderSource, keyword string) ([]model.FulfillmentOrder, int64, error) {
|
||||
return s.listOrders(orderFilters{
|
||||
merchantID: &merchantID,
|
||||
orderStatus: orderStatus,
|
||||
orderSource: orderSource,
|
||||
keyword: keyword,
|
||||
}, page, size, false)
|
||||
}
|
||||
|
||||
// ListPlatformOrders 平台侧跨商户订单查询,供超管在管理端查看全部下游订单。
|
||||
// merchantID 为 nil 表示不限商户。这是与 ListOrders 并行的另一条路径,
|
||||
// 刻意不改动商户侧「必须落到单个商户」的隔离语义。
|
||||
func (s *FulfillmentService) ListPlatformOrders(merchantID *uint, page, size int, orderStatus, orderSource, keyword string) ([]model.FulfillmentOrder, int64, error) {
|
||||
return s.listOrders(orderFilters{
|
||||
merchantID: merchantID,
|
||||
orderStatus: orderStatus,
|
||||
orderSource: orderSource,
|
||||
keyword: keyword,
|
||||
}, page, size, true)
|
||||
}
|
||||
|
||||
type OpenOrderQuery struct {
|
||||
OrderNo string `json:"order_no"`
|
||||
Status string `json:"status"`
|
||||
|
||||
@@ -240,6 +240,27 @@ func (s *MerchantService) ListMerchants(page, size int) ([]model.Merchant, int64
|
||||
return merchants, total, err
|
||||
}
|
||||
|
||||
// MerchantOption 是筛选下拉使用的精简商户信息。
|
||||
type MerchantOption struct {
|
||||
ID uint `json:"id"`
|
||||
Code string `json:"code"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
// ListMerchantOptions 返回全部启用商户的精简列表。
|
||||
//
|
||||
// 刻意独立于分页的 ListMerchants:下拉需要「全部」,而分页接口的 size 上限是 100,
|
||||
// 直接调大 size 只会被静默降级成 20,表现为下拉里少了一批商户。
|
||||
func (s *MerchantService) ListMerchantOptions() ([]MerchantOption, error) {
|
||||
options := make([]MerchantOption, 0)
|
||||
err := s.db.Model(&model.Merchant{}).
|
||||
Select("id", "code", "name").
|
||||
Where("status = ?", model.MerchantStatusActive).
|
||||
Order("id ASC").
|
||||
Find(&options).Error
|
||||
return options, err
|
||||
}
|
||||
|
||||
func (s *MerchantService) GetMerchant(merchantID uint) (*model.Merchant, error) {
|
||||
var merchant model.Merchant
|
||||
if err := s.db.First(&merchant, merchantID).Error; err != nil {
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"affiliate_dash/internal/model"
|
||||
)
|
||||
|
||||
// TestListMerchantOptionsReturnsAllActiveMerchants 卡住两个点:
|
||||
// 1. 下拉需要"全部商户",不能被分页的 size 上限(100,且传大值会被降级为 20)截断;
|
||||
// 2. 已禁用商户不应出现在可筛选列表里。
|
||||
func TestListMerchantOptionsReturnsAllActiveMerchants(t *testing.T) {
|
||||
db := newServiceTestDB(t)
|
||||
svc := NewMerchantService(db, nil, NewTenantService(db))
|
||||
|
||||
const activeCount = 25
|
||||
for i := 0; i < activeCount; i++ {
|
||||
merchant := model.Merchant{
|
||||
Code: fmt.Sprintf("opt-merchant-%02d", i),
|
||||
Name: fmt.Sprintf("下拉商户 %02d", i),
|
||||
Status: model.MerchantStatusActive,
|
||||
}
|
||||
if err := db.Create(&merchant).Error; err != nil {
|
||||
t.Fatalf("create merchant: %v", err)
|
||||
}
|
||||
}
|
||||
disabled := model.Merchant{Code: "opt-merchant-disabled", Name: "已禁用商户", Status: model.MerchantStatusDisabled}
|
||||
if err := db.Create(&disabled).Error; err != nil {
|
||||
t.Fatalf("create disabled merchant: %v", err)
|
||||
}
|
||||
|
||||
options, err := svc.ListMerchantOptions()
|
||||
if err != nil {
|
||||
t.Fatalf("ListMerchantOptions: %v", err)
|
||||
}
|
||||
|
||||
// 期望值与库里实际的启用商户数一致(迁移会 seed 一个自营商户,不能写死数字)。
|
||||
var activeInDB int64
|
||||
if err := db.Model(&model.Merchant{}).Where("status = ?", model.MerchantStatusActive).Count(&activeInDB).Error; err != nil {
|
||||
t.Fatalf("count active merchants: %v", err)
|
||||
}
|
||||
if int64(len(options)) != activeInDB {
|
||||
t.Fatalf("期望返回全部 %d 个启用商户,实际 %d", activeInDB, len(options))
|
||||
}
|
||||
// 分页默认上限是 20、最大 100;这里必须远超它,否则说明又被分页截断了。
|
||||
if len(options) <= 20 {
|
||||
t.Fatalf("下拉必须返回全部商户,不能被分页上限截断,实际只有 %d 个", len(options))
|
||||
}
|
||||
for _, option := range options {
|
||||
if option.ID == 0 || option.Code == "" || option.Name == "" {
|
||||
t.Fatalf("选项字段不应为空:%+v", option)
|
||||
}
|
||||
if option.ID == disabled.ID {
|
||||
t.Fatal("已禁用商户不应出现在筛选下拉里")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestListMerchantsClampsOversizedPageSize 记录上面那个接口存在的真实原因:
|
||||
// 分页查询会把 >100 的 size 静默降级为 20,所以"下拉要全部商户"不能靠它。
|
||||
// 顺带钉住一个更隐蔽的事实:total 反映真实总数,而 list 已被截断。
|
||||
func TestListMerchantsClampsOversizedPageSize(t *testing.T) {
|
||||
db := newServiceTestDB(t)
|
||||
svc := NewMerchantService(db, nil, NewTenantService(db))
|
||||
|
||||
const created = 25
|
||||
for i := 0; i < created; i++ {
|
||||
merchant := model.Merchant{
|
||||
Code: fmt.Sprintf("clamp-merchant-%02d", i),
|
||||
Name: fmt.Sprintf("截断商户 %02d", i),
|
||||
Status: model.MerchantStatusActive,
|
||||
}
|
||||
if err := db.Create(&merchant).Error; err != nil {
|
||||
t.Fatalf("create merchant: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
list, total, err := svc.ListMerchants(1, 200)
|
||||
if err != nil {
|
||||
t.Fatalf("ListMerchants: %v", err)
|
||||
}
|
||||
if len(list) != 20 {
|
||||
t.Fatalf("size=200 应被降级为 20,实际返回 %d 条", len(list))
|
||||
}
|
||||
if total <= 20 {
|
||||
t.Fatalf("total 应反映真实总数(会被截断),实际 %d", total)
|
||||
}
|
||||
}
|
||||
@@ -1,106 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// secretBearingColumns 列出所有以加密形式落库的密文字段。
|
||||
// 新增落库密文时务必同步登记,否则密钥轮换会漏表。
|
||||
var secretBearingColumns = []struct {
|
||||
Table string
|
||||
Column string
|
||||
}{
|
||||
{"api_clients", "secret_ciphertext"},
|
||||
{"callback_subscriptions", "secret_ciphertext"},
|
||||
}
|
||||
|
||||
// SecretReencryptReport 汇总一次密钥轮换的重加密结果。
|
||||
type SecretReencryptReport struct {
|
||||
Scanned int // 扫描到的非空密文行数
|
||||
Reencrypted int // 用新密钥重新写入的行数
|
||||
AlreadyNewKey int // 已能用新密钥解密的行数(重复执行时出现)
|
||||
Failed int // 新旧密钥都无法解密的行数
|
||||
}
|
||||
|
||||
// SecretReencryptTable 单个表的明细,便于输出可读日志。
|
||||
type SecretReencryptTable struct {
|
||||
Table string
|
||||
Report SecretReencryptReport
|
||||
}
|
||||
|
||||
// ReencryptSecrets 使用 newCodec 重新加密所有落库密文,用于轮换 DATA_ENCRYPTION_KEY。
|
||||
//
|
||||
// apply=false 时只统计不写库(预演)。单行解密失败不会中断整轮操作,
|
||||
// 而是计入 Failed 并由调用方决定退出码,避免一行坏数据卡死整个轮换。
|
||||
// 这里使用原生 SQL 而非 GORM 模型,软删除的行同样会被处理——
|
||||
// 否则将来恢复一条软删除记录时会因为密钥没换而解密失败。
|
||||
func ReencryptSecrets(db *gorm.DB, oldCodec, newCodec *SecretCodec, apply bool) ([]SecretReencryptTable, error) {
|
||||
if oldCodec == nil || newCodec == nil {
|
||||
return nil, fmt.Errorf("新旧密钥编解码器都不能为空")
|
||||
}
|
||||
|
||||
results := make([]SecretReencryptTable, 0, len(secretBearingColumns))
|
||||
for _, target := range secretBearingColumns {
|
||||
report := SecretReencryptReport{}
|
||||
|
||||
type row struct {
|
||||
ID uint
|
||||
Ciphertext string
|
||||
}
|
||||
var rows []row
|
||||
query := fmt.Sprintf(
|
||||
"SELECT id, %s AS ciphertext FROM %s WHERE %s IS NOT NULL AND %s <> '' ORDER BY id",
|
||||
target.Column, target.Table, target.Column, target.Column,
|
||||
)
|
||||
if err := db.Raw(query).Scan(&rows).Error; err != nil {
|
||||
return results, fmt.Errorf("读取 %s.%s 失败: %w", target.Table, target.Column, err)
|
||||
}
|
||||
|
||||
for _, r := range rows {
|
||||
report.Scanned++
|
||||
|
||||
plain, err := oldCodec.Decrypt(r.Ciphertext)
|
||||
if err != nil {
|
||||
// 旧密钥解不开:可能上一轮已经换过,也可能是数据损坏,需区分对待。
|
||||
if _, newErr := newCodec.Decrypt(r.Ciphertext); newErr == nil {
|
||||
report.AlreadyNewKey++
|
||||
continue
|
||||
}
|
||||
report.Failed++
|
||||
continue
|
||||
}
|
||||
|
||||
ciphertext, err := newCodec.Encrypt(plain)
|
||||
if err != nil {
|
||||
report.Failed++
|
||||
continue
|
||||
}
|
||||
if !apply {
|
||||
report.Reencrypted++
|
||||
continue
|
||||
}
|
||||
|
||||
update := fmt.Sprintf("UPDATE %s SET %s = ? WHERE id = ?", target.Table, target.Column)
|
||||
if err := db.Exec(update, ciphertext, r.ID).Error; err != nil {
|
||||
report.Failed++
|
||||
continue
|
||||
}
|
||||
report.Reencrypted++
|
||||
}
|
||||
|
||||
results = append(results, SecretReencryptTable{Table: target.Table, Report: report})
|
||||
}
|
||||
|
||||
return results, nil
|
||||
}
|
||||
|
||||
// TotalFailed 返回所有表中解密失败的总行数,供调用方决定退出码。
|
||||
func TotalFailed(results []SecretReencryptTable) int {
|
||||
total := 0
|
||||
for _, r := range results {
|
||||
total += r.Report.Failed
|
||||
}
|
||||
return total
|
||||
}
|
||||
@@ -1,145 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"affiliate_dash/internal/model"
|
||||
"affiliate_dash/internal/testdb"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// TestReencryptSecrets 覆盖密钥轮换的三种行:旧密钥密文、已是新密钥的密文、以及无法解密的坏数据。
|
||||
// 同时验证预演(dry-run)不写库、写入模式会真正换密钥、第二张表也被覆盖、重复执行幂等。
|
||||
func TestReencryptSecrets(t *testing.T) {
|
||||
db := testdb.New(t)
|
||||
|
||||
oldCodec, err := NewSecretCodec("old-master-key-for-rotation-test")
|
||||
if err != nil {
|
||||
t.Fatalf("初始化旧密钥失败: %v", err)
|
||||
}
|
||||
newCodec, err := NewSecretCodec("new-master-key-for-rotation-test")
|
||||
if err != nil {
|
||||
t.Fatalf("初始化新密钥失败: %v", err)
|
||||
}
|
||||
|
||||
encryptWith := func(codec *SecretCodec, plain string) string {
|
||||
ciphertext, err := codec.Encrypt(plain)
|
||||
if err != nil {
|
||||
t.Fatalf("加密 %q 失败: %v", plain, err)
|
||||
}
|
||||
return ciphertext
|
||||
}
|
||||
|
||||
const corrupt = "not-a-valid-ciphertext"
|
||||
oldClientCipher := encryptWith(oldCodec, "client-secret-a1")
|
||||
newClientCipher := encryptWith(newCodec, "client-secret-a2")
|
||||
oldCallbackCipher := encryptWith(oldCodec, "callback-secret-c1")
|
||||
|
||||
clients := []model.APIClient{
|
||||
{MerchantID: 1, Name: "旧密钥客户端", AppKey: "key-a1", SecretCiphertext: oldClientCipher, Scopes: "orders:read"},
|
||||
{MerchantID: 1, Name: "已是新密钥", AppKey: "key-a2", SecretCiphertext: newClientCipher, Scopes: "orders:read"},
|
||||
{MerchantID: 1, Name: "坏数据", AppKey: "key-a3", SecretCiphertext: corrupt, Scopes: "orders:read"},
|
||||
}
|
||||
for i := range clients {
|
||||
if err := db.Create(&clients[i]).Error; err != nil {
|
||||
t.Fatalf("写入 api_clients 失败: %v", err)
|
||||
}
|
||||
}
|
||||
subscription := model.CallbackSubscription{
|
||||
MerchantID: 1,
|
||||
Name: "回调",
|
||||
URL: "https://example.com/callback",
|
||||
Events: "order.delivered",
|
||||
SecretCiphertext: oldCallbackCipher,
|
||||
}
|
||||
if err := db.Create(&subscription).Error; err != nil {
|
||||
t.Fatalf("写入 callback_subscriptions 失败: %v", err)
|
||||
}
|
||||
|
||||
// ---- 第一轮:预演,必须只统计不写库 ----
|
||||
dryRun, err := ReencryptSecrets(db, oldCodec, newCodec, false)
|
||||
if err != nil {
|
||||
t.Fatalf("预演失败: %v", err)
|
||||
}
|
||||
assertTableReport(t, dryRun, "api_clients", SecretReencryptReport{Scanned: 3, Reencrypted: 1, AlreadyNewKey: 1, Failed: 1})
|
||||
assertTableReport(t, dryRun, "callback_subscriptions", SecretReencryptReport{Scanned: 1, Reencrypted: 1})
|
||||
if got := TotalFailed(dryRun); got != 1 {
|
||||
t.Fatalf("预演期望 1 行失败,实际 %d", got)
|
||||
}
|
||||
|
||||
var afterDryRun model.APIClient
|
||||
if err := db.First(&afterDryRun, clients[0].ID).Error; err != nil {
|
||||
t.Fatalf("读取客户端失败: %v", err)
|
||||
}
|
||||
if afterDryRun.SecretCiphertext != oldClientCipher {
|
||||
t.Fatal("预演不应修改数据库,但密文已被改写")
|
||||
}
|
||||
|
||||
// ---- 第二轮:真正写入 ----
|
||||
applied, err := ReencryptSecrets(db, oldCodec, newCodec, true)
|
||||
if err != nil {
|
||||
t.Fatalf("写入失败: %v", err)
|
||||
}
|
||||
assertTableReport(t, applied, "api_clients", SecretReencryptReport{Scanned: 3, Reencrypted: 1, AlreadyNewKey: 1, Failed: 1})
|
||||
assertTableReport(t, applied, "callback_subscriptions", SecretReencryptReport{Scanned: 1, Reencrypted: 1})
|
||||
|
||||
// 换过密钥的行必须能被新密钥解开,且旧密钥已解不开。
|
||||
assertStoredCipherDecryptsTo(t, db, newCodec, "api_clients", clients[0].ID, "client-secret-a1")
|
||||
assertStoredCipherDecryptsTo(t, db, newCodec, "callback_subscriptions", subscription.ID, "callback-secret-c1")
|
||||
|
||||
var migrated model.APIClient
|
||||
if err := db.First(&migrated, clients[0].ID).Error; err != nil {
|
||||
t.Fatalf("读取客户端失败: %v", err)
|
||||
}
|
||||
if _, err := oldCodec.Decrypt(migrated.SecretCiphertext); err == nil {
|
||||
t.Fatal("换密钥后旧密钥不应还能解密")
|
||||
}
|
||||
|
||||
// 坏数据必须原样保留,等待人工排查。
|
||||
var broken model.APIClient
|
||||
if err := db.First(&broken, clients[2].ID).Error; err != nil {
|
||||
t.Fatalf("读取坏数据行失败: %v", err)
|
||||
}
|
||||
if broken.SecretCiphertext != corrupt {
|
||||
t.Fatalf("坏数据行不应被改写,实际变为 %q", broken.SecretCiphertext)
|
||||
}
|
||||
|
||||
// ---- 第三轮:重复执行必须幂等,全部识别为已是新密钥 ----
|
||||
again, err := ReencryptSecrets(db, oldCodec, newCodec, true)
|
||||
if err != nil {
|
||||
t.Fatalf("重复执行失败: %v", err)
|
||||
}
|
||||
assertTableReport(t, again, "api_clients", SecretReencryptReport{Scanned: 3, AlreadyNewKey: 2, Failed: 1})
|
||||
assertTableReport(t, again, "callback_subscriptions", SecretReencryptReport{Scanned: 1, AlreadyNewKey: 1})
|
||||
}
|
||||
|
||||
func assertTableReport(t *testing.T, results []SecretReencryptTable, table string, want SecretReencryptReport) {
|
||||
t.Helper()
|
||||
for _, r := range results {
|
||||
if r.Table == table {
|
||||
if r.Report != want {
|
||||
t.Fatalf("%s 统计不符:期望 %+v,实际 %+v", table, want, r.Report)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
t.Fatalf("结果中缺少表 %s", table)
|
||||
}
|
||||
|
||||
// assertStoredCipherDecryptsTo 从库里读回密文,确认其能被指定密钥解出期望明文。
|
||||
func assertStoredCipherDecryptsTo(t *testing.T, db *gorm.DB, codec *SecretCodec, table string, id uint, wantPlain string) {
|
||||
t.Helper()
|
||||
var stored string
|
||||
query := "SELECT secret_ciphertext FROM " + table + " WHERE id = ?"
|
||||
if err := db.Raw(query, id).Scan(&stored).Error; err != nil {
|
||||
t.Fatalf("读取 %s#%d 密文失败: %v", table, id, err)
|
||||
}
|
||||
plain, err := codec.Decrypt(stored)
|
||||
if err != nil {
|
||||
t.Fatalf("%s#%d 无法用新密钥解密: %v", table, id, err)
|
||||
}
|
||||
if plain != wantPlain {
|
||||
t.Fatalf("%s#%d 明文不符:期望 %q,实际 %q", table, id, wantPlain, plain)
|
||||
}
|
||||
}
|
||||
-126
@@ -1,126 +0,0 @@
|
||||
# 密钥轮换说明
|
||||
|
||||
> 适用版本:2026-10-06 及之后
|
||||
> 相关代码:`backend/internal/config/config.go`、`backend/internal/service/secret_codec.go`、`backend/cmd/reencrypt_secrets`
|
||||
|
||||
## 1. 为什么需要这份文档
|
||||
|
||||
项目里有两个主密钥,职责完全不同,但历史上 `DATA_ENCRYPTION_KEY` 允许回退到 `JWT_SECRET`,
|
||||
导致两者经常是同一个值 —— 一旦这个值还是 `.env.example` 里的示例值,就同时意味着:
|
||||
|
||||
- 任何人看过仓库都能**伪造管理员 JWT**(`pkg/jwt` 用 `JWT_SECRET` 做 HS256 签名);
|
||||
- 任何人看过仓库都能**解密库里所有 API Client / 回调密钥**(AES-256-GCM,密钥由 `DATA_ENCRYPTION_KEY` 派生)。
|
||||
|
||||
所以正确做法是:**两个密钥必须独立、随机、且绝不使用示例值**。
|
||||
服务启动时会自动体检并在日志里打出安全告警(`[CONFIG] 安全告警: ...`),看到告警就说明配置需要修。
|
||||
|
||||
## 2. 两个密钥的职责
|
||||
|
||||
| 变量 | 用途 | 泄露后果 | 能否随意更换 |
|
||||
|------|------|----------|--------------|
|
||||
| `JWT_SECRET` | 签发/校验后台登录 Token(HS256) | 可伪造任意角色登录后台 | 可以,代价是**所有人被踢下线需重新登录** |
|
||||
| `DATA_ENCRYPTION_KEY` | 派生 AES-256-GCM 主密钥,加密落库的第三方密钥 | 可解密库中全部密文 | 可以,但**必须先重加密存量密文** |
|
||||
|
||||
## 3. 首次配置
|
||||
|
||||
```bash
|
||||
cp .env.example .env
|
||||
# 分别生成,不要复用同一个值
|
||||
echo "JWT_SECRET=$(openssl rand -hex 48)" >> .env # 或直接编辑 .env
|
||||
echo "DATA_ENCRYPTION_KEY=$(openssl rand -hex 32)" >> .env
|
||||
```
|
||||
|
||||
要求:两者非空且互不相同。`.env` 已在 `.gitignore` 中,**不要**把真实密钥写进 `.env.example`。
|
||||
|
||||
## 4. 轮换 `JWT_SECRET`(简单)
|
||||
|
||||
不需要动数据,直接改值并重启服务即可:
|
||||
|
||||
```bash
|
||||
# 1. 备份(备份文件已被 .gitignore 覆盖,不会误提交)
|
||||
cp .env ".env.bak.$(date +%Y%m%d%H%M%S)"
|
||||
# 2. 修改 .env 中的 JWT_SECRET
|
||||
# 3. 重启服务
|
||||
```
|
||||
|
||||
影响:所有已签发 Token 立即失效,用户需重新登录。
|
||||
|
||||
## 5. 轮换 `DATA_ENCRYPTION_KEY`(需要重加密)
|
||||
|
||||
> 只改环境变量会导致存量密文无法解密:商户的 `X-App-Key` 鉴权会全部失败,回调也发不出去。
|
||||
|
||||
**第 1 步:备份数据库**(重加密是原地更新,必须先有可回滚的快照)
|
||||
|
||||
```bash
|
||||
pg_dump "$DATABASE_URL" > backup-before-rotation.sql
|
||||
```
|
||||
|
||||
**第 2 步:备份 `.env`**
|
||||
|
||||
```bash
|
||||
cp .env ".env.bak.$(date +%Y%m%d%H%M%S)"
|
||||
```
|
||||
|
||||
**第 3 步:把新的 `DATA_ENCRYPTION_KEY` 写入 `.env`,先不要重启服务。**
|
||||
|
||||
**第 4 步:预演**(只统计,不写库)
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
OLD_DATA_ENCRYPTION_KEY='<轮换前的密钥>' go run ./cmd/reencrypt_secrets
|
||||
```
|
||||
|
||||
输出示例:
|
||||
|
||||
```
|
||||
密钥轮换模式: 预演(dry-run)
|
||||
|
||||
api_clients 扫描=12 重加密=12 已是新密钥=0 失败=0
|
||||
callback_subscriptions 扫描=3 重加密=3 已是新密钥=0 失败=0
|
||||
|
||||
预演完成,未修改任何数据。确认无误后加 -apply 执行写入。
|
||||
```
|
||||
|
||||
- `失败` 不为 0 时命令会以非零退出,且**不会修改任何数据**。请先确认这些行的来源(通常是历史脏数据),再决定处理方式。
|
||||
- 若旧密钥曾经回退到 `JWT_SECRET`,可以用 `OLD_JWT_SECRET='<旧 JWT_SECRET>'` 代替 `OLD_DATA_ENCRYPTION_KEY`。
|
||||
|
||||
**第 5 步:真正写入**
|
||||
|
||||
```bash
|
||||
OLD_DATA_ENCRYPTION_KEY='<轮换前的密钥>' go run ./cmd/reencrypt_secrets -apply
|
||||
```
|
||||
|
||||
**第 6 步:重启服务并验证**
|
||||
|
||||
- 服务启动日志中**不再出现** `DATA_ENCRYPTION_KEY` 相关安全告警;
|
||||
- 用任一商户的 `X-App-Key` 调一次 `/api/client/v1/products`,确认签名校验通过;
|
||||
- 在商户后台确认回调密钥可见/可正常推送。
|
||||
|
||||
**第 7 步:确认稳定后删除备份**
|
||||
|
||||
```bash
|
||||
rm .env.bak.* backup-before-rotation.sql
|
||||
```
|
||||
|
||||
工具是幂等的:重复执行时,已用新密钥加密的行会被识别为 `已是新密钥`,不会被二次加密。
|
||||
|
||||
## 6. 涉及的表
|
||||
|
||||
重加密工具覆盖所有以密文落库的字段。字段清单集中在
|
||||
`backend/internal/service/secret_reencrypt.go` 的 `secretBearingColumns`:
|
||||
|
||||
| 表 | 字段 | 说明 |
|
||||
|----|------|------|
|
||||
| `api_clients` | `secret_ciphertext` | 商户开放接口签名密钥 |
|
||||
| `callback_subscriptions` | `secret_ciphertext` | 商户回调签名密钥 |
|
||||
|
||||
> **新增任何落库密文字段时,必须同步登记到 `secretBearingColumns`**,否则该字段会在密钥轮换中被漏掉。
|
||||
|
||||
## 7. 回滚
|
||||
|
||||
1. 停止服务;
|
||||
2. 恢复 `.env` 备份(旧的 `DATA_ENCRYPTION_KEY`);
|
||||
3. 恢复数据库快照;
|
||||
4. 启动服务。
|
||||
|
||||
注意:**只回滚 `.env` 而不回滚数据库是无效的** —— 第 5 步已经用新密钥覆盖了密文。
|
||||
+67
-32
@@ -134,39 +134,15 @@ FulfillmentProvider → PrepareDelivery / Bind / CheckBind / Submit / SyncStatus
|
||||
|
||||
### 6.1 密钥配置修复(P0)
|
||||
|
||||
**问题**:`.env` 中 `JWT_SECRET` 与 `.env.example` 逐字节相同(公开的示例值),
|
||||
且 `DATA_ENCRYPTION_KEY` 未设置,按 `config.go` 的回退逻辑实际等于 `JWT_SECRET`。
|
||||
后果是任何见过仓库的人都能伪造管理员 JWT,并解密库中全部 API/回调密钥密文。
|
||||
**问题**:`.env` 中 `JWT_SECRET` 与 `.env.example` 逐字节相同(公开的示例值)。后果是任何见过仓库的人都能伪造管理员 JWT,并解密库中 API/回调密钥密文。
|
||||
|
||||
**处理**:
|
||||
**处理(务实单主密钥架构)**:
|
||||
|
||||
| 项 | 内容 |
|
||||
|----|------|
|
||||
| 生成新密钥 | `JWT_SECRET` 96 位十六进制(384-bit)、`DATA_ENCRYPTION_KEY` 64 位十六进制(256-bit),两者独立 |
|
||||
| 历史密文迁移 | 开发库 11 条 `api_clients` + 10 条 `callback_subscriptions` 已用 `cmd/reencrypt_secrets` 重加密,0 失败 |
|
||||
| 新增防护 | `Config.SecurityWarnings()` 启动体检,示例密钥 / 未分离 / release 下开调试日志均打印 `[CONFIG] 安全告警` |
|
||||
| 新增工具 | `backend/cmd/reencrypt_secrets`(默认预演,`-apply` 才写库;幂等,坏数据不中断整轮) |
|
||||
| 新增文档 | [`密钥轮换说明.md`](密钥轮换说明.md) |
|
||||
| 其他 | `.env` 中 `OPEN_API_DEBUG` 由 `true` 改为 `false`;`.gitignore` 忽略 `.env.bak*` |
|
||||
|
||||
**验证证据**:
|
||||
|
||||
```
|
||||
# 负例:故意使用示例密钥 → 告警如期触发,/health 仍 200
|
||||
[WARN] [CONFIG] 安全告警: JWT_SECRET 仍是 .env.example 里的示例值,任何见过仓库的人都能伪造管理员 Token
|
||||
[WARN] [CONFIG] 安全告警: DATA_ENCRYPTION_KEY 未显式设置,已回退到 JWT_SECRET;…
|
||||
[WARN] [CONFIG] 安全告警: DATA_ENCRYPTION_KEY 与 JWT_SECRET 相同,建议分离以便独立轮换
|
||||
|
||||
# 正例:使用新密钥 → 0 条告警
|
||||
游戏皮肤供货平台 API 启动: http://localhost:18080
|
||||
|
||||
# 重加密:预演 → 写入 → 复跑幂等
|
||||
api_clients 扫描=11 重加密=11 已是新密钥=0 失败=0
|
||||
callback_subscriptions 扫描=10 重加密=10 已是新密钥=0 失败=0
|
||||
# 复跑(预演)
|
||||
api_clients 扫描=11 重加密=0 已是新密钥=11 失败=0
|
||||
callback_subscriptions 扫描=10 重加密=0 已是新密钥=10 失败=0
|
||||
```
|
||||
| 架构简化 | 统一由 `JWT_SECRET` 承接 JWT 签发与 AES-GCM 敏感数据加密,避免单机容器环境下拆分双密钥的伪隔离与高危全表重加密脚本 |
|
||||
| 启动体检 | 启动时仅在仍使用公开示例密钥或 release 模式误开 `OPEN_API_DEBUG` 时告警,保持启动日志干净 |
|
||||
| 灵活兼容 | 保留可选的 `DATA_ENCRYPTION_KEY` 环境变量读取,未设置时自动由主密钥派生 |
|
||||
|
||||
### 6.2 测试可运行性修复(P1)
|
||||
|
||||
@@ -350,7 +326,67 @@ DB 里的值被静默忽略,且没有任何日志提示。
|
||||
|
||||
---
|
||||
|
||||
## 八、本地开发与验证
|
||||
## 八、管理端商户上下文复盘(2026-10-06)
|
||||
|
||||
起因是一个来自使用者的反馈:**「超级管理员是不是看不到下游订单?」**
|
||||
实测后确认属实,而且比"看不到"更糟——同一身份在同一时刻看到两个互相矛盾的数字。
|
||||
|
||||
### 8.1 现象(实测数据)
|
||||
|
||||
| 调用 | 结果 |
|
||||
|------|------|
|
||||
| `GET /api/dashboard`(管理员) | `scope=platform`,`order_count=37` |
|
||||
| `GET /api/merchant/orders`(管理员,默认) | `total=29`,全部为自营商户 |
|
||||
| `GET /api/merchant/orders` + `X-Merchant-ID: 2` | `total=8` |
|
||||
| 数据库实际分布 | 自营商户 29 + 测试商户 8 = 37 |
|
||||
|
||||
首页显示 37 单、订单页只有 29 单,界面上没有任何解释。
|
||||
|
||||
### 8.2 根因:`role=admin` 在两个接口里语义不同
|
||||
|
||||
- `handler/order.go` 的 `isPlatformAdmin` 只看 JWT 角色 → 统计是**平台视角**,跨商户聚合;
|
||||
- `middleware.Tenant` 只认 `X-Merchant-ID`,没有就回退到账号自己的成员关系 →
|
||||
管理员唯一的成员关系是自营商户,被**静默框定在单个商户**;
|
||||
- 35 条 `/platform/*` 路由里没有任何订单入口,前端也没有商户切换器或上下文提示。
|
||||
|
||||
### 8.3 更深一层:三个设计问题
|
||||
|
||||
1. **`Tenant` 中间件把「解析」与「授权」揉在一起**,解析失败直接 403。
|
||||
而解析失败有两种完全不同的原因——客户端状态过期(商户被禁用/删除)与真的无权限——
|
||||
中间件把它们压成同一个 403,客户端无法区分,也就无法自愈。
|
||||
2. **它挂在「所有已登录请求」上**,包括根本不看商户的平台接口。
|
||||
于是「LocalStorage 里躺了一个已失效的商户 ID」这种客户端状态问题,
|
||||
升级成了**整个管理端不可用**:连去把上下文改回来的平台页面都打不开。
|
||||
3. **商户上下文是前端自由拼装的请求头,不是受控状态**。
|
||||
它只存在 `localStorage`,只在登录/登出时清除;唯一的写入点是「平台商户」页的
|
||||
「成员」按钮(一个副作用),没有显式入口、没有提示、也没有退出方式。
|
||||
|
||||
### 8.4 处理
|
||||
|
||||
| 提交 | 内容 |
|
||||
|------|------|
|
||||
| `8c12d1d` | 新增 `GET /api/platform/orders` 跨商户订单视图 + 前端「下游订单」页;商户侧隔离语义不动,并补测试卡住边界 |
|
||||
| `e692790` | 平台分组从 `Tenant` 中摘出(逐条核对:35 条平台路由对租户的依赖为 0);前端对 `/platform/*` 与管理员 `/dashboard` 不再发送 `X-Merchant-ID` |
|
||||
| `04c3369` | 顶栏常驻显示「当前商户:xxx」+「退出商户视角」 |
|
||||
| `663d7e1` | 自查发现筛选下拉被分页上限静默截断,新增不分页的 `/api/platform/merchant-options` |
|
||||
|
||||
**关于"为什么不静默回退"**:商户上下文解析失败时后端仍返回 403。
|
||||
商户后台存在写操作(人工下单、取消订单、成员管理),若自动回退到默认商户,
|
||||
写入会落到**错误的商户**上——这比"多点一次退出"严重得多。
|
||||
因此选择「失败要响,但必须给得出路」,出路就是顶栏的退出入口。
|
||||
|
||||
### 8.5 修复后仍然存在的风险
|
||||
|
||||
| 风险 | 说明 | 建议 |
|
||||
|------|------|------|
|
||||
| 仍走 `Tenant` 的 42 条路由(37 merchant + 5 auth)在上下文失效时返回 403 | 前端已跳过管理员的 `/platform/*` 与 `/dashboard` 请求头,但 curl / 移动端 / 旧的缓存 bundle 仍会命中 | 给 `Tenant` 的失败加上可识别的业务错误码,客户端据此清理上下文并重试一次,实现自愈 |
|
||||
| `response.Page` 回显的是**请求的** `size`,不是**生效的** `size` | `normalizePage` 会把 `size>100` 降级为 20,但响应里仍写 200,客户端按它翻页会跳数据 | 把 size 归一化上移到 handler 边界,或让 service 返回生效值 |
|
||||
| 平台路由不再解析商户上下文 | 这是有意的:平台接口本来就跨商户。但未来若某个平台接口**确实需要**知道当前商户,不能再依赖 `GetMerchantID`,必须显式传参 | 在 router 的注释里已写明该约束 |
|
||||
| 平台商户列表页缺少「以该商户视角查看」入口 | 目前仍只能靠「成员」按钮的副作用进入商户上下文 | 补一个显式按钮 |
|
||||
|
||||
---
|
||||
|
||||
## 九、本地开发与验证
|
||||
|
||||
```bash
|
||||
make install # 安装前后端依赖
|
||||
@@ -360,5 +396,4 @@ make lint # go vet + oxlint
|
||||
make fmt # gofmt 格式化
|
||||
```
|
||||
|
||||
首次配置必须为 `JWT_SECRET` 与 `DATA_ENCRYPTION_KEY` 各自生成随机值,
|
||||
详见 [`密钥轮换说明.md`](密钥轮换说明.md)。
|
||||
生产环境部署时将 `JWT_SECRET` 配置为独立强随机密钥即可。
|
||||
|
||||
@@ -19,6 +19,7 @@ const MerchantCenter = lazy(() => import('./pages/MerchantCenter'))
|
||||
const MerchantRecharge = lazy(() => import('./pages/MerchantRecharge'))
|
||||
const AlertSettings = lazy(() => import('./pages/AlertSettings'))
|
||||
const PlatformMerchants = lazy(() => import('./pages/PlatformMerchants'))
|
||||
const PlatformOrders = lazy(() => import('./pages/PlatformOrders'))
|
||||
const PlatformProducts = lazy(() => import('./pages/PlatformProducts'))
|
||||
const PlatformUsers = lazy(() => import('./pages/PlatformUsers'))
|
||||
const PlatformRock = lazy(() => import('./pages/PlatformRock'))
|
||||
@@ -92,6 +93,14 @@ function AppRoutes() {
|
||||
<Route path="merchant-members" element={<MerchantPermissionRoute permission="members:manage"><MerchantCenter fixedTab="members" title="成员" /></MerchantPermissionRoute>} />
|
||||
<Route path="merchant-callbacks" element={<MerchantPermissionRoute permission="callbacks:manage"><MerchantCenter fixedTab="callbacks" title="回调" /></MerchantPermissionRoute>} />
|
||||
<Route path="merchant-api-keys" element={<MerchantPermissionRoute permission="api:manage"><MerchantCenter fixedTab="api" title="API 密钥" /></MerchantPermissionRoute>} />
|
||||
<Route
|
||||
path="platform-orders"
|
||||
element={
|
||||
<AdminRoute>
|
||||
<PlatformOrders />
|
||||
</AdminRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="platform-merchants"
|
||||
element={
|
||||
|
||||
@@ -19,6 +19,7 @@ import type {
|
||||
Merchant,
|
||||
MerchantMember,
|
||||
MerchantMemberGroup,
|
||||
MerchantOption,
|
||||
MerchantOwnerAccount,
|
||||
MerchantRole,
|
||||
MerchantProduct,
|
||||
@@ -207,6 +208,12 @@ export const platformApi = {
|
||||
request.delete(`/platform/merchant-accounts/${userId}`).then((r) => r.data.data),
|
||||
merchants: (params?: Record<string, unknown>) =>
|
||||
request.get('/platform/merchants', { params }).then((r) => r.data.data as PageResult<Merchant>),
|
||||
// 不分页的精简商户列表,供筛选下拉使用(/platform/merchants 的 size 上限是 100)
|
||||
merchantOptions: () =>
|
||||
request.get('/platform/merchant-options').then((r) => r.data.data as MerchantOption[]),
|
||||
// 平台侧跨商户订单视图:不传 merchant_id 即全部商户
|
||||
orders: (params?: Record<string, unknown>) =>
|
||||
request.get('/platform/orders', { params }).then((r) => r.data.data as PageResult<FulfillmentOrder>),
|
||||
createMerchant: (data: {
|
||||
code: string
|
||||
name: string
|
||||
|
||||
@@ -6,13 +6,28 @@ const request = axios.create({
|
||||
timeout: 15000,
|
||||
})
|
||||
|
||||
function currentRole(): string {
|
||||
try {
|
||||
return JSON.parse(localStorage.getItem('user') || 'null')?.role || ''
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
request.interceptors.request.use((config) => {
|
||||
const token = localStorage.getItem('token')
|
||||
if (token) {
|
||||
config.headers.Authorization = `Bearer ${token}`
|
||||
}
|
||||
// 对「商户上下文本来就不起作用」的接口,刻意不带 X-Merchant-ID:
|
||||
// - /platform/*:平台侧接口本身就是跨商户的;
|
||||
// - 管理员的 /dashboard:后端按角色判定为平台口径,压根不看商户。
|
||||
// 更要紧的是,一旦 localStorage 里残留的是已禁用/已删除的商户,服务端会对这些
|
||||
// 本该正常的请求直接 403。后端已把平台路由从租户中间件里摘出来,这里是第二道防线。
|
||||
const url = config.url || ''
|
||||
const merchantContextIrrelevant = url.startsWith('/platform/') || (url === '/dashboard' && currentRole() === 'admin')
|
||||
const merchantId = localStorage.getItem('merchant_id')
|
||||
if (merchantId) {
|
||||
if (merchantId && !merchantContextIrrelevant) {
|
||||
config.headers['X-Merchant-ID'] = merchantId
|
||||
}
|
||||
return config
|
||||
|
||||
@@ -88,7 +88,10 @@ const adminSections: SidebarSection[] = [
|
||||
key: 'orders',
|
||||
label: '订单管理',
|
||||
icon: <OrderedListOutlined />,
|
||||
children: [{ key: 'fulfillment-orders', label: '发货订单', path: '/merchant-orders' }],
|
||||
children: [
|
||||
{ key: 'platform-orders', label: '下游订单(全部商户)', path: '/platform-orders' },
|
||||
{ key: 'fulfillment-orders', label: '发货订单(当前商户)', path: '/merchant-orders' },
|
||||
],
|
||||
},
|
||||
{
|
||||
key: 'staff',
|
||||
@@ -226,6 +229,16 @@ export default function MainLayout() {
|
||||
return localStorage.getItem(SIDEBAR_COLLAPSED_KEY) === 'true'
|
||||
})
|
||||
const { user, logout, refreshProfile, isAdmin, merchant, merchantPermissions } = useAuth()
|
||||
// 管理员的商户上下文来自 localStorage(即请求头 X-Merchant-ID 的来源),
|
||||
// 之前只会在「平台商户」页点「成员」时被写入,界面上没有任何提示——
|
||||
// 管理员很容易以为自己看的是全平台数据,实际被静默框定在某个商户里。
|
||||
const [activeMerchantId] = useState<string | null>(() => localStorage.getItem('merchant_id'))
|
||||
const merchantContextLabel = merchant?.name || (activeMerchantId ? `商户 #${activeMerchantId}` : '默认商户')
|
||||
const exitMerchantContext = () => {
|
||||
localStorage.removeItem('merchant_id')
|
||||
// 整页刷新:上下文变了,当前页已经加载的数据也必须按新上下文重新取一遍。
|
||||
window.location.reload()
|
||||
}
|
||||
const [passwordOpen, setPasswordOpen] = useState(false)
|
||||
const [passwordSaving, setPasswordSaving] = useState(false)
|
||||
const [passwordForm] = Form.useForm()
|
||||
@@ -418,6 +431,22 @@ export default function MainLayout() {
|
||||
<div className="app-header__right">
|
||||
{isAdmin && (
|
||||
<Space size="small">
|
||||
<Tooltip title="商户后台页面(发货订单 / 商品 / 钱包 / 成员等)都按这个商户隔离;首页看板与「下游订单」是平台口径,不受它影响">
|
||||
<Tag
|
||||
color={activeMerchantId ? 'orange' : 'default'}
|
||||
bordered={false}
|
||||
style={{ margin: 0, fontSize: 11.5, fontWeight: 600 }}
|
||||
>
|
||||
当前商户:{merchantContextLabel}
|
||||
</Tag>
|
||||
</Tooltip>
|
||||
{activeMerchantId && (
|
||||
<Tooltip title="回到你的默认商户上下文(自营商户)">
|
||||
<Button type="text" size="small" onClick={exitMerchantContext}>
|
||||
退出商户视角
|
||||
</Button>
|
||||
</Tooltip>
|
||||
)}
|
||||
<Tooltip title="开放 API 接口文档">
|
||||
<Button
|
||||
type="text"
|
||||
|
||||
@@ -0,0 +1,252 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import { Button, Card, Col, Empty, Input, Row, Select, Space, Table, Tag, Typography, message } from 'antd'
|
||||
import type { ColumnsType } from 'antd/es/table'
|
||||
import { ReloadOutlined, SearchOutlined } from '@ant-design/icons'
|
||||
import { platformApi } from '../api'
|
||||
import { PageHeader } from '../components/PageHeader'
|
||||
import type { FulfillmentOrder, MerchantOption, PageResult } from '../types'
|
||||
import { formatDateTime } from '../utils/time'
|
||||
import { money, orderStatusMap, orderStatusOptions, pageConfig } from './merchantCenterUtils'
|
||||
|
||||
const { Text } = Typography
|
||||
|
||||
const sourceOptions = [
|
||||
{ value: '', label: '全部来源' },
|
||||
{ value: 'api', label: '开放接口' },
|
||||
{ value: 'manual', label: '人工下单' },
|
||||
{ value: 'test', label: '联调测试' },
|
||||
]
|
||||
|
||||
const sourceText: Record<string, string> = {
|
||||
api: '开放接口',
|
||||
manual: '人工下单',
|
||||
test: '联调测试',
|
||||
}
|
||||
|
||||
interface OrderFilters {
|
||||
merchantId?: number
|
||||
orderStatus?: string
|
||||
orderSource?: string
|
||||
keyword?: string
|
||||
}
|
||||
|
||||
const emptyPage: PageResult<FulfillmentOrder> = { list: [], total: 0, page: 1, size: 20 }
|
||||
|
||||
function orderStatusTag(value: string) {
|
||||
const item = orderStatusMap[value] || { color: 'default', text: value }
|
||||
return <Tag color={item.color}>{item.text}</Tag>
|
||||
}
|
||||
|
||||
/**
|
||||
* 平台侧「下游订单」页。
|
||||
*
|
||||
* 存在的理由:商户后台的「发货订单」走 /api/merchant/orders,服务端强制按单个商户隔离,
|
||||
* 而管理员的默认商户上下文是自营商户——于是首页 Dashboard 显示平台总量(跨商户),
|
||||
* 订单页却只显示自营商户的量,两个数字对不上且无法解释。本页走 /api/platform/orders,
|
||||
* 不依赖 X-Merchant-ID,管理员可以在这里看到全部下游商户的订单。
|
||||
*/
|
||||
export default function PlatformOrders() {
|
||||
const [data, setData] = useState<PageResult<FulfillmentOrder>>(emptyPage)
|
||||
const [merchants, setMerchants] = useState<MerchantOption[]>([])
|
||||
const [loading, setLoading] = useState(false)
|
||||
|
||||
const [page, setPage] = useState(1)
|
||||
const [size, setSize] = useState(20)
|
||||
// 已提交的筛选条件即唯一数据源,由 effect 驱动查询;
|
||||
// 关键字另存草稿,避免每敲一个字就打一次接口。
|
||||
const [filters, setFilters] = useState<OrderFilters>({})
|
||||
const [keywordDraft, setKeywordDraft] = useState('')
|
||||
|
||||
const load = useCallback(async () => {
|
||||
const params: Record<string, unknown> = { page, size }
|
||||
if (filters.merchantId) params.merchant_id = filters.merchantId
|
||||
if (filters.orderStatus) params.order_status = filters.orderStatus
|
||||
if (filters.orderSource) params.order_source = filters.orderSource
|
||||
if (filters.keyword) params.keyword = filters.keyword
|
||||
|
||||
setLoading(true)
|
||||
try {
|
||||
setData(await platformApi.orders(params))
|
||||
} catch (e) {
|
||||
message.error(e instanceof Error ? e.message : '加载下游订单失败')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [page, size, filters])
|
||||
|
||||
useEffect(() => {
|
||||
void load()
|
||||
}, [load])
|
||||
|
||||
useEffect(() => {
|
||||
// 用不分页的精简接口:/platform/merchants 的 size 上限是 100,
|
||||
// 传更大的值会被静默降级,下拉里会少一批商户。
|
||||
platformApi
|
||||
.merchantOptions()
|
||||
.then((options) => setMerchants(options || []))
|
||||
.catch(() => setMerchants([]))
|
||||
}, [])
|
||||
|
||||
// 改筛选条件时回到第一页,避免停留在越界页码上看到空列表。
|
||||
const updateFilters = useCallback((patch: Partial<OrderFilters>) => {
|
||||
setPage(1)
|
||||
setFilters((prev) => ({ ...prev, ...patch }))
|
||||
}, [])
|
||||
|
||||
const submitKeyword = useCallback(() => {
|
||||
updateFilters({ keyword: keywordDraft.trim() || undefined })
|
||||
}, [keywordDraft, updateFilters])
|
||||
|
||||
const columns: ColumnsType<FulfillmentOrder> = useMemo(
|
||||
() => [
|
||||
{
|
||||
title: '所属商户',
|
||||
dataIndex: 'merchant_id',
|
||||
width: 220,
|
||||
render: (_, record) => (
|
||||
<Space direction="vertical" size={0}>
|
||||
<Text strong>{record.merchant?.name || `商户 #${record.merchant_id}`}</Text>
|
||||
<Text type="secondary" style={{ fontSize: 12 }}>{record.merchant?.code || '-'}</Text>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '订单号 / 商户单号',
|
||||
dataIndex: 'order_no',
|
||||
width: 260,
|
||||
render: (_, record) => (
|
||||
<Space direction="vertical" size={0}>
|
||||
<Text copyable={{ text: record.order_no }} strong style={{ fontFamily: 'monospace', fontSize: 12 }}>
|
||||
{record.order_no}
|
||||
</Text>
|
||||
<Text type="secondary" style={{ fontSize: 12, fontFamily: 'monospace' }}>
|
||||
{record.client_order_no || '-'}
|
||||
</Text>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '商品',
|
||||
dataIndex: 'product_name',
|
||||
width: 190,
|
||||
render: (_, record) => (
|
||||
<Space direction="vertical" size={0}>
|
||||
<Text>{record.product_name}</Text>
|
||||
<Text type="secondary" style={{ fontSize: 12 }}>{record.product_sku}</Text>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '金额',
|
||||
dataIndex: 'amount',
|
||||
width: 120,
|
||||
align: 'right',
|
||||
render: (value) => money(value),
|
||||
},
|
||||
{
|
||||
title: '状态',
|
||||
dataIndex: 'order_status',
|
||||
width: 100,
|
||||
render: (value) => orderStatusTag(value),
|
||||
},
|
||||
{
|
||||
title: '来源',
|
||||
dataIndex: 'order_source',
|
||||
width: 100,
|
||||
render: (value) => <Tag>{sourceText[value] || value}</Tag>,
|
||||
},
|
||||
{
|
||||
title: '创建时间',
|
||||
dataIndex: 'created_at',
|
||||
width: 175,
|
||||
render: formatDateTime,
|
||||
},
|
||||
{
|
||||
title: '上游单号',
|
||||
dataIndex: 'provider_order_no',
|
||||
width: 200,
|
||||
render: (value) => value
|
||||
? <Text copyable={{ text: value }} style={{ fontFamily: 'monospace', fontSize: 12 }}>{value}</Text>
|
||||
: <Text type="secondary">-</Text>,
|
||||
},
|
||||
],
|
||||
[],
|
||||
)
|
||||
|
||||
return (
|
||||
<div>
|
||||
<PageHeader
|
||||
title="下游订单"
|
||||
subtitle="平台视角:跨全部下游商户,不随当前商户上下文变化。商户后台的「发货订单」只显示单个商户。"
|
||||
breadcrumbs={[{ title: '下游订单' }]}
|
||||
extra={
|
||||
<Button icon={<ReloadOutlined />} loading={loading} onClick={() => void load()}>
|
||||
刷新
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
|
||||
<Card style={{ marginBottom: 16, borderRadius: 10, border: '1px solid #e2e8f0' }} styles={{ body: { padding: '16px 20px' } }}>
|
||||
<Row gutter={[12, 12]} align="middle">
|
||||
<Col xs={24} md={6}>
|
||||
<Select
|
||||
allowClear
|
||||
style={{ width: '100%' }}
|
||||
placeholder="全部商户"
|
||||
value={filters.merchantId}
|
||||
onChange={(value) => updateFilters({ merchantId: value })}
|
||||
options={merchants.map((item) => ({ value: item.id, label: `${item.name}(${item.code})` }))}
|
||||
/>
|
||||
</Col>
|
||||
<Col xs={24} md={6}>
|
||||
<Select
|
||||
style={{ width: '100%' }}
|
||||
value={filters.orderStatus || ''}
|
||||
onChange={(value) => updateFilters({ orderStatus: value || undefined })}
|
||||
options={orderStatusOptions.map((item) => ({
|
||||
value: item.value,
|
||||
label: item.value === '' ? '全部状态' : item.label,
|
||||
}))}
|
||||
/>
|
||||
</Col>
|
||||
<Col xs={24} md={5}>
|
||||
<Select
|
||||
style={{ width: '100%' }}
|
||||
value={filters.orderSource || ''}
|
||||
onChange={(value) => updateFilters({ orderSource: value || undefined })}
|
||||
options={sourceOptions}
|
||||
/>
|
||||
</Col>
|
||||
<Col xs={24} md={7}>
|
||||
<Space.Compact style={{ width: '100%' }}>
|
||||
<Input
|
||||
allowClear
|
||||
placeholder="订单号 / 商户单号"
|
||||
prefix={<SearchOutlined style={{ color: '#94a3b8' }} />}
|
||||
value={keywordDraft}
|
||||
onChange={(e) => setKeywordDraft(e.target.value)}
|
||||
onPressEnter={submitKeyword}
|
||||
/>
|
||||
<Button type="primary" onClick={submitKeyword}>查询</Button>
|
||||
</Space.Compact>
|
||||
</Col>
|
||||
</Row>
|
||||
</Card>
|
||||
|
||||
<Card style={{ borderRadius: 10, border: '1px solid #e2e8f0' }} styles={{ body: { padding: 0 } }}>
|
||||
<Table
|
||||
rowKey="id"
|
||||
loading={loading}
|
||||
columns={columns}
|
||||
dataSource={data.list}
|
||||
locale={{ emptyText: <Empty description="没有符合条件的下游订单" /> }}
|
||||
scroll={{ x: 1370 }}
|
||||
pagination={pageConfig(data, (nextPage, nextSize) => {
|
||||
setPage(nextPage)
|
||||
setSize(nextSize)
|
||||
})}
|
||||
/>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -21,6 +21,16 @@ export interface Merchant {
|
||||
created_at: string
|
||||
}
|
||||
|
||||
// 平台侧跨商户订单列表里标识订单归属所需的商户信息(后端 Preload 的 Merchant 子集)
|
||||
export type MerchantSummary = Pick<Merchant, 'id' | 'code' | 'name' | 'status'>
|
||||
|
||||
// 筛选下拉用的精简商户(来自 /platform/merchant-options,不分页)
|
||||
export interface MerchantOption {
|
||||
id: number
|
||||
code: string
|
||||
name: string
|
||||
}
|
||||
|
||||
export interface MerchantMember {
|
||||
id: number
|
||||
merchant_id: number
|
||||
@@ -132,6 +142,9 @@ export interface WalletLedgerEntry {
|
||||
|
||||
export interface FulfillmentOrder {
|
||||
id: number
|
||||
merchant_id: number
|
||||
// merchant 仅平台侧跨商户列表会返回;商户侧响应不含该字段(后端 omitempty)
|
||||
merchant?: MerchantSummary | null
|
||||
order_no: string
|
||||
client_order_no: string
|
||||
product_sku: string
|
||||
|
||||
Reference in New Issue
Block a user