Compare commits

...

8 Commits

Author SHA1 Message Date
Yvan b4d843290d 优化结构 2026-08-23 01:31:48 +08:00
Yvan 4e5071ee65 优化结构 2026-08-23 00:38:33 +08:00
Yvan 64459574b2 优化结构 2026-08-22 23:02:44 +08:00
Yvan b18baf1547 优化结构 2026-08-22 22:34:33 +08:00
Yvan 0126995090 优化结构 2026-08-22 21:39:39 +08:00
Yvan 699bcceeea 优化结构 2026-08-22 20:14:29 +08:00
Yvan 44ab14448a 优化结构 2026-08-22 17:43:14 +08:00
Yvan 491ed21d48 优化结构 2026-08-22 15:53:14 +08:00
202 changed files with 2701 additions and 1677 deletions

View File

@ -7,7 +7,7 @@ Kra 是基于 Kratos 生命周期与 Wire 依赖注入、使用 Gin 提供管理
```text
cmd/ 服务入口与 Wire
configs/ 运行配置
internal/biz/ 领域对象、用例和仓储接口
internal/biz/ 领域对象、用例和仓储接口(按 system/payment/integration/task 拆分)
internal/data/ 数据库、缓存、对象存储及仓储实现
internal/server/ Gin 服务、路由、中间件和 Handler
internal/service/ HTTP 输入输出与领域对象转换

View File

@ -10,12 +10,13 @@ import (
"kra/internal/app"
"kra/internal/biz"
systembiz "kra/internal/biz/system"
taskbiz "kra/internal/biz/task"
"kra/internal/conf"
"kra/internal/data"
"kra/internal/initialize"
"kra/internal/integration"
"kra/internal/integration/cache"
"kra/internal/modules"
"kra/internal/server"
"kra/internal/server/handler"
"kra/internal/server/middleware"
@ -36,7 +37,7 @@ func wireApp(*conf.Server, *conf.Runtime, *slog.Logger, *logging.ReloadableLogge
handler.ProviderSet,
router.ProviderSet,
worker.ProviderSet,
app.Catalog,
modules.Catalog,
app.TaskRegistry,
runtimeContributions,
app.Runtime,
@ -46,7 +47,7 @@ func wireApp(*conf.Server, *conf.Runtime, *slog.Logger, *logging.ReloadableLogge
wire.Bind(new(initialize.Backend), new(*data.Data)),
wire.Bind(new(cache.RedisProvider), new(*data.Data)),
wire.Bind(new(middleware.TokenAuthenticator), new(*service.AuthService)),
wire.Bind(new(systembiz.TaskMethodRegistry), new(*platformtask.Registry)),
wire.Bind(new(taskbiz.TaskMethodRegistry), new(*platformtask.Registry)),
biz.ProviderSet,
service.ProviderSet,
newApp,

37
cmd/wire_gen.go generated
View File

@ -9,18 +9,24 @@ package main
import (
"github.com/go-kratos/kratos/v3"
"kra/internal/app"
integration3 "kra/internal/biz/integration"
payment2 "kra/internal/biz/payment"
system2 "kra/internal/biz/system"
task2 "kra/internal/biz/task"
"kra/internal/conf"
"kra/internal/data"
"kra/internal/data/integration"
"kra/internal/data/payment"
"kra/internal/data/repository"
"kra/internal/data/system"
"kra/internal/data/task"
"kra/internal/initialize"
"kra/internal/integration"
integration2 "kra/internal/integration"
"kra/internal/integration/cache"
"kra/internal/integration/email"
"kra/internal/integration/mq"
"kra/internal/integration/storage"
"kra/internal/integration/websocket"
"kra/internal/modules"
"kra/internal/server"
"kra/internal/server/handler"
"kra/internal/server/router"
@ -42,7 +48,7 @@ func wireApp(confServer *conf.Server, runtime *conf.Runtime, logger *slog.Logger
if err != nil {
return nil, nil, err
}
catalog := app.Catalog()
catalog := modules.Catalog()
dataData, cleanup, err := data.NewData(runtime, logger, reloadable, catalog)
if err != nil {
return nil, nil, err
@ -95,22 +101,23 @@ func wireApp(confServer *conf.Server, runtime *conf.Runtime, logger *slog.Logger
emailUsecase := system2.NewEmailUsecase(emailRepo)
emailService := service.NewEmailService(emailUsecase)
handlerEmail := handler.NewEmail(emailService)
paymentRepo := payment.NewPaymentRepo(dataData)
paymentConfigReader := integration.NewPaymentConfigReader(dataData)
paymentRepo := payment.NewPaymentRepo(dataData, paymentConfigReader)
paymentOrderRepo := payment.NewPaymentOrderRepo(dataData)
paymentUsecase := system2.NewPaymentUsecase(paymentRepo, paymentOrderRepo, logger)
paymentUsecase := payment2.NewPaymentUsecase(paymentRepo, paymentOrderRepo, logger)
paymentService := service.NewPaymentService(paymentUsecase)
handlerPayment := handler.NewPayment(paymentService)
taskRepo := system.NewTaskRepo(dataData)
taskRepo := task.NewTaskRepo(dataData)
registry := app.TaskRegistry(catalog)
taskUsecase := system2.NewTaskUsecaseWithRegistry(taskRepo, registry)
taskUsecase := task2.NewTaskUsecaseWithRegistry(taskRepo, registry)
mediaRepo := system.NewMediaRepo(dataData)
mediaUsecase := system2.NewMediaUsecase(mediaRepo, reloadable, runtimeSettings)
taskExecutor := worker.NewTaskExecutorWithRegistry(taskUsecase, mediaUsecase, runtime, registry)
taskScheduler := worker.NewTaskScheduler(taskUsecase, authorityUsecase, taskExecutor, logger)
taskRuntime := worker.NewTaskRuntime(taskScheduler)
taskApplicationUsecase := system2.NewTaskApplicationUsecase(taskUsecase, taskRuntime)
taskApplicationUsecase := task2.NewTaskApplicationUsecase(taskUsecase, taskRuntime)
taskService := service.NewTaskService(taskApplicationUsecase)
task := handler.NewTask(taskService)
handlerTask := handler.NewTask(taskService)
mediaService := service.NewMediaService(mediaUsecase, runtimeSettings)
media := handler.NewMedia(mediaService)
auditQueryRepo := system.NewAuditRepo(dataData)
@ -148,15 +155,17 @@ func wireApp(confServer *conf.Server, runtime *conf.Runtime, logger *slog.Logger
user := handler.NewUser(userService, authService)
navigation := handler.NewNavigation(userService)
session := handler.NewSession(tokenService)
integrationConfigRepo := system.NewIntegrationConfigRepo(dataData)
integrationConfigRepo := integration.NewIntegrationConfigRepo(dataData)
store := data.NewIntegrationRuntime(dataData)
connectivityTester := integration.NewConnectivityTester(store)
integrationConfigUsecase := system2.NewIntegrationConfigUsecase(integrationConfigRepo, connectivityTester)
connectivityTester := integration2.NewConnectivityTester(store)
integrationConfigUsecase := integration3.NewIntegrationConfigUsecase(integrationConfigRepo, connectivityTester)
integrationConfigService := service.NewIntegrationConfigService(integrationConfigUsecase)
integrationConfig := handler.NewIntegrationConfig(integrationConfigService)
v := handler.NewSet(authority, menu, api, permission, organization, announcement, handlerEmail, handlerPayment, task, media, audit, export, version, dictionary, parameter, apiToken, systemConfig, public, user, navigation, session, integrationConfig)
v := handler.NewSet(authority, menu, api, permission, organization, announcement, handlerEmail, handlerPayment, handlerTask, media, audit, export, version, dictionary, parameter, apiToken, systemConfig, public, user, navigation, session, integrationConfig)
routes := router.NewRoutes(v)
taskMethods := worker.NewTaskMethods(taskUsecase, mediaUsecase, runtime)
maintenanceRepo := system.NewMaintenanceRepo(dataData)
maintenanceUsecase := system2.NewMaintenanceUsecase(maintenanceRepo)
taskMethods := worker.NewTaskMethods(taskUsecase, maintenanceUsecase, mediaUsecase, runtime)
appRuntimeContributions := runtimeContributions(routes, taskMethods)
moduleRuntime := app.Runtime(appRuntimeContributions, registry)
websocketServer, cleanup2, err := websocket.New(store)

View File

@ -85,7 +85,7 @@ web/src/modules/<module>/
components/
```
修改 KRA 既有系统表和系统行为的内容仍放在现有 `internal/biz`、`internal/data/repository`、`internal/service`、`internal/server` 中,避免创建第二套用户、角色、部门和权限系统。
修改 KRA 既有系统表和系统行为的内容仍放在现有 `internal/biz/system`、`internal/data/system`、`internal/service`、`internal/server` 中,避免创建第二套用户、角色、部门和权限系统。
每个业务模块通过 KRA 现有的 `pkg/module` 机制贡献:

View File

@ -78,7 +78,7 @@ PayPal `AUTHORIZE` 意图后的授权捕获,以及账单、分账、转账等
| Provider | 实现方式 |
| --- | --- |
| `alipay`、`alipay-v3`、`wechat-v2`、`wechat-v3`、`apple-iap`、`paypal`、`douyin`、`qq`、`allinpay`、`lakala`、`saobei` | 统一走上面的 GoPay v1.5.122 adapter业务层只接收 `biz.PaymentResult` |
| `alipay`、`alipay-v3`、`wechat-v2`、`wechat-v3`、`apple-iap`、`paypal`、`douyin`、`qq`、`allinpay`、`lakala`、`saobei` | 统一走上面的 GoPay v1.5.122 adapter业务层只接收 `paymentbiz.PaymentResult` |
| `chinaums` | 配置驱动的银联商务 JSON 签名适配器 |
| `sft` | 配置驱动的商福通 JSON/MD5 适配器 |
| `supper-pay` | 配置驱动的 Supper Pay HMAC 适配器 |
@ -131,18 +131,20 @@ PayPal `AUTHORIZE` 意图后的授权捕获,以及账单、分账、转账等
每个业务模块先实现可信订单来源:
```go
import paymentbiz "kra/internal/biz/payment"
type GameItemPayment struct {
orders GameItemOrderRepo
}
func (GameItemPayment) Type() string { return "game_item" }
func (p GameItemPayment) PreparePayment(ctx context.Context, provider, tradeNo, businessID string) (*biz.PaymentIntent, error) {
func (p GameItemPayment) PreparePayment(ctx context.Context, provider, tradeNo, businessID string) (*paymentbiz.PaymentIntent, error) {
order, err := p.orders.FindPayable(ctx, businessID)
if err != nil {
return nil, err
}
return &biz.PaymentIntent{
return &paymentbiz.PaymentIntent{
Provider: provider, TradeNo: tradeNo,
BusinessType: "game_item", BusinessID: businessID,
Subject: order.Title, Amount: order.PayableAmount, Currency: order.Currency,
@ -153,7 +155,7 @@ func (p GameItemPayment) PreparePayment(ctx context.Context, provider, tradeNo,
然后注册按业务类型分发的发货处理器:
```go
func (p GameItemPayment) Fulfill(ctx context.Context, c *biz.PaymentConfirmation) error {
func (p GameItemPayment) Fulfill(ctx context.Context, c *paymentbiz.PaymentConfirmation) error {
return p.orders.Transaction(ctx, func(tx GameItemOrderTx) error {
// confirmation_id 必须有唯一约束。已处理时直接返回 nil。
if tx.HasPaymentConfirmation(c.ID) {
@ -166,7 +168,7 @@ func (p GameItemPayment) Fulfill(ctx context.Context, c *biz.PaymentConfirmation
})
}
func (p GameItemPayment) AuthorizeRefund(ctx context.Context, order *biz.PaymentOrder, amount int64) error {
func (p GameItemPayment) AuthorizeRefund(ctx context.Context, order *paymentbiz.PaymentOrder, amount int64) error {
return p.orders.CheckRefundable(ctx, order.BusinessID, amount)
}
```
@ -405,4 +407,4 @@ Chinaums、SFT、Supper Pay、微信小游戏和抖音小游戏没有在代码
## 日志
支付日志在 `internal/biz/payment_log.go` 通过 `PaymentLogger` 独立抽象,包含下单、查单失败、回调查单、金额校验、重复回调和发货结果等结构化事件。日志只记录渠道、商户订单号、业务类型、业务 ID、确认 ID 等审计字段,不记录私钥、密钥、证书内容或完整敏感回调原文。
支付日志在 `internal/biz/payment/payment_log.go` 通过 `PaymentLogger` 独立抽象,包含下单、查单失败、回调查单、金额校验、重复回调和发货结果等结构化事件。日志只记录渠道、商户订单号、业务类型、业务 ID、确认 ID 等审计字段,不记录私钥、密钥、证书内容或完整敏感回调原文。

View File

@ -10,24 +10,31 @@
| --- | --- | --- |
| HTTP JSON 响应契约 | `pkg/httpx` | `Response`、`PageResult`、状态码和 Gin 响应助手;`server/httpx/response.go` 仅保留 system 适配。 |
| protobuf JSON 局部合并 | `pkg/protoutil` | 与业务无关的字段归一化和局部反序列化;初始化直接使用公共包。 |
| 支付 provider/mode 标识 | `pkg/paymentkit` | provider 常量、支持列表、金额/签名/JSON 等跨模块协议;system `biz` 只保留兼容别名。 |
| 支付回调 ACK | `pkg/paymentkit` | 回调应答、失败包装和默认 provider 应答;具体渠道 SDK 仍留在 system integration。 |
| WebSocket 通用收发 | `pkg/websocket` | Melody 的连接、事件、点对点发送、广播和会话查询封装;system integration 管理配置与生命周期。 |
| 消息队列 | `pkg/mq` | Broker 无关的发布、订阅、JSON 和 QoS 接口EMQX/Paho 与 RabbitMQ/AMQP 客户端由 system integration 管理。 |
| 支付 provider/mode 标识 | `pkg/paymentkit` | provider 常量、支持列表、金额/签名/JSON 等跨模块协议;`biz/payment` 与 `biz/integration` 直接复用。 |
| 支付回调 ACK | `pkg/paymentkit` | 回调应答、失败包装和默认 provider 应答;具体渠道 SDK 留在 `internal/integration/payment`。 |
| WebSocket 通用收发 | `pkg/websocket` | Melody 的连接、事件、点对点发送、广播和会话查询封装;`internal/integration` 管理配置与生命周期。 |
| 消息队列 | `pkg/mq` | Broker 无关的发布、订阅、JSON 和 QoS 接口EMQX/Paho 与 RabbitMQ/AMQP 客户端由 `internal/integration` 管理。 |
| 模块、任务和迁移协议 | `pkg/module`、`pkg/task`、`pkg/database/migration` | 供不同业务模块注册贡献,不带 system 业务语义。 |
## system 内部保留边界
- `app`:组合根,汇总各模块的迁移、菜单、路由和任务贡献。
- `modules/system`system 模块的 Definition声明迁移、管理面和默认任务。
- `app`:运行时组合根,汇总依赖注入后的路由和任务贡献。
- `modules`:静态模块 catalog汇总各模块迁移、菜单、API 和默认任务。
- `modules/system`system 模块的 Definition声明系统表迁移。
- `modules/integration`integration 配置迁移和管理面贡献。
- `modules/task`:定时任务迁移和默认任务贡献。
- `modules/payment`payment 模块的 Definition声明支付迁移和支付管理面。
- `biz`:用户、权限、菜单、审计、任务、支付订单和系统配置等领域模型与用例。
- `biz/system`:用户、权限、菜单、审计、媒体和系统配置等系统领域模型与用例。
- `biz/payment`:支付订单、支付流程、支付接口和支付日志。
- `biz/integration`:支付/消息队列/WebSocket 集成配置定义与校验。
- `biz/task`:定时任务模型、任务用例和任务注册协议。
- `conf`system 配置 proto、运行时快照和生成代码。
- `data`数据库连接、PO、仓储、system 表、支付持久化和配置 watcher。
- `data`共享数据库生命周期与配置 watcherPO/仓储按 `system`、`integration`、`task`、`payment` 子包隔离
- `initialize`:首次安装、配置迁移、种子编排和运行时重载。
- `integration`Redis、邮件、存储、支付、WebSocket、EMQX 和 RabbitMQ 的 provider 生命周期。
- `security`JWT claims、签发/解析和后台安全实现。
- `service`HTTP DTO`service/dto`、DTO 与 DO 转换、应用服务和路由元数据。
- `routecatalog`HTTP 公开性、操作审计、请求体策略和 API 分组/说明的统一目录。
- `service`HTTP DTO`service/dto`、DTO 与 DO 转换和应用服务。
- `server`Gin 生命周期handler、middleware、router、HTTP 适配按子包维护。
- `worker`任务调度、执行器、SSE 订阅及其并发状态。
@ -38,11 +45,19 @@
```text
internal/
app/ # 组合根和 catalog
modules/ # 业务模块定义及其模块级贡献
biz/ # DO、usecase、repo interface
app/ # 运行时组合根
modules/ # 静态 catalog、业务模块定义及其模块级贡献
biz/
system/ # 系统领域
payment/ # 支付领域
integration/# 集成配置领域
task/ # 定时任务领域
conf/ # 配置 proto/runtime
data/ # PO、repo、数据库和迁移
data/
system/ # 系统表与系统仓储
integration/# 集成配置表与仓储
task/ # 定时任务表与仓储
payment/ # 支付表与仓储
initialize/ # 首次安装和配置编排
integration/ # 外部 I/O provider
security/ # JWT 和安全实现

View File

@ -9,8 +9,8 @@
```text
internal/
app/ # 组合根、模块 catalog 和运行时组合
modules/system/ # system 模块定义
app/ # 运行时组合
modules/ # 静态 catalog 和模块定义
modules/payment/ # payment 模块定义
biz/ # DO、usecase、repo interface
conf/ # 配置 proto/runtime
@ -40,12 +40,12 @@ internal/
独立边界时不继续拆分。
- 删除只转发 `pkg/protoutil``utils/configutil`
## `internal/app` 为什么只保留组合代码
## `internal/app` 为什么只保留运行时组合
`app/catalog.go` 是有意保留的组合根,负责组装模块、任务注册与运行时。
system 自身的迁移、管理面和默认定时任务位于
`modules/system/definition.go`,由模块包声明后再被 catalog 汇总。这样模块
定义不再和应用组合逻辑混在一起,也不能误并入 `biz`、`service` 或 `data`
`modules/catalog.go` 是静态模块注册点,负责按依赖顺序汇总各模块
`Definition()``app/runtime.go` 只负责任务注册和依赖注入后的运行时路由组合。
这样模块定义不再和应用组合逻辑混在一起,也不能误并入 `biz`、`service` 或
`data`
Catalog 只能自动汇总静态模块贡献;新增模块若提供运行时路由或依赖型任务,仍需
在 cmd/Wire 中显式注册,直到统一的 runtime contribution 协议落地。

View File

@ -3,17 +3,21 @@
系统模块承载当前管理后台的完整业务边界。`internal` 顶层只保留有明确
生命周期或分层职责的包:
- `app`:组合根、模块 catalog 和任务/路由运行时组合
- `modules`:按业务模块维护 Definition 等模块贡献
- `biz`:系统领域对象、用例和仓储接口
- `app`:运行时组合根,负责依赖注入后的任务/路由组合
- `modules`:静态模块 catalog按 system/integration/task/payment 维护 Definition
- `biz/system`:用户、权限、菜单、审计、媒体和系统配置领域
- `biz/payment`:支付订单、支付流程、支付接口和支付日志
- `biz/integration`:集成配置定义、校验和连接测试边界
- `biz/task`:定时任务模型、用例和任务注册协议
- `conf`:基础配置 proto 与运行时配置解析
- `data`:数据库生命周期、系统仓储、系统表和支付持久化
- `data`共享数据库生命周期;仓储按 `data/system`、`data/integration`、`data/task`、`data/payment` 隔离
- `initialize`:数据库首次初始化和系统种子数据编排
- `integration`Redis、邮件、对象存储、支付、WebSocket、EMQX 和 RabbitMQ 适配器
- `routecatalog`:统一声明 HTTP 路由的公开性、操作审计、请求体策略和 API 元数据
- `security`:后台 JWT 等安全实现
- `server`Gin server 组合与生命周期;横切 HTTP 代码按子包维护:
`server/handler`、`server/middleware`、`server/router`、`server/httpx`
- `service`应用服务、DTO 与领域对象转换和路由元数据DTO 集中在
- `service`应用服务、DTO 与领域对象转换DTO 集中在
`service/dto`,根包中的 `dto_aliases.go` 只负责兼容旧调用方
- `worker`:定时任务执行与调度
@ -23,14 +27,17 @@
定义位于 `modules/system`JWT 实现集中在 `security`protobuf JSON 统一使用
`pkg/protoutil`
`internal/app` 只保留 `catalog.go` 作为组合根:它负责组装模块 catalog、任务
注册和运行时。system 的迁移、管理面和定时任务由 `internal/modules/system`
自己的 `Definition()` 声明,便于后续业务模块独立接入。
`internal/modules/catalog.go` 是静态模块 catalog 的唯一注册点,负责按依赖顺序
汇总各模块 Definition。`internal/app/runtime.go` 只负责依赖注入后的任务注册
和路由运行时组合。这样新增模块只需在 modules catalog 注册一次app 不再重复
维护模块声明。
系统表统一使用 `sys_` 前缀;业务表应由新业务模块自行命名和迁移,不要混入
本目录。
system 通过 `modules/system.Definition()` 提供系统迁移、通信集成菜单/API 和默认任务;
system 通过 `modules/system.Definition()` 提供系统迁移integration 通过
`modules/integration.Definition()` 提供通信集成菜单/APItask 通过
`modules/task.Definition()` 提供定时任务迁移和默认任务;
payment 通过 `modules/payment.Definition()` 提供支付迁移及支付菜单/API。两者通过
`worker.TaskMethods` 提供依赖系统用例的任务实现,通过 `server/router.Routes` 提供
路由。静态模块贡献可由 catalog 汇总;带运行时依赖的路由和任务仍需在 cmd/Wire

View File

@ -1,26 +1,13 @@
// Package app is the composition root for the running administration service.
// It knows which business modules are enabled and wires their contributions
// into the shared platform. Individual modules do not import this package.
// It wires runtime objects that need constructed dependencies. Static module
// declarations live in the sibling internal/modules package.
package app
import (
paymentmodule "kra/internal/modules/payment"
systemmodule "kra/internal/modules/system"
"kra/pkg/module"
platformtask "kra/pkg/task"
)
// Catalog lists the business modules enabled in this binary. Static module
// contributions (migrations, admin metadata, default tasks) enter through a
// Definition; runtime routes and dependency-bearing task contributors still
// need explicit wiring below.
func Catalog() module.Catalog {
return module.Catalog{Definitions: []module.Definition{
systemmodule.Definition(),
paymentmodule.Definition(),
}}
}
// TaskRegistry builds the process-wide registry from dependency-free module
// contributions. Dependency-bearing methods are added by their module runtime
// constructors after the usecases have been created.

View File

@ -10,25 +10,6 @@ import (
platformtask "kra/pkg/task"
)
func TestCatalogIncludesSystemDefinition(t *testing.T) {
catalog := Catalog()
if len(catalog.Definitions) != 2 {
t.Fatalf("definitions = %d, want 2", len(catalog.Definitions))
}
if catalog.Definitions[0].Name != "system" || catalog.Definitions[1].Name != "payment" {
t.Fatalf("definition order = [%q, %q], want [system, payment]", catalog.Definitions[0].Name, catalog.Definitions[1].Name)
}
if got := catalog.MigrationSteps(); len(got) != 5 {
t.Fatalf("module migrations = %d, want 5", len(got))
}
if surface := catalog.Surface(); len(surface.Menus) != 3 || len(surface.APIs) != 15 {
t.Fatalf("admin surface = %d menus/%d APIs, want 3/15", len(surface.Menus), len(surface.APIs))
}
if got := catalog.DefaultTimedTasks(); len(got) != 2 {
t.Fatalf("default timed tasks = %d, want 2", len(got))
}
}
func TestTaskRegistryRegistersStaticModuleMethods(t *testing.T) {
method := platformtask.Method{
Name: "test.static",

View File

@ -1,10 +1,13 @@
package biz
import (
"kra/internal/biz/integration"
"kra/internal/biz/payment"
"kra/internal/biz/system"
"kra/internal/biz/task"
"github.com/google/wire"
)
// ProviderSet is biz providers.
var ProviderSet = wire.NewSet(system.ProviderSet)
var ProviderSet = wire.NewSet(system.ProviderSet, payment.ProviderSet, integration.ProviderSet, task.ProviderSet)

View File

@ -1,10 +1,11 @@
package system
package integration
import (
"context"
"encoding/json"
"errors"
"fmt"
paymentutil "kra/pkg/paymentkit"
"sort"
"strconv"
"strings"
@ -56,6 +57,23 @@ type IntegrationConfigRepo interface {
DeleteIntegrationConfig(context.Context, string, string) error
}
// ErrPaymentConfigNotFound marks an absent payment integration row without
// exposing the storage driver's not-found error to the payment data module.
var ErrPaymentConfigNotFound = errors.New("支付渠道配置不存在")
// PaymentConfig is the storage-neutral, unmasked snapshot used by payment
// persistence. It deliberately contains no ORM or table metadata.
type PaymentConfig struct {
Enabled bool
Values json.RawMessage
}
// PaymentConfigReader is the narrow inversion seam between the payment and
// integration data modules. The integration module owns its ConfigPO.
type PaymentConfigReader interface {
ReadPaymentConfig(context.Context, string) (*PaymentConfig, error)
}
type IntegrationConnectionTester interface {
TestIntegration(context.Context, *IntegrationConfig) error
}
@ -97,9 +115,9 @@ func (uc *IntegrationConfigUsecase) Save(ctx context.Context, config *Integratio
if !json.Valid(config.Values) {
return errors.New("集成配置必须是合法 JSON")
}
values := map[string]any{}
if err := json.Unmarshal(config.Values, &values); err != nil {
return errors.New("集成配置必须是 JSON 对象")
values, err := decodeIntegrationObject(config.Values)
if err != nil {
return err
}
if definition, ok := IntegrationDefinition(config.Kind, config.Provider); ok {
values = mergeIntegrationDefaults(definition.Defaults, values)
@ -130,9 +148,9 @@ func (uc *IntegrationConfigUsecase) Test(ctx context.Context, config *Integratio
if !json.Valid(config.Values) {
return errors.New("集成配置必须是合法 JSON")
}
values := map[string]any{}
if err := json.Unmarshal(config.Values, &values); err != nil {
return errors.New("集成配置必须是 JSON 对象")
values, err := decodeIntegrationObject(config.Values)
if err != nil {
return err
}
if definition, ok := IntegrationDefinition(config.Kind, config.Provider); ok {
values = mergeIntegrationDefaults(definition.Defaults, values)
@ -161,6 +179,14 @@ func normalizeIntegrationPart(value string) string {
return strings.ToLower(strings.TrimSpace(value))
}
func decodeIntegrationObject(raw json.RawMessage) (map[string]any, error) {
values := map[string]any{}
if err := json.Unmarshal(raw, &values); err != nil || values == nil {
return nil, errors.New("集成配置必须是 JSON 对象")
}
return values, nil
}
func IntegrationDefinitions(kind string) []IntegrationConfigDefinition {
kind = normalizeIntegrationPart(kind)
definitions := integrationDefinitions[kind]
@ -290,7 +316,7 @@ func validatePaymentIntegrationConfig(provider string, values map[string]any) er
}
}
switch provider {
case PaymentAlipayV3:
case paymentutil.ProviderAlipayV3:
for _, group := range []struct {
label string
keys []string
@ -304,21 +330,21 @@ func validatePaymentIntegrationConfig(provider string, values map[string]any) er
return fmt.Errorf("%s 缺少配置字段 %s", provider, group.label)
}
}
case PaymentWechatV2:
case paymentutil.ProviderWechatV2:
if integrationFirst(values, "client_cert", "cert_pem", "apiclient_cert") == "" || integrationFirst(values, "client_key", "key_pem", "apiclient_key") == "" {
return fmt.Errorf("%s 退款要求同时配置 client_cert 和 client_key", provider)
}
case PaymentApple:
case paymentutil.ProviderApple:
if integrationInt64(values, "price_divisor", 0) <= 0 {
if _, exists := values["price_divisors"].(map[string]any); !exists {
return fmt.Errorf("%s 缺少配置字段 price_divisor 或 price_divisors", provider)
}
}
case PaymentDouyin:
case paymentutil.ProviderDouyin:
if integrationFirst(values, "platform_serial_no", "platform_cert_serial") == "" {
return fmt.Errorf("%s 缺少配置字段 platform_serial_no", provider)
}
case PaymentQQ:
case paymentutil.ProviderQQ:
if integrationFirst(values, "mch_id", "merchant_id") == "" {
return fmt.Errorf("%s 缺少配置字段 mch_id", provider)
}
@ -329,12 +355,12 @@ func validatePaymentIntegrationConfig(provider string, values map[string]any) er
if signType != "" && signType != "MD5" && signType != "HMAC-SHA256" {
return fmt.Errorf("%s sign_type 必须是 MD5 或 HMAC-SHA256", provider)
}
case PaymentAllinPay:
case paymentutil.ProviderAllinPay:
orderType := strings.ToLower(integrationFirst(values, "query_order_type", "order_type"))
if orderType != "" && orderType != "reqsn" && orderType != "trxid" {
return fmt.Errorf("%s query_order_type 必须是 reqsn 或 trxid", provider)
}
case PaymentChinaums, PaymentSFT, PaymentSuperPay, PaymentWechatGame, PaymentDouyinGame:
case paymentutil.ProviderChinaums, paymentutil.ProviderSFT, paymentutil.ProviderSuperPay, paymentutil.ProviderWechatGame, paymentutil.ProviderDouyinGame:
if integrationFirst(values, "app_key", "merchant_key", "signing_secret", "token") == "" {
return fmt.Errorf("%s 缺少签名密钥", provider)
}
@ -343,7 +369,7 @@ func validatePaymentIntegrationConfig(provider string, values map[string]any) er
}
}
if environment := strings.ToLower(integrationText(values, "environment")); environment != "" {
allowedSandbox := provider != PaymentQQ && provider != PaymentDouyin && provider != PaymentLakala
allowedSandbox := provider != paymentutil.ProviderQQ && provider != paymentutil.ProviderDouyin && provider != paymentutil.ProviderLakala
if environment != "production" && environment != "prod" && (!allowedSandbox || environment != "sandbox") {
return fmt.Errorf("%s environment 配置无效", provider)
}

View File

@ -1,4 +1,4 @@
package system
package integration
import (
"context"
@ -96,3 +96,14 @@ func TestIntegrationConfigTestDoesNotPersistCandidate(t *testing.T) {
t.Fatalf("tested values = %#v", values)
}
}
func TestIntegrationConfigRejectsJSONNull(t *testing.T) {
repo := &integrationConfigRepoTestDouble{}
usecase := NewIntegrationConfigUsecase(repo, &integrationConnectionTesterDouble{})
if err := usecase.Save(context.Background(), &IntegrationConfig{Kind: IntegrationKindMQ, Provider: "emqx", Values: json.RawMessage("null")}); err == nil {
t.Fatal("Save() accepted JSON null as an object")
}
if err := usecase.Test(context.Background(), &IntegrationConfig{Kind: IntegrationKindMQ, Provider: "emqx", Values: json.RawMessage("null")}); err == nil {
t.Fatal("Test() accepted JSON null as an object")
}
}

View File

@ -1,4 +1,6 @@
package system
package integration
import paymentutil "kra/pkg/paymentkit"
func integrationField(key, label string, required, secret bool, fieldType string) IntegrationConfigField {
if fieldType == "" {
@ -144,35 +146,35 @@ var integrationDefinitions = map[string][]IntegrationConfigDefinition{
},
},
IntegrationKindPayment: {
paymentDefinition(PaymentAlipay, "支付宝", "支付宝 OpenAPI RSA2 支付", map[string]any{"app_id": "", "private_key": "", "public_key": "", "environment": "production", "sign_type": "RSA2", "gateway_url": "https://openapi.alipay.com/gateway.do", "method": "alipay.trade.create"},
paymentDefinition(paymentutil.ProviderAlipay, "支付宝", "支付宝 OpenAPI RSA2 支付", map[string]any{"app_id": "", "private_key": "", "public_key": "", "environment": "production", "sign_type": "RSA2", "gateway_url": "https://openapi.alipay.com/gateway.do", "method": "alipay.trade.create"},
integrationField("app_id", "应用 ID", true, false, "text"), integrationField("private_key", "应用私钥", true, true, "textarea"), integrationField("public_key", "支付宝公钥", true, true, "textarea"),
integrationSelect("environment", "环境", false, "production", "sandbox"), integrationSelect("sign_type", "签名算法", false, "RSA2", "RSA"), integrationField("gateway_url", "网关地址", false, false, "url"),
integrationSelect("method", "默认支付方式", false, "alipay.trade.create", "alipay.trade.pay", "alipay.trade.precreate", "alipay.trade.app.pay", "alipay.trade.page.pay", "alipay.trade.wap.pay")),
paymentDefinition(PaymentAlipayV3, "支付宝 V3", "支付宝证书模式 V3 接口", map[string]any{"app_id": "", "private_key": "", "app_cert": "", "root_cert": "", "public_cert": "", "environment": "production", "api_base_url": "https://openapi.alipay.com", "gateway_url": "https://openapi.alipay.com/gateway.do", "method": "alipay.trade.create"},
paymentDefinition(paymentutil.ProviderAlipayV3, "支付宝 V3", "支付宝证书模式 V3 接口", map[string]any{"app_id": "", "private_key": "", "app_cert": "", "root_cert": "", "public_cert": "", "environment": "production", "api_base_url": "https://openapi.alipay.com", "gateway_url": "https://openapi.alipay.com/gateway.do", "method": "alipay.trade.create"},
integrationField("app_id", "应用 ID", true, false, "text"), integrationField("private_key", "应用私钥", false, true, "textarea"), integrationField("app_cert", "应用公钥证书", false, true, "textarea"), integrationField("root_cert", "支付宝根证书", false, true, "textarea"), integrationField("public_cert", "支付宝公钥证书", false, true, "textarea"),
integrationSelect("environment", "环境", false, "production", "sandbox"), integrationField("api_base_url", "API 地址", false, false, "url"), integrationField("gateway_url", "网关地址", false, false, "url"), integrationSelect("method", "默认支付方式", false, "alipay.trade.create", "alipay.trade.pay", "alipay.trade.precreate", "alipay.trade.app.pay", "alipay.trade.page.pay", "alipay.trade.wap.pay")),
paymentDefinition(PaymentWechatV2, "微信支付 V2", "微信支付 V2含退款双向证书", map[string]any{"app_id": "", "merchant_id": "", "mch_key": "", "sign_type": "MD5", "trade_type": "NATIVE", "client_cert": "", "client_key": ""},
paymentDefinition(paymentutil.ProviderWechatV2, "微信支付 V2", "微信支付 V2含退款双向证书", map[string]any{"app_id": "", "merchant_id": "", "mch_key": "", "sign_type": "MD5", "trade_type": "NATIVE", "client_cert": "", "client_key": ""},
integrationField("app_id", "应用 ID", true, false, "text"), integrationField("merchant_id", "商户号", true, false, "text"), integrationField("mch_key", "API 密钥", true, true, "password"), integrationSelect("sign_type", "签名算法", false, "MD5", "HMAC-SHA256"), integrationSelect("trade_type", "默认交易类型", false, "JSAPI", "APP", "NATIVE", "MWEB", "MICROPAY"), integrationField("client_cert", "商户证书", false, true, "textarea"), integrationField("client_key", "证书私钥", false, true, "textarea")),
paymentDefinition(PaymentWechatV3, "微信支付 V3", "微信支付 API v3", map[string]any{"app_id": "", "merchant_id": "", "serial_no": "", "private_key": "", "api_v3_key": "", "platform_cert": "", "platform_serial_no": "", "trade_type": "jsapi"},
paymentDefinition(paymentutil.ProviderWechatV3, "微信支付 V3", "微信支付 API v3", map[string]any{"app_id": "", "merchant_id": "", "serial_no": "", "private_key": "", "api_v3_key": "", "platform_cert": "", "platform_serial_no": "", "trade_type": "jsapi"},
integrationField("app_id", "应用 ID", true, false, "text"), integrationField("merchant_id", "商户号", true, false, "text"), integrationField("serial_no", "商户证书序列号", true, false, "text"), integrationField("private_key", "商户私钥", true, true, "textarea"), integrationField("api_v3_key", "API v3 密钥", true, true, "password"), integrationField("platform_cert", "平台证书", true, true, "textarea"), integrationField("platform_serial_no", "平台证书序列号", false, false, "text"), integrationSelect("trade_type", "默认交易类型", false, "jsapi", "app", "native", "h5", "codepay")),
paymentDefinition(PaymentApple, "Apple IAP", "Apple App Store Server API", map[string]any{"issuer_id": "", "key_id": "", "bundle_id": "", "private_key": "", "price_divisor": 10, "environment": "production", "test_product_id": "", "test_transaction_id": ""},
paymentDefinition(paymentutil.ProviderApple, "Apple IAP", "Apple App Store Server API", map[string]any{"issuer_id": "", "key_id": "", "bundle_id": "", "private_key": "", "price_divisor": 10, "environment": "production", "test_product_id": "", "test_transaction_id": ""},
integrationField("issuer_id", "Issuer ID", true, false, "text"), integrationField("key_id", "Key ID", true, false, "text"), integrationField("bundle_id", "Bundle ID", true, false, "text"), integrationField("private_key", "P8 私钥", true, true, "textarea"), integrationField("price_divisor", "价格除数", false, false, "number"), integrationSelect("environment", "环境", false, "production", "sandbox"), integrationField("test_product_id", "测试商品 ID", false, false, "text"), integrationField("test_transaction_id", "沙箱交易 ID", false, false, "text")),
paymentDefinition(PaymentDouyin, "抖音支付", "抖音开放平台支付", map[string]any{"app_id": "", "merchant_id": "", "serial_no": "", "api_key": "", "private_key": "", "platform_cert": "", "platform_serial_no": "", "trade_type": "jsapi", "environment": "production"},
paymentDefinition(paymentutil.ProviderDouyin, "抖音支付", "抖音开放平台支付", map[string]any{"app_id": "", "merchant_id": "", "serial_no": "", "api_key": "", "private_key": "", "platform_cert": "", "platform_serial_no": "", "trade_type": "jsapi", "environment": "production"},
integrationField("app_id", "应用 ID", true, false, "text"), integrationField("merchant_id", "商户号", true, false, "text"), integrationField("serial_no", "商户证书序列号", true, false, "text"), integrationField("api_key", "API 密钥", true, true, "password"), integrationField("private_key", "商户私钥", true, true, "textarea"), integrationField("platform_cert", "平台证书", true, true, "textarea"), integrationField("platform_serial_no", "平台证书序列号", false, false, "text"), integrationSelect("trade_type", "默认交易类型", false, "app", "jsapi", "h5", "native"), integrationSelect("environment", "环境", false, "production")),
paymentDefinition(PaymentQQ, "QQ 钱包", "QQ 钱包支付", map[string]any{"mch_id": "", "api_key": "", "sign_type": "MD5", "trade_type": "NATIVE", "cert_file": "", "key_file": "", "environment": "production"},
paymentDefinition(paymentutil.ProviderQQ, "QQ 钱包", "QQ 钱包支付", map[string]any{"mch_id": "", "api_key": "", "sign_type": "MD5", "trade_type": "NATIVE", "cert_file": "", "key_file": "", "environment": "production"},
integrationField("mch_id", "商户号", true, false, "text"), integrationField("api_key", "API 密钥", true, true, "password"), integrationSelect("sign_type", "签名算法", false, "MD5", "HMAC-SHA256"), integrationSelect("trade_type", "默认交易类型", false, "JSAPI", "NATIVE", "APP", "MICROPAY"), integrationField("cert_file", "退款证书路径", false, false, "text"), integrationField("key_file", "退款私钥路径", false, true, "text"), integrationSelect("environment", "环境", false, "production")),
paymentDefinition(PaymentAllinPay, "通联支付", "通联收银宝支付", map[string]any{"cus_id": "", "app_id": "", "private_key": "", "public_key": "", "org_id": "", "pay_type": "W02", "query_order_type": "reqsn", "currency": "CNY", "environment": "production"},
paymentDefinition(paymentutil.ProviderAllinPay, "通联支付", "通联收银宝支付", map[string]any{"cus_id": "", "app_id": "", "private_key": "", "public_key": "", "org_id": "", "pay_type": "W02", "query_order_type": "reqsn", "currency": "CNY", "environment": "production"},
integrationField("cus_id", "商户号", true, false, "text"), integrationField("app_id", "应用 ID", true, false, "text"), integrationField("private_key", "商户私钥", true, true, "textarea"), integrationField("public_key", "平台公钥", true, true, "textarea"), integrationField("org_id", "机构号", false, false, "text"), integrationField("pay_type", "支付类型", false, false, "text"), integrationSelect("query_order_type", "查单标识", false, "reqsn", "trxid"), integrationField("currency", "币种", false, false, "text"), integrationSelect("environment", "环境", false, "production", "sandbox")),
paymentDefinition(PaymentLakala, "拉卡拉", "拉卡拉聚合支付", map[string]any{"partner_code": "", "credential_code": "", "channel": "Wechat", "method": "jsapi", "currency": "CNY", "environment": "production"},
paymentDefinition(paymentutil.ProviderLakala, "拉卡拉", "拉卡拉聚合支付", map[string]any{"partner_code": "", "credential_code": "", "channel": "Wechat", "method": "jsapi", "currency": "CNY", "environment": "production"},
integrationField("partner_code", "合作方编号", true, false, "text"), integrationField("credential_code", "凭证码", true, true, "password"), integrationSelect("channel", "支付渠道", false, "Wechat", "Alipay", "UnionPay"), integrationSelect("method", "默认支付方式", false, "jsapi", "h5", "mini", "native", "qrcode", "native_jsapi", "sdk", "web", "retail", "retail_qrcode"), integrationField("currency", "币种", false, false, "text"), integrationSelect("environment", "环境", false, "production")),
paymentDefinition(PaymentPayPal, "PayPal", "PayPal Checkout", map[string]any{"client_id": "", "client_secret": "", "webhook_id": "", "environment": "sandbox", "return_url": "", "cancel_url": "", "auto_capture": true, "test_currency": "USD"},
paymentDefinition(paymentutil.ProviderPayPal, "PayPal", "PayPal Checkout", map[string]any{"client_id": "", "client_secret": "", "webhook_id": "", "environment": "sandbox", "return_url": "", "cancel_url": "", "auto_capture": true, "test_currency": "USD"},
integrationField("client_id", "Client ID", true, false, "text"), integrationField("client_secret", "Client Secret", true, true, "password"), integrationField("webhook_id", "Webhook ID", true, false, "text"), integrationSelect("environment", "环境", false, "sandbox", "production"), integrationField("cancel_url", "取消跳转地址", false, false, "url"), integrationField("auto_capture", "自动捕获", false, false, "switch")),
paymentDefinition(PaymentSaobei, "扫呗", "扫呗聚合支付", map[string]any{"inst_no": "", "key": "", "merchant_no": "", "terminal_id": "", "access_token": "", "pay_type": "010", "currency": "CNY", "environment": "production"},
paymentDefinition(paymentutil.ProviderSaobei, "扫呗", "扫呗聚合支付", map[string]any{"inst_no": "", "key": "", "merchant_no": "", "terminal_id": "", "access_token": "", "pay_type": "010", "currency": "CNY", "environment": "production"},
integrationField("inst_no", "机构号", true, false, "text"), integrationField("key", "机构密钥", true, true, "password"), integrationField("merchant_no", "商户号", true, false, "text"), integrationField("terminal_id", "终端号", true, false, "text"), integrationField("access_token", "访问令牌", true, true, "password"), integrationField("pay_type", "支付类型", false, false, "text"), integrationField("currency", "币种", false, false, "text"), integrationSelect("environment", "环境", false, "production", "sandbox")),
genericPaymentDefinition(PaymentChinaums, "银联商务", "按商户协议配置的银联商务适配器"),
genericPaymentDefinition(PaymentSFT, "商福通", "按商户协议配置的商福通适配器"),
genericPaymentDefinition(PaymentSuperPay, "Supper Pay", "按商户协议配置的 Supper Pay 适配器"),
genericPaymentDefinition(PaymentWechatGame, "微信小游戏支付", "微信小游戏虚拟支付配置驱动适配器"),
genericPaymentDefinition(PaymentDouyinGame, "抖音小游戏支付", "抖音小游戏支付配置驱动适配器"),
genericPaymentDefinition(paymentutil.ProviderChinaums, "银联商务", "按商户协议配置的银联商务适配器"),
genericPaymentDefinition(paymentutil.ProviderSFT, "商福通", "按商户协议配置的商福通适配器"),
genericPaymentDefinition(paymentutil.ProviderSuperPay, "Supper Pay", "按商户协议配置的 Supper Pay 适配器"),
genericPaymentDefinition(paymentutil.ProviderWechatGame, "微信小游戏支付", "微信小游戏虚拟支付配置驱动适配器"),
genericPaymentDefinition(paymentutil.ProviderDouyinGame, "抖音小游戏支付", "抖音小游戏支付配置驱动适配器"),
},
}

View File

@ -0,0 +1,6 @@
package integration
import "github.com/google/wire"
// ProviderSet wires communication and integration-configuration usecases.
var ProviderSet = wire.NewSet(NewIntegrationConfigUsecase)

View File

@ -1,4 +1,4 @@
package system
package payment
import (
"context"

View File

@ -1,4 +1,4 @@
package system
package payment
import (
"context"

View File

@ -1,4 +1,4 @@
package system
package payment
import (
"context"

View File

@ -1,4 +1,4 @@
package system
package payment
import (
"context"

View File

@ -0,0 +1,8 @@
package payment
import "github.com/google/wire"
// ProviderSet wires the payment domain usecase independently from other
// business domains. Persistence and transport layers consume the payment
// interfaces without depending on the system package.
var ProviderSet = wire.NewSet(NewPaymentUsecase)

View File

@ -0,0 +1,19 @@
package system
import "context"
// MaintenanceRepo owns retention work for system-owned tables. Other data
// modules clean their own tables and worker composes the operations.
type MaintenanceRepo interface {
CleanupExpired(context.Context) error
}
type MaintenanceUsecase struct{ repo MaintenanceRepo }
func NewMaintenanceUsecase(repo MaintenanceRepo) *MaintenanceUsecase {
return &MaintenanceUsecase{repo: repo}
}
func (uc *MaintenanceUsecase) CleanupExpired(ctx context.Context) error {
return uc.repo.CleanupExpired(ctx)
}

View File

@ -24,11 +24,8 @@ var ProviderSet = wire.NewSet(
NewAuditUsecase,
NewAuditRecorderUsecase,
NewLogViewerUsecase,
NewTaskUsecaseWithRegistry,
NewTaskApplicationUsecase,
NewMediaUsecase,
NewAnnouncementUsecase,
NewEmailUsecase,
NewPaymentUsecase,
NewIntegrationConfigUsecase,
NewMaintenanceUsecase,
)

View File

@ -30,6 +30,8 @@ type InitializationRepo interface {
DiskMountPoints() []string
}
// TaskReloader is the narrow scheduler boundary needed after configuration
// changes. The consumer owns this interface; worker supplies the implementation.
type TaskReloader interface {
Reload(context.Context) error
}

View File

@ -0,0 +1,9 @@
package task
import "github.com/google/wire"
// ProviderSet wires timed-task usecases independently from the system domain.
var ProviderSet = wire.NewSet(
NewTaskUsecaseWithRegistry,
NewTaskApplicationUsecase,
)

View File

@ -1,4 +1,4 @@
package system
package task
import (
"context"
@ -58,7 +58,7 @@ type TaskRepo interface {
ToggleTask(context.Context, uint, bool) error
RecordTaskLog(context.Context, *TimedTaskLog) error
ListTaskLogs(context.Context, int, int, uint, string) ([]*TimedTaskLog, int64, error)
CleanupLogs(context.Context) error
CleanupTaskLogs(context.Context) error
TaskNameExists(context.Context, string, uint) (bool, error)
}

View File

@ -1,4 +1,4 @@
package system
package task
import platformtask "kra/pkg/task"

View File

@ -1,4 +1,4 @@
package system
package task
import (
"context"
@ -65,7 +65,7 @@ func (r *applicationTaskRepo) RecordTaskLog(context.Context, *TimedTaskLog) erro
func (r *applicationTaskRepo) ListTaskLogs(context.Context, int, int, uint, string) ([]*TimedTaskLog, int64, error) {
return nil, 0, nil
}
func (r *applicationTaskRepo) CleanupLogs(context.Context) error { return nil }
func (r *applicationTaskRepo) CleanupTaskLogs(context.Context) error { return nil }
func (r *applicationTaskRepo) TaskNameExists(context.Context, string, uint) (bool, error) {
return r.nameExists, r.nameExistsErr
}

View File

@ -3,12 +3,30 @@
`data` owns database clients, persistence models, migrations, configuration
watching, and repository implementations.
- `repository/`: system repositories and table persistence
- `payment/`: payment configuration and payment-order persistence
- `system/`: system repositories and system table persistence
- `task/`: timed-task tables and task persistence
- `integration/`: `sys_integration_configs` and integration configuration persistence
- `payment/`: payment-order persistence
- each subpackage owns its Wire `ProviderSet`; the root package only binds the
shared `Data` infrastructure and aggregates those sets
- root files: shared database lifecycle, runtime clients, integration-config
storage, data-scope auditing, and migration orchestration
shared `Data` infrastructure and aggregates those sets, mirroring `biz`
- root files: shared database lifecycle, runtime clients, configuration
orchestration, data-scope auditing, and migration orchestration
新增数据模块时创建 `internal/data/<module>`,提供 `ProviderSet`
`Migrations()`,再在 `internal/modules/<module>/definition.go` 注册迁移与
管理面,最后在根 `data.ProviderSet` 中注册该模块。根 `data` 不应直接
拥有业务表 PO也不应让一个模块引用另一个模块的私有 PO。
Root files intentionally stay in one package because they share `Data` state and
reload locks. Do not split them into packages only to reduce file count.
当前内置数据模块为 `system`、`integration`、`task` 和 `payment`。其中:
- `system` 只拥有 `sys_*` 系统表、系统仓储、种子和系统维护清理;
- `integration` 唯一拥有 `sys_integration_configs` 表模型、配置仓储和通信默认值;
- `task` 只拥有定时任务与任务日志表;
- `payment` 只拥有 `pay_orders` 等支付持久化,通过 `biz/integration.PaymentConfigReader`
读取支付配置,不感知 integration 的 PO 或表结构。
配置文件迁移、数据库切换、Redis/Mongo/对象存储重载仍属于根 data 的生命周期编排,
不等同于某个业务模块的表仓储。

View File

@ -382,6 +382,12 @@ func (d *Data) reloadConfig(ctx context.Context) error {
}
useRedis := next.Admin.System != nil && next.Admin.System.UseRedis
candidateRedis := openRedis(next.Data.Redis, useRedis, d.logger())
candidateRedisAccepted := false
defer func() {
if !candidateRedisAccepted && candidateRedis != nil {
_ = candidateRedis.Close()
}
}()
useMongo := next.Admin.System != nil && next.Admin.System.UseMongo
candidateMongo, mongoErr := openMongo(next.Data.Mongo, useMongo)
if mongoErr != nil {
@ -397,6 +403,16 @@ func (d *Data) reloadConfig(ctx context.Context) error {
if err != nil {
return err
}
candidateDBListAccepted := false
defer func() {
if !candidateDBListAccepted {
closeDatabaseList(candidateDBList)
}
}()
integrationConfigs, err := readIntegrationRuntime(candidateDB)
if err != nil {
return fmt.Errorf("reload integration runtime: %w", err)
}
d.gormDB.replace(candidateDB, d.enqueueDataScopeAudit)
d.databaseReady.Store(databaseReady)
@ -409,14 +425,16 @@ func (d *Data) reloadConfig(ctx context.Context) error {
d.mongo.replace(candidateMongo)
mongoAccepted = true
}
closeCandidate = false
candidateDBListAccepted = true
candidateRedisAccepted = true
d.runtime.Replace(next.Data, next.Admin)
if err = d.loadIntegrationRuntime(candidateDB); err != nil {
return fmt.Errorf("reload integration runtime: %w", err)
if d.integrations != nil {
d.integrations.Replace(integrationConfigs)
}
if d.storage != nil {
d.storage.Replace(candidateStorage)
}
closeCandidate = false
return nil
}

View File

@ -12,8 +12,10 @@ import (
"github.com/redis/go-redis/v9"
"gorm.io/gorm"
"kra/internal/conf"
dataintegration "kra/internal/data/integration"
datapayment "kra/internal/data/payment"
datasystem "kra/internal/data/repository"
datasystem "kra/internal/data/system"
datatask "kra/internal/data/task"
"kra/internal/integration/runtimeconfig"
"kra/internal/integration/storage"
"kra/pkg/module"
@ -24,8 +26,12 @@ var ProviderSet = wire.NewSet(
NewIntegrationRuntime,
wire.Bind(new(datasystem.Provider), new(*Data)),
wire.Bind(new(datasystem.DatabaseProvider), new(*Data)),
wire.Bind(new(dataintegration.Provider), new(*Data)),
wire.Bind(new(datatask.Provider), new(*Data)),
wire.Bind(new(datapayment.Provider), new(*Data)),
datasystem.ProviderSet,
dataintegration.ProviderSet,
datatask.ProviderSet,
datapayment.ProviderSet,
)
@ -170,6 +176,34 @@ func NewData(runtime *conf.Runtime, appLogger *slog.Logger, storageManager *stor
c.Database = &conf.Data_Database{}
}
d := &Data{runtime: runtime, integrations: runtimeconfig.NewStore(), appLogger: appLogger, storage: storageManager, catalog: catalog}
var stopConfigWatcher func()
var cleanupOnce sync.Once
cleanup := func() {
cleanupOnce.Do(func() {
if stopConfigWatcher != nil {
stopConfigWatcher()
}
if d.auditLog != nil {
d.auditLog.Close()
}
if d.gormDB != nil {
d.gormDB.close()
}
closeDatabaseList(d.dbList)
if d.redis != nil {
d.redis.close()
}
if d.mongo != nil {
d.mongo.close()
}
})
}
initialized := false
defer func() {
if !initialized {
cleanup()
}
}()
usingFallback := !databaseConnectionConfigured(c.Database)
var db *gorm.DB
var err error
@ -193,8 +227,6 @@ func NewData(runtime *conf.Runtime, appLogger *slog.Logger, storageManager *stor
d.auditLog = newDataScopeAuditWriter(d, appLogger)
d.dbList, err = openDatabaseList(c.DatabaseList, appLogger)
if err != nil {
d.auditLog.Close()
d.gormDB.close()
return nil, nil, err
}
for _, item := range d.dbList {
@ -232,7 +264,7 @@ func NewData(runtime *conf.Runtime, appLogger *slog.Logger, storageManager *stor
if storageManager != nil {
storageManager.Replace(activeStorage)
}
if db.Migrator().HasTable(&integrationConfigPO{}) {
if db.Migrator().HasTable("sys_integration_configs") {
if removeErr := d.removeIntegrationConfigFromFile(); removeErr != nil {
appLogger.Warn("remove legacy integration configuration from file", "mod", "integration", "error", removeErr)
}
@ -250,15 +282,8 @@ func NewData(runtime *conf.Runtime, appLogger *slog.Logger, storageManager *stor
mongoClient = nil
}
d.mongo = newReloadableMongo(mongoClient)
stopConfigWatcher := d.watchConfig()
cleanup := func() {
stopConfigWatcher()
d.auditLog.Close()
d.gormDB.close()
closeDatabaseList(d.dbList)
d.redis.close()
d.mongo.close()
}
stopConfigWatcher = d.watchConfig()
initialized = true
return d, cleanup, nil
}

View File

@ -1,22 +1,9 @@
package data
import (
"time"
"gorm.io/gorm"
datasystem "kra/internal/data/system"
)
// dataAccessLogPO is the infrastructure-side write model used by GORM
// callbacks. The system module owns the query repository for the same table.
type dataAccessLogPO struct {
ID uint `gorm:"primaryKey"`
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt gorm.DeletedAt `gorm:"index"`
EventType, TargetTable, Operation string
UserID, AuthorityID uint
Scope int
RequestID, Method, Path, Detail string
}
func (dataAccessLogPO) TableName() string { return "sys_data_access_logs" }
type dataAccessLogPO = datasystem.DataAccessLogPO

View File

@ -209,7 +209,12 @@ func (d *Data) InitializeDatabase(ctx context.Context, input *system.DatabaseCon
if err := d.persistDatabaseConfig(config, signingKey); err != nil {
return fmt.Errorf("persist database configuration: %w", err)
}
integrationConfigs, err := readIntegrationRuntime(candidate)
if err != nil {
return fmt.Errorf("initialize integration runtime: %w", err)
}
d.activateDatabase(candidate, config)
activated = true
currentData, currentAdmin := d.runtime.Values()
if currentAdmin == nil {
currentAdmin = &conf.AdminBackend{}
@ -221,9 +226,8 @@ func (d *Data) InitializeDatabase(ctx context.Context, input *system.DatabaseCon
currentAdmin.Storage = storageConfig
currentAdmin.Email = emailConfig
d.runtime.Replace(currentData, currentAdmin)
if err = d.loadIntegrationRuntime(candidate); err != nil {
return fmt.Errorf("initialize integration runtime: %w", err)
if d.integrations != nil {
d.integrations.Replace(integrationConfigs)
}
activated = true
return nil
}

View File

@ -1,10 +1,10 @@
package system
package integration
import (
"context"
"encoding/json"
"errors"
"kra/internal/biz/system"
integrationbiz "kra/internal/biz/integration"
"strings"
"time"
@ -13,7 +13,7 @@ import (
"gorm.io/gorm"
)
type integrationConfigPO struct {
type ConfigPO struct {
ID uint `gorm:"primaryKey"`
CreatedAt time.Time
UpdatedAt time.Time
@ -23,32 +23,56 @@ type integrationConfigPO struct {
Config string `gorm:"type:text;not null"`
}
func (integrationConfigPO) TableName() string { return "sys_integration_configs" }
func (ConfigPO) TableName() string { return "sys_integration_configs" }
type integrationConfigRepo struct{ data Provider }
type integrationRuntimeProvider interface {
IntegrationRuntime() *runtimeconfig.Store
}
type paymentConfigReader struct{ data Provider }
func NewIntegrationConfigRepo(data Provider) system.IntegrationConfigRepo {
func NewIntegrationConfigRepo(data Provider) integrationbiz.IntegrationConfigRepo {
return &integrationConfigRepo{data: data}
}
func (r *integrationConfigRepo) ListIntegrationConfigs(ctx context.Context, kind string) ([]*system.IntegrationConfig, error) {
var rows []integrationConfigPO
// NewPaymentConfigReader exposes only the raw payment configuration needed by
// the payment data module. The ConfigPO and its table name stay private here.
func NewPaymentConfigReader(data Provider) integrationbiz.PaymentConfigReader {
return &paymentConfigReader{data: data}
}
func (r *paymentConfigReader) ReadPaymentConfig(ctx context.Context, provider string) (*integrationbiz.PaymentConfig, error) {
if r == nil || r.data == nil || r.data.DB() == nil {
return nil, errors.New("集成配置数据库未初始化")
}
provider = strings.ToLower(strings.TrimSpace(provider))
if provider == "" {
return nil, errors.New("支付渠道不能为空")
}
var row ConfigPO
if err := r.data.DB().WithContext(ctx).
Where("kind = ? AND provider = ?", integrationbiz.IntegrationKindPayment, provider).
First(&row).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, integrationbiz.ErrPaymentConfigNotFound
}
return nil, err
}
return &integrationbiz.PaymentConfig{Enabled: row.Enabled, Values: append(json.RawMessage(nil), []byte(row.Config)...)}, nil
}
func (r *integrationConfigRepo) ListIntegrationConfigs(ctx context.Context, kind string) ([]*integrationbiz.IntegrationConfig, error) {
var rows []ConfigPO
if err := r.data.DB().WithContext(ctx).Where("kind = ?", kind).Order("provider ASC").Find(&rows).Error; err != nil {
return nil, err
}
result := make([]*system.IntegrationConfig, 0, len(rows))
result := make([]*integrationbiz.IntegrationConfig, 0, len(rows))
for _, row := range rows {
result = append(result, integrationConfigFromPO(row))
}
return result, nil
}
func (r *integrationConfigRepo) FindIntegrationConfig(ctx context.Context, kind, provider string) (*system.IntegrationConfig, error) {
var row integrationConfigPO
func (r *integrationConfigRepo) FindIntegrationConfig(ctx context.Context, kind, provider string) (*integrationbiz.IntegrationConfig, error) {
var row ConfigPO
if err := r.data.DB().WithContext(ctx).Where("kind = ? AND provider = ?", kind, provider).First(&row).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, errors.New("集成配置不存在")
@ -58,19 +82,19 @@ func (r *integrationConfigRepo) FindIntegrationConfig(ctx context.Context, kind,
return integrationConfigFromPO(row), nil
}
func (r *integrationConfigRepo) SaveIntegrationConfig(ctx context.Context, config *system.IntegrationConfig) error {
func (r *integrationConfigRepo) SaveIntegrationConfig(ctx context.Context, config *integrationbiz.IntegrationConfig) error {
db := r.data.DB().WithContext(ctx)
var row integrationConfigPO
var row ConfigPO
err := db.Where("kind = ? AND provider = ?", config.Kind, config.Provider).First(&row).Error
values := integrationObject(config.Values)
if errors.Is(err, gorm.ErrRecordNotFound) {
if config.Enabled {
if err = system.ValidateIntegrationConfig(config.Kind, config.Provider, values); err != nil {
if err = integrationbiz.ValidateIntegrationConfig(config.Kind, config.Provider, values); err != nil {
return err
}
}
encoded, _ := json.Marshal(values)
if err := db.Create(&integrationConfigPO{Kind: config.Kind, Provider: config.Provider, Enabled: config.Enabled, Config: string(encoded)}).Error; err != nil {
if err := db.Create(&ConfigPO{Kind: config.Kind, Provider: config.Provider, Enabled: config.Enabled, Config: string(encoded)}).Error; err != nil {
return err
}
r.publish(config.Kind, config.Provider, config.Enabled, encoded)
@ -81,7 +105,7 @@ func (r *integrationConfigRepo) SaveIntegrationConfig(ctx context.Context, confi
}
mergeIntegrationSecrets(config.Kind, config.Provider, values, integrationObject(json.RawMessage(row.Config)))
if config.Enabled {
if err = system.ValidateIntegrationConfig(config.Kind, config.Provider, values); err != nil {
if err = integrationbiz.ValidateIntegrationConfig(config.Kind, config.Provider, values); err != nil {
return err
}
}
@ -94,7 +118,7 @@ func (r *integrationConfigRepo) SaveIntegrationConfig(ctx context.Context, confi
}
func (r *integrationConfigRepo) DeleteIntegrationConfig(ctx context.Context, kind, provider string) error {
if err := r.data.DB().WithContext(ctx).Where("kind = ? AND provider = ?", kind, provider).Delete(&integrationConfigPO{}).Error; err != nil {
if err := r.data.DB().WithContext(ctx).Where("kind = ? AND provider = ?", kind, provider).Delete(&ConfigPO{}).Error; err != nil {
return err
}
if runtime := integrationRuntime(r.data); runtime != nil {
@ -110,17 +134,17 @@ func (r *integrationConfigRepo) publish(kind, provider string, enabled bool, val
}
func integrationRuntime(provider Provider) *runtimeconfig.Store {
if value, ok := provider.(integrationRuntimeProvider); ok {
return value.IntegrationRuntime()
if provider != nil {
return provider.IntegrationRuntime()
}
return nil
}
func integrationConfigFromPO(row integrationConfigPO) *system.IntegrationConfig {
func integrationConfigFromPO(row ConfigPO) *integrationbiz.IntegrationConfig {
values := integrationObject(json.RawMessage(row.Config))
maskIntegrationSecrets(row.Kind, row.Provider, values)
encoded, _ := json.Marshal(values)
return &system.IntegrationConfig{Kind: row.Kind, Provider: row.Provider, Enabled: row.Enabled, Values: encoded}
return &integrationbiz.IntegrationConfig{Kind: row.Kind, Provider: row.Provider, Enabled: row.Enabled, Values: encoded}
}
func integrationObject(raw json.RawMessage) map[string]any {
@ -165,7 +189,7 @@ func mergeIntegrationSecrets(kind, provider string, values, old map[string]any)
func integrationSecretFields(kind, provider string) map[string]bool {
result := map[string]bool{}
if definition, ok := system.IntegrationDefinition(kind, provider); ok {
if definition, ok := integrationbiz.IntegrationDefinition(kind, provider); ok {
for _, field := range definition.Fields {
if field.Secret {
result[field.Key] = true

View File

@ -1,9 +1,9 @@
package system
package integration
import (
"context"
"encoding/json"
"kra/internal/biz/system"
integrationbiz "kra/internal/biz/integration"
"testing"
"kra/internal/integration/runtimeconfig"
@ -21,25 +21,25 @@ func TestIntegrationConfigSavePublishesUnmaskedRuntimeValues(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if err = db.AutoMigrate(&integrationConfigPO{}); err != nil {
if err = db.AutoMigrate(&ConfigPO{}); err != nil {
t.Fatal(err)
}
provider := &integrationRuntimeTestProvider{Data: &Data{gormDB: newReloadableDB(db, nil)}, store: runtimeconfig.NewStore()}
repo := &integrationConfigRepo{data: provider}
values := system.DefaultIntegrationConfig(system.IntegrationKindMQ, "rabbitmq")
values := integrationbiz.DefaultIntegrationConfig(integrationbiz.IntegrationKindMQ, "rabbitmq")
values["password"] = "runtime-secret"
raw, _ := json.Marshal(values)
if err = repo.SaveIntegrationConfig(context.Background(), &system.IntegrationConfig{Kind: system.IntegrationKindMQ, Provider: "rabbitmq", Enabled: true, Values: raw}); err != nil {
if err = repo.SaveIntegrationConfig(context.Background(), &integrationbiz.IntegrationConfig{Kind: integrationbiz.IntegrationKindMQ, Provider: "rabbitmq", Enabled: true, Values: raw}); err != nil {
t.Fatal(err)
}
values["password"] = "******"
raw, _ = json.Marshal(values)
if err = repo.SaveIntegrationConfig(context.Background(), &system.IntegrationConfig{Kind: system.IntegrationKindMQ, Provider: "rabbitmq", Enabled: true, Values: raw}); err != nil {
if err = repo.SaveIntegrationConfig(context.Background(), &integrationbiz.IntegrationConfig{Kind: integrationbiz.IntegrationKindMQ, Provider: "rabbitmq", Enabled: true, Values: raw}); err != nil {
t.Fatal(err)
}
active, ok := provider.store.Get(system.IntegrationKindMQ, "rabbitmq")
active, ok := provider.store.Get(integrationbiz.IntegrationKindMQ, "rabbitmq")
if !ok || !active.Enabled {
t.Fatalf("runtime config = %#v, ok=%v", active, ok)
}

View File

@ -0,0 +1,87 @@
package integration
import (
"encoding/json"
"errors"
integrationbiz "kra/internal/biz/integration"
"kra/pkg/database/migration"
"gorm.io/gorm"
)
func Migrations() []migration.Step {
return []migration.Step{
{ID: "202608200001_data_infrastructure", Migrate: func(db *gorm.DB) error {
return migration.CreateMissingTables(db, &ConfigPO{})
}},
{ID: "202608210001_communication_integration_defaults", Migrate: ensureCommunicationIntegrationConfigs},
{ID: "202608200004_payment_defaults", Migrate: ensurePaymentIntegrationConfigs},
}
}
func ensureCommunicationIntegrationConfigs(db *gorm.DB) error {
defaults := []struct{ kind, provider string }{
{integrationbiz.IntegrationKindMQ, "emqx"},
{integrationbiz.IntegrationKindMQ, "rabbitmq"},
{integrationbiz.IntegrationKindWebSocket, "melody"},
}
for _, item := range defaults {
var row ConfigPO
err := db.Where("kind = ? AND provider = ?", item.kind, item.provider).First(&row).Error
if gorm.ErrRecordNotFound == err {
values, marshalErr := json.Marshal(integrationbiz.DefaultIntegrationConfig(item.kind, item.provider))
if marshalErr != nil {
return marshalErr
}
if err = db.Create(&ConfigPO{Kind: item.kind, Provider: item.provider, Enabled: false, Config: string(values)}).Error; err != nil {
return err
}
continue
}
if err != nil {
return err
}
}
return nil
}
func ensurePaymentIntegrationConfigs(db *gorm.DB) error {
for _, definition := range integrationbiz.IntegrationDefinitions(integrationbiz.IntegrationKindPayment) {
provider := definition.Provider
var row ConfigPO
err := db.Where("kind = ? AND provider = ?", integrationbiz.IntegrationKindPayment, provider).First(&row).Error
defaults := integrationbiz.DefaultIntegrationConfig(integrationbiz.IntegrationKindPayment, provider)
if errors.Is(err, gorm.ErrRecordNotFound) {
encoded, marshalErr := json.Marshal(defaults)
if marshalErr != nil {
return marshalErr
}
if err := db.Create(&ConfigPO{Kind: integrationbiz.IntegrationKindPayment, Provider: provider, Config: string(encoded)}).Error; err != nil {
return err
}
continue
}
if err != nil {
return err
}
values := integrationObject(json.RawMessage(row.Config))
changed := false
for key, value := range defaults {
if _, exists := values[key]; !exists {
values[key] = value
changed = true
}
}
if changed {
encoded, marshalErr := json.Marshal(values)
if marshalErr != nil {
return marshalErr
}
if err := db.Model(&row).Update("config", string(encoded)).Error; err != nil {
return err
}
}
}
return nil
}

View File

@ -0,0 +1,12 @@
package integration
import (
"gorm.io/gorm"
"kra/internal/integration/runtimeconfig"
)
// Provider is the minimal database/runtime seam for integration configuration.
type Provider interface {
DB() *gorm.DB
IntegrationRuntime() *runtimeconfig.Store
}

View File

@ -0,0 +1,5 @@
package integration
import "github.com/google/wire"
var ProviderSet = wire.NewSet(NewIntegrationConfigRepo, NewPaymentConfigReader)

View File

@ -0,0 +1,29 @@
package integration
import (
"errors"
"kra/internal/integration/runtimeconfig"
"gorm.io/gorm"
)
// ReadRuntime returns the communication integration snapshot used by the
// long-lived MQ/WebSocket adapters.
func ReadRuntime(db *gorm.DB) ([]runtimeconfig.Config, error) {
if db == nil || !db.Migrator().HasTable(&ConfigPO{}) {
return nil, nil
}
var rows []ConfigPO
if err := db.Session(&gorm.Session{NewDB: true}).
Where("kind IN ?", []string{"mq", "websocket"}).
Order("kind ASC, provider ASC").
Find(&rows).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
return nil, err
}
configs := make([]runtimeconfig.Config, 0, len(rows))
for _, row := range rows {
configs = append(configs, runtimeconfig.Config{Kind: row.Kind, Provider: row.Provider, Enabled: row.Enabled, Values: []byte(row.Config)})
}
return configs, nil
}

View File

@ -0,0 +1,42 @@
package integration
import (
"context"
"fmt"
"github.com/glebarez/sqlite"
"gorm.io/gorm"
"kra/internal/integration/runtimeconfig"
)
type Data struct {
gormDB *reloadableDB
store *runtimeconfig.Store
}
func (d *Data) DB() *gorm.DB {
if d == nil || d.gormDB == nil {
return nil
}
return d.gormDB.DB()
}
func (d *Data) IntegrationRuntime() *runtimeconfig.Store { return d.store }
type reloadableDB struct{ db *gorm.DB }
func newReloadableDB(db *gorm.DB, _ ...any) *reloadableDB { return &reloadableDB{db: db} }
func (r *reloadableDB) DB() *gorm.DB {
if r == nil {
return nil
}
return r.db
}
func (r *reloadableDB) WithContext(ctx context.Context) *gorm.DB { return r.db.WithContext(ctx) }
func openWithDriver(driver, dsn string) (*gorm.DB, error) {
if driver != "sqlite" {
return nil, fmt.Errorf("unsupported test database driver %q", driver)
}
return gorm.Open(sqlite.Open(dsn), &gorm.Config{})
}

View File

@ -6,9 +6,9 @@ import (
"errors"
"fmt"
"strings"
"time"
"kra/internal/conf"
dataintegration "kra/internal/data/integration"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
@ -18,24 +18,8 @@ import (
const (
integrationKindStorage = "storage"
integrationKindEmail = "email"
integrationKindPayment = "payment"
)
// integrationConfigPO stores credentials and provider-specific options for
// external services. Payment integrations use the same table with kind
// "payment", keeping secrets out of the bootstrap configuration file.
type integrationConfigPO struct {
ID uint `gorm:"primaryKey"`
CreatedAt time.Time
UpdatedAt time.Time
Kind string `gorm:"size:32;not null;uniqueIndex:idx_integration_kind_provider"`
Provider string `gorm:"size:64;not null;uniqueIndex:idx_integration_kind_provider"`
Enabled bool `gorm:"not null;default:false;index"`
Config string `gorm:"type:text;not null"`
}
func (integrationConfigPO) TableName() string { return "sys_integration_configs" }
var storageProviderNames = []string{
"local",
"qiniu",
@ -140,11 +124,11 @@ func saveStorageIntegrationConfig(db *gorm.DB, storage *conf.AdminBackend_Storag
if err != nil {
return fmt.Errorf("encode %s integration configuration: %w", provider, err)
}
var current integrationConfigPO
var current dataintegration.ConfigPO
err = tx.Where("kind = ? AND provider = ?", integrationKindStorage, provider).First(&current).Error
switch {
case errors.Is(err, gorm.ErrRecordNotFound):
current = integrationConfigPO{Kind: integrationKindStorage, Provider: provider}
current = dataintegration.ConfigPO{Kind: integrationKindStorage, Provider: provider}
current.Enabled, current.Config = provider == active, value
if err = tx.Create(&current).Error; err != nil {
return err
@ -162,7 +146,7 @@ func saveStorageIntegrationConfig(db *gorm.DB, storage *conf.AdminBackend_Storag
}
func loadStorageIntegrationConfig(db *gorm.DB) (*conf.AdminBackend_Storage, bool, error) {
var rows []integrationConfigPO
var rows []dataintegration.ConfigPO
err := db.Session(&gorm.Session{NewDB: true}).
Where("kind = ?", integrationKindStorage).
Order("id ASC").
@ -191,7 +175,7 @@ func loadStorageIntegrationConfig(db *gorm.DB) (*conf.AdminBackend_Storage, bool
// sole source of truth.
func resolveStorageIntegrationConfig(db *gorm.DB, legacy *conf.AdminBackend_Storage) (*conf.AdminBackend_Storage, error) {
clean := db.Session(&gorm.Session{NewDB: true})
if !clean.Migrator().HasTable(&integrationConfigPO{}) {
if !clean.Migrator().HasTable(&dataintegration.ConfigPO{}) {
if legacy == nil {
return &conf.AdminBackend_Storage{Type: "local"}, nil
}
@ -219,7 +203,7 @@ func (d *Data) persistStorageIntegrationConfig(ctx context.Context, storage *con
return errors.New("database is not initialized")
}
db := d.gormDB.WithContext(ctx)
if !db.Migrator().HasTable(&integrationConfigPO{}) {
if !db.Migrator().HasTable(&dataintegration.ConfigPO{}) {
return errors.New("integration configuration table does not exist")
}
return saveStorageIntegrationConfig(db, storage)
@ -239,11 +223,11 @@ func saveEmailIntegrationConfig(db *gorm.DB, email *conf.AdminBackend_Email) err
}
enabled := email.Host != "" && email.From != "" && email.Secret != "" && email.Port > 0
clean := db.Session(&gorm.Session{NewDB: true})
var current integrationConfigPO
var current dataintegration.ConfigPO
err = clean.Where("kind = ? AND provider = ?", integrationKindEmail, "smtp").First(&current).Error
switch {
case errors.Is(err, gorm.ErrRecordNotFound):
return clean.Create(&integrationConfigPO{
return clean.Create(&dataintegration.ConfigPO{
Kind: integrationKindEmail, Provider: "smtp", Enabled: enabled, Config: string(raw),
}).Error
case err != nil:
@ -254,7 +238,7 @@ func saveEmailIntegrationConfig(db *gorm.DB, email *conf.AdminBackend_Email) err
}
func loadEmailIntegrationConfig(db *gorm.DB) (*conf.AdminBackend_Email, bool, error) {
var row integrationConfigPO
var row dataintegration.ConfigPO
err := db.Session(&gorm.Session{NewDB: true}).
Where("kind = ? AND provider = ?", integrationKindEmail, "smtp").
First(&row).Error
@ -276,7 +260,7 @@ func loadEmailIntegrationConfig(db *gorm.DB) (*conf.AdminBackend_Email, bool, er
func resolveEmailIntegrationConfig(db *gorm.DB, legacy *conf.AdminBackend_Email) (*conf.AdminBackend_Email, error) {
clean := db.Session(&gorm.Session{NewDB: true})
if !clean.Migrator().HasTable(&integrationConfigPO{}) {
if !clean.Migrator().HasTable(&dataintegration.ConfigPO{}) {
if legacy == nil {
return defaultEmailIntegrationConfig(), nil
}
@ -304,7 +288,7 @@ func (d *Data) persistEmailIntegrationConfig(ctx context.Context, email *conf.Ad
return errors.New("database is not initialized")
}
db := d.gormDB.WithContext(ctx)
if !db.Migrator().HasTable(&integrationConfigPO{}) {
if !db.Migrator().HasTable(&dataintegration.ConfigPO{}) {
return errors.New("integration configuration table does not exist")
}
return saveEmailIntegrationConfig(db, email)

View File

@ -7,7 +7,9 @@ import (
"strings"
"testing"
integrationbiz "kra/internal/biz/integration"
"kra/internal/conf"
dataintegration "kra/internal/data/integration"
"kra/internal/integration/storage"
"google.golang.org/protobuf/encoding/protojson"
@ -26,7 +28,7 @@ func openIntegrationConfigTestDB(t *testing.T) *gorm.DB {
t.Fatal(err)
}
t.Cleanup(func() { _ = sqlDB.Close() })
if err = db.AutoMigrate(&integrationConfigPO{}); err != nil {
if err = db.AutoMigrate(&dataintegration.ConfigPO{}); err != nil {
t.Fatal(err)
}
return db
@ -42,10 +44,10 @@ func TestMigrateAllCreatesIntegrationConfigTable(t *testing.T) {
t.Fatal(err)
}
t.Cleanup(func() { _ = sqlDB.Close() })
if err = migrateAll(db); err != nil {
if err = migrateAll(db, testCatalog()); err != nil {
t.Fatal(err)
}
if !db.Migrator().HasTable(&integrationConfigPO{}) {
if !db.Migrator().HasTable(&dataintegration.ConfigPO{}) {
t.Fatal("migrateAll did not create sys_integration_configs")
}
}
@ -73,7 +75,7 @@ func TestStorageIntegrationConfigRoundTrip(t *testing.T) {
if err := saveEmailIntegrationConfig(db, email); err != nil {
t.Fatal(err)
}
if err := db.Create(&integrationConfigPO{Kind: integrationKindPayment, Provider: "wechat-pay", Config: `{"merchant_id":"123"}`}).Error; err != nil {
if err := db.Create(&dataintegration.ConfigPO{Kind: integrationbiz.IntegrationKindPayment, Provider: "wechat-pay", Config: `{"merchant_id":"123"}`}).Error; err != nil {
t.Fatal(err)
}
@ -103,13 +105,13 @@ func TestStorageIntegrationConfigRoundTrip(t *testing.T) {
}
var storageCount, emailCount, paymentCount int64
if err = db.Model(&integrationConfigPO{}).Where("kind = ?", integrationKindStorage).Count(&storageCount).Error; err != nil {
if err = db.Model(&dataintegration.ConfigPO{}).Where("kind = ?", integrationKindStorage).Count(&storageCount).Error; err != nil {
t.Fatal(err)
}
if err = db.Model(&integrationConfigPO{}).Where("kind = ?", integrationKindPayment).Count(&paymentCount).Error; err != nil {
if err = db.Model(&dataintegration.ConfigPO{}).Where("kind = ?", integrationbiz.IntegrationKindPayment).Count(&paymentCount).Error; err != nil {
t.Fatal(err)
}
if err = db.Model(&integrationConfigPO{}).Where("kind = ?", integrationKindEmail).Count(&emailCount).Error; err != nil {
if err = db.Model(&dataintegration.ConfigPO{}).Where("kind = ?", integrationKindEmail).Count(&emailCount).Error; err != nil {
t.Fatal(err)
}
if storageCount != int64(len(storageProviderNames)) {

View File

@ -1,38 +0,0 @@
package data
import (
"encoding/json"
"errors"
"kra/internal/biz/system"
"gorm.io/gorm"
)
func ensureCommunicationIntegrationConfigs(db *gorm.DB) error {
defaults := []struct {
kind string
provider string
}{
{kind: system.IntegrationKindMQ, provider: "emqx"},
{kind: system.IntegrationKindMQ, provider: "rabbitmq"},
{kind: system.IntegrationKindWebSocket, provider: "melody"},
}
for _, item := range defaults {
var row integrationConfigPO
err := db.Where("kind = ? AND provider = ?", item.kind, item.provider).First(&row).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
values, marshalErr := json.Marshal(system.DefaultIntegrationConfig(item.kind, item.provider))
if marshalErr != nil {
return marshalErr
}
if err = db.Create(&integrationConfigPO{Kind: item.kind, Provider: item.provider, Enabled: false, Config: string(values)}).Error; err != nil {
return err
}
continue
}
if err != nil {
return err
}
}
return nil
}

View File

@ -1,29 +1,13 @@
package data
import (
"errors"
"kra/internal/integration/runtimeconfig"
"gorm.io/gorm"
dataintegration "kra/internal/data/integration"
"kra/internal/integration/runtimeconfig"
)
func readIntegrationRuntime(db *gorm.DB) ([]runtimeconfig.Config, error) {
if db == nil || !db.Migrator().HasTable(&integrationConfigPO{}) {
return nil, nil
}
var rows []integrationConfigPO
if err := db.Session(&gorm.Session{NewDB: true}).
Where("kind IN ?", []string{"mq", "websocket"}).
Order("kind ASC, provider ASC").
Find(&rows).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
return nil, err
}
configs := make([]runtimeconfig.Config, 0, len(rows))
for _, row := range rows {
configs = append(configs, runtimeconfig.Config{Kind: row.Kind, Provider: row.Provider, Enabled: row.Enabled, Values: []byte(row.Config)})
}
return configs, nil
return dataintegration.ReadRuntime(db)
}
func (d *Data) loadIntegrationRuntime(db *gorm.DB) error {

View File

@ -1,35 +1,15 @@
package data
import (
datapayment "kra/internal/data/payment"
datasystem "kra/internal/data/repository"
"kra/pkg/database/migration"
"kra/pkg/module"
"gorm.io/gorm"
)
func InfrastructureMigrations() []migration.Step {
return []migration.Step{
{
ID: "202608200001_data_infrastructure",
Migrate: func(db *gorm.DB) error {
return migration.CreateMissingTables(db, &integrationConfigPO{})
},
},
{ID: "202608210001_communication_integration_defaults", Migrate: ensureCommunicationIntegrationConfigs},
}
}
// migrateAll is the single data-layer migration entry point. Module-specific
// schema work stays with the module that owns its persistent objects.
func migrateAll(db *gorm.DB, catalogs ...module.Catalog) error {
steps := InfrastructureMigrations()
if len(catalogs) > 0 && len(catalogs[0].MigrationSteps()) > 0 {
steps = append(steps, catalogs[0].MigrationSteps()...)
} else {
steps = append(steps, datasystem.Migrations()...)
steps = append(steps, datapayment.Migrations()...)
}
return migration.Run(db, steps)
// migrateAll is the single data-layer migration entry point. Every module
// must register its migrations through the application catalog; there is no
// hidden system/payment fallback that could silently omit a new module.
func migrateAll(db *gorm.DB, catalog module.Catalog) error {
return migration.Run(db, catalog.MigrationSteps())
}

View File

@ -3,18 +3,26 @@ package data
import (
"testing"
bizpayment "kra/internal/biz/payment"
dataintegration "kra/internal/data/integration"
"kra/internal/modules"
"kra/pkg/database/migration"
platformmodule "kra/pkg/module"
)
func testCatalog() platformmodule.Catalog {
return modules.Catalog()
}
func TestMigrateAllRunsModuleSchemasWithoutBootstrapSeed(t *testing.T) {
db, err := openWithDriver("sqlite", "file:"+t.Name()+"?mode=memory&cache=shared")
if err != nil {
t.Fatal(err)
}
if err = migrateAll(db); err != nil {
if err = migrateAll(db, testCatalog()); err != nil {
t.Fatal(err)
}
if err = migrateAll(db); err != nil {
if err = migrateAll(db, testCatalog()); err != nil {
t.Fatalf("second migration run: %v", err)
}
for _, table := range []string{"sys_integration_configs", "sys_users", "sys_base_menus", "pay_orders"} {
@ -26,16 +34,23 @@ func TestMigrateAllRunsModuleSchemasWithoutBootstrapSeed(t *testing.T) {
if err = db.Table(migration.TableName).Count(&versions).Error; err != nil {
t.Fatal(err)
}
if versions != 7 {
t.Fatalf("migration versions = %d, want 7", versions)
if versions != 8 {
t.Fatalf("migration versions = %d, want 8", versions)
}
var communicationRows []integrationConfigPO
var communicationRows []dataintegration.ConfigPO
if err = db.Where("kind IN ?", []string{"mq", "websocket"}).Order("kind, provider").Find(&communicationRows).Error; err != nil {
t.Fatal(err)
}
if len(communicationRows) != 3 {
t.Fatalf("communication integration rows = %d, want 3", len(communicationRows))
}
var paymentRows int64
if err = db.Model(&dataintegration.ConfigPO{}).Where("kind = ?", "payment").Count(&paymentRows).Error; err != nil {
t.Fatal(err)
}
if paymentRows != int64(len(bizpayment.SupportedPaymentProviders)) {
t.Fatalf("payment integration rows = %d, want %d", paymentRows, len(bizpayment.SupportedPaymentProviders))
}
for _, row := range communicationRows {
if row.Enabled || row.Config == "" {
t.Fatalf("default communication integration = %#v", row)

View File

@ -11,6 +11,5 @@ func Migrations() []migration.Step {
{ID: "202608200003_payment_schema", Migrate: func(db *gorm.DB) error {
return migration.CreateMissingTables(db, &paymentOrderPO{})
}},
{ID: "202608200004_payment_defaults", Migrate: ensurePaymentIntegrationConfigs},
}
}

View File

@ -1,17 +0,0 @@
package payment
import "time"
const integrationKindPayment = "payment"
type integrationConfigPO struct {
ID uint `gorm:"primaryKey"`
CreatedAt time.Time
UpdatedAt time.Time
Kind string `gorm:"size:32;not null;uniqueIndex:idx_integration_kind_provider"`
Provider string `gorm:"size:64;not null;uniqueIndex:idx_integration_kind_provider"`
Enabled bool `gorm:"not null;default:false;index"`
Config string `gorm:"type:text;not null"`
}
func (integrationConfigPO) TableName() string { return "sys_integration_configs" }

View File

@ -7,7 +7,8 @@ import (
"encoding/json"
"errors"
"fmt"
"kra/internal/biz/system"
integrationbiz "kra/internal/biz/integration"
bizpayment "kra/internal/biz/payment"
"net/url"
"strconv"
"strings"
@ -16,67 +17,40 @@ import (
datapayment "kra/internal/integration/payment"
"github.com/google/uuid"
"gorm.io/gorm"
)
type paymentRepo struct{ data Provider }
func NewPaymentRepo(data Provider) system.PaymentRepo { return &paymentRepo{data: data} }
func ensurePaymentIntegrationConfigs(db *gorm.DB) error {
for _, provider := range system.SupportedPaymentProviders {
var row integrationConfigPO
err := db.Where("kind = ? AND provider = ?", integrationKindPayment, provider).First(&row).Error
defaults := system.DefaultIntegrationConfig(integrationKindPayment, provider)
if errors.Is(err, gorm.ErrRecordNotFound) {
encoded, _ := json.Marshal(defaults)
if err := db.Create(&integrationConfigPO{Kind: integrationKindPayment, Provider: provider, Enabled: false, Config: string(encoded)}).Error; err != nil {
return err
}
continue
}
if err != nil {
return err
}
values := map[string]any{}
_ = json.Unmarshal([]byte(row.Config), &values)
changed := false
for key, value := range defaults {
if _, exists := values[key]; !exists {
values[key] = value
changed = true
}
}
if changed {
encoded, _ := json.Marshal(values)
if err := db.Model(&row).Update("config", string(encoded)).Error; err != nil {
return err
}
}
}
return nil
type paymentRepo struct {
data Provider
config integrationbiz.PaymentConfigReader
}
func (r *paymentRepo) row(ctx context.Context, provider string) (*integrationConfigPO, map[string]any, error) {
var row integrationConfigPO
if err := r.data.DB().WithContext(ctx).Where("kind = ? AND provider = ?", integrationKindPayment, provider).First(&row).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, nil, system.ErrPaymentProviderNotFound
}
return nil, nil, err
func NewPaymentRepo(data Provider, config integrationbiz.PaymentConfigReader) bizpayment.PaymentRepo {
return &paymentRepo{data: data, config: config}
}
func (r *paymentRepo) values(ctx context.Context, provider string) (map[string]any, error) {
if r == nil || r.config == nil {
return nil, errors.New("支付配置仓储未接入")
}
if !row.Enabled {
return nil, nil, fmt.Errorf("支付渠道 %s 未启用", provider)
config, err := r.config.ReadPaymentConfig(ctx, provider)
if err != nil {
if errors.Is(err, integrationbiz.ErrPaymentConfigNotFound) {
return nil, bizpayment.ErrPaymentProviderNotFound
}
return nil, err
}
if config == nil || !config.Enabled {
return nil, fmt.Errorf("支付渠道 %s 未启用", provider)
}
values := map[string]any{}
if err := json.Unmarshal([]byte(row.Config), &values); err != nil {
return nil, nil, fmt.Errorf("支付配置格式错误: %w", err)
if err := json.Unmarshal(config.Values, &values); err != nil {
return nil, fmt.Errorf("支付配置格式错误: %w", err)
}
return &row, values, nil
return values, nil
}
func (r *paymentRepo) adapter(ctx context.Context, provider string) (datapayment.Adapter, map[string]any, error) {
_, values, err := r.row(ctx, provider)
values, err := r.values(ctx, provider)
if err != nil {
return nil, nil, err
}
@ -84,11 +58,11 @@ func (r *paymentRepo) adapter(ctx context.Context, provider string) (datapayment
return adapter, values, err
}
func (r *paymentRepo) TestProvider(ctx context.Context, provider string) (*system.PaymentTestResult, error) {
func (r *paymentRepo) TestProvider(ctx context.Context, provider string) (*bizpayment.PaymentTestResult, error) {
started := time.Now()
test := &system.PaymentTestResult{Provider: provider, TradeNo: "", Passed: false, Stages: []system.PaymentTestStage{}}
test := &bizpayment.PaymentTestResult{Provider: provider, TradeNo: "", Passed: false, Stages: []bizpayment.PaymentTestStage{}}
add := func(name, status, message, tradeNo string, since time.Time) {
test.Stages = append(test.Stages, system.PaymentTestStage{Name: name, Status: status, Message: message, TradeNo: tradeNo, Duration: time.Since(since).Milliseconds()})
test.Stages = append(test.Stages, bizpayment.PaymentTestStage{Name: name, Status: status, Message: message, TradeNo: tradeNo, Duration: time.Since(since).Milliseconds()})
}
values, err := r.testRow(ctx, provider)
if err != nil {
@ -97,7 +71,7 @@ func (r *paymentRepo) TestProvider(ctx context.Context, provider string) (*syste
}
test.Mode = strings.ToLower(strings.TrimSpace(text(values, "environment")))
configStart := time.Now()
if err = system.ValidateIntegrationConfig(system.IntegrationKindPayment, provider, values); err != nil {
if err = integrationbiz.ValidateIntegrationConfig(integrationbiz.IntegrationKindPayment, provider, values); err != nil {
add("config", "failed", err.Error(), "", configStart)
return test, err
}
@ -117,11 +91,11 @@ func (r *paymentRepo) TestProvider(ctx context.Context, provider string) (*syste
orders := &paymentOrderRepo{data: r.data}
extra, _ := json.Marshal(req.Extra)
localStart := time.Now()
order, _, err := orders.CreatePaymentOrder(ctx, &system.PaymentOrder{
order, _, err := orders.CreatePaymentOrder(ctx, &bizpayment.PaymentOrder{
TradeNo: req.TradeNo, Provider: provider, BusinessType: req.BusinessType, BusinessID: req.BusinessID,
Subject: req.Subject, PaymentMode: system.PaymentModeExternal, OriginalAmount: req.Amount, Amount: req.Amount,
Currency: req.Currency, PaymentStatus: system.PaymentStatusInitialized, FulfillmentStatus: system.FulfillmentStatusPending,
RefundStatus: system.RefundStatusNone, ConfirmationID: uuid.NewString(), RequestFingerprint: paymentTestFingerprint(req), Extra: extra,
Subject: req.Subject, PaymentMode: bizpayment.PaymentModeExternal, OriginalAmount: req.Amount, Amount: req.Amount,
Currency: req.Currency, PaymentStatus: bizpayment.PaymentStatusInitialized, FulfillmentStatus: bizpayment.FulfillmentStatusPending,
RefundStatus: bizpayment.RefundStatusNone, ConfirmationID: uuid.NewString(), RequestFingerprint: paymentTestFingerprint(req), Extra: extra,
})
if err != nil {
add("local_order", "failed", err.Error(), req.TradeNo, localStart)
@ -159,7 +133,7 @@ func (r *paymentRepo) TestProvider(ctx context.Context, provider string) (*syste
if queryID == "" {
queryID = req.TradeNo
}
if provider == system.PaymentApple {
if provider == bizpayment.PaymentApple {
queryID = strings.TrimSpace(text(values, "test_transaction_id"))
if queryID == "" {
err = errors.New("Apple 连通性测试需要配置 test_transaction_id沙箱交易 ID")
@ -179,7 +153,7 @@ func (r *paymentRepo) TestProvider(ctx context.Context, provider string) (*syste
add("query", "failed", err.Error(), req.TradeNo, queryStart)
return test, err
}
if provider != system.PaymentApple {
if provider != bizpayment.PaymentApple {
if order, err = orders.ApplyPaymentResult(ctx, provider, req.TradeNo, paymentTestProviderUpdate(queried)); err != nil {
add("local_order", "failed", "回写测试查单结果失败: "+err.Error(), req.TradeNo, queryStart)
return test, err
@ -193,9 +167,9 @@ func (r *paymentRepo) TestProvider(ctx context.Context, provider string) (*syste
test.Result = queried
add("query", "passed", "测试订单查询成功,状态: "+queried.Status, req.TradeNo, queryStart)
if queried.Status != "success" || provider == system.PaymentApple {
if queried.Status != "success" || provider == bizpayment.PaymentApple {
message := "订单尚未支付成功,已完成配置、下单和查单连通性测试;请在沙箱完成付款后重试"
if provider == system.PaymentApple {
if provider == bizpayment.PaymentApple {
message = "Apple 退款由 App Store 管理,已完成配置、下单和交易查询测试"
}
add("refund", "skipped", message, req.TradeNo, time.Now())
@ -208,7 +182,7 @@ func (r *paymentRepo) TestProvider(ctx context.Context, provider string) (*syste
add("refund", "failed", beginErr.Error(), req.TradeNo, refundStart)
return test, beginErr
}
refund, refundErr := adapter.Refund(ctx, &system.PaymentRefundRequest{Provider: provider, TradeNo: req.TradeNo, ProviderTradeNo: order.ProviderTradeNo, QueryID: order.QueryID, RefundNo: order.RefundNo, Amount: req.Amount, TotalAmount: req.Amount, Currency: req.Currency}, values)
refund, refundErr := adapter.Refund(ctx, &bizpayment.PaymentRefundRequest{Provider: provider, TradeNo: req.TradeNo, ProviderTradeNo: order.ProviderTradeNo, QueryID: order.QueryID, RefundNo: order.RefundNo, Amount: req.Amount, TotalAmount: req.Amount, Currency: req.Currency}, values)
if refundErr != nil {
recordPaymentTestError(ctx, r.data, provider, req.TradeNo, refundErr)
add("refund", "failed", refundErr.Error(), req.TradeNo, refundStart)
@ -230,17 +204,17 @@ func (r *paymentRepo) TestProvider(ctx context.Context, provider string) (*syste
return test, nil
}
func paymentTestFingerprint(req *system.PaymentRequest) string {
func paymentTestFingerprint(req *bizpayment.PaymentRequest) string {
raw, _ := json.Marshal(req)
hash := sha256.Sum256(raw)
return hex.EncodeToString(hash[:])
}
func paymentTestProviderUpdate(result *system.PaymentResult) *system.PaymentProviderUpdate {
func paymentTestProviderUpdate(result *bizpayment.PaymentResult) *bizpayment.PaymentProviderUpdate {
if result == nil {
return nil
}
return &system.PaymentProviderUpdate{
return &bizpayment.PaymentProviderUpdate{
Status: result.Status, ProviderStatus: result.Status, ProviderTradeNo: result.ProviderTradeNo, QueryID: result.QueryID,
Amount: result.Amount, PayerPaidAmount: result.PayerPaidAmount, CashPaidAmount: result.CashPaidAmount,
PointPaidAmount: result.PointPaidAmount, DiscountAmount: result.DiscountAmount,
@ -250,21 +224,21 @@ func paymentTestProviderUpdate(result *system.PaymentResult) *system.PaymentProv
}
}
func validatePaymentTestResult(provider, tradeNo string, result *system.PaymentResult) error {
func validatePaymentTestResult(provider, tradeNo string, result *bizpayment.PaymentResult) error {
if result == nil {
return errors.New("支付渠道响应为空")
}
if strings.TrimSpace(result.Provider) != provider {
return errors.New("支付渠道响应的 provider 不匹配")
}
if value := strings.TrimSpace(result.TradeNo); provider != system.PaymentApple && value != "" && value != tradeNo {
if value := strings.TrimSpace(result.TradeNo); provider != bizpayment.PaymentApple && value != "" && value != tradeNo {
return errors.New("支付渠道响应的商户订单号不匹配")
}
return nil
}
func queryPaymentTest(ctx context.Context, adapter datapayment.Adapter, queryID string, values map[string]any) (*system.PaymentResult, error) {
var result *system.PaymentResult
func queryPaymentTest(ctx context.Context, adapter datapayment.Adapter, queryID string, values map[string]any) (*bizpayment.PaymentResult, error) {
var result *bizpayment.PaymentResult
var err error
for attempt := 0; attempt < 3; attempt++ {
result, err = adapter.Query(ctx, queryID, values)
@ -297,31 +271,37 @@ func recordPaymentTestError(ctx context.Context, data Provider, provider, tradeN
}
func (r *paymentRepo) testRow(ctx context.Context, provider string) (map[string]any, error) {
var row integrationConfigPO
if err := r.data.DB().WithContext(ctx).Where("kind = ? AND provider = ?", integrationKindPayment, provider).First(&row).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, system.ErrPaymentProviderNotFound
if r == nil || r.config == nil {
return nil, errors.New("支付配置仓储未接入")
}
config, err := r.config.ReadPaymentConfig(ctx, provider)
if err != nil {
if errors.Is(err, integrationbiz.ErrPaymentConfigNotFound) {
return nil, bizpayment.ErrPaymentProviderNotFound
}
return nil, err
}
if config == nil {
return nil, errors.New("支付配置为空")
}
values := map[string]any{}
if err := json.Unmarshal([]byte(row.Config), &values); err != nil {
return nil, fmt.Errorf("支付配置格式错误: %w", err)
if err := json.Unmarshal(config.Values, &values); err != nil || values == nil {
return nil, errors.New("支付配置格式错误")
}
return values, nil
}
func paymentTestRequest(provider string, values map[string]any) *system.PaymentRequest {
func paymentTestRequest(provider string, values map[string]any) *bizpayment.PaymentRequest {
tradeNo := "kra-test-" + time.Now().UTC().Format("20060102150405.000000000")
amount := configuredInt64(values, "test_amount", 1)
if amount <= 0 {
amount = 1
}
req := &system.PaymentRequest{Provider: provider, TradeNo: strings.ReplaceAll(tradeNo, ".", ""), Subject: "Kra 支付渠道连通性测试", Amount: amount, Currency: strings.ToUpper(firstAny(values, "test_currency", "currency", "fee_type")), NotifyURL: text(values, "notify_url"), ReturnURL: text(values, "return_url"), BusinessType: "system_payment_test", BusinessID: uuid.NewString(), Extra: map[string]any{}}
req := &bizpayment.PaymentRequest{Provider: provider, TradeNo: strings.ReplaceAll(tradeNo, ".", ""), Subject: "Kra 支付渠道连通性测试", Amount: amount, Currency: strings.ToUpper(firstAny(values, "test_currency", "currency", "fee_type")), NotifyURL: text(values, "notify_url"), ReturnURL: text(values, "return_url"), BusinessType: "system_payment_test", BusinessID: uuid.NewString(), Extra: map[string]any{}}
if req.Currency == "" {
req.Currency = "CNY"
}
if provider == system.PaymentApple {
if provider == bizpayment.PaymentApple {
req.TradeNo = uuid.NewString()
req.Extra["product_id"] = firstAny(values, "product_id", "test_product_id")
}
@ -351,10 +331,10 @@ func validatePaymentTestSettings(provider string, values map[string]any) error {
return fmt.Errorf("test_extra 必须是 JSON 对象: %w", err)
}
}
if provider == system.PaymentApple && strings.TrimSpace(text(values, "test_transaction_id")) == "" {
if provider == bizpayment.PaymentApple && strings.TrimSpace(text(values, "test_transaction_id")) == "" {
return errors.New("Apple 测试需要 test_transaction_id沙箱交易 ID")
}
if provider == system.PaymentApple && strings.TrimSpace(firstAny(values, "test_product_id", "product_id")) == "" {
if provider == bizpayment.PaymentApple && strings.TrimSpace(firstAny(values, "test_product_id", "product_id")) == "" {
return errors.New("Apple 测试需要 test_product_id沙箱商品 ID")
}
return nil
@ -377,7 +357,7 @@ func testModeEnabled(values map[string]any) bool {
}
}
func (r *paymentRepo) Create(ctx context.Context, req *system.PaymentRequest) (*system.PaymentResult, error) {
func (r *paymentRepo) Create(ctx context.Context, req *bizpayment.PaymentRequest) (*bizpayment.PaymentResult, error) {
if req == nil {
return nil, errors.New("支付下单请求为空")
}
@ -396,7 +376,7 @@ func (r *paymentRepo) Create(ctx context.Context, req *system.PaymentRequest) (*
func paymentProviderRequiresNotifyURL(provider string) bool {
switch provider {
case system.PaymentApple, system.PaymentAllinPay, system.PaymentSaobei, system.PaymentPayPal:
case bizpayment.PaymentApple, bizpayment.PaymentAllinPay, bizpayment.PaymentSaobei, bizpayment.PaymentPayPal:
return false
default:
return true
@ -413,15 +393,15 @@ func paymentCreateRequiresNotifyURL(provider string, extra, config map[string]an
}
keys := []string{"method", "pay_method", "trade_type", "pay_type", "channel"}
switch provider {
case system.PaymentAlipay, system.PaymentAlipayV3:
case bizpayment.PaymentAlipay, bizpayment.PaymentAlipayV3:
keys = []string{"method", "pay_method", "trade_type", "channel"}
case system.PaymentWechatV2:
case bizpayment.PaymentWechatV2:
keys = []string{"trade_type", "pay_type", "method", "pay_method", "channel"}
case system.PaymentWechatV3:
case bizpayment.PaymentWechatV3:
keys = []string{"trade_type", "pay_type", "method"}
case system.PaymentQQ:
case bizpayment.PaymentQQ:
keys = []string{"trade_type", "pay_type", "method", "pay_method"}
case system.PaymentLakala:
case bizpayment.PaymentLakala:
keys = []string{"method", "pay_method", "trade_type"}
}
value := firstAny(extra, keys...)
@ -430,28 +410,28 @@ func paymentCreateRequiresNotifyURL(provider string, extra, config map[string]an
}
normalized := strings.NewReplacer(".", "_", "-", "_", " ", "_").Replace(strings.ToLower(strings.TrimSpace(value)))
switch provider {
case system.PaymentAlipay, system.PaymentAlipayV3:
case bizpayment.PaymentAlipay, bizpayment.PaymentAlipayV3:
return !contains([]string{"pay", "trade_pay", "alipay_trade_pay", "barcode", "barcode_pay", "micropay", "face_to_face"}, normalized)
case system.PaymentWechatV2:
case bizpayment.PaymentWechatV2:
return !contains([]string{"micropay", "micro_pay", "barcode", "barcode_pay", "pay_code", "payment_code"}, normalized)
case system.PaymentWechatV3:
case bizpayment.PaymentWechatV3:
return !contains([]string{"micropay", "micro_pay", "codepay", "code_pay", "barcode", "barcode_pay", "facepay", "face_pay"}, normalized)
case system.PaymentQQ:
case bizpayment.PaymentQQ:
return !contains([]string{"micropay", "micro_pay", "barcode", "barcode_pay"}, normalized)
case system.PaymentLakala:
case bizpayment.PaymentLakala:
return !contains([]string{"retail", "retail_pay", "micropay", "barcode"}, normalized)
default:
return true
}
}
func (r *paymentRepo) Query(ctx context.Context, provider, tradeNo string) (*system.PaymentResult, error) {
func (r *paymentRepo) Query(ctx context.Context, provider, tradeNo string) (*bizpayment.PaymentResult, error) {
a, c, err := r.adapter(ctx, provider)
if err != nil {
return nil, err
}
return a.Query(ctx, tradeNo, c)
}
func (r *paymentRepo) Refund(ctx context.Context, req *system.PaymentRefundRequest) (*system.PaymentResult, error) {
func (r *paymentRepo) Refund(ctx context.Context, req *bizpayment.PaymentRefundRequest) (*bizpayment.PaymentResult, error) {
if req == nil {
return nil, errors.New("支付退款请求为空")
}
@ -461,7 +441,7 @@ func (r *paymentRepo) Refund(ctx context.Context, req *system.PaymentRefundReque
}
return a.Refund(ctx, req, c)
}
func (r *paymentRepo) HandleCallback(ctx context.Context, callback *system.PaymentCallback) (*system.PaymentResult, error) {
func (r *paymentRepo) HandleCallback(ctx context.Context, callback *bizpayment.PaymentCallback) (*bizpayment.PaymentResult, error) {
if callback == nil {
return nil, errors.New("支付回调为空")
}
@ -471,23 +451,23 @@ func (r *paymentRepo) HandleCallback(ctx context.Context, callback *system.Payme
}
result, err := a.Callback(ctx, callback, c)
if err != nil {
return nil, &system.PaymentCallbackError{Cause: err, Ack: paymentCallbackAck(callback.Provider, c, false)}
return nil, &bizpayment.PaymentCallbackError{Cause: err, Ack: paymentCallbackAck(callback.Provider, c, false)}
}
if result == nil {
err = errors.New("支付回调解析结果为空")
return nil, &system.PaymentCallbackError{Cause: err, Ack: paymentCallbackAck(callback.Provider, c, false)}
return nil, &bizpayment.PaymentCallbackError{Cause: err, Ack: paymentCallbackAck(callback.Provider, c, false)}
}
result.SuccessAck = paymentCallbackAck(callback.Provider, c, true)
result.FailureAck = paymentCallbackAck(callback.Provider, c, false)
if result.Provider != callback.Provider {
err = errors.New("支付回调渠道不匹配")
return nil, &system.PaymentCallbackError{Cause: err, Ack: result.FailureAck}
return nil, &bizpayment.PaymentCallbackError{Cause: err, Ack: result.FailureAck}
}
result.EventID = paymentCallbackEventID(callback, result)
return result, nil
}
func paymentCallbackEventID(callback *system.PaymentCallback, result *system.PaymentResult) string {
func paymentCallbackEventID(callback *bizpayment.PaymentCallback, result *bizpayment.PaymentResult) string {
if result != nil {
if eventID := strings.TrimSpace(result.EventID); eventID != "" {
return eventID
@ -504,8 +484,8 @@ func paymentCallbackEventID(callback *system.PaymentCallback, result *system.Pay
return hex.EncodeToString(hash[:])
}
func paymentCallbackAck(provider string, values map[string]any, success bool) system.PaymentCallbackAck {
ack := system.DefaultPaymentCallbackAck(provider, success)
func paymentCallbackAck(provider string, values map[string]any, success bool) bizpayment.PaymentCallbackAck {
ack := bizpayment.DefaultPaymentCallbackAck(provider, success)
prefix := "callback_success_"
if !success {
prefix = "callback_failure_"
@ -524,7 +504,7 @@ func paymentCallbackAck(provider string, values map[string]any, success bool) sy
return ack
}
func callbackFields(callback *system.PaymentCallback) map[string]string {
func callbackFields(callback *bizpayment.PaymentCallback) map[string]string {
fields := map[string]string{}
for key, value := range callback.Query {
fields[key] = value
@ -569,5 +549,5 @@ func contains(values []string, value string) bool {
}
func validatePaymentConfig(provider string, values map[string]any) error {
return system.ValidateIntegrationConfig(system.IntegrationKindPayment, provider, values)
return integrationbiz.ValidateIntegrationConfig(integrationbiz.IntegrationKindPayment, provider, values)
}

View File

@ -1,7 +1,8 @@
package payment
import (
"kra/internal/biz/system"
integrationbiz "kra/internal/biz/integration"
bizpayment "kra/internal/biz/payment"
"strings"
"testing"
)
@ -11,18 +12,18 @@ func TestValidatePaymentConfigRequiresDouyinAppIDWhenEnabled(t *testing.T) {
"merchant_id": "merchant-douyin", "serial_no": "merchant-serial", "api_key": "01234567890123456789012345678901",
"private_key": "merchant-private-key", "platform_cert": "platform-public-key", "platform_serial_no": "platform-serial",
}
err := system.ValidateIntegrationConfig(system.IntegrationKindPayment, system.PaymentDouyin, values)
err := integrationbiz.ValidateIntegrationConfig(integrationbiz.IntegrationKindPayment, bizpayment.PaymentDouyin, values)
if err == nil || !strings.Contains(err.Error(), "app_id") {
t.Fatalf("missing app_id error = %v", err)
}
values["app_id"] = "douyin-app"
if err = system.ValidateIntegrationConfig(system.IntegrationKindPayment, system.PaymentDouyin, values); err != nil {
if err = integrationbiz.ValidateIntegrationConfig(integrationbiz.IntegrationKindPayment, bizpayment.PaymentDouyin, values); err != nil {
t.Fatalf("valid Douyin configuration rejected: %v", err)
}
}
func TestValidatePaymentConfigAcceptsProviderAliases(t *testing.T) {
err := validatePaymentConfig(system.PaymentDouyin, map[string]any{
err := validatePaymentConfig(bizpayment.PaymentDouyin, map[string]any{
"app_id": "douyin-app", "merchant_id": "merchant-douyin", "serial_no": "merchant-serial", "api_key": "01234567890123456789012345678901",
"private_key": "merchant-private-key", "platform_cert": "platform-public-key", "platform_cert_serial": "platform-serial",
})
@ -36,13 +37,13 @@ func TestValidatePaymentConfigProviderRules(t *testing.T) {
name, provider, want string
values map[string]any
}{
{"allinpay order type", system.PaymentAllinPay, "reqsn", map[string]any{"cus_id": "customer", "app_id": "app", "private_key": "private-key", "public_key": "public-key", "query_order_type": "payinfo"}},
{"paypal webhook", system.PaymentPayPal, "webhook_id", map[string]any{"client_id": "client-id", "client_secret": "client-secret"}},
{"wechat v2 refund cert", system.PaymentWechatV2, "client_cert", map[string]any{"app_id": "app", "merchant_id": "merchant", "mch_key": "key"}},
{"allinpay order type", bizpayment.PaymentAllinPay, "reqsn", map[string]any{"cus_id": "customer", "app_id": "app", "private_key": "private-key", "public_key": "public-key", "query_order_type": "payinfo"}},
{"paypal webhook", bizpayment.PaymentPayPal, "webhook_id", map[string]any{"client_id": "client-id", "client_secret": "client-secret"}},
{"wechat v2 refund cert", bizpayment.PaymentWechatV2, "client_cert", map[string]any{"app_id": "app", "merchant_id": "merchant", "mch_key": "key"}},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
err := system.ValidateIntegrationConfig(system.IntegrationKindPayment, test.provider, test.values)
err := integrationbiz.ValidateIntegrationConfig(integrationbiz.IntegrationKindPayment, test.provider, test.values)
if err == nil || !strings.Contains(err.Error(), test.want) {
t.Fatalf("error = %v, want %q", err, test.want)
}
@ -51,13 +52,13 @@ func TestValidatePaymentConfigProviderRules(t *testing.T) {
}
func TestValidatePaymentConfigGenericRequiresRuntimeFields(t *testing.T) {
values := system.DefaultIntegrationConfig(system.IntegrationKindPayment, system.PaymentChinaums)
if err := system.ValidateIntegrationConfig(system.IntegrationKindPayment, system.PaymentChinaums, values); err == nil {
values := integrationbiz.DefaultIntegrationConfig(integrationbiz.IntegrationKindPayment, bizpayment.PaymentChinaums)
if err := integrationbiz.ValidateIntegrationConfig(integrationbiz.IntegrationKindPayment, bizpayment.PaymentChinaums, values); err == nil {
t.Fatal("empty generic payment config unexpectedly accepted")
}
values["app_id"], values["merchant_id"] = "app", "merchant"
values["create_url"], values["query_url"], values["refund_url"], values["app_key"] = "https://pay.test/create", "https://pay.test/query", "https://pay.test/refund", "secret"
if err := system.ValidateIntegrationConfig(system.IntegrationKindPayment, system.PaymentChinaums, values); err == nil {
if err := integrationbiz.ValidateIntegrationConfig(integrationbiz.IntegrationKindPayment, bizpayment.PaymentChinaums, values); err == nil {
t.Fatal("generic config with only identity/endpoints unexpectedly accepted")
}
}

View File

@ -1,15 +1,16 @@
package payment
import (
"kra/internal/biz/system"
integrationbiz "kra/internal/biz/integration"
bizpayment "kra/internal/biz/payment"
"strings"
"testing"
)
func TestPaymentDefinitionsProvideNonEmptyDefaults(t *testing.T) {
definitions := system.IntegrationDefinitions(system.IntegrationKindPayment)
if len(definitions) != len(system.SupportedPaymentProviders) {
t.Fatalf("payment definitions = %d, want %d", len(definitions), len(system.SupportedPaymentProviders))
definitions := integrationbiz.IntegrationDefinitions(integrationbiz.IntegrationKindPayment)
if len(definitions) != len(bizpayment.SupportedPaymentProviders) {
t.Fatalf("payment definitions = %d, want %d", len(definitions), len(bizpayment.SupportedPaymentProviders))
}
for _, definition := range definitions {
if definition.Provider == "" || definition.Name == "" || len(definition.Fields) == 0 {

View File

@ -4,7 +4,7 @@ import (
"context"
"encoding/json"
"errors"
"kra/internal/biz/system"
bizpayment "kra/internal/biz/payment"
"strings"
"time"
@ -68,11 +68,11 @@ func (paymentOrderPO) TableName() string { return "pay_orders" }
type paymentOrderRepo struct{ data Provider }
func NewPaymentOrderRepo(data Provider) system.PaymentOrderRepo {
func NewPaymentOrderRepo(data Provider) bizpayment.PaymentOrderRepo {
return &paymentOrderRepo{data: data}
}
func newPaymentOrderPO(order *system.PaymentOrder) (*paymentOrderPO, error) {
func newPaymentOrderPO(order *bizpayment.PaymentOrder) (*paymentOrderPO, error) {
if order == nil {
return nil, errors.New("支付订单为空")
}
@ -85,16 +85,16 @@ func newPaymentOrderPO(order *system.PaymentOrder) (*paymentOrderPO, error) {
ID: order.ID, TradeNo: order.TradeNo, Provider: order.Provider,
ProviderTradeNo: optionalString(order.ProviderTradeNo), QueryID: order.QueryID,
BusinessType: order.BusinessType, BusinessID: order.BusinessID, Subject: order.Subject,
PaymentMode: defaultString(order.PaymentMode, system.PaymentModeExternal), OriginalAmount: order.OriginalAmount,
PaymentMode: defaultString(order.PaymentMode, bizpayment.PaymentModeExternal), OriginalAmount: order.OriginalAmount,
Amount: order.Amount, PaidAmount: order.PaidAmount, PayerPaidAmount: order.PayerPaidAmount,
CashPaidAmount: order.CashPaidAmount, PointPaidAmount: order.PointPaidAmount, DiscountAmount: order.DiscountAmount,
ProviderDiscountAmount: order.ProviderDiscountAmount, MerchantDiscountAmount: order.MerchantDiscountAmount,
SettlementAmount: order.SettlementAmount, Currency: order.Currency, PayerCurrency: order.PayerCurrency,
AmountBreakdownKnown: order.AmountBreakdownKnown,
PaymentStatus: defaultString(order.PaymentStatus, system.PaymentStatusInitialized),
PaymentStatus: defaultString(order.PaymentStatus, bizpayment.PaymentStatusInitialized),
ProviderStatus: order.ProviderStatus,
FulfillmentStatus: defaultString(order.FulfillmentStatus, system.FulfillmentStatusPending),
RefundStatus: defaultString(order.RefundStatus, system.RefundStatusNone),
FulfillmentStatus: defaultString(order.FulfillmentStatus, bizpayment.FulfillmentStatusPending),
RefundStatus: defaultString(order.RefundStatus, bizpayment.RefundStatusNone),
RefundedAmount: order.RefundedAmount, RefundRequestedAmount: order.RefundRequestedAmount, RefundNo: order.RefundNo,
ConfirmationID: order.ConfirmationID, RequestFingerprint: order.RequestFingerprint,
CreatePayload: createPayload, Extra: extra, LastEventID: order.LastEventID,
@ -105,15 +105,15 @@ func newPaymentOrderPO(order *system.PaymentOrder) (*paymentOrderPO, error) {
}, nil
}
func toBizPaymentOrder(po *paymentOrderPO) *system.PaymentOrder {
func toBizPaymentOrder(po *paymentOrderPO) *bizpayment.PaymentOrder {
if po == nil {
return nil
}
return &system.PaymentOrder{
return &bizpayment.PaymentOrder{
ID: po.ID, TradeNo: po.TradeNo, Provider: po.Provider,
ProviderTradeNo: dereferenceString(po.ProviderTradeNo), QueryID: po.QueryID,
BusinessType: po.BusinessType, BusinessID: po.BusinessID, Subject: po.Subject,
PaymentMode: defaultString(po.PaymentMode, system.PaymentModeExternal), OriginalAmount: po.OriginalAmount,
PaymentMode: defaultString(po.PaymentMode, bizpayment.PaymentModeExternal), OriginalAmount: po.OriginalAmount,
Amount: po.Amount, PaidAmount: po.PaidAmount, PayerPaidAmount: po.PayerPaidAmount,
CashPaidAmount: po.CashPaidAmount, PointPaidAmount: po.PointPaidAmount, DiscountAmount: po.DiscountAmount,
ProviderDiscountAmount: po.ProviderDiscountAmount, MerchantDiscountAmount: po.MerchantDiscountAmount,
@ -131,7 +131,7 @@ func toBizPaymentOrder(po *paymentOrderPO) *system.PaymentOrder {
}
}
func (r *paymentOrderRepo) CreatePaymentOrder(ctx context.Context, order *system.PaymentOrder) (*system.PaymentOrder, bool, error) {
func (r *paymentOrderRepo) CreatePaymentOrder(ctx context.Context, order *bizpayment.PaymentOrder) (*bizpayment.PaymentOrder, bool, error) {
po, err := newPaymentOrderPO(order)
if err != nil {
return nil, false, err
@ -154,18 +154,18 @@ func (r *paymentOrderRepo) CreatePaymentOrder(ctx context.Context, order *system
return nil, false, err
}
func (r *paymentOrderRepo) FindPaymentOrder(ctx context.Context, provider, tradeNo string) (*system.PaymentOrder, error) {
func (r *paymentOrderRepo) FindPaymentOrder(ctx context.Context, provider, tradeNo string) (*bizpayment.PaymentOrder, error) {
var po paymentOrderPO
if err := r.data.DB().WithContext(ctx).Where("provider = ? AND trade_no = ?", provider, tradeNo).First(&po).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, system.ErrPaymentOrderNotFound
return nil, bizpayment.ErrPaymentOrderNotFound
}
return nil, err
}
return toBizPaymentOrder(&po), nil
}
func (r *paymentOrderRepo) ListPaymentOrders(ctx context.Context, page, pageSize int, filter system.PaymentOrderFilter) ([]*system.PaymentOrder, int64, error) {
func (r *paymentOrderRepo) ListPaymentOrders(ctx context.Context, page, pageSize int, filter bizpayment.PaymentOrderFilter) ([]*bizpayment.PaymentOrder, int64, error) {
db := r.data.DB().WithContext(ctx).Model(&paymentOrderPO{})
if value := strings.TrimSpace(filter.Provider); value != "" {
db = db.Where("provider = ?", value)
@ -193,14 +193,14 @@ func (r *paymentOrderRepo) ListPaymentOrders(ctx context.Context, page, pageSize
if err := pagination.ApplyRequired(db.Order("id desc"), page, pageSize, 100).Find(&rows).Error; err != nil {
return nil, 0, err
}
items := make([]*system.PaymentOrder, 0, len(rows))
items := make([]*bizpayment.PaymentOrder, 0, len(rows))
for i := range rows {
items = append(items, toBizPaymentOrder(&rows[i]))
}
return items, total, nil
}
func (r *paymentOrderRepo) RecordPaymentCreate(ctx context.Context, provider, tradeNo string, update *system.PaymentProviderUpdate) (*system.PaymentOrder, error) {
func (r *paymentOrderRepo) RecordPaymentCreate(ctx context.Context, provider, tradeNo string, update *bizpayment.PaymentProviderUpdate) (*bizpayment.PaymentOrder, error) {
return r.withLockedOrder(ctx, provider, tradeNo, func(tx *gorm.DB, po *paymentOrderPO) error {
if update == nil {
return errors.New("支付下单结果为空")
@ -215,11 +215,11 @@ func (r *paymentOrderRepo) RecordPaymentCreate(ctx context.Context, provider, tr
po.LastEventID = trimTo(update.EventID, 128)
po.LastPayloadHash = trimTo(update.PayloadHash, 64)
status := normalizeOrderPaymentStatus(update.Status)
if status == system.PaymentStatusPaid {
if status == bizpayment.PaymentStatusPaid {
// Provider create responses are never sufficient proof of payment.
status = system.PaymentStatusPending
status = bizpayment.PaymentStatusPending
}
if po.PaymentStatus != system.PaymentStatusPaid && po.PaymentStatus != system.PaymentStatusPartiallyRefunded && po.PaymentStatus != system.PaymentStatusRefunded && status != "" {
if po.PaymentStatus != bizpayment.PaymentStatusPaid && po.PaymentStatus != bizpayment.PaymentStatusPartiallyRefunded && po.PaymentStatus != bizpayment.PaymentStatusRefunded && status != "" {
po.PaymentStatus = status
}
po.Version++
@ -227,7 +227,7 @@ func (r *paymentOrderRepo) RecordPaymentCreate(ctx context.Context, provider, tr
})
}
func (r *paymentOrderRepo) ApplyPaymentResult(ctx context.Context, provider, tradeNo string, update *system.PaymentProviderUpdate) (*system.PaymentOrder, error) {
func (r *paymentOrderRepo) ApplyPaymentResult(ctx context.Context, provider, tradeNo string, update *bizpayment.PaymentProviderUpdate) (*bizpayment.PaymentOrder, error) {
return r.withLockedOrder(ctx, provider, tradeNo, func(tx *gorm.DB, po *paymentOrderPO) error {
if update == nil {
return errors.New("支付查单结果为空")
@ -236,13 +236,13 @@ func (r *paymentOrderRepo) ApplyPaymentResult(ctx context.Context, provider, tra
return err
}
if update.Amount > 0 && update.Amount != po.Amount {
return system.ErrPaymentOrderConflict
return bizpayment.ErrPaymentOrderConflict
}
if update.PayerPaidAmount < 0 || update.CashPaidAmount < 0 || update.PointPaidAmount < 0 || update.DiscountAmount < 0 || update.ProviderDiscountAmount < 0 || update.MerchantDiscountAmount < 0 || update.SettlementAmount < 0 {
return system.ErrPaymentOrderConflict
return bizpayment.ErrPaymentOrderConflict
}
if update.Currency != "" && !strings.EqualFold(update.Currency, po.Currency) {
return system.ErrPaymentOrderConflict
return bizpayment.ErrPaymentOrderConflict
}
po.ProviderStatus = trimTo(update.ProviderStatus, 64)
po.LastEventID = trimTo(update.EventID, 128)
@ -259,22 +259,22 @@ func (r *paymentOrderRepo) ApplyPaymentResult(ctx context.Context, provider, tra
po.AmountBreakdownKnown = true
}
switch normalizeOrderPaymentStatus(update.Status) {
case system.PaymentStatusPaid:
if po.PaymentStatus != system.PaymentStatusPartiallyRefunded && po.PaymentStatus != system.PaymentStatusRefunded {
po.PaymentStatus = system.PaymentStatusPaid
case bizpayment.PaymentStatusPaid:
if po.PaymentStatus != bizpayment.PaymentStatusPartiallyRefunded && po.PaymentStatus != bizpayment.PaymentStatusRefunded {
po.PaymentStatus = bizpayment.PaymentStatusPaid
}
po.PaidAmount = po.Amount
if po.PaidAt == nil {
now := time.Now().UTC()
po.PaidAt = &now
}
case system.PaymentStatusPending:
if po.PaymentStatus != system.PaymentStatusPaid && po.PaymentStatus != system.PaymentStatusPartiallyRefunded && po.PaymentStatus != system.PaymentStatusRefunded {
po.PaymentStatus = system.PaymentStatusPending
case bizpayment.PaymentStatusPending:
if po.PaymentStatus != bizpayment.PaymentStatusPaid && po.PaymentStatus != bizpayment.PaymentStatusPartiallyRefunded && po.PaymentStatus != bizpayment.PaymentStatusRefunded {
po.PaymentStatus = bizpayment.PaymentStatusPending
}
case system.PaymentStatusFailed:
if po.PaymentStatus != system.PaymentStatusPaid && po.PaymentStatus != system.PaymentStatusPartiallyRefunded && po.PaymentStatus != system.PaymentStatusRefunded {
po.PaymentStatus = system.PaymentStatusFailed
case bizpayment.PaymentStatusFailed:
if po.PaymentStatus != bizpayment.PaymentStatusPaid && po.PaymentStatus != bizpayment.PaymentStatusPartiallyRefunded && po.PaymentStatus != bizpayment.PaymentStatusRefunded {
po.PaymentStatus = bizpayment.PaymentStatusFailed
}
}
po.Version++
@ -282,27 +282,27 @@ func (r *paymentOrderRepo) ApplyPaymentResult(ctx context.Context, provider, tra
})
}
func (r *paymentOrderRepo) BeginPaymentFulfillment(ctx context.Context, provider, tradeNo string, lease time.Duration) (*system.PaymentOrder, string, bool, error) {
func (r *paymentOrderRepo) BeginPaymentFulfillment(ctx context.Context, provider, tradeNo string, lease time.Duration) (*bizpayment.PaymentOrder, string, bool, error) {
var token string
var duplicate bool
order, err := r.withLockedOrder(ctx, provider, tradeNo, func(tx *gorm.DB, po *paymentOrderPO) error {
if po.FulfillmentStatus == system.FulfillmentStatusSucceeded {
if po.FulfillmentStatus == bizpayment.FulfillmentStatusSucceeded {
duplicate = true
return nil
}
if po.PaymentStatus != system.PaymentStatusPaid {
return system.ErrPaymentOrderState
if po.PaymentStatus != bizpayment.PaymentStatusPaid {
return bizpayment.ErrPaymentOrderState
}
now := time.Now().UTC()
if po.FulfillmentStatus == system.FulfillmentStatusProcessing && po.FulfillmentLeaseUntil != nil && po.FulfillmentLeaseUntil.After(now) {
return system.ErrPaymentOrderBusy
if po.FulfillmentStatus == bizpayment.FulfillmentStatusProcessing && po.FulfillmentLeaseUntil != nil && po.FulfillmentLeaseUntil.After(now) {
return bizpayment.ErrPaymentOrderBusy
}
if lease <= 0 {
lease = 10 * time.Minute
}
token = uuid.NewString()
until := now.Add(lease)
po.FulfillmentStatus = system.FulfillmentStatusProcessing
po.FulfillmentStatus = bizpayment.FulfillmentStatusProcessing
po.FulfillmentToken = token
po.FulfillmentLeaseUntil = &until
po.LastError = ""
@ -312,56 +312,56 @@ func (r *paymentOrderRepo) BeginPaymentFulfillment(ctx context.Context, provider
return order, token, duplicate, err
}
func (r *paymentOrderRepo) CompletePaymentFulfillment(ctx context.Context, provider, tradeNo, token string, success bool, message string) (*system.PaymentOrder, error) {
func (r *paymentOrderRepo) CompletePaymentFulfillment(ctx context.Context, provider, tradeNo, token string, success bool, message string) (*bizpayment.PaymentOrder, error) {
return r.withLockedOrder(ctx, provider, tradeNo, func(tx *gorm.DB, po *paymentOrderPO) error {
if po.FulfillmentStatus != system.FulfillmentStatusProcessing || po.FulfillmentToken != token {
return system.ErrPaymentOrderBusy
if po.FulfillmentStatus != bizpayment.FulfillmentStatusProcessing || po.FulfillmentToken != token {
return bizpayment.ErrPaymentOrderBusy
}
po.FulfillmentToken = ""
po.FulfillmentLeaseUntil = nil
po.LastError = trimTo(message, 512)
if success {
po.FulfillmentStatus = system.FulfillmentStatusSucceeded
po.FulfillmentStatus = bizpayment.FulfillmentStatusSucceeded
now := time.Now().UTC()
po.FulfilledAt = &now
} else {
po.FulfillmentStatus = system.FulfillmentStatusFailed
po.FulfillmentStatus = bizpayment.FulfillmentStatusFailed
}
po.Version++
return tx.Save(po).Error
})
}
func (r *paymentOrderRepo) BeginPaymentRefund(ctx context.Context, provider, tradeNo string, amount int64, lease time.Duration) (*system.PaymentOrder, string, error) {
func (r *paymentOrderRepo) BeginPaymentRefund(ctx context.Context, provider, tradeNo string, amount int64, lease time.Duration) (*bizpayment.PaymentOrder, string, error) {
var token string
order, err := r.withLockedOrder(ctx, provider, tradeNo, func(tx *gorm.DB, po *paymentOrderPO) error {
if po.PaymentStatus != system.PaymentStatusPaid && po.PaymentStatus != system.PaymentStatusPartiallyRefunded {
return system.ErrPaymentOrderState
if po.PaymentStatus != bizpayment.PaymentStatusPaid && po.PaymentStatus != bizpayment.PaymentStatusPartiallyRefunded {
return bizpayment.ErrPaymentOrderState
}
if amount <= 0 {
return system.ErrPaymentOrderConflict
return bizpayment.ErrPaymentOrderConflict
}
now := time.Now().UTC()
if po.RefundStatus == system.RefundStatusProcessing && po.RefundLeaseUntil != nil && po.RefundLeaseUntil.After(now) {
return system.ErrPaymentOrderBusy
if po.RefundStatus == bizpayment.RefundStatusProcessing && po.RefundLeaseUntil != nil && po.RefundLeaseUntil.After(now) {
return bizpayment.ErrPaymentOrderBusy
}
if po.RefundStatus == system.RefundStatusProcessing && po.RefundRequestedAmount != amount {
return system.ErrPaymentOrderConflict
if po.RefundStatus == bizpayment.RefundStatusProcessing && po.RefundRequestedAmount != amount {
return bizpayment.ErrPaymentOrderConflict
}
if po.RefundStatus == system.RefundStatusPending {
return system.ErrPaymentOrderBusy
if po.RefundStatus == bizpayment.RefundStatusPending {
return bizpayment.ErrPaymentOrderBusy
}
// An expired processing lease means the provider outcome is unknown.
// Retry the same refund amount with the same durable refund number. A
// different amount must never reuse that operation identity.
reserved := int64(0)
if po.RefundStatus == system.RefundStatusProcessing && po.RefundLeaseUntil != nil && !po.RefundLeaseUntil.After(now) {
if po.RefundStatus == bizpayment.RefundStatusProcessing && po.RefundLeaseUntil != nil && !po.RefundLeaseUntil.After(now) {
reserved = 0
} else {
reserved = po.RefundRequestedAmount
}
if amount > po.Amount-po.RefundedAmount-reserved {
return system.ErrPaymentOrderConflict
return bizpayment.ErrPaymentOrderConflict
}
if lease <= 0 {
lease = 10 * time.Minute
@ -371,7 +371,7 @@ func (r *paymentOrderRepo) BeginPaymentRefund(ctx context.Context, provider, tra
po.RefundNo = uuid.NewString()
}
until := now.Add(lease)
po.RefundStatus = system.RefundStatusProcessing
po.RefundStatus = bizpayment.RefundStatusProcessing
po.RefundRequestedAmount = amount
po.RefundToken = token
po.RefundLeaseUntil = &until
@ -382,18 +382,18 @@ func (r *paymentOrderRepo) BeginPaymentRefund(ctx context.Context, provider, tra
return order, token, err
}
func (r *paymentOrderRepo) CompletePaymentRefundRequest(ctx context.Context, provider, tradeNo, token string, accepted bool, message string) (*system.PaymentOrder, error) {
func (r *paymentOrderRepo) CompletePaymentRefundRequest(ctx context.Context, provider, tradeNo, token string, accepted bool, message string) (*bizpayment.PaymentOrder, error) {
return r.withLockedOrder(ctx, provider, tradeNo, func(tx *gorm.DB, po *paymentOrderPO) error {
if po.RefundStatus != system.RefundStatusProcessing || po.RefundToken != token {
return system.ErrPaymentOrderBusy
if po.RefundStatus != bizpayment.RefundStatusProcessing || po.RefundToken != token {
return bizpayment.ErrPaymentOrderBusy
}
po.RefundToken = ""
po.RefundLeaseUntil = nil
po.LastError = trimTo(message, 512)
if accepted {
po.RefundStatus = system.RefundStatusPending
po.RefundStatus = bizpayment.RefundStatusPending
} else {
po.RefundStatus = system.RefundStatusFailed
po.RefundStatus = bizpayment.RefundStatusFailed
po.RefundRequestedAmount = 0
po.RefundNo = ""
}
@ -402,26 +402,26 @@ func (r *paymentOrderRepo) CompletePaymentRefundRequest(ctx context.Context, pro
})
}
func (r *paymentOrderRepo) ConfirmPaymentRefund(ctx context.Context, provider, tradeNo, refundNo string, amount int64, success bool, message string) (*system.PaymentOrder, error) {
func (r *paymentOrderRepo) ConfirmPaymentRefund(ctx context.Context, provider, tradeNo, refundNo string, amount int64, success bool, message string) (*bizpayment.PaymentOrder, error) {
return r.withLockedOrder(ctx, provider, tradeNo, func(tx *gorm.DB, po *paymentOrderPO) error {
if po.RefundStatus != system.RefundStatusPending || po.RefundNo == "" || po.RefundNo != refundNo || po.RefundRequestedAmount != amount {
return system.ErrPaymentOrderState
if po.RefundStatus != bizpayment.RefundStatusPending || po.RefundNo == "" || po.RefundNo != refundNo || po.RefundRequestedAmount != amount {
return bizpayment.ErrPaymentOrderState
}
po.LastError = trimTo(message, 512)
po.RefundRequestedAmount = 0
if !success {
po.RefundStatus = system.RefundStatusFailed
po.RefundStatus = bizpayment.RefundStatusFailed
po.RefundNo = ""
po.Version++
return tx.Save(po).Error
}
po.RefundedAmount += amount
if po.RefundedAmount >= po.Amount {
po.PaymentStatus = system.PaymentStatusRefunded
po.RefundStatus = system.RefundStatusSucceeded
po.PaymentStatus = bizpayment.PaymentStatusRefunded
po.RefundStatus = bizpayment.RefundStatusSucceeded
} else {
po.PaymentStatus = system.PaymentStatusPartiallyRefunded
po.RefundStatus = system.RefundStatusPartial
po.PaymentStatus = bizpayment.PaymentStatusPartiallyRefunded
po.RefundStatus = bizpayment.RefundStatusPartial
}
po.RefundNo = ""
now := time.Now().UTC()
@ -431,13 +431,13 @@ func (r *paymentOrderRepo) ConfirmPaymentRefund(ctx context.Context, provider, t
})
}
func (r *paymentOrderRepo) withLockedOrder(ctx context.Context, provider, tradeNo string, fn func(*gorm.DB, *paymentOrderPO) error) (*system.PaymentOrder, error) {
var result *system.PaymentOrder
func (r *paymentOrderRepo) withLockedOrder(ctx context.Context, provider, tradeNo string, fn func(*gorm.DB, *paymentOrderPO) error) (*bizpayment.PaymentOrder, error) {
var result *bizpayment.PaymentOrder
err := r.data.DB().WithContext(ctx).Transaction(func(tx *gorm.DB) error {
var po paymentOrderPO
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("provider = ? AND trade_no = ?", provider, tradeNo).First(&po).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return system.ErrPaymentOrderNotFound
return bizpayment.ErrPaymentOrderNotFound
}
return err
}
@ -450,16 +450,16 @@ func (r *paymentOrderRepo) withLockedOrder(ctx context.Context, provider, tradeN
return result, err
}
func applyProviderIdentity(tx *gorm.DB, po *paymentOrderPO, update *system.PaymentProviderUpdate) error {
func applyProviderIdentity(tx *gorm.DB, po *paymentOrderPO, update *bizpayment.PaymentProviderUpdate) error {
if update.ProviderTradeNo != "" {
if po.ProviderTradeNo != nil && *po.ProviderTradeNo != update.ProviderTradeNo {
return system.ErrPaymentProviderConflict
return bizpayment.ErrPaymentProviderConflict
}
var other paymentOrderPO
// This check is repeated under the order transaction so a platform
// transaction cannot be attached to a different merchant order.
if err := tx.Where("provider = ? AND provider_trade_no = ? AND id <> ?", po.Provider, update.ProviderTradeNo, po.ID).First(&other).Error; err == nil {
return system.ErrPaymentProviderConflict
return bizpayment.ErrPaymentProviderConflict
} else if !errors.Is(err, gorm.ErrRecordNotFound) {
return err
}
@ -468,7 +468,7 @@ func applyProviderIdentity(tx *gorm.DB, po *paymentOrderPO, update *system.Payme
}
if update.QueryID != "" {
if po.QueryID != "" && po.QueryID != update.QueryID {
return system.ErrPaymentProviderConflict
return bizpayment.ErrPaymentProviderConflict
}
po.QueryID = update.QueryID
}
@ -478,11 +478,11 @@ func applyProviderIdentity(tx *gorm.DB, po *paymentOrderPO, update *system.Payme
func normalizeOrderPaymentStatus(value string) string {
switch strings.ToLower(strings.TrimSpace(value)) {
case "success", "paid", "fulfilled":
return system.PaymentStatusPaid
return bizpayment.PaymentStatusPaid
case "pending", "created", "client_pending", "processing":
return system.PaymentStatusPending
return bizpayment.PaymentStatusPending
case "failed", "closed", "cancelled", "canceled":
return system.PaymentStatusFailed
return bizpayment.PaymentStatusFailed
default:
return ""
}

View File

@ -2,7 +2,7 @@ package payment
import (
"context"
"kra/internal/biz/system"
bizpayment "kra/internal/biz/payment"
"testing"
"time"
)
@ -19,11 +19,11 @@ func newPaymentOrderRepoForTest(t *testing.T) *paymentOrderRepo {
return &paymentOrderRepo{data: &Data{gormDB: newReloadableDB(db, nil)}}
}
func testPaymentOrder() *system.PaymentOrder {
return &system.PaymentOrder{
TradeNo: "order-1", Provider: system.PaymentAlipay, BusinessType: "game_item", BusinessID: "item-1",
Subject: "item", Amount: 100, Currency: "CNY", PaymentStatus: system.PaymentStatusInitialized,
FulfillmentStatus: system.FulfillmentStatusPending, RefundStatus: system.RefundStatusNone,
func testPaymentOrder() *bizpayment.PaymentOrder {
return &bizpayment.PaymentOrder{
TradeNo: "order-1", Provider: bizpayment.PaymentAlipay, BusinessType: "game_item", BusinessID: "item-1",
Subject: "item", Amount: 100, Currency: "CNY", PaymentStatus: bizpayment.PaymentStatusInitialized,
FulfillmentStatus: bizpayment.FulfillmentStatusPending, RefundStatus: bizpayment.RefundStatusNone,
ConfirmationID: "11111111-1111-1111-1111-111111111111", RequestFingerprint: "fingerprint",
}
}
@ -35,36 +35,36 @@ func TestPaymentOrderRepositoryPersistsPaymentFulfillmentAndRefundState(t *testi
if err != nil || !created {
t.Fatalf("create order = %#v created=%v err=%v", order, created, err)
}
update := &system.PaymentProviderUpdate{Status: "success", ProviderStatus: "TRADE_SUCCESS", ProviderTradeNo: "provider-1", Amount: 100, Currency: "CNY", EventID: "event-1"}
order, err = repo.ApplyPaymentResult(ctx, system.PaymentAlipay, "order-1", update)
if err != nil || order.PaymentStatus != system.PaymentStatusPaid || order.PaidAmount != 100 {
update := &bizpayment.PaymentProviderUpdate{Status: "success", ProviderStatus: "TRADE_SUCCESS", ProviderTradeNo: "provider-1", Amount: 100, Currency: "CNY", EventID: "event-1"}
order, err = repo.ApplyPaymentResult(ctx, bizpayment.PaymentAlipay, "order-1", update)
if err != nil || order.PaymentStatus != bizpayment.PaymentStatusPaid || order.PaidAmount != 100 {
t.Fatalf("apply payment = %#v err=%v", order, err)
}
order, token, duplicate, err := repo.BeginPaymentFulfillment(ctx, system.PaymentAlipay, "order-1", time.Minute)
if err != nil || duplicate || token == "" || order.FulfillmentStatus != system.FulfillmentStatusProcessing {
order, token, duplicate, err := repo.BeginPaymentFulfillment(ctx, bizpayment.PaymentAlipay, "order-1", time.Minute)
if err != nil || duplicate || token == "" || order.FulfillmentStatus != bizpayment.FulfillmentStatusProcessing {
t.Fatalf("begin fulfillment = %#v token=%q duplicate=%v err=%v", order, token, duplicate, err)
}
if _, _, _, err = repo.BeginPaymentFulfillment(ctx, system.PaymentAlipay, "order-1", time.Minute); err == nil {
if _, _, _, err = repo.BeginPaymentFulfillment(ctx, bizpayment.PaymentAlipay, "order-1", time.Minute); err == nil {
t.Fatal("concurrent fulfillment was accepted")
}
order, err = repo.CompletePaymentFulfillment(ctx, system.PaymentAlipay, "order-1", token, true, "")
if err != nil || order.FulfillmentStatus != system.FulfillmentStatusSucceeded {
order, err = repo.CompletePaymentFulfillment(ctx, bizpayment.PaymentAlipay, "order-1", token, true, "")
if err != nil || order.FulfillmentStatus != bizpayment.FulfillmentStatusSucceeded {
t.Fatalf("complete fulfillment = %#v err=%v", order, err)
}
_, _, duplicate, err = repo.BeginPaymentFulfillment(ctx, system.PaymentAlipay, "order-1", time.Minute)
_, _, duplicate, err = repo.BeginPaymentFulfillment(ctx, bizpayment.PaymentAlipay, "order-1", time.Minute)
if err != nil || !duplicate {
t.Fatalf("duplicate fulfillment = duplicate=%v err=%v", duplicate, err)
}
order, token, err = repo.BeginPaymentRefund(ctx, system.PaymentAlipay, "order-1", 40, time.Minute)
if err != nil || token == "" || order.RefundStatus != system.RefundStatusProcessing {
order, token, err = repo.BeginPaymentRefund(ctx, bizpayment.PaymentAlipay, "order-1", 40, time.Minute)
if err != nil || token == "" || order.RefundStatus != bizpayment.RefundStatusProcessing {
t.Fatalf("begin refund = %#v token=%q err=%v", order, token, err)
}
order, err = repo.CompletePaymentRefundRequest(ctx, system.PaymentAlipay, "order-1", token, true, "")
if err != nil || order.RefundStatus != system.RefundStatusPending || order.RefundRequestedAmount != 40 {
order, err = repo.CompletePaymentRefundRequest(ctx, bizpayment.PaymentAlipay, "order-1", token, true, "")
if err != nil || order.RefundStatus != bizpayment.RefundStatusPending || order.RefundRequestedAmount != 40 {
t.Fatalf("accept refund = %#v err=%v", order, err)
}
order, err = repo.ConfirmPaymentRefund(ctx, system.PaymentAlipay, "order-1", order.RefundNo, 40, true, "")
if err != nil || order.RefundedAmount != 40 || order.PaymentStatus != system.PaymentStatusPartiallyRefunded {
order, err = repo.ConfirmPaymentRefund(ctx, bizpayment.PaymentAlipay, "order-1", order.RefundNo, 40, true, "")
if err != nil || order.RefundedAmount != 40 || order.PaymentStatus != bizpayment.PaymentStatusPartiallyRefunded {
t.Fatalf("confirm refund = %#v err=%v", order, err)
}
}
@ -82,11 +82,11 @@ func TestPaymentOrderRepositoryRejectsProviderTradeReuse(t *testing.T) {
if _, _, err := repo.CreatePaymentOrder(ctx, second); err != nil {
t.Fatal(err)
}
update := &system.PaymentProviderUpdate{Status: "success", ProviderTradeNo: "provider-1", Amount: 100, Currency: "CNY"}
if _, err := repo.ApplyPaymentResult(ctx, system.PaymentAlipay, "order-1", update); err != nil {
update := &bizpayment.PaymentProviderUpdate{Status: "success", ProviderTradeNo: "provider-1", Amount: 100, Currency: "CNY"}
if _, err := repo.ApplyPaymentResult(ctx, bizpayment.PaymentAlipay, "order-1", update); err != nil {
t.Fatal(err)
}
if _, err := repo.ApplyPaymentResult(ctx, system.PaymentAlipay, "order-2", update); err != system.ErrPaymentProviderConflict {
if _, err := repo.ApplyPaymentResult(ctx, bizpayment.PaymentAlipay, "order-2", update); err != bizpayment.ErrPaymentProviderConflict {
t.Fatalf("provider trade reuse err = %v", err)
}
}
@ -100,13 +100,13 @@ func TestPaymentOrderRepositoryListsWithFilters(t *testing.T) {
}
second := testPaymentOrder()
second.TradeNo = "wechat-order-2"
second.Provider = system.PaymentWechatV3
second.Provider = bizpayment.PaymentWechatV3
second.BusinessID = "item-2"
second.ConfirmationID = "33333333-3333-3333-3333-333333333333"
if _, _, err := repo.CreatePaymentOrder(ctx, second); err != nil {
t.Fatal(err)
}
items, total, err := repo.ListPaymentOrders(ctx, 1, 10, system.PaymentOrderFilter{Provider: system.PaymentWechatV3, TradeNo: "wechat", BusinessID: "item-2"})
items, total, err := repo.ListPaymentOrders(ctx, 1, 10, bizpayment.PaymentOrderFilter{Provider: bizpayment.PaymentWechatV3, TradeNo: "wechat", BusinessID: "item-2"})
if err != nil {
t.Fatal(err)
}

View File

@ -1,8 +1,6 @@
package payment
import (
"gorm.io/gorm"
)
import "gorm.io/gorm"
// Provider is the narrow persistence seam required by payment repositories.
// Keeping it here lets payment remain an independent data module.

View File

@ -2,7 +2,6 @@ package payment
import (
"fmt"
"testing"
"github.com/glebarez/sqlite"
"gorm.io/gorm"
@ -29,32 +28,3 @@ func openWithDriver(driver, dsn string) (*gorm.DB, error) {
}
return gorm.Open(sqlite.Open(dsn), &gorm.Config{})
}
func openIntegrationConfigTestDB(t *testing.T) *gorm.DB {
t.Helper()
db, err := openWithDriver("sqlite", "file:"+t.Name()+"?mode=memory&cache=shared")
if err != nil {
t.Fatal(err)
}
if err := db.AutoMigrate(&integrationConfigPO{}); err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
if sqlDB, err := db.DB(); err == nil {
_ = sqlDB.Close()
}
})
return db
}
func migrateAll(db *gorm.DB) error {
if err := db.AutoMigrate(&integrationConfigPO{}); err != nil {
return err
}
for _, step := range Migrations() {
if err := step.Migrate(db); err != nil {
return err
}
}
return nil
}

View File

@ -10,7 +10,7 @@ import (
"gorm.io/gorm"
)
type dataAccessLogPO struct {
type DataAccessLogPO struct {
ID uint `gorm:"primaryKey"`
CreatedAt time.Time
UpdatedAt time.Time
@ -21,16 +21,16 @@ type dataAccessLogPO struct {
RequestID, Method, Path, Detail string
}
func (dataAccessLogPO) TableName() string { return "sys_data_access_logs" }
func (DataAccessLogPO) TableName() string { return "sys_data_access_logs" }
func (r *auditRecorderRepo) RecordDataAccess(ctx context.Context, v *system.DataAccessLog) error {
return r.data.DB().WithContext(ctx).Create(&dataAccessLogPO{EventType: v.EventType, TargetTable: v.TargetTable, Operation: v.Operation, UserID: v.UserID, AuthorityID: v.AuthorityID, Scope: v.Scope, RequestID: v.RequestID, Method: v.Method, Path: v.Path, Detail: v.Detail}).Error
return r.data.DB().WithContext(ctx).Create(&DataAccessLogPO{EventType: v.EventType, TargetTable: v.TargetTable, Operation: v.Operation, UserID: v.UserID, AuthorityID: v.AuthorityID, Scope: v.Scope, RequestID: v.RequestID, Method: v.Method, Path: v.Path, Detail: v.Detail}).Error
}
func dataAccessFromPO(v dataAccessLogPO) *system.DataAccessLog {
func dataAccessFromPO(v DataAccessLogPO) *system.DataAccessLog {
return &system.DataAccessLog{ID: v.ID, CreatedAt: v.CreatedAt, UpdatedAt: v.UpdatedAt, EventType: v.EventType, TargetTable: v.TargetTable, Operation: v.Operation, UserID: v.UserID, AuthorityID: v.AuthorityID, Scope: v.Scope, RequestID: v.RequestID, Method: v.Method, Path: v.Path, Detail: v.Detail}
}
func (r *auditQueryRepo) ListDataAccess(ctx context.Context, page, size int, q *system.DataAccessLog) ([]*system.DataAccessLog, int64, error) {
db := r.data.DB().WithContext(ctx).Model(&dataAccessLogPO{})
db := r.data.DB().WithContext(ctx).Model(&DataAccessLogPO{})
if q != nil {
if q.EventType != "" {
db = db.Where("event_type = ?", q.EventType)
@ -43,7 +43,7 @@ func (r *auditQueryRepo) ListDataAccess(ctx context.Context, page, size int, q *
if err := db.Count(&total).Error; err != nil {
return nil, 0, err
}
var pos []dataAccessLogPO
var pos []DataAccessLogPO
if err := pagination.ApplyRequired(db.Order("id desc"), page, size, 100).Find(&pos).Error; err != nil {
return nil, 0, err
}
@ -54,5 +54,5 @@ func (r *auditQueryRepo) ListDataAccess(ctx context.Context, page, size int, q *
return out, total, nil
}
func (r *auditQueryRepo) DeleteDataAccess(ctx context.Context, ids []uint) error {
return r.data.DB().WithContext(ctx).Delete(&dataAccessLogPO{}, "id IN ?", ids).Error
return r.data.DB().WithContext(ctx).Delete(&DataAccessLogPO{}, "id IN ?", ids).Error
}

View File

@ -0,0 +1,26 @@
package system
import (
"context"
"time"
bizsystem "kra/internal/biz/system"
"gorm.io/gorm"
)
type maintenanceRepo struct{ data Provider }
func NewMaintenanceRepo(data Provider) bizsystem.MaintenanceRepo {
return &maintenanceRepo{data: data}
}
func (r *maintenanceRepo) CleanupExpired(ctx context.Context) error {
now := time.Now()
return r.data.DB().WithContext(ctx).Transaction(func(tx *gorm.DB) error {
if err := tx.Unscoped().Where("created_at < ?", now.Add(-2160*time.Hour)).Delete(&operationPO{}).Error; err != nil {
return err
}
return tx.Unscoped().Where("created_at < ?", now.Add(-168*time.Hour)).Delete(&jwtBlacklistPO{}).Error
})
}

View File

@ -22,8 +22,8 @@ func Migrations() []migration.Step {
&departmentPO{}, &positionPO{}, &userDepartmentPO{}, &userPositionPO{}, &authorityDepartmentPO{},
&dictionaryPO{}, &dictionaryDetailPO{}, &parameterPO{}, &apiTokenPO{}, &jwtBlacklistPO{}, &SecurityConfigPO{},
&versionPO{}, &exportTemplatePO{}, &exportConditionPO{}, &exportJoinPO{},
&operationPO{}, &loginLogPO{}, &dataAccessLogPO{}, &errorRecordPO{},
&taskPO{}, &taskLogPO{}, &mediaPO{}, &categoryPO{}, &uploadSessionPO{}, &uploadChunkPO{},
&operationPO{}, &loginLogPO{}, &DataAccessLogPO{}, &errorRecordPO{},
&mediaPO{}, &categoryPO{}, &uploadSessionPO{}, &uploadChunkPO{},
&announcementPO{},
)
},

View File

@ -22,8 +22,7 @@ var ProviderSet = wire.NewSet(
NewAuditRepo,
NewAuditRecorderRepo,
NewLogFileRepo,
NewTaskRepo,
NewMediaRepo,
NewAnnouncementRepo,
NewIntegrationConfigRepo,
NewMaintenanceRepo,
)

View File

@ -112,7 +112,7 @@ func (i *tokenIssuer) ReissueToken(source *system.AuthClaims, authorityID uint)
AuthorityID: authorityID, BufferTime: int64(source.BufferTime / time.Second), UserType: source.UserType,
MustChangePwd: source.MustChangePwd, PasswordVersion: source.PasswordVersion,
RegisteredClaims: jwt.RegisteredClaims{
Audience: jwt.ClaimStrings(append([]string(nil), source.Audience...)), Issuer: source.Issuer,
Audience: jwt.ClaimStrings{security.TokenAudience}, Issuer: settings.Issuer,
IssuedAt: jwt.NewNumericDate(source.IssuedAt), NotBefore: jwt.NewNumericDate(source.NotBefore), ExpiresAt: jwt.NewNumericDate(source.ExpiresAt),
},
}
@ -124,7 +124,8 @@ func (i *tokenIssuer) ReissueToken(source *system.AuthClaims, authorityID uint)
}
func (i *tokenIssuer) ParseToken(token string) (*system.AuthClaims, error) {
claims, err := security.Parse(token, i.settings.JWTSettings().SigningKey)
settings := i.settings.JWTSettings()
claims, err := security.ParseWithIssuer(token, settings.SigningKey, settings.Issuer)
if err != nil {
switch {
case errors.Is(err, security.ErrTokenExpired):
@ -144,5 +145,12 @@ func (i *tokenIssuer) ParseToken(token string) (*system.AuthClaims, error) {
if claims.IssuedAt != nil {
issuedAt = claims.IssuedAt.Time
}
return &system.AuthClaims{UUID: claims.UUID, ID: claims.ID, Username: claims.Username, NickName: claims.NickName, AuthorityID: claims.AuthorityID, UserType: claims.UserType, BufferTime: time.Duration(claims.BufferTime) * time.Second, MustChangePwd: claims.MustChangePwd, PasswordVersion: claims.PasswordVersion, Issuer: claims.Issuer, Audience: audience, IssuedAt: issuedAt, NotBefore: claims.NotBefore.Time, ExpiresAt: claims.ExpiresAt.Time}, nil
notBefore, expiresAt := time.Time{}, time.Time{}
if claims.NotBefore != nil {
notBefore = claims.NotBefore.Time
}
if claims.ExpiresAt != nil {
expiresAt = claims.ExpiresAt.Time
}
return &system.AuthClaims{UUID: claims.UUID, ID: claims.ID, Username: claims.Username, NickName: claims.NickName, AuthorityID: claims.AuthorityID, UserType: claims.UserType, BufferTime: time.Duration(claims.BufferTime) * time.Second, MustChangePwd: claims.MustChangePwd, PasswordVersion: claims.PasswordVersion, Issuer: claims.Issuer, Audience: audience, IssuedAt: issuedAt, NotBefore: notBefore, ExpiresAt: expiresAt}, nil
}

View File

@ -14,21 +14,20 @@ import (
)
func SeedSystem(ctx context.Context, db *gorm.DB, input *system.DatabaseConfig, surfaces ...platformmodule.Surface) error {
return seedSystem(ctx, db, input, nil, surfaces...)
return seedSystem(ctx, db, input, surfaces...)
}
// SeedSystemWithCatalog applies module-contributed administration surfaces and
// default timed tasks in one transaction. The system module remains the owner
// of the system tables, while other modules contribute through the catalog.
// SeedSystemWithCatalog applies module-contributed administration surfaces in
// one transaction. Each data module seeds its own persistent tables.
func SeedSystemWithCatalog(ctx context.Context, db *gorm.DB, input *system.DatabaseConfig, catalog platformmodule.Catalog) error {
surfaces := make([]platformmodule.Surface, 0, len(catalog.Definitions))
for _, definition := range catalog.Definitions {
surfaces = append(surfaces, definition.Surface)
}
return seedSystem(ctx, db, input, catalog.DefaultTimedTasks(), surfaces...)
return seedSystem(ctx, db, input, surfaces...)
}
func seedSystem(ctx context.Context, db *gorm.DB, input *system.DatabaseConfig, defaults []platformmodule.TimedTask, surfaces ...platformmodule.Surface) error {
func seedSystem(ctx context.Context, db *gorm.DB, input *system.DatabaseConfig, surfaces ...platformmodule.Surface) error {
return db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
rootParentID := uint(0)
authority := authorityPO{AuthorityID: 888, AuthorityName: "超级管理员", ParentID: &rootParentID, DataScope: 1, DefaultRouter: "dashboard"}
@ -112,18 +111,6 @@ func seedSystem(ctx context.Context, db *gorm.DB, input *system.DatabaseConfig,
if err := tx.Where("template_id = ?", exportTemplate.TemplateID).FirstOrCreate(&exportTemplate).Error; err != nil {
return err
}
var defaultTasks []taskPO
if defaults == nil {
defaultTasks = []taskPO{{Name: "ClearDB", Description: "定时清理数据库过期日志(操作记录/JWT黑名单/定时任务执行日志)", Spec: "@daily", ExecutorType: "method", MethodName: "ClearDB", Enabled: true}, {Name: "CleanStaleUploads", Description: "定时清理过期大文件上传会话", Spec: "@hourly", ExecutorType: "method", MethodName: "CleanStaleUploads", Enabled: true}}
}
for _, item := range defaults {
defaultTasks = append(defaultTasks, taskPO{Name: item.Name, Description: item.Description, Spec: item.Spec, WithSeconds: item.WithSeconds, ExecutorType: "method", MethodName: item.MethodName, Enabled: item.Enabled})
}
for _, task := range defaultTasks {
if err := tx.Where("name = ?", task.Name).FirstOrCreate(&task).Error; err != nil {
return err
}
}
for _, item := range input.APIs {
if item != nil {
po := apiPO{Path: item.Path, Method: strings.ToUpper(item.Method), Description: item.Description, APIGroup: item.APIGroup}

Some files were not shown because too many files have changed in this diff Show More