Compare commits
17 Commits
b7a7430cc3
...
Iteration/
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
46f3a7741b | ||
|
|
4967f4df43 | ||
|
|
94f86ab217 | ||
|
|
76d0f38b9e | ||
|
|
0138a3fb9c | ||
|
|
7b13431f36 | ||
|
|
b2fc74c021 | ||
|
|
8b0a01753d | ||
|
|
d3face6f66 | ||
|
|
226a15573a | ||
|
|
eb0d86df4f | ||
|
|
3f593b912d | ||
|
|
7d705cf1e8 | ||
|
|
1214181e78 | ||
|
|
7e0e37933e | ||
|
|
94cbf2adab | ||
|
|
8eb7d403c4 |
@@ -50,8 +50,10 @@ jobs:
|
||||
- name: 部署到测试环境(仅八月迭代分支)
|
||||
if: github.ref == 'refs/heads/Iteration/8-11'
|
||||
run: |
|
||||
# 确保部署目录存在(仅需日志目录,配置已嵌入二进制文件)
|
||||
mkdir -p ${{ env.DEPLOY_DIR }}/logs
|
||||
# 确保部署目录存在:api、worker 各自的日志目录与 worker 的采集记录归档目录(配置已嵌入二进制文件)
|
||||
mkdir -p ${{ env.DEPLOY_DIR }}/api/logs ${{ env.DEPLOY_DIR }}/worker/logs ${{ env.DEPLOY_DIR }}/worker/archive
|
||||
# 容器以 uid 1000(appuser)运行,新目录需可写;无权限修改属主时保持原样
|
||||
chown 1000:1000 ${{ env.DEPLOY_DIR }}/api/logs ${{ env.DEPLOY_DIR }}/worker/logs ${{ env.DEPLOY_DIR }}/worker/archive 2>/dev/null || true
|
||||
|
||||
umask 077
|
||||
{
|
||||
|
||||
@@ -42,9 +42,11 @@ type carrierSchedulerRuntime struct {
|
||||
srConsumers *nsqbus.ConsumerManager
|
||||
devConsumers *nsqbus.ConsumerManager
|
||||
srActive bool
|
||||
singleton bool
|
||||
instanceID string
|
||||
logger *zap.Logger
|
||||
// ingest 是轮询观测入库消费者与积压监控(add-polling-async-ingest);未配置 nsqd 时为 nil。
|
||||
ingest *pollingIngestRuntime
|
||||
singleton bool
|
||||
instanceID string
|
||||
logger *zap.Logger
|
||||
|
||||
mu sync.Mutex
|
||||
lastMode string
|
||||
@@ -104,6 +106,7 @@ func startCarrierScheduler(ctx context.Context, cfg *config.Config, runtime *wor
|
||||
MsgTimeout: carrierCfg.MsgTimeout, MaxAttempts: carrierCfg.MaxAttempts,
|
||||
}, constants.NSQChannelWorker, executor.Handle, appLogger)
|
||||
}
|
||||
c.ingest = startPollingIngest(ctx, cfg, runtime, c.producer, singleton, c.grace(), appLogger)
|
||||
c.setupStopResume(carrierCfg, alerts)
|
||||
var budgets carrierqueue.BudgetProvider
|
||||
if runtime.gatewayLimit != nil && runtime.gatewayLimit.Limiter != nil {
|
||||
@@ -302,6 +305,8 @@ func (c *carrierSchedulerRuntime) shutdown() {
|
||||
}(manager)
|
||||
}
|
||||
wg.Wait()
|
||||
// 卡任务消费者停止后不再产生入库消息,再停入库与采集记录消费者,最后停生产者。
|
||||
c.ingest.shutdown()
|
||||
if c.producer != nil {
|
||||
c.producer.Stop()
|
||||
}
|
||||
|
||||
@@ -863,10 +863,10 @@ func startOutboxRelay(ctx context.Context, runtime *workerRuntime, instanceName
|
||||
appLogger.Info("Outbox Relay 已启动", zap.String("lease_owner", owner))
|
||||
}
|
||||
|
||||
// startTrafficCollectionPartitionMaintainer 为 leader/all 维护卡流量采集记录月分区并扫描采集告警:
|
||||
// 每 12 小时预建本月起 2 个月的分区、删除整月都早于保留期的分区;每天扫描一次前一天的采集告警。
|
||||
// startTrafficCollectionPartitionMaintainer 为 leader/all 维护卡流量采集记录(成功与失败)月分区并扫描采集告警:
|
||||
// 每 12 小时预建本月起 2 个月的分区,到期分区导出为 csv.gz、校验后删除;每天扫描一次前一天的采集告警。
|
||||
func startTrafficCollectionPartitionMaintainer(ctx context.Context, runtime *workerRuntime, appLogger *zap.Logger) {
|
||||
store := postgres.NewCardTrafficCollectionStore(runtime.db)
|
||||
archiver := cardObservationInfra.NewCollectionArchiver(runtime.db, constants.TrafficCollectionArchiveDir, constants.TrafficCollectionArchiveKeepFiles, appLogger)
|
||||
alerts := cardObservationInfra.NewTrafficAlertScanner(runtime.db, appLogger)
|
||||
go func() {
|
||||
ticker := time.NewTicker(time.Hour)
|
||||
@@ -876,7 +876,7 @@ func startTrafficCollectionPartitionMaintainer(ctx context.Context, runtime *wor
|
||||
for {
|
||||
now := time.Now()
|
||||
if now.Sub(lastMaintained) >= 12*time.Hour {
|
||||
if err := store.MaintainPartitions(ctx, now, 2, constants.TrafficCollectionRetentionDays); err != nil && ctx.Err() == nil {
|
||||
if err := archiver.Maintain(ctx, now); err != nil && ctx.Err() == nil {
|
||||
appLogger.Error("维护卡流量采集记录分区失败", zap.Error(err))
|
||||
} else {
|
||||
lastMaintained = now
|
||||
|
||||
160
cmd/worker/polling_ingest.go
Normal file
160
cmd/worker/polling_ingest.go
Normal file
@@ -0,0 +1,160 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"go.uber.org/zap"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/infrastructure/nsqbus"
|
||||
"github.com/break/junhong_cmp_fiber/internal/store/postgres"
|
||||
"github.com/break/junhong_cmp_fiber/internal/task"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/config"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
)
|
||||
|
||||
// pollingIngestRuntime 是轮询观测入库异步化在 Worker 内的运行组件(add-polling-async-ingest):
|
||||
// 入库消费者、采集记录批量消费者、活动优先项索引重建与积压监控。入库消费者常驻订阅,
|
||||
// 使切回同步模式后队列中已有的入库消息仍会被处理完。
|
||||
type pollingIngestRuntime struct {
|
||||
runtime *workerRuntime
|
||||
nsqdAddress string
|
||||
executor *task.IngestExecutor
|
||||
collector *task.CollectionBatchConsumer
|
||||
ingest *nsqbus.ConsumerManager
|
||||
collection *nsqbus.ConsumerManager
|
||||
rebuilder *task.PriorityIndexRebuilder
|
||||
stopCollect context.CancelFunc
|
||||
grace time.Duration
|
||||
logger *zap.Logger
|
||||
}
|
||||
|
||||
// startPollingIngest 注入入库发布器并启动入库与采集记录消费者;未配置 nsqd 时返回 nil,轮询保持同步入库。
|
||||
func startPollingIngest(ctx context.Context, cfg *config.Config, runtime *workerRuntime, producer *nsqbus.Producer,
|
||||
singleton bool, grace time.Duration, logger *zap.Logger) *pollingIngestRuntime {
|
||||
carrierCfg := cfg.Polling.Carrier
|
||||
if producer == nil || carrierCfg.NSQDAddress == "" {
|
||||
return nil
|
||||
}
|
||||
checkIngestConnBudget(cfg, logger)
|
||||
publisher := task.NewIngestPublisher(producer)
|
||||
runtime.pollingBase.SetIngest(publisher, func(ctx context.Context) bool {
|
||||
return runtime.carrierSettings.Current(ctx).IngestAsync()
|
||||
})
|
||||
observation := runtime.workerResult.Services.CardObservation
|
||||
if observation != nil {
|
||||
observation.SetCollectionSink(publisher)
|
||||
}
|
||||
r := &pollingIngestRuntime{
|
||||
runtime: runtime, nsqdAddress: carrierCfg.NSQDAddress, grace: grace, logger: logger,
|
||||
executor: task.NewIngestExecutor(runtime.pollingBase, observation, cfg.Polling.Ingest.EffectiveTimeout()),
|
||||
collector: task.NewCollectionBatchConsumer(runtime.db, cfg.Polling.Collection.EffectiveBatchSize(), logger),
|
||||
rebuilder: task.NewPriorityIndexRebuilder(postgres.NewPollingPriorityItemStore(runtime.db), runtime.redisClient, logger),
|
||||
}
|
||||
collectCtx, stopCollect := context.WithCancel(context.Background())
|
||||
r.stopCollect = stopCollect
|
||||
r.collector.Start(collectCtx)
|
||||
consumerCfg := nsqbus.ConsumerConfig{
|
||||
NSQDAddress: carrierCfg.NSQDAddress, NSQLookupdAddresses: nsqbus.SplitAddresses(carrierCfg.NSQLookupdAddresses),
|
||||
MsgTimeout: carrierCfg.MsgTimeout, UnlimitedAttempts: true,
|
||||
}
|
||||
r.ingest = nsqbus.NewRetryConsumerManager(consumerCfg, constants.NSQChannelWorker, r.executor.Handle, logger)
|
||||
r.collection = nsqbus.NewRetryConsumerManager(consumerCfg, constants.NSQChannelWorker, r.collector.Handle, logger)
|
||||
r.ingest.Sync(map[string]int{constants.NSQCardIngestTopic: cfg.Polling.Ingest.EffectiveConcurrency()})
|
||||
r.collection.Sync(map[string]int{constants.NSQCardCollectionTopic: constants.PollingCollectionMaxInFlight})
|
||||
logger.Info("轮询观测入库消费者已启动", zap.Int("ingest_concurrency", cfg.Polling.Ingest.EffectiveConcurrency()),
|
||||
zap.Duration("ingest_timeout", cfg.Polling.Ingest.EffectiveTimeout()),
|
||||
zap.Int("collection_batch_size", cfg.Polling.Collection.EffectiveBatchSize()))
|
||||
if singleton {
|
||||
go r.loop(ctx)
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
// checkIngestConnBudget 启动时检查入库并发与采集记录写并发不超过数据库连接数减去预留,超过只记 ERROR、不阻止启动。
|
||||
func checkIngestConnBudget(cfg *config.Config, logger *zap.Logger) {
|
||||
maxOpen := cfg.Database.MaxOpenConns
|
||||
if maxOpen <= 0 {
|
||||
maxOpen = constants.DefaultMaxOpenConns
|
||||
}
|
||||
need := cfg.Polling.Ingest.EffectiveConcurrency() + constants.PollingIngestCollectionWriters
|
||||
if budget := maxOpen - constants.PollingIngestConnReserve; need > budget {
|
||||
logger.Error("入库并发超出数据库连接预算,请调小 polling.ingest.concurrency 或调大数据库连接数",
|
||||
zap.Int("ingest_concurrency", cfg.Polling.Ingest.EffectiveConcurrency()),
|
||||
zap.Int("collection_writers", constants.PollingIngestCollectionWriters),
|
||||
zap.Int("max_open_conns", maxOpen), zap.Int("reserved", constants.PollingIngestConnReserve))
|
||||
}
|
||||
}
|
||||
|
||||
// loop 在 leader 上定期重建活动优先项索引并检查入库积压。
|
||||
func (r *pollingIngestRuntime) loop(ctx context.Context) {
|
||||
r.rebuilder.Rebuild(ctx)
|
||||
rebuild := time.NewTicker(constants.PollingPriorityIndexRebuildEvery)
|
||||
monitor := time.NewTicker(constants.PollingIngestMonitorInterval)
|
||||
defer rebuild.Stop()
|
||||
defer monitor.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-rebuild.C:
|
||||
r.rebuilder.Rebuild(ctx)
|
||||
case <-monitor.C:
|
||||
r.checkBacklog(ctx)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// checkBacklog 记录入库与采集记录积压,超过告警阈值或等待过久记 ERROR;入库积压超过反压阈值时暂停派发新卡任务,降到一半以下恢复。
|
||||
func (r *pollingIngestRuntime) checkBacklog(ctx context.Context) {
|
||||
defer func() {
|
||||
if recovered := recover(); recovered != nil {
|
||||
r.logger.Error("入库积压检查 panic,已恢复", zap.Any("panic", recovered))
|
||||
}
|
||||
}()
|
||||
settings := r.runtime.carrierSettings.Current(ctx)
|
||||
ingestDepth, ingestErr := nsqbus.TopicBacklog(ctx, r.nsqdAddress, constants.NSQCardIngestTopic)
|
||||
collectionDepth, collectionErr := nsqbus.TopicBacklog(ctx, r.nsqdAddress, constants.NSQCardCollectionTopic)
|
||||
if ingestErr != nil || collectionErr != nil {
|
||||
r.logger.Warn("读取入库积压失败", zap.NamedError("ingest_error", ingestErr), zap.NamedError("collection_error", collectionErr))
|
||||
return
|
||||
}
|
||||
lag := r.executor.LastLag()
|
||||
fields := []zap.Field{zap.Int64("ingest_backlog", ingestDepth), zap.Int64("collection_backlog", collectionDepth),
|
||||
zap.Duration("ingest_lag", lag), zap.String("ingest_mode", settings.IngestMode)}
|
||||
r.logger.Info("轮询入库积压", append(fields, zap.String("metric", "polling.ingest.backlog"))...)
|
||||
alertDepth := int64(settings.IngestAlertDepth)
|
||||
if ingestDepth > alertDepth || collectionDepth > alertDepth || lag > constants.PollingIngestLagAlert {
|
||||
r.logger.Error("轮询入库积压超过告警阈值", append(fields, zap.Int64("alert_depth", alertDepth))...)
|
||||
}
|
||||
r.applyBackpressure(ctx, ingestDepth, int64(settings.IngestPauseDepth))
|
||||
}
|
||||
|
||||
// applyBackpressure 按积压置位或清除暂停标记;标记带 TTL,leader 失联时自动解除。
|
||||
func (r *pollingIngestRuntime) applyBackpressure(ctx context.Context, depth, pauseDepth int64) {
|
||||
redisClient := r.runtime.redisClient
|
||||
paused, _ := redisClient.Exists(ctx, constants.RedisPollingIngestPausedKey).Result()
|
||||
ttl := 3 * constants.PollingIngestMonitorInterval
|
||||
switch {
|
||||
case depth > pauseDepth:
|
||||
redisClient.Set(ctx, constants.RedisPollingIngestPausedKey, depth, ttl)
|
||||
if paused == 0 {
|
||||
r.logger.Error("入库积压超过反压阈值,暂停派发新卡任务", zap.Int64("ingest_backlog", depth), zap.Int64("pause_depth", pauseDepth))
|
||||
}
|
||||
case paused > 0 && depth > pauseDepth/2:
|
||||
redisClient.Expire(ctx, constants.RedisPollingIngestPausedKey, ttl)
|
||||
case paused > 0:
|
||||
redisClient.Del(ctx, constants.RedisPollingIngestPausedKey)
|
||||
r.logger.Info("入库积压已降到反压阈值一半以下,恢复派发卡任务", zap.Int64("ingest_backlog", depth), zap.Int64("pause_depth", pauseDepth))
|
||||
}
|
||||
}
|
||||
|
||||
// shutdown 先停入库消费者(处理中的消息在宽限期内完成),再停采集记录消费者,最后停止攒批循环(写完已缓冲的一批)。
|
||||
func (r *pollingIngestRuntime) shutdown() {
|
||||
if r == nil {
|
||||
return
|
||||
}
|
||||
r.ingest.StopAll(r.grace)
|
||||
r.collection.StopAll(r.grace)
|
||||
r.stopCollect()
|
||||
}
|
||||
@@ -36,15 +36,15 @@ services:
|
||||
- "3000:3000"
|
||||
environment:
|
||||
# 数据库配置(必填)
|
||||
- JUNHONG_DATABASE_HOST=cxd.whcxd.cn
|
||||
- JUNHONG_DATABASE_PORT=16159
|
||||
- JUNHONG_DATABASE_HOST=kt.whcxd.cn
|
||||
- JUNHONG_DATABASE_PORT=15434
|
||||
- JUNHONG_DATABASE_USER=erp_pgsql
|
||||
- JUNHONG_DATABASE_PASSWORD=erp_2025
|
||||
- JUNHONG_DATABASE_DBNAME=junhong_cmp_test
|
||||
- JUNHONG_DATABASE_SSLMODE=disable
|
||||
# Redis 配置(必填)
|
||||
- JUNHONG_REDIS_ADDRESS=cxd.whcxd.cn
|
||||
- JUNHONG_REDIS_PORT=16299
|
||||
- JUNHONG_REDIS_ADDRESS=kt.whcxd.cn
|
||||
- JUNHONG_REDIS_PORT=16380
|
||||
- JUNHONG_REDIS_PASSWORD=cpNbWtAaqgo1YJmbMp3h
|
||||
- JUNHONG_REDIS_DB=6
|
||||
# JWT 配置(必填)
|
||||
@@ -54,6 +54,9 @@ services:
|
||||
# 日志配置
|
||||
- JUNHONG_LOGGING_LEVEL=info
|
||||
- JUNHONG_LOGGING_DEVELOPMENT=false
|
||||
# 应用日志轮换:单文件 100MB(默认),保留 40 个压缩备份,api 与 worker 合计约 1GB
|
||||
- JUNHONG_LOGGING_APP_LOG_MAX_BACKUPS=40
|
||||
- JUNHONG_LOGGING_APP_LOG_MAX_AGE=14
|
||||
# 跨域配置
|
||||
- JUNHONG_MIDDLEWARE_CORS_ENABLED=true
|
||||
- JUNHONG_MIDDLEWARE_CORS_ALLOW_ORIGINS=*
|
||||
@@ -88,7 +91,7 @@ services:
|
||||
- JUNHONG_MIDDLEWARE_CORS_ALLOW_ORIGINS=https://cmp-admin.boss160.cn,https://cmp-agent.boss160.cn,https://cmp-c.boss160.cn
|
||||
- JUNHONG_MIDDLEWARE_CORS_ALLOW_CREDENTIALS=true
|
||||
volumes:
|
||||
- ./logs:/app/logs
|
||||
- ./api/logs:/app/logs
|
||||
networks:
|
||||
- junhong-network
|
||||
healthcheck:
|
||||
@@ -109,15 +112,15 @@ services:
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
# 数据库配置(必填)
|
||||
- JUNHONG_DATABASE_HOST=cxd.whcxd.cn
|
||||
- JUNHONG_DATABASE_PORT=16159
|
||||
- JUNHONG_DATABASE_HOST=kt.whcxd.cn
|
||||
- JUNHONG_DATABASE_PORT=15434
|
||||
- JUNHONG_DATABASE_USER=erp_pgsql
|
||||
- JUNHONG_DATABASE_PASSWORD=erp_2025
|
||||
- JUNHONG_DATABASE_DBNAME=junhong_cmp_test
|
||||
- JUNHONG_DATABASE_SSLMODE=disable
|
||||
# Redis 配置(必填)
|
||||
- JUNHONG_REDIS_ADDRESS=cxd.whcxd.cn
|
||||
- JUNHONG_REDIS_PORT=16299
|
||||
- JUNHONG_REDIS_ADDRESS=kt.whcxd.cn
|
||||
- JUNHONG_REDIS_PORT=16380
|
||||
- JUNHONG_REDIS_PASSWORD=cpNbWtAaqgo1YJmbMp3h
|
||||
- JUNHONG_REDIS_DB=6
|
||||
# worker 并发轮询与按账户并行分发共用连接池,默认 10 不够
|
||||
@@ -134,6 +137,9 @@ services:
|
||||
# 日志配置
|
||||
- JUNHONG_LOGGING_LEVEL=info
|
||||
- JUNHONG_LOGGING_DEVELOPMENT=false
|
||||
# 应用日志轮换:单文件 100MB(默认),保留 40 个压缩备份,api 与 worker 合计约 1GB
|
||||
- JUNHONG_LOGGING_APP_LOG_MAX_BACKUPS=40
|
||||
- JUNHONG_LOGGING_APP_LOG_MAX_AGE=14
|
||||
# 对象存储配置
|
||||
- JUNHONG_STORAGE_PROVIDER=s3
|
||||
- JUNHONG_STORAGE_S3_ENDPOINT=https://obs-helf.cucloud.cn
|
||||
@@ -161,7 +167,9 @@ services:
|
||||
- JUNHONG_POLLING_CARRIER_NSQD_ADDRESS=${JUNHONG_POLLING_CARRIER_NSQD_ADDRESS:-nsqd:4150}
|
||||
- JUNHONG_POLLING_CARRIER_NSQLOOKUPD_ADDRESSES=${JUNHONG_POLLING_CARRIER_NSQLOOKUPD_ADDRESSES:-nsqlookupd:4161}
|
||||
volumes:
|
||||
- ./logs:/app/logs
|
||||
- ./worker/logs:/app/logs
|
||||
# 采集记录到期归档压缩包(archive/traffic-collection),由同步服务器拉走
|
||||
- ./worker/archive:/app/archive
|
||||
networks:
|
||||
- junhong-network
|
||||
depends_on:
|
||||
@@ -193,7 +201,7 @@ services:
|
||||
image: nsqio/nsq:v1.3.0
|
||||
container_name: junhong-cmp-nsqd
|
||||
restart: unless-stopped
|
||||
command: /nsqd --lookupd-tcp-address=nsqlookupd:4160 --broadcast-address=nsqd --data-path=/data --mem-queue-size=10000 --max-msg-timeout=15m
|
||||
command: /nsqd --lookupd-tcp-address=nsqlookupd:4160 --broadcast-address=nsqd --data-path=/data --mem-queue-size=0 --max-msg-timeout=15m
|
||||
volumes:
|
||||
- ./nsq-data:/data
|
||||
networks:
|
||||
|
||||
230
docs/2026-11-06-轮询入库异步化技术方案.md
Normal file
230
docs/2026-11-06-轮询入库异步化技术方案.md
Normal file
@@ -0,0 +1,230 @@
|
||||
# 轮询入库异步化技术方案
|
||||
|
||||
- 日期:2026-11-06
|
||||
- 分支:`Iteration/8-11`(只部署测试环境,不涉及生产配置与重启)
|
||||
- 关联:`add-carrier-polling-scheduler`(按运营商账户调度)、`add-card-traffic-queue-and-observed-deduction`(采集队列与按观测扣减)、`refactor-audit-log-persistence`(采集记录分表)
|
||||
|
||||
## 1. 背景
|
||||
|
||||
### 1.1 测试环境现状(2026-11-06 上午,只读统计)
|
||||
|
||||
| 指标 | 数值 |
|
||||
|---|---|
|
||||
| worker 报 `context deadline exceeded` 的 SQL | 每分钟 90–220 次,平均约 130 次,即每小时约 8,000 次,部署审计改造前已存在 |
|
||||
| 慢查询告警(> 500ms) | 每小时约 13.8 万条,占 worker 日志行数 53% |
|
||||
| 按主键查单行 `tb_iot_card` | 经常 0.7–2.4 秒 |
|
||||
| worker 日志量 | 每小时约 26 万行,18 分钟写满一个 100MB 文件,40 个备份只能留约 12 小时 |
|
||||
| 数据库连接 | worker 连接池 `MAX_OPEN_CONNS=60`,测试库上 61 个连接,基本占满;有一次 30 个会话同时等锁 |
|
||||
| 采集记录丢失 | 写采集成功表/失败表 3 秒超时,约每 16 分钟丢 60 条 |
|
||||
|
||||
### 1.2 原因:消费并发没有总量限制
|
||||
|
||||
NSQ 只限制了每个运营商账户的并发(保护网关),没有限制全部账户加起来的并发(保护数据库):
|
||||
|
||||
| 来源 | 规则 | 理论上限 | 实测 |
|
||||
|---|---|---|---|
|
||||
| 卡轮询 `polling.card.<账户>` | 每账户 20(`default_card_max_in_flight`,`tb_carrier_polling_param` 无记录) | 41 × 20 = 820 | 约 310 |
|
||||
| 停复机 `polling.stop_resume.<账户>` | 每账户 10 | 41 × 10 = 410 | 约 22 |
|
||||
| 设备评估 `polling.device_eval` | 10 | 10 | 10 |
|
||||
| 异步任务队列 | `JUNHONG_QUEUE_CONCURRENCY=50` | 50 | — |
|
||||
| 合计 | | 约 1,290 | 约 380 |
|
||||
|
||||
`worker.polling_total_max_concurrency: 100` 只传给旧分片轮询(`cmd/worker/main.go:371`),按账户调度的 NSQ 消费者不受它约束。
|
||||
|
||||
每个轮询步骤在**同一个任务里**先调网关、再同步写库,所有写库都在步骤超时内完成。三百多个任务抢 60 个连接,等连接的时间计入超时,数据库稍有抖动就成批超时。
|
||||
|
||||
### 1.3 超时分布(按调用栈,约 16 分钟样本)
|
||||
|
||||
| 占比 | 位置 | 说明 |
|
||||
|---|---|---|
|
||||
| 约 40% | 配置匹配查套餐状态(`TierResolver.Prefill`,`internal/polling/config_manager.go:191`,共用 3 秒) | 绑定设备的卡连查 3 次;失败后把"未知"结果写进缓存 |
|
||||
| 约 20% | `writeTrafficFailureAudit` | 沿用已超时的上下文再查卡,属连带报错 |
|
||||
| 约 20% | 写采集成功表、失败表(`collectionRecordTimeout = 3s`) | 记录直接丢失 |
|
||||
| 其余 | 流量观测事务、网络状态观测、实名缓存失效等 | |
|
||||
|
||||
## 2. 目标与原则
|
||||
|
||||
1. **调上游与入库分开控制**:调网关按账户并发(保持现有每账户上限),入库单独发消息、由单独的消费者处理。
|
||||
2. **数据库并发有总上限**:入库消费者的并发是一个固定、可配置的数,与账户数量无关;加账户不会挤爆数据库。
|
||||
3. **消费慢一点没关系**:消息在 NSQ 里排队,入库按数据库承受的速度处理;不丢、不重复算。
|
||||
4. **轮询步骤只做"调网关 + 发消息"**:调网关前必要的读查询走缓存,尽量不碰数据库。
|
||||
5. **可切回**:保留同步入库路径,用系统配置一键切换,异常时可回退。
|
||||
6. **范围**:只在 `Iteration/8-11` 上实现,只部署测试环境。
|
||||
|
||||
## 3. 现状链路(一次流量步骤)
|
||||
|
||||
```
|
||||
NSQ 卡任务 ──► 步骤(15s 超时)
|
||||
├─ 读:优先轮询项 FindActive(tb_polling_priority_item)
|
||||
├─ 读:卡(先清缓存再查库 tb_iot_card)
|
||||
├─ 读:轮询范围校验(tb_carrier、tb_device、tb_device_sim_binding)
|
||||
├─ 调网关 QueryFlow
|
||||
├─ 写:ApplyTrafficObservation
|
||||
│ ├─ Redis 采集队列 Push
|
||||
│ ├─ 事务:锁卡行、查有效套餐、写日快照、更新卡、写流量事件 outbox、通道阈值评估、审计
|
||||
│ └─ 写采集成功表/失败表(3s)
|
||||
├─ 写:对接日志、优先项完成
|
||||
└─ 返回 TriggeredEvaluation(决定是否跳过本轮套餐步骤)
|
||||
```
|
||||
|
||||
网络状态步骤(`ApplyNetworkObservation`)、实名步骤(`ApplyCardObservation`)结构相同;套餐步骤不调网关,只读写库。
|
||||
|
||||
## 4. 技术设计
|
||||
|
||||
### 4.1 两段式
|
||||
|
||||
```
|
||||
采集段(按账户并发,现有 NSQ 卡任务) 入库段(固定小并发)
|
||||
┌────────────────────────────────┐ ┌──────────────────────────────┐
|
||||
│ 读缓存 → 调网关 → 发入库消息 │──NSQ──► │ card.ingest 消费者(并发 N) │
|
||||
│ 网关失败 → 发采集失败消息 │ │ Apply*Observation(事务) │
|
||||
└────────────────────────────────┘ │ → 发采集记录消息 │
|
||||
└──────────────┬───────────────┘
|
||||
│NSQ
|
||||
┌──────────────▼───────────────┐
|
||||
│ card.collection 消费者 │
|
||||
│ 攒批写成功表/失败表 │
|
||||
└──────────────────────────────┘
|
||||
```
|
||||
|
||||
- **采集段**:现有卡任务消费者,并发规则不变(每账户 `card_max_in_flight`)。步骤拿到网关结果后发一条入库消息就结束,步骤结果只反映"网关是否成功"。
|
||||
- **入库段**:新 topic `card.ingest`,单独消费者,`max_in_flight` = `polling.ingest.concurrency`(默认 30)。
|
||||
- **采集记录**:新 topic `card.collection`,单独的批量消费者(见 4.5)。
|
||||
|
||||
### 4.2 入库消息
|
||||
|
||||
topic `card.ingest`,JSON:
|
||||
|
||||
| 字段 | 说明 |
|
||||
|---|---|
|
||||
| `kind` | `traffic` / `network` / `realname` |
|
||||
| `card_id`、`carrier_id`、`iccid` | 卡标识 |
|
||||
| `observation_id` | 现有 `attempt.IntegrationID`,幂等键 |
|
||||
| `observed_at` | 网关返回时刻(不是入库时刻) |
|
||||
| `source`、`scene`、`correlation_id` | 现有观测元数据 |
|
||||
| `payload` | 流量:`reading_mb`、`reading_result`、`reset_day`;网络:`status`、`extend`、`imei`;实名:`verified` |
|
||||
| `raw`、`failure` | 网关原始数据(截断规则同采集记录) |
|
||||
| `priority_item_id` | 本轮认领的优先轮询项,入库成功后由入库段完成 |
|
||||
| `published_at` | 发出时刻,用于积压与延迟统计 |
|
||||
|
||||
### 4.3 入库消费者
|
||||
|
||||
处理一条消息:
|
||||
|
||||
1. 幂等检查:Redis `ingest:done:<observation_id>` 存在则直接 FIN。
|
||||
2. 按 `kind` 调用现有 `ApplyTrafficObservation` / `ApplyNetworkObservation` / `ApplyCardObservation`,上下文超时 `polling.ingest.timeout`(默认 30s),从拿到消息开始计时。
|
||||
3. 成功后:写 `ingest:done:<observation_id>`(TTL 48h);流量有变化时写 Redis 标记 `flow_evaluated:<card_id>`(见 4.6)。
|
||||
- 本轮认领了优先轮询项的观测不走消息,仍在卡任务内同步入库,优先项完成与对接日志沿用原逻辑。
|
||||
- 网络观测命中风险停机或已销户时,卡任务按网关结果直接停止该卡轮询,入库段写库时关闭轮询开关。
|
||||
4. 失败:
|
||||
- 数据库超时、连接错误等可重试错误:NSQ 延迟重投,退避 5s、15s、30s、1m、2m,之后每 5 分钟一次,**不设次数上限、不丢弃**(入库消费者的 NSQ `max_attempts` 设为 0);第 10 次起每次重投记 ERROR,带 `observation_id`、卡号与错误,便于排查。
|
||||
- 业务性错误(卡不存在、数据校验失败):不重投,记 WARN 后 FIN。
|
||||
- 本期不做死信表。长时间重试的消息会体现在积压量与最老消息等待时间上(见 4.7)。
|
||||
|
||||
### 4.4 顺序与幂等
|
||||
|
||||
NSQ 不保证顺序,也可能重投。逐项说明现有逻辑能否承受:
|
||||
|
||||
| 风险 | 处理 |
|
||||
|---|---|
|
||||
| 同一张卡两条流量消息乱序 | 采集队列按 `observed_at` 插入,"新点在队尾才写"——旧消息后到时不在队尾,不写快照,只记采集记录。现有规则已覆盖 |
|
||||
| 同一张卡两条消息并发处理 | 事务内 `FOR UPDATE` 锁卡行,串行执行 |
|
||||
| 同一条消息重投 | ① `ingest:done` 键挡掉已成功的;② 事务提交后、写键前崩溃:日快照取当日最大值、增量按"本月最大 − 已结算"计算,重放得到 0 增量;流量事件 outbox ID 由 `observation_id` 生成,重复写入被唯一键挡掉;③ 采集队列 Push 同一个点需改为按 `observed_at` 去重(Lua 内判断) |
|
||||
| 网络/实名状态乱序 | 现有 `ApplyNetworkObservation`、`ApplyCardObservation` 需确认按 `observed_at` 比较"更新的才生效";没有的补上 |
|
||||
| 采集记录重复 | 成功表/失败表按 `(observation_id, observed_at)` 建唯一索引(含分区键),批量写用 `ON CONFLICT DO NOTHING` |
|
||||
|
||||
### 4.5 采集记录批量写
|
||||
|
||||
- 入库段写完事务后,把采集成功记录发到 `card.collection`;采集段网关失败、无读数时直接把失败记录发到 `card.collection`,不经过入库段。
|
||||
- `card.collection` 消费者 `max_in_flight` = 500,攒满 `polling.collection.batch_size`(默认 200)或等满 1 秒就批量写一次(多行 INSERT),成功后统一 FIN,失败统一重投。
|
||||
- 写库并发固定 1–2 个连接。按测试环境每小时约 2.1 万条计算,每秒约 6 条,一次批量写即可。
|
||||
- 现有 3 秒超时和"写失败只记日志"的逻辑删除,不再丢记录。
|
||||
|
||||
### 4.6 采集段剩余读查询
|
||||
|
||||
步骤里调网关前的读查询不能异步,改为走缓存:
|
||||
|
||||
| 读查询 | 现状 | 改为 |
|
||||
|---|---|---|
|
||||
| 卡信息 | 每步先清缓存再查库 | 读 Redis 卡缓存;入库段写完后失效缓存 |
|
||||
| 优先轮询项 `FindActive` | 每步每类型查一次库 | Redis 维护"有活动优先项的卡"集合,不在集合里不查库 |
|
||||
| 运营商实名开关、重置日 | 每步查库 | 进程内缓存 1 分钟 |
|
||||
| 设备轮询开关、绑定关系 | 每步查库 | 并入卡缓存 |
|
||||
| 套餐状态(配置匹配) | 3 次查询共用 3 秒,失败缓存"未知" | 每次查询各自计时;失败不写缓存,下次重查 |
|
||||
|
||||
套餐步骤跳过逻辑:现在根据同一任务里流量步骤的 `TriggeredEvaluation` 跳过。异步后改为读 Redis 标记 `flow_evaluated:<card_id>`(入库段写,TTL = 套餐检查间隔)。
|
||||
|
||||
### 4.7 积压与反压
|
||||
|
||||
- 监控:每分钟读 nsqd `/stats`,记录 `card.ingest`、`card.collection` 的积压量和最老消息等待时间,写应用日志。
|
||||
- 告警:积压超过 `polling.ingest.alert_depth`(默认 200,000)或等待超过 10 分钟,记 ERROR(接现有告警通道)。
|
||||
- 反压:积压超过 `polling.ingest.pause_depth`(默认 500,000,须大于告警阈值)时,调度器暂停发新的卡任务;降到一半以下恢复。账户限流状态不受影响。
|
||||
|
||||
### 4.8 NSQ 持久化
|
||||
|
||||
nsqd 当前参数 `--mem-queue-size=10000`:消息先放内存,nsqd 意外退出会丢掉内存里的部分。
|
||||
|
||||
- 测试环境改为 `--mem-queue-size=0`:所有消息直接落盘(`./nsq-data` 已挂载),按现有量级(每秒几十条)性能没有影响。
|
||||
- 卡任务 topic 也会一起落盘,对现有调度无行为变化。
|
||||
- 磁盘占用:入库消息带网关原始数据,单条约 2KB;积压到反压阈值 50 万条约 1GB,测试服务器剩余 32G,足够。
|
||||
|
||||
### 4.9 不改的同步路径
|
||||
|
||||
以下入口量小、需要立即返回结果,保持同步入库:后台人工刷新、运营商回调(移动/联通/电信实名)、激活前结算、观测序列(series runner)。
|
||||
|
||||
### 4.10 配置项
|
||||
|
||||
| 配置 | 默认 | 说明 |
|
||||
|---|---|---|
|
||||
| `polling.ingest.mode` | `sync` | `sync` 为现在的同步入库;部署确认无误后切 `async` |
|
||||
| `polling.ingest.concurrency` | 30 | 入库消费者并发 |
|
||||
| `polling.ingest.timeout` | 30s | 单条入库超时 |
|
||||
| `polling.collection.batch_size` | 200 | 采集记录批量大小 |
|
||||
| `polling.ingest.alert_depth` / `pause_depth` | 200,000 / 500,000 | 告警与反压阈值 |
|
||||
|
||||
`mode` 与阈值放系统配置(改了几秒内生效),并发放启动配置。启动时检查:入库并发 + 采集记录写并发(2)不超过 `MAX_OPEN_CONNS` − 20(给采集段读查询、异步任务队列与其他查询留出至少 20 个连接),超过记 ERROR。测试环境 `MAX_OPEN_CONNS=60`:入库 30 + 采集记录 2 = 32 ≤ 40,满足。
|
||||
|
||||
### 4.11 发布失败兜底
|
||||
|
||||
采集段发消息失败(nsqd 不可用)时,降级为当前的同步入库,并记 WARN;不因 nsqd 故障丢观测。
|
||||
|
||||
## 5. 影响与代价
|
||||
|
||||
- 入库延迟:正常几秒;积压时更长。卡流量、状态在后台的刷新会比现在晚几秒。
|
||||
- 停复机判断:超量停机、通道阈值停机依赖入库结果,跟着入库段触发,晚几秒。
|
||||
- 优先轮询(加急):完成时间从"网关返回"推迟到"入库成功"。
|
||||
- 同一张卡的数据库写入从"一个任务内"变成"跨两个消费者",排查时按 `observation_id` 串联日志。
|
||||
|
||||
## 6. 分支与范围
|
||||
|
||||
- 基于 `Iteration/8-11`,只部署测试环境;不写生产配置、不涉及生产重启。
|
||||
- 依赖 `add-carrier-polling-scheduler`、`add-card-traffic-queue-and-observed-deduction` 的现有实现,不改它们的业务规则。
|
||||
|
||||
## 7. 实施步骤
|
||||
|
||||
1. 采集队列 Push 按 `observed_at` 去重;网络/实名观测补"更新的才生效"判断(如缺)。
|
||||
2. 采集记录唯一索引迁移;`card.collection` 批量消费者;采集段失败记录改发消息。
|
||||
3. `card.ingest` 消息、入库消费者、幂等键、不限次数的退避重试。
|
||||
4. 三个轮询步骤改为发消息;优先项完成、对接日志、`StopPolling`、`flow_evaluated` 移到入库段;发布失败降级。
|
||||
5. 采集段读查询走缓存;套餐状态查询各自计时、失败不缓存。
|
||||
6. 积压监控、告警、反压;启动并发检查。
|
||||
7. 系统配置与回退开关;测试环境 nsqd 改 `--mem-queue-size=0`。
|
||||
|
||||
## 8. 测试与验证(测试环境)
|
||||
|
||||
| 验证项 | 通过标准 |
|
||||
|---|---|
|
||||
| SQL 超时 | `context deadline exceeded` 从每小时约 8,000 次降到个位数 |
|
||||
| 慢查询 | 每小时告警数明显下降,worker 日志留存能达到 14 天目标的量级 |
|
||||
| 采集记录完整 | 每小时:入库消息数 = 成功表 + 失败表新增行数(按 `observation_id` 对账) |
|
||||
| 计量正确 | 抽样卡日快照、套餐扣减与同步模式结果一致;重投、乱序不重复扣减 |
|
||||
| 积压 | `card.ingest` 等待时间常态 < 30 秒 |
|
||||
| 回退 | `polling.ingest.mode=sync` 后恢复现有行为 |
|
||||
| 降级 | 停掉 nsqd 时采集段改为同步入库,不丢观测 |
|
||||
|
||||
## 9. 已定事项(2026-11-06)
|
||||
|
||||
1. 入库消费者默认并发 30。
|
||||
2. 测试环境 nsqd 改为 `--mem-queue-size=0`,所有消息直接落盘。
|
||||
3. 本期不做死信:可重试错误不限次数退避重试,不丢弃;业务性错误记 WARN 后丢弃。
|
||||
4. 积压告警阈值 200,000 条;反压(暂停派发新卡任务)阈值 500,000 条。
|
||||
@@ -20,10 +20,11 @@ import (
|
||||
|
||||
// RealnameChangedEvent 是卡实名状态变化的可靠领域事实。
|
||||
type RealnameChangedEvent struct {
|
||||
EventID string `json:"event_id"`
|
||||
CardID uint `json:"card_id"`
|
||||
BeforeStatus int `json:"before_status"`
|
||||
AfterStatus int `json:"after_status"`
|
||||
EventID string `json:"event_id"`
|
||||
CardID uint `json:"card_id"`
|
||||
BeforeStatus int `json:"before_status"`
|
||||
AfterStatus int `json:"after_status"`
|
||||
// FirstVerified 表示需要触发实名激活:首次实名,或二次实名完成(此时 first_realname_at 不变)。
|
||||
FirstVerified bool `json:"first_verified"`
|
||||
ObservedAt time.Time `json:"observed_at"`
|
||||
Source string `json:"source"`
|
||||
@@ -82,6 +83,18 @@ type Service struct {
|
||||
logger *zap.Logger
|
||||
// commandGrace 返回停复机成功后的状态保护窗口;未注入时不保护。
|
||||
commandGrace func(ctx context.Context) time.Duration
|
||||
// collectionSink 把采集记录发布到批量写入消息;未注入或发布失败时同步写库。
|
||||
collectionSink CollectionSink
|
||||
}
|
||||
|
||||
// CollectionSink 发布一条采集记录(成功表或失败表二选一),由批量消费者写库。
|
||||
type CollectionSink interface {
|
||||
PublishCollection(ctx context.Context, success *model.CardTrafficCollection, failure *model.CardTrafficCollectionFailure) error
|
||||
}
|
||||
|
||||
// SetCollectionSink 注入采集记录发布器(Worker 启用 card.collection 批量写入时使用)。
|
||||
func (s *Service) SetCollectionSink(sink CollectionSink) {
|
||||
s.collectionSink = sink
|
||||
}
|
||||
|
||||
// SetCommandGrace 注入停复机成功后的状态保护窗口(受控系统配置 polling.stop_resume.status_grace_seconds)。
|
||||
@@ -144,6 +157,7 @@ func (s *Service) ApplyCardObservation(ctx context.Context, observation domain.R
|
||||
}
|
||||
var decision domain.RealnameDecision
|
||||
var auditedCard *model.IotCard
|
||||
stale := false
|
||||
err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var card model.IotCard
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ?", observation.CardID).First(&card).Error; err != nil {
|
||||
@@ -153,6 +167,36 @@ func (s *Service) ApplyCardObservation(ctx context.Context, observation domain.R
|
||||
return errors.Wrap(errors.CodeDatabaseError, err, "锁定IoT卡失败")
|
||||
}
|
||||
auditedCard = &card
|
||||
if staleObservation(card.LastRealNameCheckAt, observation.Metadata.ObservedAt) {
|
||||
// 异步入库可能乱序:早于已应用观测的实名结果不改卡事实,只记录。
|
||||
s.warnLogger().Info("实名观测早于卡上最近一次已应用的检查,忽略",
|
||||
zap.Uint("card_id", card.ID), zap.String("observation_id", observation.Metadata.ObservationID),
|
||||
zap.Time("observed_at", observation.Metadata.ObservedAt), zap.Timep("last_checked_at", card.LastRealNameCheckAt),
|
||||
zap.String("metric", "card_observation.realname_stale"))
|
||||
stale = true
|
||||
return nil
|
||||
}
|
||||
realnameRecord, realnameSnapshot, loadErr := loadRealnameTime(ctx, tx, card.ID)
|
||||
if loadErr != nil {
|
||||
return loadErr
|
||||
}
|
||||
resetGate := domain.EvaluateRealnameResetGate(realnameSnapshot, observation)
|
||||
if resetGate == domain.RealnameResetGateBlocked {
|
||||
// 等待二次实名期间读到的仍是旧实名(上游实名时间不晚于清除前时间,或没有上游时间):不改实名状态,只记检查时间。
|
||||
decision = domain.RealnameDecision{BeforeStatus: card.RealNameStatus, AfterStatus: card.RealNameStatus,
|
||||
ReversalCount: card.RealnameReversalCount, ReversalStartedAt: card.RealnameReversalStartedAt}
|
||||
checked := map[string]any{"last_real_name_check_at": observation.Metadata.ObservedAt}
|
||||
if observation.Metadata.Source != constants.CardObservationSourceManualOverride {
|
||||
checked["last_sync_time"] = observation.Metadata.ObservedAt
|
||||
}
|
||||
if err := tx.Model(&model.IotCard{}).Where("id = ?", card.ID).Updates(checked).Error; err != nil {
|
||||
return errors.Wrap(errors.CodeDatabaseError, err, "更新卡实名检查时间失败")
|
||||
}
|
||||
s.warnLogger().Info("等待二次实名的卡读到旧实名,不覆盖",
|
||||
zap.Uint("card_id", card.ID), zap.String("observation_id", observation.Metadata.ObservationID),
|
||||
zap.Timep("upstream_realname_at", observation.UpstreamRealnameAt), zap.Timep("baseline_at", realnameSnapshot.ResetBaselineAt))
|
||||
return nil
|
||||
}
|
||||
nextDecision, decisionErr := domain.ApplyRealname(domain.CardRealnameSnapshot{
|
||||
CardID: card.ID, Status: card.RealNameStatus, FirstRealnameAt: card.FirstRealnameAt,
|
||||
ReversalCount: card.RealnameReversalCount, ReversalStartedAt: card.RealnameReversalStartedAt,
|
||||
@@ -185,11 +229,16 @@ func (s *Service) ApplyCardObservation(ctx context.Context, observation domain.R
|
||||
if result.RowsAffected != 1 {
|
||||
return errors.New(errors.CodeConflict, "卡实名状态已被其他请求更新")
|
||||
}
|
||||
if observation.Verified && decision.AfterStatus == constants.RealNameStatusVerified {
|
||||
if err := applyRealnameTime(ctx, tx, &card, realnameRecord, observation, resetGate); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if decision.StatusChanged {
|
||||
eventID := realnameChangedEventID(card.ID, observation.Metadata.ObservationID)
|
||||
if err := s.eventWriter.AppendRealname(ctx, tx, RealnameChangedEvent{
|
||||
EventID: eventID, CardID: card.ID, BeforeStatus: card.RealNameStatus, AfterStatus: decision.AfterStatus,
|
||||
FirstVerified: decision.FirstVerified, ObservedAt: observation.Metadata.ObservedAt,
|
||||
FirstVerified: decision.FirstVerified || resetGate == domain.RealnameResetGateCompleted, ObservedAt: observation.Metadata.ObservedAt,
|
||||
Source: observation.Metadata.Source, Scene: observation.Metadata.Scene,
|
||||
RequestID: observation.Metadata.RequestID, CorrelationID: observation.Metadata.CorrelationID,
|
||||
}); err != nil {
|
||||
@@ -275,6 +324,9 @@ func (s *Service) ApplyCardObservation(ctx context.Context, observation domain.R
|
||||
}
|
||||
return domain.RealnameDecision{}, err
|
||||
}
|
||||
if stale {
|
||||
return domain.RealnameDecision{}, nil
|
||||
}
|
||||
if s.cache != nil {
|
||||
s.cache.Invalidate(ctx, observation.CardID)
|
||||
}
|
||||
|
||||
@@ -37,6 +37,7 @@ func (s *Service) ApplyNetworkObservation(ctx context.Context, observation domai
|
||||
}
|
||||
var decision domain.NetworkDecision
|
||||
var auditedCard *model.IotCard
|
||||
stale := false
|
||||
err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var card model.IotCard
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ?", observation.CardID).First(&card).Error; err != nil {
|
||||
@@ -46,6 +47,15 @@ func (s *Service) ApplyNetworkObservation(ctx context.Context, observation domai
|
||||
return errors.Wrap(errors.CodeDatabaseError, err, "锁定IoT卡网络事实失败")
|
||||
}
|
||||
auditedCard = &card
|
||||
if staleObservation(card.LastCardStatusCheckAt, observation.Metadata.ObservedAt) {
|
||||
// 异步入库可能乱序:早于已应用观测的网络状态不改卡事实,只记录。
|
||||
s.warnLogger().Info("网络状态观测早于卡上最近一次已应用的检查,忽略",
|
||||
zap.Uint("card_id", card.ID), zap.String("observation_id", observation.Metadata.ObservationID),
|
||||
zap.Time("observed_at", observation.Metadata.ObservedAt), zap.Timep("last_checked_at", card.LastCardStatusCheckAt),
|
||||
zap.String("metric", "card_observation.network_stale"))
|
||||
stale = true
|
||||
return nil
|
||||
}
|
||||
nextDecision, decisionErr := domain.ApplyNetwork(domain.CardNetworkSnapshot{
|
||||
CardID: card.ID, NetworkStatus: card.NetworkStatus, StopReason: card.StopReason,
|
||||
EnablePolling: card.EnablePolling, StoppedAt: card.StoppedAt, ResumedAt: card.ResumedAt,
|
||||
@@ -176,8 +186,16 @@ func (s *Service) ApplyNetworkObservation(ctx context.Context, observation domai
|
||||
}
|
||||
return domain.NetworkDecision{}, err
|
||||
}
|
||||
if stale {
|
||||
return domain.NetworkDecision{}, nil
|
||||
}
|
||||
if s.cache != nil {
|
||||
s.cache.Invalidate(ctx, observation.CardID)
|
||||
}
|
||||
return decision, nil
|
||||
}
|
||||
|
||||
// staleObservation 判断观测时间是否早于卡上最近一次已应用的同类检查时间(异步入库乱序保护)。
|
||||
func staleObservation(lastChecked *time.Time, observedAt time.Time) bool {
|
||||
return lastChecked != nil && !observedAt.IsZero() && observedAt.Before(*lastChecked)
|
||||
}
|
||||
|
||||
177
internal/application/cardobservation/realname_reset.go
Normal file
177
internal/application/cardobservation/realname_reset.go
Normal file
@@ -0,0 +1,177 @@
|
||||
package cardobservation
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
domain "github.com/break/junhong_cmp_fiber/internal/domain/cardobservation"
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/errors"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/outboxid"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
// RealnameResetCommand 描述对一张卡的二次实名清除或撤销。
|
||||
type RealnameResetCommand struct {
|
||||
CardID uint
|
||||
BatchID uint
|
||||
OperatorID uint
|
||||
}
|
||||
|
||||
// 二次实名不可执行的原因(业务可预期,按行记录,不当作系统错误)。
|
||||
var (
|
||||
ErrRealnameResetNotVerified = errors.New(errors.CodeInvalidStatus, "卡未实名,无需二次实名")
|
||||
ErrRealnameResetNoUpstream = errors.New(errors.CodeInvalidStatus, "上游未返回实名时间,不支持二次实名")
|
||||
ErrRealnameResetAlreadyReset = errors.New(errors.CodeInvalidStatus, "卡已在等待二次实名")
|
||||
ErrRealnameResetNotPending = errors.New(errors.CodeInvalidStatus, "卡不在等待二次实名,不能撤销")
|
||||
)
|
||||
|
||||
// ResetRealname 二次实名清除:卡置为未实名、当前实名时间置空,记下清除前的上游实名时间作为新旧判定基准。
|
||||
// 只支持上游返回过 archiveTime 的卡;已激活套餐不回退,first_realname_at 不修改。
|
||||
// 状态变化按现有流程写实名变化事件与审计,下游停复机评估与普通未实名卡一致。
|
||||
func (s *Service) ResetRealname(ctx context.Context, command RealnameResetCommand) error {
|
||||
return s.changeRealnameForReset(ctx, command, false)
|
||||
}
|
||||
|
||||
// RevertRealnameReset 撤销等待中的二次实名:卡恢复已实名,当前实名时间恢复为清除前时间。
|
||||
func (s *Service) RevertRealnameReset(ctx context.Context, command RealnameResetCommand) error {
|
||||
return s.changeRealnameForReset(ctx, command, true)
|
||||
}
|
||||
|
||||
func (s *Service) changeRealnameForReset(ctx context.Context, command RealnameResetCommand, revert bool) error {
|
||||
if s == nil || s.db == nil || s.eventWriter == nil || s.auditWriter == nil {
|
||||
return errors.New(errors.CodeInternalError, "卡实名观测能力未完整配置")
|
||||
}
|
||||
if command.CardID == 0 {
|
||||
return errors.New(errors.CodeInvalidParam, "卡 ID 无效")
|
||||
}
|
||||
now := time.Now()
|
||||
err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var card model.IotCard
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ?", command.CardID).First(&card).Error; err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return errors.New(errors.CodeNotFound, "IoT卡不存在")
|
||||
}
|
||||
return errors.Wrap(errors.CodeDatabaseError, err, "锁定IoT卡失败")
|
||||
}
|
||||
record, snapshot, err := loadRealnameTime(ctx, tx, card.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if revert {
|
||||
return s.revertResetInTx(ctx, tx, &card, record, snapshot, command, now)
|
||||
}
|
||||
return s.resetInTx(ctx, tx, &card, record, snapshot, command, now)
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if s.cache != nil {
|
||||
s.cache.Invalidate(ctx, command.CardID)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) resetInTx(ctx context.Context, tx *gorm.DB, card *model.IotCard, record *model.IotCardRealname,
|
||||
snapshot domain.RealnameTimeSnapshot, command RealnameResetCommand, now time.Time) error {
|
||||
if card.RealNameStatus != constants.RealNameStatusVerified {
|
||||
return ErrRealnameResetNotVerified
|
||||
}
|
||||
if record == nil || record.UpstreamRealnameAt == nil {
|
||||
return ErrRealnameResetNoUpstream
|
||||
}
|
||||
if snapshot.ResetStatus == constants.RealnameResetStatusPending {
|
||||
return ErrRealnameResetAlreadyReset
|
||||
}
|
||||
if err := s.updateCardRealnameStatusInTx(ctx, tx, card, constants.RealNameStatusNotVerified, now, "reset", command.BatchID); err != nil {
|
||||
return err
|
||||
}
|
||||
batchID := command.BatchID
|
||||
if err := tx.WithContext(ctx).Model(&model.IotCardRealname{}).Where("id = ?", record.ID).Updates(map[string]any{
|
||||
"realname_at": nil, "reset_status": constants.RealnameResetStatusPending, "reset_at": now,
|
||||
"reset_baseline_at": *record.UpstreamRealnameAt, "reset_batch_id": batchID, "updated_at": now,
|
||||
}).Error; err != nil {
|
||||
return errors.Wrap(errors.CodeDatabaseError, err, "写入二次实名等待状态失败")
|
||||
}
|
||||
return writeResetHistory(ctx, tx, card, record.RealnameAt, nil, "", constants.RealnameChangeReset, command, now)
|
||||
}
|
||||
|
||||
func (s *Service) revertResetInTx(ctx context.Context, tx *gorm.DB, card *model.IotCard, record *model.IotCardRealname,
|
||||
snapshot domain.RealnameTimeSnapshot, command RealnameResetCommand, now time.Time) error {
|
||||
if record == nil || snapshot.ResetStatus != constants.RealnameResetStatusPending {
|
||||
return ErrRealnameResetNotPending
|
||||
}
|
||||
if command.BatchID != 0 && (record.ResetBatchID == nil || *record.ResetBatchID != command.BatchID) {
|
||||
return ErrRealnameResetNotPending
|
||||
}
|
||||
if card.RealNameStatus != constants.RealNameStatusVerified {
|
||||
if err := s.updateCardRealnameStatusInTx(ctx, tx, card, constants.RealNameStatusVerified, now, "revert", command.BatchID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
restored := record.ResetBaselineAt
|
||||
if err := tx.WithContext(ctx).Model(&model.IotCardRealname{}).Where("id = ?", record.ID).Updates(map[string]any{
|
||||
"realname_at": restored, "realname_at_source": constants.RealnameAtSourceUpstream,
|
||||
"reset_status": constants.RealnameResetStatusNone, "reset_at": nil, "reset_baseline_at": nil, "reset_batch_id": nil,
|
||||
"updated_at": now,
|
||||
}).Error; err != nil {
|
||||
return errors.Wrap(errors.CodeDatabaseError, err, "撤销二次实名等待状态失败")
|
||||
}
|
||||
return writeResetHistory(ctx, tx, card, nil, restored, constants.RealnameAtSourceUpstream, constants.RealnameChangeResetReverted, command, now)
|
||||
}
|
||||
|
||||
// updateCardRealnameStatusInTx 按实名观测的同一口径更新卡实名状态,并写实名变化事件与人工审计。
|
||||
func (s *Service) updateCardRealnameStatusInTx(ctx context.Context, tx *gorm.DB, card *model.IotCard, after int, now time.Time, kind string, batchID uint) error {
|
||||
verified := after == constants.RealNameStatusVerified
|
||||
result := tx.WithContext(ctx).Model(&model.IotCard{}).Where("id = ? AND real_name_status = ?", card.ID, card.RealNameStatus).Updates(map[string]any{
|
||||
"real_name_status": after,
|
||||
"realname_reversal_count": 0,
|
||||
"realname_reversal_started_at": nil,
|
||||
"activation_status": gorm.Expr(`CASE WHEN network_status = ? AND (card_category = ? OR ?) THEN 1 ELSE 0 END`, constants.NetworkStatusOnline, constants.CardCategoryIndustry, verified),
|
||||
})
|
||||
if result.Error != nil {
|
||||
return errors.Wrap(errors.CodeDatabaseError, result.Error, "更新卡实名状态失败")
|
||||
}
|
||||
if result.RowsAffected != 1 {
|
||||
return errors.New(errors.CodeConflict, "卡实名状态已被其他请求更新")
|
||||
}
|
||||
observationID := "realname-" + kind + ":" + strconv.FormatUint(uint64(batchID), 10) + ":" + strconv.FormatInt(now.UnixNano(), 10)
|
||||
eventID := outboxid.Stable("card-realname:", strconv.FormatUint(uint64(card.ID), 10)+":"+observationID+":changed")
|
||||
if err := s.eventWriter.AppendRealname(ctx, tx, RealnameChangedEvent{
|
||||
EventID: eventID, CardID: card.ID, BeforeStatus: card.RealNameStatus, AfterStatus: after,
|
||||
ObservedAt: now, Source: constants.CardObservationSourceManualOverride, Scene: "realname_" + kind,
|
||||
CorrelationID: observationID,
|
||||
}); err != nil {
|
||||
return errors.Wrap(errors.CodeDatabaseError, err, "写入卡实名 Outbox 事件失败")
|
||||
}
|
||||
summary := "二次实名清除:卡实名状态置为未实名"
|
||||
if verified {
|
||||
summary = "二次实名撤销:卡恢复已实名"
|
||||
}
|
||||
return s.auditWriter.WriteCardStateAudit(ctx, tx, StateAudit{
|
||||
ActionCode: constants.AuditActionIotCardRealnameStatusUpdated, Summary: summary, Card: card,
|
||||
BeforeData: map[string]any{"real_name_status": card.RealNameStatus},
|
||||
AfterData: map[string]any{"real_name_status": after, "realname_reset_batch_id": batchID},
|
||||
})
|
||||
}
|
||||
|
||||
func writeResetHistory(ctx context.Context, tx *gorm.DB, card *model.IotCard, before, after *time.Time, afterSource, changeType string,
|
||||
command RealnameResetCommand, now time.Time) error {
|
||||
var batchID *uint
|
||||
if command.BatchID != 0 {
|
||||
value := command.BatchID
|
||||
batchID = &value
|
||||
}
|
||||
history := model.IotCardRealnameHistory{
|
||||
CardID: card.ID, ICCID: card.ICCID, BeforeAt: before, AfterAt: after, AfterSource: afterSource,
|
||||
ChangeType: changeType, ObservationSource: constants.CardObservationSourceManualOverride,
|
||||
ResetBatchID: batchID, OperatorID: command.OperatorID, ObservedAt: now, CreatedAt: now,
|
||||
}
|
||||
if err := tx.WithContext(ctx).Create(&history).Error; err != nil {
|
||||
return errors.Wrap(errors.CodeDatabaseError, err, "写入卡实名时间历史失败")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
96
internal/application/cardobservation/realname_time.go
Normal file
96
internal/application/cardobservation/realname_time.go
Normal file
@@ -0,0 +1,96 @@
|
||||
package cardobservation
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
domain "github.com/break/junhong_cmp_fiber/internal/domain/cardobservation"
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/errors"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// loadRealnameTime 在调用方事务中读取卡当前实名记录;调用方已锁定卡行,同一张卡的写入因此串行。
|
||||
func loadRealnameTime(ctx context.Context, tx *gorm.DB, cardID uint) (*model.IotCardRealname, domain.RealnameTimeSnapshot, error) {
|
||||
var record model.IotCardRealname
|
||||
err := tx.WithContext(ctx).Where("card_id = ?", cardID).Take(&record).Error
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return nil, domain.RealnameTimeSnapshot{}, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, domain.RealnameTimeSnapshot{}, errors.Wrap(errors.CodeDatabaseError, err, "查询卡当前实名记录失败")
|
||||
}
|
||||
return &record, realnameTimeSnapshot(&record), nil
|
||||
}
|
||||
|
||||
func realnameTimeSnapshot(record *model.IotCardRealname) domain.RealnameTimeSnapshot {
|
||||
if record == nil {
|
||||
return domain.RealnameTimeSnapshot{}
|
||||
}
|
||||
return domain.RealnameTimeSnapshot{
|
||||
Exists: true, RealnameAt: record.RealnameAt, RealnameAtSource: record.RealnameAtSource,
|
||||
UpstreamRealnameAt: record.UpstreamRealnameAt, FirstObservedAt: record.FirstObservedAt,
|
||||
ResetStatus: record.ResetStatus, ResetBaselineAt: record.ResetBaselineAt,
|
||||
}
|
||||
}
|
||||
|
||||
// applyRealnameTime 在卡已被采纳为已实名后更新当前实名记录;只有实名时间变化才写历史。
|
||||
func applyRealnameTime(ctx context.Context, tx *gorm.DB, card *model.IotCard, record *model.IotCardRealname,
|
||||
observation domain.RealnameObservation, gate domain.RealnameResetGate) error {
|
||||
decision := domain.DecideRealnameTime(realnameTimeSnapshot(record), observation, gate)
|
||||
if !decision.Changed {
|
||||
return nil
|
||||
}
|
||||
now := time.Now()
|
||||
var resetBatchID *uint
|
||||
if record != nil {
|
||||
resetBatchID = record.ResetBatchID
|
||||
}
|
||||
if record == nil {
|
||||
created := model.IotCardRealname{
|
||||
CardID: card.ID, RealnameAt: decision.RealnameAt, RealnameAtSource: decision.Source,
|
||||
UpstreamRealnameAt: decision.UpstreamRealnameAt, FirstObservedAt: decision.FirstObservedAt,
|
||||
ResetStatus: constants.RealnameResetStatusNone, CreatedAt: now, UpdatedAt: now,
|
||||
}
|
||||
if err := tx.WithContext(ctx).Create(&created).Error; err != nil {
|
||||
return errors.Wrap(errors.CodeDatabaseError, err, "创建卡当前实名记录失败")
|
||||
}
|
||||
} else {
|
||||
updates := map[string]any{
|
||||
"realname_at": decision.RealnameAt, "realname_at_source": decision.Source,
|
||||
"upstream_realname_at": decision.UpstreamRealnameAt, "first_observed_at": decision.FirstObservedAt,
|
||||
"updated_at": now,
|
||||
}
|
||||
if decision.ClearReset {
|
||||
updates["reset_status"] = constants.RealnameResetStatusNone
|
||||
updates["reset_at"] = nil
|
||||
updates["reset_baseline_at"] = nil
|
||||
updates["reset_batch_id"] = nil
|
||||
}
|
||||
if err := tx.WithContext(ctx).Model(&model.IotCardRealname{}).Where("id = ?", record.ID).Updates(updates).Error; err != nil {
|
||||
return errors.Wrap(errors.CodeDatabaseError, err, "更新卡当前实名记录失败")
|
||||
}
|
||||
}
|
||||
if decision.ClearReset && resetBatchID != nil {
|
||||
if err := tx.WithContext(ctx).Model(&model.IotCardRealnameResetBatch{}).Where("id = ?", *resetBatchID).
|
||||
Updates(map[string]any{"completed_count": gorm.Expr("completed_count + 1"), "updated_at": now}).Error; err != nil {
|
||||
return errors.Wrap(errors.CodeDatabaseError, err, "更新二次实名批次完成数失败")
|
||||
}
|
||||
}
|
||||
if !decision.WriteHistory {
|
||||
return nil
|
||||
}
|
||||
history := model.IotCardRealnameHistory{
|
||||
CardID: card.ID, ICCID: card.ICCID, BeforeAt: decision.BeforeAt, AfterAt: decision.RealnameAt,
|
||||
AfterSource: decision.Source, ChangeType: decision.ChangeType, ObservationSource: observation.Metadata.Source,
|
||||
ObservedAt: observation.Metadata.ObservedAt, CreatedAt: now,
|
||||
}
|
||||
if decision.ClearReset {
|
||||
history.ResetBatchID = resetBatchID
|
||||
}
|
||||
if err := tx.WithContext(ctx).Create(&history).Error; err != nil {
|
||||
return errors.Wrap(errors.CodeDatabaseError, err, "写入卡实名时间历史失败")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -84,6 +84,7 @@ func (s *Service) ApplyTrafficObservation(ctx context.Context, observation domai
|
||||
return errors.Wrap(errors.CodeDatabaseError, err, "查询卡采集时刻有效套餐失败")
|
||||
}
|
||||
record.HasPackage = len(packages.Packages) > 0
|
||||
record.CarrierID = card.CarrierID
|
||||
if judge != cardflow.QueueWrite {
|
||||
if observation.Metadata.Scene == constants.CardObservationScenePreActivationSettlement {
|
||||
// 激活前结算没写入:用已有本月最大快照结算,不新写快照。
|
||||
@@ -230,6 +231,10 @@ func (s *Service) writeTrafficFailureAudit(ctx context.Context, observation doma
|
||||
if !workerObservationAudited(ctx) || s.auditWriter == nil {
|
||||
return
|
||||
}
|
||||
// 观测失败常因上下文已超时,失败审计改用独立短超时上下文,避免连带报错。
|
||||
auditCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
|
||||
defer cancel()
|
||||
ctx = auditCtx
|
||||
var card model.IotCard
|
||||
if loadErr := s.db.WithContext(ctx).Where("id = ?", observation.CardID).First(&card).Error; loadErr != nil {
|
||||
return
|
||||
|
||||
@@ -4,8 +4,10 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/datatypes"
|
||||
|
||||
cardflow "github.com/break/junhong_cmp_fiber/internal/domain/cardflow"
|
||||
domain "github.com/break/junhong_cmp_fiber/internal/domain/cardobservation"
|
||||
@@ -14,13 +16,15 @@ import (
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
)
|
||||
|
||||
// collectionRecordTimeout 是事务提交后写采集记录的超时;采集记录只用于排查,写失败只告警。
|
||||
const collectionRecordTimeout = 3 * time.Second
|
||||
// rawResponseMaxBytes 是原始响应体保存上限,超过时截断并标记。
|
||||
const rawResponseMaxBytes = 4096
|
||||
|
||||
// collectionRecord 是一次采集的留痕内容;HasPackage 在观测事务内判断,读数无效的观测写记录前再查。
|
||||
// collectionRecord 是一次采集的留痕内容;HasPackage 在观测事务内判断(只对成功读数有意义)。
|
||||
type collectionRecord struct {
|
||||
model.CardTrafficCollection
|
||||
HasPackage bool
|
||||
failure *domain.CollectionFailure
|
||||
iccid string
|
||||
}
|
||||
|
||||
func newCollectionRecord(observation domain.TrafficObservation) *collectionRecord {
|
||||
@@ -28,7 +32,8 @@ func newCollectionRecord(observation domain.TrafficObservation) *collectionRecor
|
||||
IotCardID: observation.CardID, ObservedAt: observation.Metadata.ObservedAt,
|
||||
ObservationID: observation.Metadata.ObservationID, Source: observation.Metadata.Source,
|
||||
Scene: observation.Metadata.Scene, Result: domain.ResolveReadingResult(observation),
|
||||
}}
|
||||
CollectionRaw: buildCollectionRaw(observation.Raw), CarrierID: observation.CarrierID,
|
||||
}, failure: observation.Failure, iccid: observation.ICCID}
|
||||
if record.Result == constants.TrafficCollectionResultOK {
|
||||
reading := observation.GatewayReadingMB
|
||||
record.VendorUsedMB = &reading
|
||||
@@ -51,24 +56,112 @@ func (r *collectionRecord) applyOutcome(outcome *flowOutcome) {
|
||||
r.MonthUsedMB, r.DeltaMB, r.StaleGuarded, r.EventID = &monthUsed, &delta, &stale, outcome.EventID
|
||||
}
|
||||
|
||||
// writeCollectionRecord 在观测事务之外为采集时刻有套餐的卡写采集记录;没套餐的卡不写。
|
||||
func (s *Service) writeCollectionRecord(ctx context.Context, record *collectionRecord, observedAt time.Time) {
|
||||
writeCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), collectionRecordTimeout)
|
||||
defer cancel()
|
||||
hasPackage := record.HasPackage
|
||||
// writeCollectionRecord 在观测事务之外写采集记录:成功读数只为采集时刻有套餐的卡写成功表;
|
||||
// 失败读数不判断有无套餐,写失败表。注入发布器时发布到批量写入消息,由消费者攒批写库并失败重投;
|
||||
// 未注入或发布失败时同步写库。
|
||||
func (s *Service) writeCollectionRecord(ctx context.Context, record *collectionRecord, _ time.Time) {
|
||||
if record.Result != constants.TrafficCollectionResultOK {
|
||||
packages, err := postgres.FindEffectivePackagesAt(writeCtx, s.db, record.IotCardID, observedAt, false)
|
||||
if err != nil {
|
||||
s.logTrafficWarn("查询卡采集时刻有效套餐失败,跳过采集记录", zap.Uint("card_id", record.IotCardID), zap.Error(err))
|
||||
return
|
||||
}
|
||||
hasPackage = len(packages.Packages) > 0
|
||||
}
|
||||
if !hasPackage {
|
||||
s.writeCollectionFailure(ctx, record)
|
||||
return
|
||||
}
|
||||
if err := postgres.NewCardTrafficCollectionStore(s.db).Create(writeCtx, &record.CardTrafficCollection); err != nil {
|
||||
if !record.HasPackage {
|
||||
return
|
||||
}
|
||||
row := &record.CardTrafficCollection
|
||||
if s.collectionSink != nil {
|
||||
err := s.collectionSink.PublishCollection(ctx, row, nil)
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
s.logTrafficWarn("发布卡流量采集记录消息失败,改为同步写库", zap.Uint("card_id", record.IotCardID),
|
||||
zap.String("observation_id", record.ObservationID), zap.Error(err))
|
||||
}
|
||||
writeCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), constants.PollingIngestSyncCollectionTimeout)
|
||||
defer cancel()
|
||||
if err := postgres.NewCardTrafficCollectionStore(s.db).Create(writeCtx, row); err != nil {
|
||||
s.logTrafficWarn("写卡流量采集记录失败", zap.Uint("card_id", record.IotCardID),
|
||||
zap.String("observation_id", record.ObservationID), zap.Error(err))
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) writeCollectionFailure(ctx context.Context, record *collectionRecord) {
|
||||
row := &model.CardTrafficCollectionFailure{
|
||||
IotCardID: record.IotCardID, ObservedAt: record.ObservedAt, ObservationID: record.ObservationID,
|
||||
Source: record.Source, Scene: record.Scene, Result: record.Result, CollectionRaw: record.CollectionRaw,
|
||||
ICCID: record.iccid, CarrierID: record.CarrierID,
|
||||
}
|
||||
if failure := record.failure; failure != nil {
|
||||
row.ErrorCategory, row.ProviderCode = failure.ErrorCategory, failure.ProviderCode
|
||||
row.ProviderMessage, row.DurationMS = truncateText(failure.ProviderMessage, 500), failure.DurationMS
|
||||
}
|
||||
writeCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), constants.PollingIngestSyncCollectionTimeout)
|
||||
defer cancel()
|
||||
if row.ICCID == "" || row.CarrierID == 0 {
|
||||
var card model.IotCard
|
||||
if err := s.db.WithContext(writeCtx).Unscoped().Select("iccid", "carrier_id").Where("id = ?", record.IotCardID).Take(&card).Error; err == nil {
|
||||
row.ICCID, row.CarrierID = card.ICCID, card.CarrierID
|
||||
}
|
||||
}
|
||||
if s.collectionSink != nil {
|
||||
err := s.collectionSink.PublishCollection(ctx, nil, row)
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
s.logTrafficWarn("发布卡流量采集失败记录消息失败,改为同步写库", zap.Uint("card_id", record.IotCardID),
|
||||
zap.String("observation_id", record.ObservationID), zap.Error(err))
|
||||
}
|
||||
if err := postgres.NewCardTrafficCollectionFailureStore(s.db).Create(writeCtx, row); err != nil {
|
||||
s.logTrafficWarn("写卡流量采集失败记录失败", zap.Uint("card_id", record.IotCardID),
|
||||
zap.String("observation_id", record.ObservationID), zap.Error(err))
|
||||
}
|
||||
}
|
||||
|
||||
// buildCollectionRaw 把网关原始数据转为留存字段:响应可解析为 JSON 且不超过 4KB 时存 JSON,否则存文本并按 4KB 截断。
|
||||
func buildCollectionRaw(raw *domain.GatewayRaw) model.CollectionRaw {
|
||||
if raw == nil {
|
||||
return model.CollectionRaw{}
|
||||
}
|
||||
out := model.CollectionRaw{
|
||||
GatewayCode: raw.GatewayCode, GatewayMsg: truncateText(raw.GatewayMsg, 500),
|
||||
GatewayTraceID: truncateText(raw.TraceID, 128), GatewayAttempts: raw.Attempts,
|
||||
}
|
||||
if raw.HTTPStatus > 0 {
|
||||
status := raw.HTTPStatus
|
||||
out.HTTPStatus = &status
|
||||
}
|
||||
if len(raw.Request) > 0 && json.Valid(raw.Request) {
|
||||
out.RawRequest = datatypes.JSON(raw.Request)
|
||||
}
|
||||
switch {
|
||||
case len(raw.Response) == 0:
|
||||
case len(raw.Response) > rawResponseMaxBytes:
|
||||
out.RawResponseText, out.RawTruncated = validUTF8Prefix(raw.Response, rawResponseMaxBytes), true
|
||||
case json.Valid(raw.Response):
|
||||
out.RawResponse = datatypes.JSON(raw.Response)
|
||||
default:
|
||||
out.RawResponseText = validUTF8Prefix(raw.Response, rawResponseMaxBytes)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// validUTF8Prefix 返回不超过 limit 字节且不截断多字节字符的前缀,并替换非法 UTF-8(PostgreSQL text 不接受)。
|
||||
func validUTF8Prefix(data []byte, limit int) string {
|
||||
if len(data) > limit {
|
||||
data = data[:limit]
|
||||
for len(data) > 0 && !utf8.Valid(data) {
|
||||
data = data[:len(data)-1]
|
||||
}
|
||||
}
|
||||
if !utf8.Valid(data) {
|
||||
return string([]rune(string(data)))
|
||||
}
|
||||
return string(data)
|
||||
}
|
||||
|
||||
func truncateText(value string, limit int) string {
|
||||
runes := []rune(value)
|
||||
if len(runes) <= limit {
|
||||
return value
|
||||
}
|
||||
return string(runes[:limit])
|
||||
}
|
||||
|
||||
@@ -45,6 +45,7 @@ type ExtensionService struct {
|
||||
runtime *merchantpayment.RuntimeLoader
|
||||
payments PaymentPorts
|
||||
refunder refundchannel.Refunder
|
||||
jsapi JSAPIPayer
|
||||
logger *zap.Logger
|
||||
now func() time.Time
|
||||
}
|
||||
@@ -269,7 +270,21 @@ func (s *ExtensionService) Eligibility(ctx context.Context, usageID uint, scope
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return eligibilityResponse(facts), nil
|
||||
resp := eligibilityResponse(facts)
|
||||
// 办理延期时一并展示套餐订购时间、到期时间与沉默期截止时间
|
||||
resp.PackageName = usage.PackageName
|
||||
resp.PurchasedAt = usage.SilenceStartAt
|
||||
if resp.PurchasedAt == nil {
|
||||
createdAt := usage.CreatedAt
|
||||
resp.PurchasedAt = &createdAt
|
||||
}
|
||||
resp.ActivatedAt = usage.ActivatedAt
|
||||
resp.ExpiresAt = usage.ExpiresAt
|
||||
resp.SilenceDeadlineAt = usage.SilenceDeadlineAt
|
||||
if identifier, idErr := assetIdentifier(ctx, s.db, usage); idErr == nil {
|
||||
resp.AssetIdentifier = identifier
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// Quote 按输入天数试算付费延期。
|
||||
|
||||
64
internal/application/packagesilence/online_jsapi.go
Normal file
64
internal/application/packagesilence/online_jsapi.go
Normal file
@@ -0,0 +1,64 @@
|
||||
package packagesilence
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
"github.com/break/junhong_cmp_fiber/internal/model/dto"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/errors"
|
||||
)
|
||||
|
||||
// jsapiContentPrefix 标记支付单 qr_content 里保存的是微信 JSAPI 调起参数(JSON),而不是二维码 / 支付链接。
|
||||
const jsapiContentPrefix = "jsapi:"
|
||||
|
||||
// JSAPIPayer 为 C 端客户按已冻结商户创建微信 JSAPI 预下单(复用套餐购买的公众号 / 小程序支付)。
|
||||
type JSAPIPayer interface {
|
||||
CreateJSAPIPayConfig(ctx context.Context, customerID uint, appType string, config *model.WechatConfig,
|
||||
paymentNo, description string, amount int64) (*dto.ClientPayConfig, error)
|
||||
}
|
||||
|
||||
// SetJSAPIPayer 注入微信 JSAPI 预下单能力;未注入时 H5 微信延期仍走 H5 支付链接。
|
||||
func (s *ExtensionService) SetJSAPIPayer(payer JSAPIPayer) { s.jsapi = payer }
|
||||
|
||||
// useJSAPI 判断本次下单是否走微信内直接支付:H5 客户、微信支付、带应用类型、商户为微信直连(v3 / v2)。
|
||||
// 富友商户仍走扫码,避免查单与下单协议不一致。
|
||||
func (s *ExtensionService) useJSAPI(source string, req dto.SilenceOnlineOrderRequest, config *model.WechatConfig) bool {
|
||||
return s.jsapi != nil && source == constants.SilenceOrderSourceClient && req.PaymentMethod == model.PaymentByWechat &&
|
||||
strings.TrimSpace(req.AppType) != "" && config != nil &&
|
||||
(config.ProviderType == model.ProviderTypeWechat || config.ProviderType == model.ProviderTypeWechatV2)
|
||||
}
|
||||
|
||||
// createJSAPIContent 预下单并把调起参数编码成支付单内容,便于"继续支付"复用(预支付有效期 2 小时,长于支付截止)。
|
||||
func (s *ExtensionService) createJSAPIContent(ctx context.Context, customerID uint, appType string, config *model.WechatConfig, payment *model.Payment) (string, error) {
|
||||
payConfig, err := s.jsapi.CreateJSAPIPayConfig(ctx, customerID, appType, config, payment.PaymentNo, "沉默期延期", payment.Amount)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if payConfig == nil || strings.TrimSpace(payConfig.PackageVal) == "" {
|
||||
return "", errors.New(errors.CodeWechatPayFailed, "微信支付未返回调起参数")
|
||||
}
|
||||
raw, err := json.Marshal(payConfig)
|
||||
if err != nil {
|
||||
return "", errors.Wrap(errors.CodeInternalError, err, "编码微信支付参数失败")
|
||||
}
|
||||
return jsapiContentPrefix + string(raw), nil
|
||||
}
|
||||
|
||||
// ApplyPaymentContent 把支付单内容写到响应:JSAPI 参数放 pay_config,其余(二维码 / 支付链接)放 qr_content。
|
||||
func ApplyPaymentContent(resp *dto.SilenceExtensionOrderResponse, content string) {
|
||||
if resp == nil || content == "" {
|
||||
return
|
||||
}
|
||||
if strings.HasPrefix(content, jsapiContentPrefix) {
|
||||
var payConfig dto.ClientPayConfig
|
||||
if err := json.Unmarshal([]byte(strings.TrimPrefix(content, jsapiContentPrefix)), &payConfig); err == nil {
|
||||
resp.PayConfig = &payConfig
|
||||
resp.QRContent = ""
|
||||
}
|
||||
return
|
||||
}
|
||||
resp.QRContent = content
|
||||
}
|
||||
57
internal/application/packagesilence/online_jsapi_test.go
Normal file
57
internal/application/packagesilence/online_jsapi_test.go
Normal file
@@ -0,0 +1,57 @@
|
||||
package packagesilence
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
"github.com/break/junhong_cmp_fiber/internal/model/dto"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
)
|
||||
|
||||
type fakeJSAPIPayer struct{}
|
||||
|
||||
func (fakeJSAPIPayer) CreateJSAPIPayConfig(context.Context, uint, string, *model.WechatConfig, string, string, int64) (*dto.ClientPayConfig, error) {
|
||||
return &dto.ClientPayConfig{PackageVal: "prepay_id=wx1"}, nil
|
||||
}
|
||||
|
||||
func TestUseJSAPI(t *testing.T) {
|
||||
s := &ExtensionService{jsapi: fakeJSAPIPayer{}}
|
||||
wechatReq := dto.SilenceOnlineOrderRequest{PaymentMethod: model.PaymentByWechat, AppType: "official_account"}
|
||||
tests := []struct {
|
||||
name string
|
||||
svc *ExtensionService
|
||||
source string
|
||||
req dto.SilenceOnlineOrderRequest
|
||||
config *model.WechatConfig
|
||||
want bool
|
||||
}{
|
||||
{"H5 微信直连 v2", s, constants.SilenceOrderSourceClient, wechatReq, &model.WechatConfig{ProviderType: model.ProviderTypeWechatV2}, true},
|
||||
{"H5 微信直连 v3", s, constants.SilenceOrderSourceClient, wechatReq, &model.WechatConfig{ProviderType: model.ProviderTypeWechat}, true},
|
||||
{"富友仍走扫码", s, constants.SilenceOrderSourceClient, wechatReq, &model.WechatConfig{ProviderType: model.ProviderTypeFuiou}, false},
|
||||
{"后台二维码", s, constants.SilenceOrderSourceAdmin, wechatReq, &model.WechatConfig{ProviderType: model.ProviderTypeWechatV2}, false},
|
||||
{"未带应用类型", s, constants.SilenceOrderSourceClient, dto.SilenceOnlineOrderRequest{PaymentMethod: model.PaymentByWechat}, &model.WechatConfig{ProviderType: model.ProviderTypeWechatV2}, false},
|
||||
{"支付宝", s, constants.SilenceOrderSourceClient, dto.SilenceOnlineOrderRequest{PaymentMethod: model.PaymentByAlipay, AppType: "official_account"}, &model.WechatConfig{ProviderType: "alipay"}, false},
|
||||
{"未注入", &ExtensionService{}, constants.SilenceOrderSourceClient, wechatReq, &model.WechatConfig{ProviderType: model.ProviderTypeWechatV2}, false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := tt.svc.useJSAPI(tt.source, tt.req, tt.config); got != tt.want {
|
||||
t.Fatalf("useJSAPI() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyPaymentContent(t *testing.T) {
|
||||
resp := &dto.SilenceExtensionOrderResponse{}
|
||||
ApplyPaymentContent(resp, `jsapi:{"app_id":"wxA","package":"prepay_id=wx1","pay_sign":"S"}`)
|
||||
if resp.PayConfig == nil || resp.PayConfig.PackageVal != "prepay_id=wx1" || resp.PayConfig.AppID != "wxA" || resp.QRContent != "" {
|
||||
t.Fatalf("jsapi content not mapped: %+v", resp)
|
||||
}
|
||||
link := &dto.SilenceExtensionOrderResponse{}
|
||||
ApplyPaymentContent(link, "https://wx.tenpay.com/checkmweb?x=1")
|
||||
if link.QRContent != "https://wx.tenpay.com/checkmweb?x=1" || link.PayConfig != nil {
|
||||
t.Fatalf("link content not mapped: %+v", link)
|
||||
}
|
||||
}
|
||||
@@ -101,6 +101,20 @@ func (s *ExtensionService) CreateOnlineOrder(ctx context.Context, command Online
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if s.useJSAPI(source, req, config) {
|
||||
// H5 客户在微信内用微信支付:走 JSAPI 直接拉起,不生成 H5 支付链接(H5 链接在微信内无法支付)
|
||||
content, jsapiErr := s.createJSAPIContent(ctx, command.Scope.CustomerID, req.AppType, config, payment)
|
||||
if jsapiErr != nil {
|
||||
_ = s.closeOrder(ctx, order.ID, "微信支付参数生成失败")
|
||||
return nil, jsapiErr
|
||||
}
|
||||
if err := s.db.WithContext(ctx).Model(&model.Payment{}).
|
||||
Where("id = ? AND status = ? AND (qr_content IS NULL OR qr_content = '')", payment.ID, model.PaymentRecordStatusPending).
|
||||
Update("qr_content", content).Error; err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "保存支付内容失败")
|
||||
}
|
||||
return s.orderResponse(ctx, order, true)
|
||||
}
|
||||
paymentResult, err := adapter.CreatePaymentURL(ctx, agentrechargeApp.OnlinePaymentRequest{
|
||||
PaymentID: payment.ID, PaymentNo: payment.PaymentNo, CorrelationID: payment.PaymentNo,
|
||||
Description: "沉默期延期", Amount: payment.Amount, ExpireAt: *payment.ExpireAt,
|
||||
|
||||
101
internal/application/packagesilence/order_cancel.go
Normal file
101
internal/application/packagesilence/order_cancel.go
Normal file
@@ -0,0 +1,101 @@
|
||||
package packagesilence
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
agentrechargeApp "github.com/break/junhong_cmp_fiber/internal/application/agentrecharge"
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
"github.com/break/junhong_cmp_fiber/internal/model/dto"
|
||||
"github.com/break/junhong_cmp_fiber/internal/store/postgres"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/errors"
|
||||
)
|
||||
|
||||
// CancelOrderCommand 是作废待支付延期订单的命令:Scope.CustomerID 非 0 为 H5 客户作废自己的订单,为 0 为后台运营作废。
|
||||
type CancelOrderCommand struct {
|
||||
OrderID uint
|
||||
Scope Scope
|
||||
Reason string
|
||||
}
|
||||
|
||||
// CancelPendingOrder 作废未支付的在线延期订单,作废后同一套餐可以重新下单。
|
||||
//
|
||||
// 作废前先按冻结商户查单:渠道已支付则按支付成功处理(照常延期)并拒绝作废;
|
||||
// 其余情况(未支付、渠道无此订单、查单失败)直接关闭。关闭后才到达的支付会进入异常并由恢复任务原路退款,不会吞款。
|
||||
func (s *ExtensionService) CancelPendingOrder(ctx context.Context, command CancelOrderCommand) (*dto.SilenceExtensionOrderResponse, error) {
|
||||
if command.Scope.CustomerID == 0 {
|
||||
if err := s.requirePermission(ctx, constants.PermissionPackageSilenceExtend); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
order, err := postgres.NewPackageSilenceOrderStore(s.db).GetByID(ctx, command.OrderID)
|
||||
if err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return nil, errors.New(errors.CodeNotFound, "延期订单不存在")
|
||||
}
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询延期订单失败")
|
||||
}
|
||||
if command.Scope.CustomerID != 0 && (order.CustomerID == nil || *order.CustomerID != command.Scope.CustomerID) {
|
||||
return nil, errors.New(errors.CodeNotFound, "延期订单不存在")
|
||||
}
|
||||
if order.Status != constants.SilenceOrderStatusPendingPayment {
|
||||
return nil, errors.New(errors.CodeInvalidStatus, "只有待支付的延期订单可以作废")
|
||||
}
|
||||
|
||||
paid, err := s.confirmIfPaid(ctx, order)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if paid {
|
||||
return nil, errors.New(errors.CodeInvalidStatus, "该订单已支付,已按支付成功办理延期,不能作废")
|
||||
}
|
||||
|
||||
reason := "手动作废"
|
||||
if command.Scope.CustomerID != 0 {
|
||||
reason = "客户作废"
|
||||
}
|
||||
if extra := strings.TrimSpace(command.Reason); extra != "" {
|
||||
reason += ":" + extra
|
||||
}
|
||||
if err := s.closeOrder(ctx, order.ID, reason); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
current, err := postgres.NewPackageSilenceOrderStore(s.db).GetByID(ctx, order.ID)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询延期订单失败")
|
||||
}
|
||||
return s.orderResponse(ctx, current, false)
|
||||
}
|
||||
|
||||
// confirmIfPaid 查询订单下待支付的支付单;渠道已支付时走支付确认并返回 true。查单失败不阻止作废。
|
||||
func (s *ExtensionService) confirmIfPaid(ctx context.Context, order *model.PackageSilenceExtensionOrder) (bool, error) {
|
||||
if order.PaymentMethod == model.PaymentByOffline {
|
||||
return false, nil
|
||||
}
|
||||
var payments []model.Payment
|
||||
if err := s.db.WithContext(ctx).Where("order_type = ? AND order_id = ? AND status = ?", constants.PaymentOrderTypeSilenceExtension, order.ID, model.PaymentRecordStatusPending).
|
||||
Order("id DESC").Find(&payments).Error; err != nil {
|
||||
return false, errors.Wrap(errors.CodeDatabaseError, err, "查询延期支付单失败")
|
||||
}
|
||||
for index := range payments {
|
||||
payment := &payments[index]
|
||||
state, query, err := s.queryPayment(ctx, payment)
|
||||
if err != nil || state != agentrechargeApp.OnlinePaymentStatePaid {
|
||||
continue
|
||||
}
|
||||
paidAt := s.now()
|
||||
if query.PaidAt != nil {
|
||||
paidAt = *query.PaidAt
|
||||
}
|
||||
if err := s.ConfirmPayment(ctx, PaymentConfirmCommand{
|
||||
PaymentNo: payment.PaymentNo, ThirdPartyTradeNo: query.ThirdPartyTradeNo, Amount: query.Amount, PaidAt: paidAt,
|
||||
}); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
@@ -67,8 +67,9 @@ func (s *ExtensionService) orderResponse(ctx context.Context, order *model.Packa
|
||||
resp.ThirdPartyTradeNo = payment.ThirdPartyTradeNo
|
||||
resp.PaymentNo = payment.PaymentNo
|
||||
}
|
||||
if includeQR && order.Status == constants.SilenceOrderStatusPendingPayment && payment.Status == model.PaymentRecordStatusPending && resp.QRContent == "" {
|
||||
resp.QRContent = payment.QRContent
|
||||
if includeQR && order.Status == constants.SilenceOrderStatusPendingPayment && payment.Status == model.PaymentRecordStatusPending &&
|
||||
resp.QRContent == "" && resp.PayConfig == nil {
|
||||
ApplyPaymentContent(resp, payment.QRContent)
|
||||
resp.PaymentNo = payment.PaymentNo
|
||||
}
|
||||
}
|
||||
|
||||
@@ -223,6 +223,10 @@ func (r *Resolver) applyExpire(ctx context.Context, tx *gorm.DB, usage *model.Pa
|
||||
return ResolveResult{Decision: packagedomain.SilenceDecisionExpire, Changed: true, Status: constants.SilenceStatusExpired}, nil
|
||||
}
|
||||
|
||||
// cardRealnameAtExpr 是卡当前实名时间:取卡当前实名记录的实名时间(上游 archiveTime 优先,见 add-realname-time-history);
|
||||
// 还没有当前实名记录的卡(上线迁移前后的空窗)回退到 first_realname_at。
|
||||
const cardRealnameAtExpr = "CASE WHEN r.id IS NULL THEN c.first_realname_at ELSE r.realname_at END"
|
||||
|
||||
// realnameFacts 是判定所需的资产实名事实(技术方案 §5.1)。
|
||||
type realnameFacts struct {
|
||||
realnamed bool
|
||||
@@ -239,15 +243,16 @@ type boundCardRow struct {
|
||||
}
|
||||
|
||||
// loadRealnameFacts 读取实名事实:
|
||||
// - 卡:first_realname_at;已实名但时间为空时视为期内实名并补写。
|
||||
// - 卡:当前实名时间;已实名但时间为空时视为期内实名并补写。
|
||||
// - 设备:所有已绑定且已实名卡中 max(卡实名时间, 绑定时间) 的最小值,使截止后才绑定的已实名卡不能倒推为期内实名;
|
||||
// 卡实名时间为空时按绑定时间计并补写卡的实名时间。
|
||||
func loadRealnameFacts(ctx context.Context, tx *gorm.DB, usage *model.PackageUsage) (realnameFacts, error) {
|
||||
if usage.DeviceID > 0 {
|
||||
var rows []boundCardRow
|
||||
err := tx.WithContext(ctx).Table("tb_device_sim_binding AS b").
|
||||
Select("c.id AS card_id, c.real_name_status, c.first_realname_at, b.bind_time, b.created_at AS bind_created_at").
|
||||
Select("c.id AS card_id, c.real_name_status, "+cardRealnameAtExpr+" AS first_realname_at, b.bind_time, b.created_at AS bind_created_at").
|
||||
Joins("JOIN tb_iot_card AS c ON c.id = b.iot_card_id AND c.deleted_at IS NULL").
|
||||
Joins("LEFT JOIN tb_iot_card_realname AS r ON r.card_id = c.id").
|
||||
Where("b.device_id = ? AND b.bind_status = ? AND b.deleted_at IS NULL", usage.DeviceID, constants.BindStatusBound).
|
||||
Where("c.real_name_status = ?", constants.RealNameStatusVerified).
|
||||
Scan(&rows).Error
|
||||
@@ -277,22 +282,25 @@ func loadRealnameFacts(ctx context.Context, tx *gorm.DB, usage *model.PackageUsa
|
||||
if usage.IotCardID == 0 {
|
||||
return realnameFacts{}, nil
|
||||
}
|
||||
var card model.IotCard
|
||||
if err := tx.WithContext(ctx).Select("id", "real_name_status", "first_realname_at").
|
||||
Where("id = ?", usage.IotCardID).First(&card).Error; err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return realnameFacts{}, nil
|
||||
}
|
||||
var cards []boundCardRow
|
||||
if err := tx.WithContext(ctx).Table("tb_iot_card AS c").
|
||||
Select("c.id AS card_id, c.real_name_status, "+cardRealnameAtExpr+" AS first_realname_at").
|
||||
Joins("LEFT JOIN tb_iot_card_realname AS r ON r.card_id = c.id").
|
||||
Where("c.id = ?", usage.IotCardID).Limit(1).Scan(&cards).Error; err != nil {
|
||||
return realnameFacts{}, errors.Wrap(errors.CodeDatabaseError, err, "查询卡实名事实失败")
|
||||
}
|
||||
if len(cards) == 0 {
|
||||
return realnameFacts{}, nil
|
||||
}
|
||||
card := cards[0]
|
||||
facts := realnameFacts{realnamed: card.RealNameStatus == constants.RealNameStatusVerified, realnameAt: card.FirstRealnameAt}
|
||||
if facts.realnamed && card.FirstRealnameAt == nil {
|
||||
facts.backfillCardIDs = []uint{card.ID}
|
||||
facts.backfillCardIDs = []uint{card.CardID}
|
||||
}
|
||||
return facts, nil
|
||||
}
|
||||
|
||||
// backfillRealnameAt 为已实名但实名时间为空的卡补写 first_realname_at(只写为空的,返回补写数量)。
|
||||
// backfillRealnameAt 为已实名但实名时间为空的卡补写实名时间(first_realname_at 与当前实名记录都只写为空的,返回补写数量)。
|
||||
func backfillRealnameAt(ctx context.Context, tx *gorm.DB, facts realnameFacts, now time.Time) (int64, error) {
|
||||
if len(facts.backfillCardIDs) == 0 {
|
||||
return 0, nil
|
||||
@@ -303,6 +311,9 @@ func backfillRealnameAt(ctx context.Context, tx *gorm.DB, facts realnameFacts, n
|
||||
if result.Error != nil {
|
||||
return 0, errors.Wrap(errors.CodeDatabaseError, result.Error, "补写卡实名时间失败")
|
||||
}
|
||||
if err := backfillCurrentRealnameAt(ctx, tx, facts.backfillCardIDs, now); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected, nil
|
||||
}
|
||||
|
||||
@@ -326,3 +337,44 @@ func (r *Resolver) AllowActivationInTx(ctx context.Context, tx *gorm.DB, usage *
|
||||
}
|
||||
return !result.Blocked(), nil
|
||||
}
|
||||
|
||||
// backfillCurrentRealnameAt 为已实名但当前实名时间为空的卡写入当前实名记录(来源"首次读到",取判定时间)并记一条首次实名历史。
|
||||
// 二次实名等待中的卡是未实名状态,不会进入这里。
|
||||
func backfillCurrentRealnameAt(ctx context.Context, tx *gorm.DB, cardIDs []uint, now time.Time) error {
|
||||
var rows []struct {
|
||||
CardID uint `gorm:"column:card_id"`
|
||||
ICCID string `gorm:"column:iccid"`
|
||||
RecordID *uint `gorm:"column:record_id"`
|
||||
Realname *time.Time `gorm:"column:realname_at"`
|
||||
}
|
||||
if err := tx.WithContext(ctx).Table("tb_iot_card AS c").
|
||||
Select("c.id AS card_id, c.iccid, r.id AS record_id, r.realname_at").
|
||||
Joins("LEFT JOIN tb_iot_card_realname AS r ON r.card_id = c.id").
|
||||
Where("c.id IN ? AND c.real_name_status = ?", cardIDs, constants.RealNameStatusVerified).
|
||||
Scan(&rows).Error; err != nil {
|
||||
return errors.Wrap(errors.CodeDatabaseError, err, "查询卡当前实名记录失败")
|
||||
}
|
||||
for _, row := range rows {
|
||||
if row.Realname != nil {
|
||||
continue
|
||||
}
|
||||
updates := map[string]any{"realname_at": now, "realname_at_source": constants.RealnameAtSourceFirstObserved, "updated_at": now}
|
||||
if row.RecordID == nil {
|
||||
record := model.IotCardRealname{CardID: row.CardID, RealnameAt: &now, RealnameAtSource: constants.RealnameAtSourceFirstObserved,
|
||||
FirstObservedAt: &now, ResetStatus: constants.RealnameResetStatusNone, CreatedAt: now, UpdatedAt: now}
|
||||
if err := tx.WithContext(ctx).Create(&record).Error; err != nil {
|
||||
return errors.Wrap(errors.CodeDatabaseError, err, "补写卡当前实名记录失败")
|
||||
}
|
||||
} else if err := tx.WithContext(ctx).Model(&model.IotCardRealname{}).Where("id = ? AND realname_at IS NULL", *row.RecordID).
|
||||
Updates(updates).Error; err != nil {
|
||||
return errors.Wrap(errors.CodeDatabaseError, err, "补写卡当前实名时间失败")
|
||||
}
|
||||
history := model.IotCardRealnameHistory{CardID: row.CardID, ICCID: row.ICCID, AfterAt: &now,
|
||||
AfterSource: constants.RealnameAtSourceFirstObserved, ChangeType: constants.RealnameChangeFirst,
|
||||
ObservationSource: "package_silence", ObservedAt: now, CreatedAt: now}
|
||||
if err := tx.WithContext(ctx).Create(&history).Error; err != nil {
|
||||
return errors.Wrap(errors.CodeDatabaseError, err, "写入卡实名时间历史失败")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
259
internal/application/realnamereset/service.go
Normal file
259
internal/application/realnamereset/service.go
Normal file
@@ -0,0 +1,259 @@
|
||||
// Package realnamereset 提供二次实名批次的导入与撤销用例。
|
||||
// 二次实名:清除卡的实名状态与当前实名时间,之后只有上游 archiveTime 晚于清除前时间才算重新实名(见 add-realname-time-history)。
|
||||
package realnamereset
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/bytedance/sonic"
|
||||
"gorm.io/gorm"
|
||||
|
||||
cardobservationapp "github.com/break/junhong_cmp_fiber/internal/application/cardobservation"
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
"github.com/break/junhong_cmp_fiber/internal/model/dto"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/errors"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/middleware"
|
||||
)
|
||||
|
||||
// CardResetter 执行单卡二次实名清除与撤销。
|
||||
type CardResetter interface {
|
||||
ResetRealname(ctx context.Context, command cardobservationapp.RealnameResetCommand) error
|
||||
RevertRealnameReset(ctx context.Context, command cardobservationapp.RealnameResetCommand) error
|
||||
}
|
||||
|
||||
// PermissionChecker 校验后台账号权限点。
|
||||
type PermissionChecker interface {
|
||||
CheckPermission(ctx context.Context, userID uint, permCode string, platform string) (bool, error)
|
||||
}
|
||||
|
||||
// Service 是二次实名批次用例。
|
||||
type Service struct {
|
||||
db *gorm.DB
|
||||
resetter CardResetter
|
||||
perms PermissionChecker
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
// NewService 创建二次实名批次用例。
|
||||
func NewService(db *gorm.DB, resetter CardResetter, perms PermissionChecker) *Service {
|
||||
return &Service{db: db, resetter: resetter, perms: perms, now: time.Now}
|
||||
}
|
||||
|
||||
// resetTarget 是一行资产号展开出的一张卡。
|
||||
type resetTarget struct {
|
||||
CardID uint `gorm:"column:id"`
|
||||
ICCID string `gorm:"column:iccid"`
|
||||
}
|
||||
|
||||
// Import 导入二次实名名单:逐行展开为卡并逐卡清除,不合格的行记录原因跳过,不影响其他行。
|
||||
func (s *Service) Import(ctx context.Context, req dto.RealnameResetImportRequest) (*dto.RealnameResetBatchResponse, error) {
|
||||
operatorID, err := s.authorize(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
identifiers := normalizeIdentifiers(req.Identifiers)
|
||||
if len(identifiers) == 0 {
|
||||
return nil, errors.New(errors.CodeInvalidParam, "请导入至少一个资产号")
|
||||
}
|
||||
if len(identifiers) > constants.RealnameResetBatchMaxRows {
|
||||
return nil, errors.New(errors.CodeInvalidParam, fmt.Sprintf("单批最多导入 %d 个资产号", constants.RealnameResetBatchMaxRows))
|
||||
}
|
||||
now := s.now()
|
||||
batch := &model.IotCardRealnameResetBatch{
|
||||
BatchNo: generateBatchNo(now), ImportFileKey: strings.TrimSpace(req.ImportFileKey), Reason: strings.TrimSpace(req.Reason),
|
||||
Items: []byte("[]"), OperatorID: operatorID, OperatorName: middleware.GetUsernameFromContext(ctx), CreatedAt: now, UpdatedAt: now,
|
||||
}
|
||||
if err := s.db.WithContext(ctx).Create(batch).Error; err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "创建二次实名批次失败")
|
||||
}
|
||||
items := make([]dto.RealnameResetItem, 0, len(identifiers))
|
||||
seen := make(map[uint]bool)
|
||||
succeeded, skipped := 0, 0
|
||||
for index, identifier := range identifiers {
|
||||
rowNo := index + 1
|
||||
targets, resolveErr := s.resolveTargets(ctx, identifier)
|
||||
if resolveErr != nil {
|
||||
return nil, resolveErr
|
||||
}
|
||||
if len(targets) == 0 {
|
||||
items = append(items, skippedItem(rowNo, identifier, resetTarget{}, "资产不存在或设备未绑定卡"))
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
for _, target := range targets {
|
||||
if seen[target.CardID] {
|
||||
items = append(items, skippedItem(rowNo, identifier, target, "同一张卡在名单中重复"))
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
seen[target.CardID] = true
|
||||
resetErr := s.resetter.ResetRealname(ctx, cardobservationapp.RealnameResetCommand{CardID: target.CardID, BatchID: batch.ID, OperatorID: operatorID})
|
||||
switch {
|
||||
case resetErr == nil:
|
||||
items = append(items, dto.RealnameResetItem{RowNo: rowNo, Input: identifier, CardID: target.CardID, ICCID: target.ICCID,
|
||||
Result: constants.RealnameResetItemPending})
|
||||
succeeded++
|
||||
case isExpectedResetError(resetErr):
|
||||
items = append(items, skippedItem(rowNo, identifier, target, errorMessage(resetErr)))
|
||||
skipped++
|
||||
default:
|
||||
items = append(items, dto.RealnameResetItem{RowNo: rowNo, Input: identifier, CardID: target.CardID, ICCID: target.ICCID,
|
||||
Result: constants.RealnameResetItemFailed, Reason: errorMessage(resetErr)})
|
||||
skipped++
|
||||
}
|
||||
}
|
||||
}
|
||||
encoded, err := sonic.Marshal(items)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(errors.CodeInternalError, err, "编码二次实名批次结果失败")
|
||||
}
|
||||
batch.Items, batch.TotalCount, batch.SucceededCount, batch.SkippedCount = encoded, len(items), succeeded, skipped
|
||||
if err := s.db.WithContext(ctx).Model(&model.IotCardRealnameResetBatch{}).Where("id = ?", batch.ID).Updates(map[string]any{
|
||||
"items": encoded, "total_count": len(items), "succeeded_count": succeeded, "skipped_count": skipped, "updated_at": s.now(),
|
||||
}).Error; err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "更新二次实名批次结果失败")
|
||||
}
|
||||
return &dto.RealnameResetBatchResponse{
|
||||
ID: batch.ID, BatchNo: batch.BatchNo, Reason: batch.Reason, ImportFileKey: batch.ImportFileKey,
|
||||
TotalCount: len(items), SucceededCount: succeeded, SkippedCount: skipped, PendingCount: succeeded,
|
||||
OperatorID: operatorID, OperatorName: batch.OperatorName, CreatedAt: batch.CreatedAt, Items: withResultNames(items),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Revert 撤销批次中仍在等待二次实名的卡;card_ids 为空时撤销整批。
|
||||
func (s *Service) Revert(ctx context.Context, req dto.RealnameResetRevertRequest) (*dto.RealnameResetRevertResponse, error) {
|
||||
operatorID, err := s.authorize(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var batch model.IotCardRealnameResetBatch
|
||||
if err := s.db.WithContext(ctx).Select("id").Where("id = ?", req.ID).Take(&batch).Error; err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return nil, errors.New(errors.CodeNotFound, "二次实名批次不存在")
|
||||
}
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询二次实名批次失败")
|
||||
}
|
||||
query := s.db.WithContext(ctx).Model(&model.IotCardRealname{}).
|
||||
Where("reset_batch_id = ? AND reset_status = ?", batch.ID, constants.RealnameResetStatusPending)
|
||||
if len(req.CardIDs) > 0 {
|
||||
query = query.Where("card_id IN ?", req.CardIDs)
|
||||
}
|
||||
var cardIDs []uint
|
||||
if err := query.Pluck("card_id", &cardIDs).Error; err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询等待二次实名的卡失败")
|
||||
}
|
||||
result := &dto.RealnameResetRevertResponse{}
|
||||
for _, cardID := range cardIDs {
|
||||
if err := s.resetter.RevertRealnameReset(ctx, cardobservationapp.RealnameResetCommand{CardID: cardID, BatchID: batch.ID, OperatorID: operatorID}); err != nil {
|
||||
result.FailedCount++
|
||||
result.Failures = append(result.Failures, fmt.Sprintf("卡 %d:%s", cardID, errorMessage(err)))
|
||||
continue
|
||||
}
|
||||
result.RevertedCount++
|
||||
}
|
||||
if result.RevertedCount > 0 {
|
||||
if err := s.db.WithContext(ctx).Model(&model.IotCardRealnameResetBatch{}).Where("id = ?", batch.ID).Updates(map[string]any{
|
||||
"reverted_count": gorm.Expr("reverted_count + ?", result.RevertedCount), "updated_at": s.now(),
|
||||
}).Error; err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "更新二次实名批次撤销数失败")
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// authorize 二次实名只允许平台账号,且需要 iot_card:realname_reset 权限(超级管理员不受限)。
|
||||
func (s *Service) authorize(ctx context.Context) (uint, error) {
|
||||
operatorID := middleware.GetUserIDFromContext(ctx)
|
||||
switch middleware.GetUserTypeFromContext(ctx) {
|
||||
case constants.UserTypeSuperAdmin:
|
||||
return operatorID, nil
|
||||
case constants.UserTypePlatform:
|
||||
default:
|
||||
return 0, errors.New(errors.CodeForbidden, "仅平台账号可办理二次实名")
|
||||
}
|
||||
if s.perms == nil {
|
||||
return 0, errors.New(errors.CodeForbidden)
|
||||
}
|
||||
allowed, err := s.perms.CheckPermission(ctx, operatorID, constants.PermissionIotCardRealnameReset, constants.PlatformWeb)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if !allowed {
|
||||
return 0, errors.New(errors.CodeForbidden, "无二次实名权限")
|
||||
}
|
||||
return operatorID, nil
|
||||
}
|
||||
|
||||
// resolveTargets 把资产号展开为卡:先按卡 ICCID / 虚拟号,再按设备虚拟号 / IMEI 取设备当前全部绑定卡。
|
||||
func (s *Service) resolveTargets(ctx context.Context, identifier string) ([]resetTarget, error) {
|
||||
var cards []resetTarget
|
||||
if err := s.db.WithContext(ctx).Table("tb_iot_card").Select("id, iccid").
|
||||
Where("deleted_at IS NULL AND (iccid = ? OR virtual_no = ?)", identifier, identifier).
|
||||
Order("id").Limit(1).Scan(&cards).Error; err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "按资产号查询卡失败")
|
||||
}
|
||||
if len(cards) > 0 {
|
||||
return cards, nil
|
||||
}
|
||||
if err := s.db.WithContext(ctx).Table("tb_device AS d").Select("c.id, c.iccid").
|
||||
Joins("JOIN tb_device_sim_binding AS b ON b.device_id = d.id AND b.bind_status = ? AND b.deleted_at IS NULL", constants.BindStatusBound).
|
||||
Joins("JOIN tb_iot_card AS c ON c.id = b.iot_card_id AND c.deleted_at IS NULL").
|
||||
Where("d.deleted_at IS NULL AND (d.virtual_no = ? OR d.imei = ?)", identifier, identifier).
|
||||
Order("c.id").Scan(&cards).Error; err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "按资产号查询设备绑定卡失败")
|
||||
}
|
||||
return cards, nil
|
||||
}
|
||||
|
||||
func normalizeIdentifiers(raw []string) []string {
|
||||
result := make([]string, 0, len(raw))
|
||||
seen := make(map[string]bool, len(raw))
|
||||
for _, value := range raw {
|
||||
value = strings.TrimSpace(value)
|
||||
if value == "" || seen[value] {
|
||||
continue
|
||||
}
|
||||
seen[value] = true
|
||||
result = append(result, value)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func isExpectedResetError(err error) bool {
|
||||
return err == cardobservationapp.ErrRealnameResetNotVerified || err == cardobservationapp.ErrRealnameResetNoUpstream ||
|
||||
err == cardobservationapp.ErrRealnameResetAlreadyReset
|
||||
}
|
||||
|
||||
func errorMessage(err error) string {
|
||||
if appErr, ok := err.(*errors.AppError); ok && appErr.Message != "" {
|
||||
return appErr.Message
|
||||
}
|
||||
return err.Error()
|
||||
}
|
||||
|
||||
func skippedItem(rowNo int, input string, target resetTarget, reason string) dto.RealnameResetItem {
|
||||
return dto.RealnameResetItem{RowNo: rowNo, Input: input, CardID: target.CardID, ICCID: target.ICCID,
|
||||
Result: constants.RealnameResetItemSkipped, Reason: reason}
|
||||
}
|
||||
|
||||
// withResultNames 补结果中文名。
|
||||
func withResultNames(items []dto.RealnameResetItem) []dto.RealnameResetItem {
|
||||
for index := range items {
|
||||
items[index].ResultName = constants.RealnameResetItemName(items[index].Result)
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
func generateBatchNo(now time.Time) string {
|
||||
suffix, err := rand.Int(rand.Reader, big.NewInt(10000))
|
||||
if err != nil {
|
||||
suffix = big.NewInt(now.UnixNano() % 10000)
|
||||
}
|
||||
return fmt.Sprintf("%s%s%04d", constants.RealnameResetBatchNoPrefix, now.Format("20060102150405"), suffix.Int64())
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
notificationApp "github.com/break/junhong_cmp_fiber/internal/application/notification"
|
||||
packageExpiryApp "github.com/break/junhong_cmp_fiber/internal/application/packageexpiry"
|
||||
packagesilenceApp "github.com/break/junhong_cmp_fiber/internal/application/packagesilence"
|
||||
realnameresetApp "github.com/break/junhong_cmp_fiber/internal/application/realnamereset"
|
||||
roleApp "github.com/break/junhong_cmp_fiber/internal/application/role"
|
||||
shopApp "github.com/break/junhong_cmp_fiber/internal/application/shop"
|
||||
systemConfigApp "github.com/break/junhong_cmp_fiber/internal/application/systemconfig"
|
||||
@@ -37,6 +38,7 @@ import (
|
||||
assetQuery "github.com/break/junhong_cmp_fiber/internal/query/asset"
|
||||
auditQuery "github.com/break/junhong_cmp_fiber/internal/query/audit"
|
||||
businessUserGroupQuery "github.com/break/junhong_cmp_fiber/internal/query/businessusergroup"
|
||||
cardrealnameQuery "github.com/break/junhong_cmp_fiber/internal/query/cardrealname"
|
||||
distributionwithdrawalQuery "github.com/break/junhong_cmp_fiber/internal/query/distributionwithdrawal"
|
||||
employeecollectionQuery "github.com/break/junhong_cmp_fiber/internal/query/employeecollection"
|
||||
exchangeQuery "github.com/break/junhong_cmp_fiber/internal/query/exchange"
|
||||
@@ -122,6 +124,10 @@ func initHandlers(svc *services, deps *Dependencies) *Handlers {
|
||||
deps.Redis,
|
||||
deps.Logger,
|
||||
)
|
||||
// 沉默期延期的 H5 微信支付复用套餐购买的 JSAPI 预下单(微信内直接拉起支付)
|
||||
if svc.PackageSilence != nil && svc.PackageSilence.Extensions != nil {
|
||||
svc.PackageSilence.Extensions.SetJSAPIPayer(clientOrderService)
|
||||
}
|
||||
systemConfigRegistry := deps.SystemConfigRegistry
|
||||
if systemConfigRegistry == nil {
|
||||
systemConfigRegistry = systemConfigInfra.NewRegistry()
|
||||
@@ -356,7 +362,9 @@ func initHandlers(svc *services, deps *Dependencies) *Handlers {
|
||||
pollingSvcPkg.NewPollingStatusImportService(deps.DB, deps.QueueClient, deps.Logger), validate),
|
||||
CarrierScheduler: admin.NewCarrierSchedulerHandler(pollingSvcPkg.NewCarrierSchedulerService(deps.DB, deps.Redis,
|
||||
auditInfra.NewWriter(auditInfra.NewRegistry(), nil), carrierSchedulerConfig()), validate),
|
||||
PollingMonitoring: admin.NewPollingMonitoringHandler(svc.PollingMonitoring),
|
||||
PollingMonitoring: admin.NewPollingMonitoringHandler(svc.PollingMonitoring),
|
||||
CardRealname: admin.NewCardRealnameHandler(realnameresetApp.NewService(deps.DB, svc.CardObservation, svc.Permission),
|
||||
cardrealnameQuery.NewQuery(deps.DB), validate),
|
||||
PollingAlert: admin.NewPollingAlertHandler(svc.PollingAlert),
|
||||
PollingCleanup: admin.NewPollingCleanupHandler(svc.PollingCleanup),
|
||||
PollingManualTrigger: admin.NewPollingManualTriggerHandler(svc.PollingManualTrigger),
|
||||
|
||||
@@ -68,6 +68,7 @@ type Handlers struct {
|
||||
CarrierScheduler *admin.CarrierSchedulerHandler
|
||||
PollingPause *admin.PollingPauseHandler
|
||||
PackageSilence *admin.PackageSilenceHandler
|
||||
CardRealname *admin.CardRealnameHandler
|
||||
ClientPackageSilence *app.ClientPackageSilenceHandler
|
||||
PollingConcurrency *admin.PollingConcurrencyHandler
|
||||
PollingMonitoring *admin.PollingMonitoringHandler
|
||||
|
||||
@@ -28,7 +28,9 @@ type ObservationMetadata struct {
|
||||
type RealnameObservation struct {
|
||||
CardID uint
|
||||
Verified bool
|
||||
Metadata ObservationMetadata
|
||||
// UpstreamRealnameAt 是上游返回的实名时间 archiveTime;未返回时为 nil。
|
||||
UpstreamRealnameAt *time.Time
|
||||
Metadata ObservationMetadata
|
||||
}
|
||||
|
||||
// CardRealnameSnapshot 是应用层从持久化模型映射出的最小卡实名快照。
|
||||
|
||||
144
internal/domain/cardobservation/realname_time.go
Normal file
144
internal/domain/cardobservation/realname_time.go
Normal file
@@ -0,0 +1,144 @@
|
||||
package cardobservation
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
)
|
||||
|
||||
// RealnameTimeSnapshot 是卡当前实名记录的最小快照;Exists=false 表示还没有当前实名记录。
|
||||
type RealnameTimeSnapshot struct {
|
||||
Exists bool
|
||||
RealnameAt *time.Time
|
||||
RealnameAtSource string
|
||||
UpstreamRealnameAt *time.Time
|
||||
FirstObservedAt *time.Time
|
||||
ResetStatus string
|
||||
ResetBaselineAt *time.Time
|
||||
}
|
||||
|
||||
// RealnameResetGate 描述二次实名等待期间对一次"已实名"观测的处理。
|
||||
type RealnameResetGate int
|
||||
|
||||
const (
|
||||
// RealnameResetGateNone 卡不在等待二次实名,或本次不是已实名观测。
|
||||
RealnameResetGateNone RealnameResetGate = iota
|
||||
// RealnameResetGateBlocked 读到的仍是旧实名(或没有上游实名时间),不得改实名状态。
|
||||
RealnameResetGateBlocked
|
||||
// RealnameResetGateCompleted 上游实名时间晚于清除前时间,二次实名完成。
|
||||
RealnameResetGateCompleted
|
||||
)
|
||||
|
||||
// EvaluateRealnameResetGate 判断等待二次实名的卡本次已实名观测是新实名还是旧实名。
|
||||
// 以上游 archiveTime 为准:晚于清除前的上游实名时间才算新实名;没有上游时间一律视为旧实名。
|
||||
// 人工纠偏是运营明确操作,不受拦截。
|
||||
func EvaluateRealnameResetGate(snapshot RealnameTimeSnapshot, observation RealnameObservation) RealnameResetGate {
|
||||
if !observation.Verified || snapshot.ResetStatus != constants.RealnameResetStatusPending {
|
||||
return RealnameResetGateNone
|
||||
}
|
||||
if observation.Metadata.Source == constants.CardObservationSourceManualOverride {
|
||||
return RealnameResetGateCompleted
|
||||
}
|
||||
upstream := observation.UpstreamRealnameAt
|
||||
if upstream == nil || snapshot.ResetBaselineAt == nil || !upstream.After(*snapshot.ResetBaselineAt) {
|
||||
return RealnameResetGateBlocked
|
||||
}
|
||||
return RealnameResetGateCompleted
|
||||
}
|
||||
|
||||
// RealnameTimeDecision 描述一次已实名观测后当前实名记录应如何更新。
|
||||
type RealnameTimeDecision struct {
|
||||
// Changed 表示当前实名记录有任何字段需要写入(含不写历史的上游最近时间等)。
|
||||
Changed bool
|
||||
// RealnameAt / Source 是写入后的当前实名时间与来源。
|
||||
RealnameAt *time.Time
|
||||
Source string
|
||||
// UpstreamRealnameAt / FirstObservedAt 是写入后的值。
|
||||
UpstreamRealnameAt *time.Time
|
||||
FirstObservedAt *time.Time
|
||||
// ClearReset 表示清除二次实名等待状态。
|
||||
ClearReset bool
|
||||
// WriteHistory 仅在当前实名时间变化时为 true。
|
||||
WriteHistory bool
|
||||
ChangeType string
|
||||
BeforeAt *time.Time
|
||||
}
|
||||
|
||||
// DecideRealnameTime 根据已被采纳为"已实名"的观测确定当前实名时间:
|
||||
// 1. 有上游实名时间 → 以它为准(来源 upstream);
|
||||
// 2. 否则已有当前实名时间 → 保持不变;
|
||||
// 3. 否则 → 取本次观测时间(来源 first_observed)。
|
||||
//
|
||||
// 只有当前实名时间变化才写历史;相同时间只可能静默更新来源或上游最近返回时间。
|
||||
// 调用方只应在观测被采纳为已实名(卡最终为已实名、且未被二次实名拦截)时调用。
|
||||
func DecideRealnameTime(snapshot RealnameTimeSnapshot, observation RealnameObservation, gate RealnameResetGate) RealnameTimeDecision {
|
||||
decision := RealnameTimeDecision{
|
||||
RealnameAt: snapshot.RealnameAt, Source: snapshot.RealnameAtSource,
|
||||
UpstreamRealnameAt: snapshot.UpstreamRealnameAt, FirstObservedAt: snapshot.FirstObservedAt,
|
||||
BeforeAt: snapshot.RealnameAt,
|
||||
}
|
||||
if !snapshot.Exists {
|
||||
decision.Changed = true
|
||||
}
|
||||
observedAt := observation.Metadata.ObservedAt
|
||||
if decision.FirstObservedAt == nil {
|
||||
decision.FirstObservedAt = timePtr(observedAt)
|
||||
decision.Changed = true
|
||||
}
|
||||
upstream := observation.UpstreamRealnameAt
|
||||
if upstream != nil && !sameTime(decision.UpstreamRealnameAt, upstream) {
|
||||
decision.UpstreamRealnameAt = timePtr(*upstream)
|
||||
decision.Changed = true
|
||||
}
|
||||
|
||||
var next *time.Time
|
||||
source := decision.Source
|
||||
switch {
|
||||
case upstream != nil:
|
||||
next, source = timePtr(*upstream), constants.RealnameAtSourceUpstream
|
||||
case snapshot.RealnameAt != nil:
|
||||
next = snapshot.RealnameAt
|
||||
default:
|
||||
next, source = timePtr(observedAt), constants.RealnameAtSourceFirstObserved
|
||||
}
|
||||
|
||||
if gate == RealnameResetGateCompleted {
|
||||
decision.ClearReset = true
|
||||
decision.Changed = true
|
||||
decision.ChangeType = constants.RealnameChangeResetCompleted
|
||||
}
|
||||
if !sameTime(snapshot.RealnameAt, next) {
|
||||
decision.RealnameAt, decision.Source = next, source
|
||||
decision.Changed = true
|
||||
decision.WriteHistory = true
|
||||
if decision.ChangeType == "" {
|
||||
if snapshot.RealnameAt == nil {
|
||||
decision.ChangeType = constants.RealnameChangeFirst
|
||||
} else {
|
||||
decision.ChangeType = constants.RealnameChangeUpstreamFix
|
||||
}
|
||||
}
|
||||
return decision
|
||||
}
|
||||
if source != decision.Source {
|
||||
// 时间相同只是来源不同(如迁移时间恰好等于上游时间):静默更正来源,不写历史。
|
||||
decision.Source = source
|
||||
decision.Changed = true
|
||||
}
|
||||
if gate == RealnameResetGateCompleted {
|
||||
// 二次实名完成但时间未变(理论上不会发生,上游时间一定晚于基准):仍记一条完成历史。
|
||||
decision.WriteHistory = true
|
||||
}
|
||||
return decision
|
||||
}
|
||||
|
||||
func sameTime(left, right *time.Time) bool {
|
||||
if left == nil || right == nil {
|
||||
return left == nil && right == nil
|
||||
}
|
||||
return left.Equal(*right)
|
||||
}
|
||||
|
||||
func timePtr(value time.Time) *time.Time {
|
||||
return &value
|
||||
}
|
||||
149
internal/domain/cardobservation/realname_time_test.go
Normal file
149
internal/domain/cardobservation/realname_time_test.go
Normal file
@@ -0,0 +1,149 @@
|
||||
package cardobservation
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
)
|
||||
|
||||
var cst = time.FixedZone("CST", 8*3600)
|
||||
|
||||
func at(value string) *time.Time {
|
||||
parsed, err := time.ParseInLocation("2006-01-02 15:04:05", value, cst)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return &parsed
|
||||
}
|
||||
|
||||
func verifiedObservation(source string, observedAt, upstream *time.Time) RealnameObservation {
|
||||
return RealnameObservation{CardID: 1, Verified: true, UpstreamRealnameAt: upstream,
|
||||
Metadata: ObservationMetadata{ObservationID: "o", Source: source, Scene: "s", ObservedAt: *observedAt}}
|
||||
}
|
||||
|
||||
func TestDecideRealnameTime(t *testing.T) {
|
||||
polling := constants.CardObservationSourcePolling
|
||||
cases := []struct {
|
||||
name string
|
||||
snapshot RealnameTimeSnapshot
|
||||
observation RealnameObservation
|
||||
gate RealnameResetGate
|
||||
wantAt *time.Time
|
||||
wantSource string
|
||||
wantHistory bool
|
||||
wantChange string
|
||||
wantChanged bool
|
||||
wantUpstream *time.Time
|
||||
}{
|
||||
{
|
||||
name: "每次轮询读到相同上游时间不写",
|
||||
snapshot: RealnameTimeSnapshot{Exists: true, RealnameAt: at("2026-07-16 19:43:39"), RealnameAtSource: constants.RealnameAtSourceUpstream,
|
||||
UpstreamRealnameAt: at("2026-07-16 19:43:39"), FirstObservedAt: at("2026-07-16 20:03:25")},
|
||||
observation: verifiedObservation(polling, at("2026-11-08 17:10:51"), at("2026-07-16 19:43:39")),
|
||||
wantAt: at("2026-07-16 19:43:39"), wantSource: constants.RealnameAtSourceUpstream,
|
||||
wantUpstream: at("2026-07-16 19:43:39"),
|
||||
},
|
||||
{
|
||||
name: "上游更正迁移时间",
|
||||
snapshot: RealnameTimeSnapshot{Exists: true, RealnameAt: at("2026-07-16 20:03:25"), RealnameAtSource: constants.RealnameAtSourceMigrated,
|
||||
FirstObservedAt: at("2026-07-16 20:03:25")},
|
||||
observation: verifiedObservation(polling, at("2026-11-08 17:10:51"), at("2026-07-16 19:43:39")),
|
||||
wantAt: at("2026-07-16 19:43:39"), wantSource: constants.RealnameAtSourceUpstream,
|
||||
wantHistory: true, wantChange: constants.RealnameChangeUpstreamFix, wantChanged: true, wantUpstream: at("2026-07-16 19:43:39"),
|
||||
},
|
||||
{
|
||||
name: "不返回时间的运营商首次实名",
|
||||
snapshot: RealnameTimeSnapshot{},
|
||||
observation: verifiedObservation(polling, at("2026-11-08 10:00:00"), nil),
|
||||
wantAt: at("2026-11-08 10:00:00"), wantSource: constants.RealnameAtSourceFirstObserved,
|
||||
wantHistory: true, wantChange: constants.RealnameChangeFirst, wantChanged: true,
|
||||
},
|
||||
{
|
||||
name: "不返回时间的运营商再次读到不写",
|
||||
snapshot: RealnameTimeSnapshot{Exists: true, RealnameAt: at("2026-11-08 10:00:00"), RealnameAtSource: constants.RealnameAtSourceFirstObserved,
|
||||
FirstObservedAt: at("2026-11-08 10:00:00")},
|
||||
observation: verifiedObservation(polling, at("2026-11-08 12:00:00"), nil),
|
||||
wantAt: at("2026-11-08 10:00:00"), wantSource: constants.RealnameAtSourceFirstObserved,
|
||||
},
|
||||
{
|
||||
name: "迁移沿用的时间在无上游时间时保持",
|
||||
snapshot: RealnameTimeSnapshot{Exists: true, RealnameAt: at("2026-09-01 10:00:00"), RealnameAtSource: constants.RealnameAtSourceMigrated,
|
||||
FirstObservedAt: at("2026-09-01 10:00:00")},
|
||||
observation: verifiedObservation(polling, at("2026-11-08 12:00:00"), nil),
|
||||
wantAt: at("2026-09-01 10:00:00"), wantSource: constants.RealnameAtSourceMigrated,
|
||||
},
|
||||
{
|
||||
name: "已实名但无记录的老卡首次读到上游时间",
|
||||
snapshot: RealnameTimeSnapshot{},
|
||||
observation: verifiedObservation(polling, at("2026-11-09 00:10:00"), at("2026-08-01 09:00:00")),
|
||||
wantAt: at("2026-08-01 09:00:00"), wantSource: constants.RealnameAtSourceUpstream,
|
||||
wantHistory: true, wantChange: constants.RealnameChangeFirst, wantChanged: true, wantUpstream: at("2026-08-01 09:00:00"),
|
||||
},
|
||||
{
|
||||
name: "二次实名完成",
|
||||
snapshot: RealnameTimeSnapshot{Exists: true, RealnameAt: nil, RealnameAtSource: "", UpstreamRealnameAt: at("2026-07-16 19:43:39"),
|
||||
FirstObservedAt: at("2026-07-16 20:03:25"), ResetStatus: constants.RealnameResetStatusPending, ResetBaselineAt: at("2026-07-16 19:43:39")},
|
||||
observation: verifiedObservation(polling, at("2026-11-09 10:05:00"), at("2026-11-09 10:00:00")),
|
||||
gate: RealnameResetGateCompleted,
|
||||
wantAt: at("2026-11-09 10:00:00"), wantSource: constants.RealnameAtSourceUpstream,
|
||||
wantHistory: true, wantChange: constants.RealnameChangeResetCompleted, wantChanged: true, wantUpstream: at("2026-11-09 10:00:00"),
|
||||
},
|
||||
{
|
||||
name: "时间相同只是来源不同静默更正",
|
||||
snapshot: RealnameTimeSnapshot{Exists: true, RealnameAt: at("2026-07-16 19:43:39"), RealnameAtSource: constants.RealnameAtSourceMigrated,
|
||||
FirstObservedAt: at("2026-07-16 19:43:39")},
|
||||
observation: verifiedObservation(polling, at("2026-11-08 17:10:51"), at("2026-07-16 19:43:39")),
|
||||
wantAt: at("2026-07-16 19:43:39"), wantSource: constants.RealnameAtSourceUpstream, wantChanged: true,
|
||||
wantUpstream: at("2026-07-16 19:43:39"),
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
got := DecideRealnameTime(tc.snapshot, tc.observation, tc.gate)
|
||||
if !sameTime(got.RealnameAt, tc.wantAt) || got.Source != tc.wantSource {
|
||||
t.Fatalf("realname_at=%v source=%s, want %v %s", got.RealnameAt, got.Source, tc.wantAt, tc.wantSource)
|
||||
}
|
||||
if got.WriteHistory != tc.wantHistory || got.ChangeType != tc.wantChange {
|
||||
t.Fatalf("history=%v change=%s, want %v %s", got.WriteHistory, got.ChangeType, tc.wantHistory, tc.wantChange)
|
||||
}
|
||||
if got.Changed != tc.wantChanged {
|
||||
t.Fatalf("changed=%v, want %v", got.Changed, tc.wantChanged)
|
||||
}
|
||||
if tc.wantUpstream != nil && !sameTime(got.UpstreamRealnameAt, tc.wantUpstream) {
|
||||
t.Fatalf("upstream=%v, want %v", got.UpstreamRealnameAt, tc.wantUpstream)
|
||||
}
|
||||
if tc.gate == RealnameResetGateCompleted && !got.ClearReset {
|
||||
t.Fatal("reset completion must clear reset state")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestEvaluateRealnameResetGate(t *testing.T) {
|
||||
pending := RealnameTimeSnapshot{Exists: true, ResetStatus: constants.RealnameResetStatusPending, ResetBaselineAt: at("2026-07-16 19:43:39")}
|
||||
polling := constants.CardObservationSourcePolling
|
||||
now := at("2026-11-09 10:05:00")
|
||||
cases := []struct {
|
||||
name string
|
||||
snapshot RealnameTimeSnapshot
|
||||
observation RealnameObservation
|
||||
want RealnameResetGate
|
||||
}{
|
||||
{"不在等待", RealnameTimeSnapshot{Exists: true}, verifiedObservation(polling, now, nil), RealnameResetGateNone},
|
||||
{"读到旧实名", pending, verifiedObservation(polling, now, at("2026-07-16 19:43:39")), RealnameResetGateBlocked},
|
||||
{"读到更早实名", pending, verifiedObservation(polling, now, at("2026-07-01 00:00:00")), RealnameResetGateBlocked},
|
||||
{"没有上游时间", pending, verifiedObservation(polling, now, nil), RealnameResetGateBlocked},
|
||||
{"回调没有时间", pending, verifiedObservation(constants.CardObservationSourceCarrierCallback, now, nil), RealnameResetGateBlocked},
|
||||
{"新实名", pending, verifiedObservation(polling, now, at("2026-11-09 10:00:00")), RealnameResetGateCompleted},
|
||||
{"人工改为已实名", pending, verifiedObservation(constants.CardObservationSourceManualOverride, now, nil), RealnameResetGateCompleted},
|
||||
{"未实名观测", pending, RealnameObservation{CardID: 1, Metadata: ObservationMetadata{Source: polling, ObservedAt: *now}}, RealnameResetGateNone},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if got := EvaluateRealnameResetGate(tc.snapshot, tc.observation); got != tc.want {
|
||||
t.Fatalf("got %v, want %v", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,32 @@ type TrafficObservation struct {
|
||||
ReadingResult string
|
||||
ResetDay int
|
||||
Metadata ObservationMetadata
|
||||
// Raw 是本次网关调用的原始请求与响应,未收集时为 nil。
|
||||
Raw *GatewayRaw
|
||||
// Failure 是读数结果非 ok 时的失败详情,未提供时为 nil。
|
||||
Failure *CollectionFailure
|
||||
// ICCID、CarrierID 是调用方已知的卡标识,写采集失败记录时直接使用;为空时由观测用例查库补齐。
|
||||
ICCID string
|
||||
CarrierID uint
|
||||
}
|
||||
|
||||
// GatewayRaw 是一次网关调用的原始数据(最后一次 HTTP 尝试),只含明文业务请求与网关响应。
|
||||
type GatewayRaw struct {
|
||||
Request []byte
|
||||
HTTPStatus int
|
||||
Response []byte
|
||||
GatewayCode *int
|
||||
GatewayMsg string
|
||||
TraceID string
|
||||
Attempts int
|
||||
}
|
||||
|
||||
// CollectionFailure 是一次采集失败的错误详情。
|
||||
type CollectionFailure struct {
|
||||
ErrorCategory string
|
||||
ProviderCode string
|
||||
ProviderMessage string
|
||||
DurationMS int
|
||||
}
|
||||
|
||||
// TrafficDecision 描述一次流量观测的处理结果。
|
||||
|
||||
@@ -61,7 +61,7 @@ func (s *IotCardDataSource) Fetch(ctx context.Context, params ExportParams, offs
|
||||
COALESCE(d.device_name, '') AS device_name,
|
||||
c.real_name_status,
|
||||
c.enable_polling,
|
||||
c.first_realname_at,
|
||||
CASE WHEN rn.id IS NULL THEN c.first_realname_at ELSE rn.realname_at END AS first_realname_at,
|
||||
c.first_purchase_at,
|
||||
c.network_status,
|
||||
COALESCE(pkg.package_name, '') AS package_name,
|
||||
@@ -169,6 +169,7 @@ func (s *IotCardDataSource) baseQuery(ctx context.Context) *gorm.DB {
|
||||
return s.db.WithContext(ctx).
|
||||
Table("tb_iot_card AS c").
|
||||
Joins("LEFT JOIN tb_shop AS sh ON sh.id = c.shop_id").
|
||||
Joins("LEFT JOIN tb_iot_card_realname AS rn ON rn.card_id = c.id").
|
||||
Joins(`
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT d.device_name
|
||||
|
||||
@@ -114,6 +114,10 @@ func (c *Client) doRequest(ctx context.Context, path string, params interface{})
|
||||
return nil, errors.Wrap(errors.CodeInternalError, err, "序列化业务数据失败")
|
||||
}
|
||||
|
||||
if capture := rawCaptureFrom(ctx); capture != nil {
|
||||
capture.Request = append(json.RawMessage(nil), dataBytes...)
|
||||
}
|
||||
|
||||
// 加密业务数据(加密结果不变,可在重试间复用)
|
||||
encryptedData, err := aesEncrypt(dataBytes, c.appSecret)
|
||||
if err != nil {
|
||||
@@ -184,8 +188,13 @@ func (c *Client) executeWithRetry(ctx context.Context, path, encryptedData strin
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
capture := rawCaptureFrom(ctx)
|
||||
if capture != nil {
|
||||
capture.resetResponse()
|
||||
capture.Attempts = attemptNumber
|
||||
}
|
||||
attemptStartedAt := time.Now()
|
||||
result, retryable, err := c.executeHTTPRequest(ctx, path, encryptedData)
|
||||
result, retryable, err := c.executeHTTPRequest(ctx, path, encryptedData, capture != nil && logPayload)
|
||||
attemptDuration := time.Since(attemptStartedAt)
|
||||
if gwErr, ok := AsGatewayError(err); ok {
|
||||
gwErr.Duration = attemptDuration
|
||||
@@ -237,7 +246,12 @@ func (c *Client) executeWithRetry(ctx context.Context, path, encryptedData strin
|
||||
|
||||
// executeHTTPRequest 执行单次 HTTP 请求(无重试逻辑)
|
||||
// 返回值:响应数据、是否可重试、错误
|
||||
func (c *Client) executeHTTPRequest(ctx context.Context, path string, encryptedData string) (json.RawMessage, bool, error) {
|
||||
// captureRaw 为 true 时把状态码、响应体与外层字段写入上下文上的原始数据收集器。
|
||||
func (c *Client) executeHTTPRequest(ctx context.Context, path string, encryptedData string, captureRaw bool) (json.RawMessage, bool, error) {
|
||||
var capture *RawCapture
|
||||
if captureRaw {
|
||||
capture = rawCaptureFrom(ctx)
|
||||
}
|
||||
// 每次重试使用新的时间戳和签名
|
||||
timestamp := time.Now().Unix()
|
||||
sign := generateSign(c.appID, encryptedData, timestamp, c.appSecret)
|
||||
@@ -277,6 +291,9 @@ func (c *Client) executeHTTPRequest(ctx context.Context, path string, encryptedD
|
||||
return nil, true, newGatewayError(constants.GatewayErrorNetwork, errors.Wrap(errors.CodeGatewayError, err, "发送 HTTP 请求失败"))
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if capture != nil {
|
||||
capture.HTTPStatus = resp.StatusCode
|
||||
}
|
||||
|
||||
// HTTP 状态码错误 — 不可重试
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
@@ -290,10 +307,18 @@ func (c *Client) executeHTTPRequest(ctx context.Context, path string, encryptedD
|
||||
return nil, false, newGatewayError(constants.GatewayErrorInvalidResponse, errors.Wrap(errors.CodeGatewayInvalidResp, err, "读取响应体失败"))
|
||||
}
|
||||
|
||||
if capture != nil {
|
||||
capture.Response = body
|
||||
}
|
||||
|
||||
var gatewayResp GatewayResponse
|
||||
if err := sonic.Unmarshal(body, &gatewayResp); err != nil {
|
||||
return nil, false, newGatewayError(constants.GatewayErrorInvalidResponse, errors.Wrap(errors.CodeGatewayInvalidResp, err, "解析 Gateway 响应失败"))
|
||||
}
|
||||
if capture != nil {
|
||||
code := gatewayResp.Code
|
||||
capture.GatewayCode, capture.GatewayMsg, capture.TraceID = &code, gatewayResp.Msg, gatewayResp.TraceID
|
||||
}
|
||||
|
||||
// Gateway 业务错误 — 不可重试
|
||||
if gatewayResp.Code != gatewaySuccessCode {
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"encoding/json"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// FlexBool 灵活布尔类型
|
||||
@@ -206,8 +207,17 @@ type CardOperationReq struct {
|
||||
|
||||
// RealnameStatusResp 是实名认证状态的响应
|
||||
type RealnameStatusResp struct {
|
||||
ICCID string `json:"iccid" description:"ICCID"`
|
||||
RealStatus bool `json:"realStatus" description:"实名状态(true=已实名, false=未实名)"`
|
||||
ICCID string `json:"iccid" description:"ICCID"`
|
||||
RealStatus bool `json:"realStatus" description:"实名状态(true=已实名, false=未实名)"`
|
||||
ArchiveTime *string `json:"archiveTime,omitempty" description:"上游实名时间(YYYY-MM-DD HH:mm:ss,北京时间;部分运营商不返回)"`
|
||||
}
|
||||
|
||||
// UpstreamRealnameAt 返回上游实名时间:仅已实名且 archiveTime 可解析时有值;缺失、空、格式错误或未实名时返回 nil。
|
||||
func (r *RealnameStatusResp) UpstreamRealnameAt() *time.Time {
|
||||
if r == nil || !r.RealStatus || r.ArchiveTime == nil {
|
||||
return nil
|
||||
}
|
||||
return parseUpstreamTime(*r.ArchiveTime)
|
||||
}
|
||||
|
||||
// RealnameLinkResp 是实名认证链接的响应
|
||||
|
||||
44
internal/gateway/raw_capture.go
Normal file
44
internal/gateway/raw_capture.go
Normal file
@@ -0,0 +1,44 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
)
|
||||
|
||||
// RawCapture 收集一次网关调用的原始数据(最后一次 HTTP 尝试),供业务记录留存。
|
||||
// 只保存加密前的明文业务请求与网关响应;不含加密报文、签名、应用标识、密钥与请求头。
|
||||
type RawCapture struct {
|
||||
// Request 是加密前的明文业务请求({"params": ...});不记录载荷的调用为空。
|
||||
Request json.RawMessage
|
||||
// HTTPStatus 是 HTTP 状态码;没拿到响应(超时、连接失败)时为 0。
|
||||
HTTPStatus int
|
||||
// Response 是网关原始响应体;没拿到响应体时为空。
|
||||
Response []byte
|
||||
// GatewayCode、GatewayMsg、TraceID 是网关响应外层字段;响应无法解析时为空。
|
||||
GatewayCode *int
|
||||
GatewayMsg string
|
||||
TraceID string
|
||||
// Attempts 是网关客户端内部 HTTP 尝试次数。
|
||||
Attempts int
|
||||
}
|
||||
|
||||
type rawCaptureKey struct{}
|
||||
|
||||
// WithRawCapture 在请求上下文上挂载原始数据收集器;未挂载的调用不收集。
|
||||
func WithRawCapture(ctx context.Context) (context.Context, *RawCapture) {
|
||||
capture := &RawCapture{}
|
||||
return context.WithValue(ctx, rawCaptureKey{}, capture), capture
|
||||
}
|
||||
|
||||
func rawCaptureFrom(ctx context.Context) *RawCapture {
|
||||
capture, _ := ctx.Value(rawCaptureKey{}).(*RawCapture)
|
||||
return capture
|
||||
}
|
||||
|
||||
// resetResponse 在每次 HTTP 尝试前清空上一次的响应,保证留存的是最后一次尝试。
|
||||
func (c *RawCapture) resetResponse() {
|
||||
if c == nil {
|
||||
return
|
||||
}
|
||||
c.HTTPStatus, c.Response, c.GatewayCode, c.GatewayMsg, c.TraceID = 0, nil, nil, "", ""
|
||||
}
|
||||
25
internal/gateway/upstream_time.go
Normal file
25
internal/gateway/upstream_time.go
Normal file
@@ -0,0 +1,25 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// upstreamLocation 是上游时间字段的时区(北京时间,固定 +08:00,不依赖系统时区数据库)。
|
||||
var upstreamLocation = time.FixedZone("CST", 8*3600)
|
||||
|
||||
var upstreamTimeLayouts = []string{"2006-01-02 15:04:05", "2006-01-02T15:04:05", "2006/01/02 15:04:05"}
|
||||
|
||||
// parseUpstreamTime 按北京时间解析上游时间字符串,空或无法解析返回 nil。
|
||||
func parseUpstreamTime(raw string) *time.Time {
|
||||
value := strings.TrimSpace(raw)
|
||||
if value == "" || strings.EqualFold(value, "null") {
|
||||
return nil
|
||||
}
|
||||
for _, layout := range upstreamTimeLayouts {
|
||||
if parsed, err := time.ParseInLocation(layout, value, upstreamLocation); err == nil {
|
||||
return &parsed
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
42
internal/gateway/upstream_time_test.go
Normal file
42
internal/gateway/upstream_time_test.go
Normal file
@@ -0,0 +1,42 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestRealnameStatusRespUpstreamRealnameAt(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
body string
|
||||
want string
|
||||
}{
|
||||
{"移动返回实名时间", `{"archiveTime":"2026-07-16 19:43:39","iccid":"89860885192590574640","realStatus":true}`, "2026-07-16T19:43:39+08:00"},
|
||||
{"电信不返回", `{"iccid":"8986112520903884400","realStatus":true}`, ""},
|
||||
{"联通 extend 无时间", `{"extend":"已实名","iccid":"89860625750010460562","realStatus":true}`, ""},
|
||||
{"未实名 null", `{"archiveTime":null,"iccid":"898608851925D1284902","realStatus":false}`, ""},
|
||||
{"未实名但带时间忽略", `{"archiveTime":"2026-07-16 19:43:39","realStatus":false}`, ""},
|
||||
{"空串", `{"archiveTime":"","realStatus":true}`, ""},
|
||||
{"格式错误", `{"archiveTime":"07/16/2026","realStatus":true}`, ""},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var resp RealnameStatusResp
|
||||
if err := json.Unmarshal([]byte(tc.body), &resp); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
got := resp.UpstreamRealnameAt()
|
||||
if tc.want == "" {
|
||||
if got != nil {
|
||||
t.Fatalf("want nil, got %v", got)
|
||||
}
|
||||
return
|
||||
}
|
||||
want, _ := time.Parse(time.RFC3339, tc.want)
|
||||
if got == nil || !got.Equal(want) {
|
||||
t.Fatalf("want %v, got %v", want, got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
128
internal/handler/admin/card_realname.go
Normal file
128
internal/handler/admin/card_realname.go
Normal file
@@ -0,0 +1,128 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"github.com/go-playground/validator/v10"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/application/realnamereset"
|
||||
"github.com/break/junhong_cmp_fiber/internal/model/dto"
|
||||
"github.com/break/junhong_cmp_fiber/internal/query/cardrealname"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/errors"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/response"
|
||||
)
|
||||
|
||||
// CardRealnameHandler 处理卡实名记录与二次实名批次。
|
||||
type CardRealnameHandler struct {
|
||||
reset *realnamereset.Service
|
||||
query *cardrealname.Query
|
||||
validator *validator.Validate
|
||||
}
|
||||
|
||||
// NewCardRealnameHandler 创建卡实名记录处理器。
|
||||
func NewCardRealnameHandler(reset *realnamereset.Service, query *cardrealname.Query, validate *validator.Validate) *CardRealnameHandler {
|
||||
if validate == nil {
|
||||
validate = validator.New()
|
||||
}
|
||||
return &CardRealnameHandler{reset: reset, query: query, validator: validate}
|
||||
}
|
||||
|
||||
func (h *CardRealnameHandler) validate(prefix string, req any) error {
|
||||
if err := h.validator.Struct(req); err != nil {
|
||||
return errors.New(errors.CodeInvalidParam, validationMessage(prefix, req, err))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CardHistory 查询单卡当前实名时间与实名时间历史。
|
||||
// GET /api/admin/iot-cards/:id/realname-history
|
||||
func (h *CardRealnameHandler) CardHistory(c *fiber.Ctx) error {
|
||||
var req dto.CardRealnameHistoryListRequest
|
||||
if err := c.QueryParser(&req); err != nil {
|
||||
return errors.New(errors.CodeInvalidParam, "请求参数解析失败")
|
||||
}
|
||||
id, err := rateLimitPathID(c, "id", "IoT 卡 ID")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.ID = id
|
||||
if err := h.validate("实名记录查询参数不合法", &req); err != nil {
|
||||
return err
|
||||
}
|
||||
result, err := h.query.CardHistory(c.UserContext(), req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return response.Success(c, result)
|
||||
}
|
||||
|
||||
// ImportResetBatch 导入二次实名名单。
|
||||
// POST /api/admin/realname-reset/batches
|
||||
func (h *CardRealnameHandler) ImportResetBatch(c *fiber.Ctx) error {
|
||||
var req dto.RealnameResetImportRequest
|
||||
if err := c.BodyParser(&req); err != nil {
|
||||
return errors.New(errors.CodeInvalidParam, "请求参数解析失败")
|
||||
}
|
||||
if err := h.validate("二次实名导入参数不合法", &req); err != nil {
|
||||
return err
|
||||
}
|
||||
result, err := h.reset.Import(c.UserContext(), req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return response.Success(c, result)
|
||||
}
|
||||
|
||||
// ListResetBatches 分页查询二次实名批次。
|
||||
// GET /api/admin/realname-reset/batches
|
||||
func (h *CardRealnameHandler) ListResetBatches(c *fiber.Ctx) error {
|
||||
var req dto.RealnameResetBatchListRequest
|
||||
if err := c.QueryParser(&req); err != nil {
|
||||
return errors.New(errors.CodeInvalidParam, "请求参数解析失败")
|
||||
}
|
||||
if err := h.validate("二次实名批次查询参数不合法", &req); err != nil {
|
||||
return err
|
||||
}
|
||||
list, total, page, size, err := h.query.ListResetBatches(c.UserContext(), req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return response.SuccessWithPagination(c, list, total, page, size)
|
||||
}
|
||||
|
||||
// GetResetBatch 查询二次实名批次详情。
|
||||
// GET /api/admin/realname-reset/batches/:id
|
||||
func (h *CardRealnameHandler) GetResetBatch(c *fiber.Ctx) error {
|
||||
id, err := rateLimitPathID(c, "id", "批次 ID")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
result, err := h.query.GetResetBatch(c.UserContext(), id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return response.Success(c, result)
|
||||
}
|
||||
|
||||
// RevertResetBatch 撤销批次中仍在等待二次实名的卡。
|
||||
// POST /api/admin/realname-reset/batches/:id/revert
|
||||
func (h *CardRealnameHandler) RevertResetBatch(c *fiber.Ctx) error {
|
||||
var req dto.RealnameResetRevertRequest
|
||||
if len(c.Body()) > 0 {
|
||||
if err := c.BodyParser(&req); err != nil {
|
||||
return errors.New(errors.CodeInvalidParam, "请求参数解析失败")
|
||||
}
|
||||
}
|
||||
id, err := rateLimitPathID(c, "id", "批次 ID")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.ID = id
|
||||
if err := h.validate("二次实名撤销参数不合法", &req); err != nil {
|
||||
return err
|
||||
}
|
||||
result, err := h.reset.Revert(c.UserContext(), req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return response.Success(c, result)
|
||||
}
|
||||
@@ -259,6 +259,31 @@ func (h *PackageSilenceHandler) GetOrder(c *fiber.Ctx) error {
|
||||
return response.Success(c, result)
|
||||
}
|
||||
|
||||
// CloseOrder 作废待支付的延期订单。POST /api/admin/package-silence/orders/:id/close
|
||||
func (h *PackageSilenceHandler) CloseOrder(c *fiber.Ctx) error {
|
||||
id, err := silencePathID(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var req dto.SilenceOrderCancelRequest
|
||||
if len(c.Body()) > 0 {
|
||||
if err := h.bindBody(c, "作废参数不合法", &req); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
// 先按数据范围查详情:看不到的订单不能作废
|
||||
if _, err := h.query.GetOrder(c.UserContext(), id, 0); err != nil {
|
||||
return err
|
||||
}
|
||||
result, err := h.extensions.CancelPendingOrder(c.UserContext(), packagesilenceapp.CancelOrderCommand{
|
||||
OrderID: id, Reason: req.Reason,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return response.Success(c, result)
|
||||
}
|
||||
|
||||
// SubmitSpecial 提交特殊延期(单个 / 批量)。POST /api/admin/package-silence/special
|
||||
func (h *PackageSilenceHandler) SubmitSpecial(c *fiber.Ctx) error {
|
||||
var req dto.SilenceSpecialRequest
|
||||
|
||||
@@ -37,7 +37,12 @@ func (h *PackageUsageHandler) GetDailyRecords(c *fiber.Ctx) error {
|
||||
endDate := c.Query("end_date", "")
|
||||
|
||||
// 任务 16.4: 调用 DailyRecordService.GetDailyRecords 获取日记录
|
||||
records, err := h.dailyRecordService.GetDailyRecords(c.UserContext(), uint(id), startDate, endDate)
|
||||
page := c.QueryInt("page", 0)
|
||||
pageSize := c.QueryInt("page_size", 0)
|
||||
if page < 0 || pageSize < 0 || pageSize > 100 {
|
||||
return errors.New(errors.CodeInvalidParam, "分页参数不合法,page_size 最大 100")
|
||||
}
|
||||
records, err := h.dailyRecordService.GetDailyRecords(c.UserContext(), uint(id), startDate, endDate, page, pageSize)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
94
internal/handler/admin/record_query.go
Normal file
94
internal/handler/admin/record_query.go
Normal file
@@ -0,0 +1,94 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"github.com/gofiber/fiber/v2"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/handler/validation"
|
||||
"github.com/break/junhong_cmp_fiber/internal/model/dto"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/errors"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/response"
|
||||
)
|
||||
|
||||
// parseRecordQuery 解析并校验记录查询参数。
|
||||
func (h *AssetHandler) parseRecordQuery(c *fiber.Ctx, req any, label string) error {
|
||||
if err := rejectEnterpriseAssetAdmin(c); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := c.QueryParser(req); err != nil {
|
||||
return errors.New(errors.CodeInvalidParam, "请求参数格式不正确")
|
||||
}
|
||||
if err := h.validator.Struct(req); err != nil {
|
||||
return errors.New(errors.CodeInvalidParam, validation.Message(label, req, err))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ListTrafficCollectionRecords 采集成功记录列表
|
||||
// GET /api/admin/traffic-collections
|
||||
func (h *AssetHandler) ListTrafficCollectionRecords(c *fiber.Ctx) error {
|
||||
var req dto.TrafficCollectionListRequest
|
||||
if err := h.parseRecordQuery(c, &req, "采集成功记录查询参数不合法"); err != nil {
|
||||
return err
|
||||
}
|
||||
result, err := h.assetService.ListTrafficCollectionRecords(c.UserContext(), &req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return response.Success(c, result)
|
||||
}
|
||||
|
||||
// ListTrafficCollectionFailures 采集失败记录列表
|
||||
// GET /api/admin/traffic-collection-failures
|
||||
func (h *AssetHandler) ListTrafficCollectionFailures(c *fiber.Ctx) error {
|
||||
var req dto.TrafficCollectionFailureListRequest
|
||||
if err := h.parseRecordQuery(c, &req, "采集失败记录查询参数不合法"); err != nil {
|
||||
return err
|
||||
}
|
||||
result, err := h.assetService.ListTrafficCollectionFailures(c.UserContext(), &req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return response.Success(c, result)
|
||||
}
|
||||
|
||||
// ListCardDailyUsages 卡日流量列表
|
||||
// GET /api/admin/card-daily-usages
|
||||
func (h *AssetHandler) ListCardDailyUsages(c *fiber.Ctx) error {
|
||||
var req dto.CardDailyUsageListRequest
|
||||
if err := h.parseRecordQuery(c, &req, "卡日流量查询参数不合法"); err != nil {
|
||||
return err
|
||||
}
|
||||
result, err := h.assetService.ListCardDailyUsages(c.UserContext(), &req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return response.Success(c, result)
|
||||
}
|
||||
|
||||
// ListPackageUsageDailyRecords 套餐日流量详单列表
|
||||
// GET /api/admin/package-usage-daily-records
|
||||
func (h *AssetHandler) ListPackageUsageDailyRecords(c *fiber.Ctx) error {
|
||||
var req dto.PackageUsageDailyRecordListRequest
|
||||
if err := h.parseRecordQuery(c, &req, "套餐日流量详单查询参数不合法"); err != nil {
|
||||
return err
|
||||
}
|
||||
result, err := h.assetService.ListPackageUsageDailyRecords(c.UserContext(), &req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return response.Success(c, result)
|
||||
}
|
||||
|
||||
// ListPackageTrafficAdjustmentRecords 套餐流量冲正流水列表
|
||||
// GET /api/admin/package-traffic-adjustments
|
||||
func (h *AssetHandler) ListPackageTrafficAdjustmentRecords(c *fiber.Ctx) error {
|
||||
var req dto.PackageTrafficAdjustmentQueryRequest
|
||||
if err := h.parseRecordQuery(c, &req, "冲正流水查询参数不合法"); err != nil {
|
||||
return err
|
||||
}
|
||||
result, err := h.assetService.ListPackageTrafficAdjustmentRecords(c.UserContext(), &req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return response.Success(c, result)
|
||||
}
|
||||
@@ -97,6 +97,37 @@ func (h *RefundHandler) RecoverApproval(c *fiber.Ctx) error {
|
||||
return response.Success(c, result)
|
||||
}
|
||||
|
||||
// RetryAssetPostProcessing 人工重试退款资产后处理
|
||||
// POST /api/admin/refunds/:id/asset-post-processing/retry
|
||||
func (h *RefundHandler) RetryAssetPostProcessing(c *fiber.Ctx) error {
|
||||
id, err := strconv.ParseUint(c.Params("id"), 10, 64)
|
||||
if err != nil || id == 0 {
|
||||
return errors.New(errors.CodeInvalidParam, "无效的退款申请ID")
|
||||
}
|
||||
result, err := h.service.RetryAssetPostProcessingByAdmin(c.UserContext(), uint(id))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return response.Success(c, result)
|
||||
}
|
||||
|
||||
// ListAssetPostProcessAttempts 退款资产后处理尝试记录列表
|
||||
// GET /api/admin/refund-post-process-attempts
|
||||
func (h *RefundHandler) ListAssetPostProcessAttempts(c *fiber.Ctx) error {
|
||||
var req dto.RefundPostProcessAttemptListRequest
|
||||
if err := c.QueryParser(&req); err != nil {
|
||||
return errors.New(errors.CodeInvalidParam, "请求参数格式不正确")
|
||||
}
|
||||
if req.StartTime == "" || req.EndTime == "" {
|
||||
return errors.New(errors.CodeInvalidParam, "开始时间与结束时间必填")
|
||||
}
|
||||
result, err := h.service.ListAssetPostProcessAttempts(c.UserContext(), &req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return response.Success(c, result)
|
||||
}
|
||||
|
||||
// Approve 审批通过退款申请
|
||||
// POST /api/admin/refunds/:id/approve
|
||||
func (h *RefundHandler) Approve(c *fiber.Ctx) error {
|
||||
|
||||
@@ -145,6 +145,31 @@ func (h *ClientPackageSilenceHandler) GetOrder(c *fiber.Ctx) error {
|
||||
return response.Success(c, result)
|
||||
}
|
||||
|
||||
// CancelOrder 客户作废自己未支付的延期订单。POST /api/c/v1/package-silence/orders/:id/cancel
|
||||
func (h *ClientPackageSilenceHandler) CancelOrder(c *fiber.Ctx) error {
|
||||
id, err := c.ParamsInt("id")
|
||||
if err != nil || id <= 0 {
|
||||
return errors.New(errors.CodeInvalidParam)
|
||||
}
|
||||
var req dto.SilenceOrderCancelRequest
|
||||
if len(c.Body()) > 0 {
|
||||
if err := c.BodyParser(&req); err != nil {
|
||||
return errors.New(errors.CodeInvalidParam)
|
||||
}
|
||||
}
|
||||
ctx, customerID, err := h.customerContext(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
result, err := h.extensions.CancelPendingOrder(ctx, packagesilenceapp.CancelOrderCommand{
|
||||
OrderID: uint(id), Scope: packagesilenceapp.Scope{CustomerID: customerID}, Reason: req.Reason,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return response.Success(c, result)
|
||||
}
|
||||
|
||||
// ListRecords 套餐沉默期流水。GET /api/c/v1/package-silence/records
|
||||
func (h *ClientPackageSilenceHandler) ListRecords(c *fiber.Ctx) error {
|
||||
var req dto.SilenceRecordListRequest
|
||||
|
||||
313
internal/infrastructure/cardobservation/collection_archive.go
Normal file
313
internal/infrastructure/cardobservation/collection_archive.go
Normal file
@@ -0,0 +1,313 @@
|
||||
package cardobservation
|
||||
|
||||
import (
|
||||
"compress/gzip"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"encoding/csv"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/stdlib"
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/domain/cardflow"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
)
|
||||
|
||||
// collectionArchiveTables 是按月分区、到期归档的采集记录父表。
|
||||
var collectionArchiveTables = []string{"tb_card_traffic_collection", "tb_card_traffic_collection_failure"}
|
||||
|
||||
// CollectionArchiver 维护采集记录月分区:预建未来分区;到期分区按"摘出 → 导出 csv.gz → 校验 → 删除"归档。
|
||||
// 导出或校验失败时保留已摘出的表,下一轮重试,不会出现数据已删但没有压缩包的情况。
|
||||
type CollectionArchiver struct {
|
||||
db *gorm.DB
|
||||
dir string
|
||||
keepFiles int
|
||||
aheadMonth int
|
||||
logger *zap.Logger
|
||||
}
|
||||
|
||||
// NewCollectionArchiver 创建采集记录归档器;dir 为压缩包目录,keepFiles 为每张表本地保留的压缩包个数。
|
||||
func NewCollectionArchiver(db *gorm.DB, dir string, keepFiles int, logger *zap.Logger) *CollectionArchiver {
|
||||
if logger == nil {
|
||||
logger = zap.NewNop()
|
||||
}
|
||||
if keepFiles <= 0 {
|
||||
keepFiles = constants.TrafficCollectionArchiveKeepFiles
|
||||
}
|
||||
return &CollectionArchiver{db: db, dir: dir, keepFiles: keepFiles, aheadMonth: 2, logger: logger}
|
||||
}
|
||||
|
||||
// archiveManifest 是压缩包同名说明文件内容。
|
||||
type archiveManifest struct {
|
||||
Table string `json:"table"`
|
||||
Partition string `json:"partition"`
|
||||
Month string `json:"month"`
|
||||
Rows int64 `json:"rows"`
|
||||
FirstObservedAt *string `json:"first_observed_at"`
|
||||
LastObservedAt *string `json:"last_observed_at"`
|
||||
File string `json:"file"`
|
||||
FileBytes int64 `json:"file_bytes"`
|
||||
SHA256 string `json:"sha256"`
|
||||
ExportedAt time.Time `json:"exported_at"`
|
||||
}
|
||||
|
||||
// Maintain 对全部采集记录表执行一轮分区维护;单张表失败不影响其他表,返回第一个错误。
|
||||
func (a *CollectionArchiver) Maintain(ctx context.Context, now time.Time) error {
|
||||
var firstErr error
|
||||
for _, table := range collectionArchiveTables {
|
||||
if err := a.maintainTable(ctx, table, now); err != nil {
|
||||
a.logger.Error("维护采集记录分区失败", zap.String("table", table), zap.Error(err))
|
||||
if firstErr == nil {
|
||||
firstErr = err
|
||||
}
|
||||
}
|
||||
}
|
||||
return firstErr
|
||||
}
|
||||
|
||||
func (a *CollectionArchiver) maintainTable(ctx context.Context, table string, now time.Time) error {
|
||||
monthStart := cardflow.MonthStart(now)
|
||||
for i := 0; i <= a.aheadMonth; i++ {
|
||||
from := monthStart.AddDate(0, i, 0)
|
||||
sqlText := fmt.Sprintf(`CREATE TABLE IF NOT EXISTS %s_%s PARTITION OF %s FOR VALUES FROM ('%s') TO ('%s')`,
|
||||
table, from.Format("200601"), table, from.Format(time.RFC3339), from.AddDate(0, 1, 0).Format(time.RFC3339))
|
||||
if err := a.db.WithContext(ctx).Exec(sqlText).Error; err != nil {
|
||||
return fmt.Errorf("预建分区失败: %w", err)
|
||||
}
|
||||
}
|
||||
// 在线保留当月加最近 N 个整月,更早的月分区到期。
|
||||
cutoff := monthStart.AddDate(0, -constants.TrafficCollectionRetentionMonths, 0)
|
||||
partitions, err := a.monthPartitions(ctx, table)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, partition := range partitions {
|
||||
if !partition.month.Before(cutoff) {
|
||||
continue
|
||||
}
|
||||
if err := a.archivePartition(ctx, table, partition); err != nil {
|
||||
return fmt.Errorf("归档分区 %s 失败: %w", partition.name, err)
|
||||
}
|
||||
}
|
||||
a.cleanupLocalFiles(table)
|
||||
return nil
|
||||
}
|
||||
|
||||
type monthPartition struct {
|
||||
name string
|
||||
month time.Time
|
||||
attached bool
|
||||
}
|
||||
|
||||
// monthPartitions 返回该表全部按月命名的分区(含上一轮已摘出未删除的表),按月份升序。
|
||||
func (a *CollectionArchiver) monthPartitions(ctx context.Context, table string) ([]monthPartition, error) {
|
||||
var rows []struct {
|
||||
Relname string
|
||||
Attached bool
|
||||
}
|
||||
err := a.db.WithContext(ctx).Raw(`
|
||||
SELECT c.relname, EXISTS (SELECT 1 FROM pg_inherits i JOIN pg_class p ON p.oid = i.inhparent
|
||||
WHERE i.inhrelid = c.oid AND p.relname = ?) AS attached
|
||||
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
|
||||
WHERE n.nspname = current_schema() AND c.relkind IN ('r', 'p') AND c.relname ~ ?`,
|
||||
table, "^"+table+`_[0-9]{6}$`).Scan(&rows).Error
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("查询分区失败: %w", err)
|
||||
}
|
||||
partitions := make([]monthPartition, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
month, err := time.ParseInLocation("200601", row.Relname[len(table)+1:], cardflow.MonthStart(time.Now()).Location())
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
partitions = append(partitions, monthPartition{name: row.Relname, month: month, attached: row.Attached})
|
||||
}
|
||||
sort.Slice(partitions, func(i, j int) bool { return partitions[i].month.Before(partitions[j].month) })
|
||||
return partitions, nil
|
||||
}
|
||||
|
||||
func (a *CollectionArchiver) archivePartition(ctx context.Context, table string, partition monthPartition) error {
|
||||
if partition.attached {
|
||||
if err := a.db.WithContext(ctx).Exec(fmt.Sprintf("ALTER TABLE %s DETACH PARTITION %s", table, partition.name)).Error; err != nil {
|
||||
return fmt.Errorf("摘出分区失败: %w", err)
|
||||
}
|
||||
}
|
||||
if err := os.MkdirAll(a.dir, 0o755); err != nil {
|
||||
return fmt.Errorf("创建归档目录失败: %w", err)
|
||||
}
|
||||
finalPath := filepath.Join(a.dir, partition.name+".csv.gz")
|
||||
tmpPath := finalPath + ".tmp"
|
||||
if err := a.exportCSV(ctx, partition.name, tmpPath); err != nil {
|
||||
_ = os.Remove(tmpPath)
|
||||
return err
|
||||
}
|
||||
manifest, err := a.verify(ctx, table, partition, tmpPath)
|
||||
if err != nil {
|
||||
_ = os.Remove(tmpPath)
|
||||
return err
|
||||
}
|
||||
manifest.File = filepath.Base(finalPath)
|
||||
if err := writeManifest(finalPath+".manifest.json", manifest); err != nil {
|
||||
_ = os.Remove(tmpPath)
|
||||
return err
|
||||
}
|
||||
if err := os.Rename(tmpPath, finalPath); err != nil {
|
||||
return fmt.Errorf("压缩包改名失败: %w", err)
|
||||
}
|
||||
if err := a.db.WithContext(ctx).Exec("DROP TABLE IF EXISTS " + partition.name).Error; err != nil {
|
||||
return fmt.Errorf("删除已归档分区失败: %w", err)
|
||||
}
|
||||
a.logger.Info("采集记录分区已归档", zap.String("partition", partition.name), zap.Int64("rows", manifest.Rows),
|
||||
zap.String("file", finalPath), zap.Int64("file_bytes", manifest.FileBytes))
|
||||
return nil
|
||||
}
|
||||
|
||||
// exportCSV 用 COPY 把分区按采集时间与 ID 排序流式导出为带表头的 CSV,并边写边 gzip。
|
||||
func (a *CollectionArchiver) exportCSV(ctx context.Context, partition, path string) error {
|
||||
file, err := os.Create(path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("创建压缩包失败: %w", err)
|
||||
}
|
||||
defer file.Close()
|
||||
gz := gzip.NewWriter(file)
|
||||
sqlDB, err := a.db.DB()
|
||||
if err != nil {
|
||||
return fmt.Errorf("获取数据库连接失败: %w", err)
|
||||
}
|
||||
conn, err := sqlDB.Conn(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("获取数据库连接失败: %w", err)
|
||||
}
|
||||
defer conn.Close()
|
||||
copySQL := fmt.Sprintf("COPY (SELECT * FROM %s ORDER BY observed_at, id) TO STDOUT WITH (FORMAT csv, HEADER)", partition)
|
||||
if err := rawCopyTo(ctx, conn, gz, copySQL); err != nil {
|
||||
return fmt.Errorf("导出分区失败: %w", err)
|
||||
}
|
||||
if err := gz.Close(); err != nil {
|
||||
return fmt.Errorf("写压缩包失败: %w", err)
|
||||
}
|
||||
if err := file.Sync(); err != nil {
|
||||
return fmt.Errorf("落盘压缩包失败: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func rawCopyTo(ctx context.Context, conn *sql.Conn, w io.Writer, copySQL string) error {
|
||||
return conn.Raw(func(driverConn any) error {
|
||||
stdConn, ok := driverConn.(*stdlib.Conn)
|
||||
if !ok {
|
||||
return fmt.Errorf("数据库驱动不支持 COPY 导出")
|
||||
}
|
||||
_, err := stdConn.Conn().PgConn().CopyTo(ctx, w, copySQL)
|
||||
return err
|
||||
})
|
||||
}
|
||||
|
||||
// verify 重新读取压缩包统计行数并与分区行数比对,生成说明文件内容。
|
||||
func (a *CollectionArchiver) verify(ctx context.Context, table string, partition monthPartition, path string) (archiveManifest, error) {
|
||||
var stats struct {
|
||||
Rows int64
|
||||
First *time.Time
|
||||
Last *time.Time
|
||||
}
|
||||
if err := a.db.WithContext(ctx).Raw(fmt.Sprintf(
|
||||
"SELECT count(*) AS rows, min(observed_at) AS first, max(observed_at) AS last FROM %s", partition.name)).Scan(&stats).Error; err != nil {
|
||||
return archiveManifest{}, fmt.Errorf("统计分区行数失败: %w", err)
|
||||
}
|
||||
fileRows, sum, size, err := countArchiveRows(path)
|
||||
if err != nil {
|
||||
return archiveManifest{}, err
|
||||
}
|
||||
if fileRows != stats.Rows {
|
||||
return archiveManifest{}, fmt.Errorf("压缩包行数 %d 与分区行数 %d 不一致", fileRows, stats.Rows)
|
||||
}
|
||||
manifest := archiveManifest{
|
||||
Table: table, Partition: partition.name, Month: partition.month.Format("2006-01"), Rows: stats.Rows,
|
||||
FileBytes: size, SHA256: sum, ExportedAt: time.Now(),
|
||||
}
|
||||
if stats.First != nil {
|
||||
first, last := stats.First.Format(time.RFC3339), stats.Last.Format(time.RFC3339)
|
||||
manifest.FirstObservedAt, manifest.LastObservedAt = &first, &last
|
||||
}
|
||||
return manifest, nil
|
||||
}
|
||||
|
||||
// countArchiveRows 解压并按 CSV 解析压缩包,返回数据行数(不含表头)、文件 SHA-256 与文件大小。
|
||||
func countArchiveRows(path string) (int64, string, int64, error) {
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
return 0, "", 0, fmt.Errorf("打开压缩包失败: %w", err)
|
||||
}
|
||||
defer file.Close()
|
||||
hash := sha256.New()
|
||||
gz, err := gzip.NewReader(io.TeeReader(file, hash))
|
||||
if err != nil {
|
||||
return 0, "", 0, fmt.Errorf("读取压缩包失败: %w", err)
|
||||
}
|
||||
reader := csv.NewReader(gz)
|
||||
reader.FieldsPerRecord = -1
|
||||
reader.ReuseRecord = true
|
||||
var records int64
|
||||
for {
|
||||
if _, err := reader.Read(); err == io.EOF {
|
||||
break
|
||||
} else if err != nil {
|
||||
return 0, "", 0, fmt.Errorf("解析压缩包失败: %w", err)
|
||||
}
|
||||
records++
|
||||
}
|
||||
if _, err := io.Copy(io.Discard, gz); err != nil {
|
||||
return 0, "", 0, fmt.Errorf("读取压缩包失败: %w", err)
|
||||
}
|
||||
info, err := file.Stat()
|
||||
if err != nil {
|
||||
return 0, "", 0, fmt.Errorf("读取压缩包大小失败: %w", err)
|
||||
}
|
||||
if records > 0 {
|
||||
records-- // 表头
|
||||
}
|
||||
return records, hex.EncodeToString(hash.Sum(nil)), info.Size(), nil
|
||||
}
|
||||
|
||||
func writeManifest(path string, manifest archiveManifest) error {
|
||||
data, err := json.MarshalIndent(manifest, "", " ")
|
||||
if err != nil {
|
||||
return fmt.Errorf("生成说明文件失败: %w", err)
|
||||
}
|
||||
tmp := path + ".tmp"
|
||||
if err := os.WriteFile(tmp, append(data, '\n'), 0o644); err != nil {
|
||||
return fmt.Errorf("写说明文件失败: %w", err)
|
||||
}
|
||||
if err := os.Rename(tmp, path); err != nil {
|
||||
return fmt.Errorf("说明文件改名失败: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// cleanupLocalFiles 每张表只保留最近 keepFiles 个月的压缩包与说明文件。
|
||||
func (a *CollectionArchiver) cleanupLocalFiles(table string) {
|
||||
matches, err := filepath.Glob(filepath.Join(a.dir, table+"_[0-9][0-9][0-9][0-9][0-9][0-9].csv.gz"))
|
||||
if err != nil || len(matches) <= a.keepFiles {
|
||||
return
|
||||
}
|
||||
sort.Strings(matches)
|
||||
for _, path := range matches[:len(matches)-a.keepFiles] {
|
||||
if err := os.Remove(path); err != nil {
|
||||
a.logger.Warn("删除过期采集记录压缩包失败", zap.String("file", path), zap.Error(err))
|
||||
continue
|
||||
}
|
||||
_ = os.Remove(path + ".manifest.json")
|
||||
a.logger.Info("已删除过期采集记录压缩包", zap.String("file", strings.TrimPrefix(path, a.dir+"/")))
|
||||
}
|
||||
}
|
||||
@@ -475,10 +475,11 @@ func (r *SeriesRunner) loadCurrentICCIDs(ctx context.Context, payload cardapp.Se
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// 显式列名:GORM 默认把 ICCID 映射成 icc_id,不写 tag 时三个值都读不到,本地预期判定永远不成立。
|
||||
var current struct {
|
||||
ICCID string
|
||||
ICCID19 string
|
||||
ICCID20 *string
|
||||
ICCID string `gorm:"column:iccid"`
|
||||
ICCID19 string `gorm:"column:iccid_19"`
|
||||
ICCID20 *string `gorm:"column:iccid_20"`
|
||||
}
|
||||
err = r.db.WithContext(ctx).Table("tb_device_sim_binding AS binding").
|
||||
Select("card.iccid, card.iccid_19, card.iccid_20").
|
||||
@@ -550,7 +551,7 @@ func (r *SeriesRunner) queryAndApply(ctx context.Context, payload cardapp.Series
|
||||
if err != nil {
|
||||
return cardapp.RunResult{}, err
|
||||
}
|
||||
decision, err := r.observation.ApplyCardObservation(ctx, carddomain.RealnameObservation{CardID: card.ID, Verified: response.RealStatus, Metadata: metadata})
|
||||
decision, err := r.observation.ApplyCardObservation(ctx, carddomain.RealnameObservation{CardID: card.ID, Verified: response.RealStatus, UpstreamRealnameAt: response.UpstreamRealnameAt(), Metadata: metadata})
|
||||
return cardapp.RunResult{StateChanged: decision.StatusChanged}, err
|
||||
case constants.CardObservationSyncTypeTraffic:
|
||||
response, err := r.gateway.QueryFlow(ctx, &gateway.FlowQueryReq{CardNo: card.ICCID})
|
||||
|
||||
@@ -133,14 +133,16 @@ func RecoverRefundPostProcessing(ctx context.Context, db *gorm.DB, repository *o
|
||||
}
|
||||
refundStats := RecoveryStats{}
|
||||
var refunds []model.RefundRequest
|
||||
if err := db.WithContext(ctx).Where("status = ? AND (commission_deducted = ? OR asset_reset = ?)", model.RefundStatusApproved, false, false).Order("id ASC").Limit(limit).Find(&refunds).Error; err != nil {
|
||||
// 需人工处理与未到下次重试时间的资产后处理不参与扫描,避免长期失败的退款单占满每轮名额。
|
||||
if err := db.WithContext(ctx).Where("status = ? AND (commission_deducted = ? OR (asset_reset = ? AND asset_post_status <> ? AND (asset_post_next_at IS NULL OR asset_post_next_at <= ?)))",
|
||||
model.RefundStatusApproved, false, false, model.RefundAssetPostManualRequired, time.Now()).Order("id ASC").Limit(limit).Find(&refunds).Error; err != nil {
|
||||
logger.Warn("扫描退款后处理失败", zap.Error(err))
|
||||
} else {
|
||||
for _, refund := range refunds {
|
||||
if !refund.CommissionDeducted {
|
||||
recoverOne(ctx, db, repository, EventRefundCommissionDeduct, refund.ID, refund.OrderID, &refundStats, logger, true)
|
||||
}
|
||||
if !refund.AssetReset {
|
||||
if !refund.AssetReset && assetPostDue(refund, time.Now()) {
|
||||
recoverOne(ctx, db, repository, EventRefundAssetProcess, refund.ID, refund.OrderID, &refundStats, logger, true)
|
||||
}
|
||||
}
|
||||
@@ -148,6 +150,14 @@ func RecoverRefundPostProcessing(ctx context.Context, db *gorm.DB, repository *o
|
||||
return refundStats
|
||||
}
|
||||
|
||||
// assetPostDue 判断退款资产后处理是否到了可自动重试的时间:需人工处理的不重投,未到下次重试时间的不重投。
|
||||
func assetPostDue(refund model.RefundRequest, now time.Time) bool {
|
||||
if refund.AssetPostStatus == model.RefundAssetPostManualRequired {
|
||||
return false
|
||||
}
|
||||
return refund.AssetPostNextAt == nil || !refund.AssetPostNextAt.After(now)
|
||||
}
|
||||
|
||||
func recoverOne(ctx context.Context, db *gorm.DB, repository *outbox.Repository, eventType string, aggregateID, orderID uint, stats *RecoveryStats, logger *zap.Logger, retryDelivered bool) {
|
||||
eventID := outboxid.Stable(eventType+":", strconv.FormatUint(uint64(aggregateID), 10))
|
||||
var event model.OutboxEvent
|
||||
|
||||
@@ -26,6 +26,8 @@ type StopResumeRecordInput struct {
|
||||
Attempt int
|
||||
CallErr error
|
||||
Duration time.Duration
|
||||
// SkipReason 非空表示指令在调用上游前结束(已是目标状态、条件不再满足等),按"跳过"记录,原因写入 ProviderMessage。
|
||||
SkipReason string
|
||||
}
|
||||
|
||||
// StopResumeRecorder 把每次停复机上游调用写入停复机记录表;写入失败只记日志与计数,不影响业务回写。
|
||||
@@ -54,7 +56,11 @@ func (r *StopResumeRecorder) Record(ctx context.Context, input StopResumeRecordI
|
||||
Attempt: input.Attempt, Result: constants.StopResumeRecordSuccess,
|
||||
DurationMS: int(input.Duration.Milliseconds()), CreatedAt: time.Now(),
|
||||
}
|
||||
if input.CallErr != nil {
|
||||
if input.SkipReason != "" {
|
||||
row.Result = constants.StopResumeRecordSkipped
|
||||
row.ErrorCategory = ""
|
||||
row.ProviderMessage = input.SkipReason
|
||||
} else if input.CallErr != nil {
|
||||
row.Result = constants.StopResumeRecordFailed
|
||||
if gwErr, ok := gateway.AsGatewayError(input.CallErr); ok {
|
||||
row.ErrorCategory = gwErr.Category
|
||||
|
||||
@@ -47,6 +47,10 @@ func (p *Producer) Stop() {
|
||||
// Handler 处理一条消息;返回后由管理器 FIN。消息处理期间可调用 touch 延长 NSQ 消息超时。
|
||||
type Handler func(ctx context.Context, body []byte, touch func())
|
||||
|
||||
// RetryHandler 处理一条消息并决定是否重投:返回 0 表示 FIN,返回正数表示按该延迟重投(REQ,不计 NSQ 退避)。
|
||||
// attempts 是 NSQ 记录的投递次数(含本次,从 1 起)。
|
||||
type RetryHandler func(ctx context.Context, body []byte, attempts uint16, touch func()) time.Duration
|
||||
|
||||
// ConsumerConfig 是消费者参数。
|
||||
type ConsumerConfig struct {
|
||||
NSQDAddress string
|
||||
@@ -55,14 +59,17 @@ type ConsumerConfig struct {
|
||||
MaxAttempts uint16
|
||||
// LookupdPollInterval 消费者向 nsqlookupd 查询 nsqd 的间隔;0 表示 15 秒。
|
||||
LookupdPollInterval time.Duration
|
||||
// UnlimitedAttempts 为 true 时不限投递次数(忽略 MaxAttempts),用于不允许丢弃的入库消息。
|
||||
UnlimitedAttempts bool
|
||||
}
|
||||
|
||||
// ConsumerManager 按 topic 动态订阅与取消订阅;每个 topic 一个消费者,max_in_flight 控制本进程对该 topic 的并发。
|
||||
type ConsumerManager struct {
|
||||
cfg ConsumerConfig
|
||||
channel string
|
||||
handler Handler
|
||||
logger *zap.Logger
|
||||
cfg ConsumerConfig
|
||||
channel string
|
||||
handler Handler
|
||||
retryHandler RetryHandler
|
||||
logger *zap.Logger
|
||||
|
||||
mu sync.Mutex
|
||||
consumers map[string]*subscription
|
||||
@@ -86,6 +93,13 @@ func NewConsumerManager(cfg ConsumerConfig, channel string, handler Handler, log
|
||||
consumers: map[string]*subscription{}, ctx: ctx, cancel: cancel}
|
||||
}
|
||||
|
||||
// NewRetryConsumerManager 创建由处理结果决定 FIN 或延迟重投的消费者管理器。
|
||||
func NewRetryConsumerManager(cfg ConsumerConfig, channel string, handler RetryHandler, logger *zap.Logger) *ConsumerManager {
|
||||
manager := NewConsumerManager(cfg, channel, nil, logger)
|
||||
manager.retryHandler = handler
|
||||
return manager
|
||||
}
|
||||
|
||||
// Sync 使订阅集合与 desired(topic → max_in_flight)一致:新增订阅、取消多余订阅、调整 max_in_flight。
|
||||
func (m *ConsumerManager) Sync(desired map[string]int) {
|
||||
m.mu.Lock()
|
||||
@@ -97,7 +111,7 @@ func (m *ConsumerManager) Sync(desired map[string]int) {
|
||||
if _, keep := desired[topic]; !keep {
|
||||
sub.consumer.Stop()
|
||||
delete(m.consumers, topic)
|
||||
m.logger.Info("取消订阅卡任务 topic", zap.String("topic", topic))
|
||||
m.logger.Info("取消订阅 NSQ topic", zap.String("topic", topic))
|
||||
}
|
||||
}
|
||||
for topic, maxInFlight := range desired {
|
||||
@@ -113,11 +127,11 @@ func (m *ConsumerManager) Sync(desired map[string]int) {
|
||||
}
|
||||
consumer, err := m.subscribe(topic, maxInFlight)
|
||||
if err != nil {
|
||||
m.logger.Warn("订阅卡任务 topic 失败,下一轮重试", zap.String("topic", topic), zap.Error(err))
|
||||
m.logger.Warn("订阅 NSQ topic 失败,下一轮重试", zap.String("topic", topic), zap.Error(err))
|
||||
continue
|
||||
}
|
||||
m.consumers[topic] = &subscription{consumer: consumer, maxInFlight: maxInFlight}
|
||||
m.logger.Info("订阅卡任务 topic", zap.String("topic", topic), zap.Int("max_in_flight", maxInFlight))
|
||||
m.logger.Info("订阅 NSQ topic", zap.String("topic", topic), zap.Int("max_in_flight", maxInFlight))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -130,6 +144,9 @@ func (m *ConsumerManager) subscribe(topic string, maxInFlight int) (*nsq.Consume
|
||||
if m.cfg.MaxAttempts > 0 {
|
||||
cfg.MaxAttempts = m.cfg.MaxAttempts
|
||||
}
|
||||
if m.cfg.UnlimitedAttempts {
|
||||
cfg.MaxAttempts = 0
|
||||
}
|
||||
cfg.LookupdPollInterval = 15 * time.Second
|
||||
if m.cfg.LookupdPollInterval > 0 {
|
||||
cfg.LookupdPollInterval = m.cfg.LookupdPollInterval
|
||||
@@ -146,6 +163,14 @@ func (m *ConsumerManager) subscribe(topic string, maxInFlight int) (*nsq.Consume
|
||||
message.DisableAutoResponse()
|
||||
m.inflight.Add(1)
|
||||
defer m.inflight.Done()
|
||||
if m.retryHandler != nil {
|
||||
if delay := m.retryHandler(handlerCtx, message.Body, message.Attempts, message.Touch); delay > 0 {
|
||||
message.RequeueWithoutBackoff(delay)
|
||||
return nil
|
||||
}
|
||||
message.Finish()
|
||||
return nil
|
||||
}
|
||||
defer message.Finish()
|
||||
m.handler(handlerCtx, message.Body, message.Touch)
|
||||
return nil
|
||||
|
||||
60
internal/infrastructure/nsqbus/stats.go
Normal file
60
internal/infrastructure/nsqbus/stats.go
Normal file
@@ -0,0 +1,60 @@
|
||||
package nsqbus
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"time"
|
||||
)
|
||||
|
||||
type nsqdStats struct {
|
||||
Topics []struct {
|
||||
TopicName string `json:"topic_name"`
|
||||
Depth int64 `json:"depth"`
|
||||
Channels []struct {
|
||||
Depth int64 `json:"depth"`
|
||||
DeferredCount int64 `json:"deferred_count"`
|
||||
} `json:"channels"`
|
||||
} `json:"topics"`
|
||||
}
|
||||
|
||||
// TopicBacklog 读取 nsqd 上某 topic 的积压量:topic 未分发量 + 各 channel 待消费量与延迟重投量(不含处理中)。
|
||||
// topic 不存在时返回 0。
|
||||
func TopicBacklog(ctx context.Context, nsqdTCPAddress, topic string) (int64, error) {
|
||||
httpAddress := nsqdHTTPAddress(nsqdTCPAddress)
|
||||
if httpAddress == "" {
|
||||
return 0, fmt.Errorf("nsqd 地址无效:%s", nsqdTCPAddress)
|
||||
}
|
||||
requestCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
endpoint := "http://" + httpAddress + "/stats?format=json&topic=" + url.QueryEscape(topic)
|
||||
request, err := http.NewRequestWithContext(requestCtx, http.MethodGet, endpoint, nil)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
response, err := http.DefaultClient.Do(request)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return 0, fmt.Errorf("读取 nsqd 统计失败,HTTP %d", response.StatusCode)
|
||||
}
|
||||
var stats nsqdStats
|
||||
if err := json.NewDecoder(response.Body).Decode(&stats); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
var backlog int64
|
||||
for _, item := range stats.Topics {
|
||||
if item.TopicName != topic {
|
||||
continue
|
||||
}
|
||||
backlog += item.Depth
|
||||
for _, channel := range item.Channels {
|
||||
backlog += channel.Depth + channel.DeferredCount
|
||||
}
|
||||
}
|
||||
return backlog, nil
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package payment
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
sdkalipay "github.com/smartwalle/alipay/v3"
|
||||
)
|
||||
|
||||
func TestAlipayTradeNotExist(t *testing.T) {
|
||||
notExist := sdkalipay.Error{Code: sdkalipay.Code("40004"), SubCode: alipayTradeNotExistCode}
|
||||
tests := []struct {
|
||||
name string
|
||||
response *sdkalipay.TradeQueryRsp
|
||||
err error
|
||||
want bool
|
||||
}{
|
||||
{name: "失败响应且交易不存在", response: &sdkalipay.TradeQueryRsp{Error: notExist}, want: true},
|
||||
{name: "SDK 以错误返回交易不存在", err: fmt.Errorf("wrap: %w", ¬Exist), want: true},
|
||||
{name: "其他业务失败", response: &sdkalipay.TradeQueryRsp{Error: sdkalipay.Error{Code: sdkalipay.Code("40004"), SubCode: "ACQ.SYSTEM_ERROR"}}, want: false},
|
||||
{name: "成功响应", response: &sdkalipay.TradeQueryRsp{Error: sdkalipay.Error{Code: sdkalipay.CodeSuccess}, TradeStatus: sdkalipay.TradeStatusWaitBuyerPay}, want: false},
|
||||
{name: "网络错误", err: fmt.Errorf("dial tcp: timeout"), want: false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := alipayTradeNotExist(tt.response, tt.err); got != tt.want {
|
||||
t.Fatalf("alipayTradeNotExist() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package payment
|
||||
|
||||
import (
|
||||
"context"
|
||||
stderrors "errors"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
@@ -54,6 +55,18 @@ func (a *AlipayWapAdapter) Query(ctx context.Context, request agentrecharge.Onli
|
||||
}
|
||||
startedAt := time.Now()
|
||||
response, callErr := client.TradeQuery(ctx, sdkalipay.TradeQuery{OutTradeNo: request.PaymentNo})
|
||||
// 客户没打开过支付链接时支付宝侧没有这笔交易(ACQ.TRADE_NOT_EXIST):按"渠道没有这笔订单"返回,
|
||||
// 恢复任务在过支付截止后据此关闭订单;不能当成查单失败,否则订单永远停在待支付。
|
||||
if alipayTradeNotExist(response, callErr) {
|
||||
if _, err = a.integration.Complete(ctx, attempt.IntegrationID, integrationlog.Completion{
|
||||
Result: constants.IntegrationResultSuccess, ProviderCode: alipayTradeNotExistCode,
|
||||
ResponseSummary: map[string]any{"state": agentrecharge.OnlinePaymentStateNotFound},
|
||||
DurationMS: time.Since(startedAt).Milliseconds(),
|
||||
}); err != nil {
|
||||
return agentrecharge.OnlinePaymentQueryResult{}, err
|
||||
}
|
||||
return agentrecharge.OnlinePaymentQueryResult{State: agentrecharge.OnlinePaymentStateNotFound}, nil
|
||||
}
|
||||
if callErr != nil {
|
||||
return agentrecharge.OnlinePaymentQueryResult{}, a.completeUnknown(ctx, attempt.IntegrationID, startedAt, callErr)
|
||||
}
|
||||
@@ -128,6 +141,18 @@ func (a *AlipayWapAdapter) completeUnknown(ctx context.Context, integrationID st
|
||||
return apperrors.Wrap(apperrors.CodeTimeout, cause, "支付宝支付请求结果未知")
|
||||
}
|
||||
|
||||
// alipayTradeNotExistCode 是支付宝查单"交易不存在"的业务子码。
|
||||
const alipayTradeNotExistCode = "ACQ.TRADE_NOT_EXIST"
|
||||
|
||||
// alipayTradeNotExist 判断查单结果是否为"交易不存在":SDK 可能以失败响应返回,也可能以 *Error 返回。
|
||||
func alipayTradeNotExist(response *sdkalipay.TradeQueryRsp, callErr error) bool {
|
||||
if response != nil && response.IsFailure() && response.SubCode == alipayTradeNotExistCode {
|
||||
return true
|
||||
}
|
||||
var sdkErr *sdkalipay.Error
|
||||
return stderrors.As(callErr, &sdkErr) && sdkErr != nil && sdkErr.SubCode == alipayTradeNotExistCode
|
||||
}
|
||||
|
||||
func mapAlipayTradeState(state sdkalipay.TradeStatus) string {
|
||||
switch state {
|
||||
case sdkalipay.TradeStatusSuccess, sdkalipay.TradeStatusFinished:
|
||||
|
||||
@@ -47,6 +47,18 @@ func (a *WechatWebAdapter) CreatePaymentURL(ctx context.Context, request agentre
|
||||
PayerClientIP: request.PayerClientIP,
|
||||
H5Type: "Wap",
|
||||
})
|
||||
// 微信明确拒绝(订单未创建):记失败并返回真实原因,调用方立即关单;
|
||||
// 用"微信配置不可用"错误码,不触发支付失败自动停用商户(如 H5 产品未开通不影响该商户的公众号支付)。
|
||||
var bizErr *wechatpay.V2BusinessError
|
||||
if stderrors.As(callErr, &bizErr) {
|
||||
if _, err = a.integration.Complete(ctx, attempt.IntegrationID, integrationlog.Completion{
|
||||
Result: constants.IntegrationResultFailed, ProviderCode: bizErr.Code, ProviderMessage: bizErr.Message,
|
||||
ResponseSummary: map[string]any{"success": false}, DurationMS: time.Since(startedAt).Milliseconds(),
|
||||
}); err != nil {
|
||||
return agentrecharge.OnlinePaymentResult{}, err
|
||||
}
|
||||
return agentrecharge.OnlinePaymentResult{}, apperrors.New(apperrors.CodeWechatConfigUnavailable, bizErr.Error())
|
||||
}
|
||||
if callErr != nil {
|
||||
return agentrecharge.OnlinePaymentResult{}, a.completeUnknown(ctx, attempt.IntegrationID, startedAt, callErr)
|
||||
}
|
||||
|
||||
@@ -22,7 +22,9 @@ type CardTrafficCollection struct {
|
||||
StaleGuarded *bool `gorm:"column:stale_guarded" json:"stale_guarded"`
|
||||
DeltaMB *float64 `gorm:"column:delta_mb;type:numeric(14,3)" json:"delta_mb"`
|
||||
EventID string `gorm:"column:event_id;type:varchar(128);not null;default:''" json:"event_id"`
|
||||
CreatedAt time.Time `gorm:"column:created_at;not null;default:now()" json:"created_at"`
|
||||
CarrierID uint `gorm:"column:carrier_id;not null;default:0" json:"carrier_id"`
|
||||
CollectionRaw
|
||||
CreatedAt time.Time `gorm:"column:created_at;not null;default:now()" json:"created_at"`
|
||||
}
|
||||
|
||||
// TableName 指定表名。
|
||||
@@ -30,6 +32,43 @@ func (CardTrafficCollection) TableName() string {
|
||||
return "tb_card_traffic_collection"
|
||||
}
|
||||
|
||||
// CollectionRaw 是采集记录保存的网关原始数据(成功表与失败表共用)。
|
||||
type CollectionRaw struct {
|
||||
RawRequest datatypes.JSON `gorm:"column:raw_request;type:jsonb" json:"raw_request"`
|
||||
HTTPStatus *int `gorm:"column:http_status" json:"http_status"`
|
||||
GatewayCode *int `gorm:"column:gateway_code" json:"gateway_code"`
|
||||
GatewayMsg string `gorm:"column:gateway_msg;type:varchar(500);not null;default:''" json:"gateway_msg"`
|
||||
GatewayTraceID string `gorm:"column:gateway_trace_id;type:varchar(128);not null;default:''" json:"gateway_trace_id"`
|
||||
RawResponse datatypes.JSON `gorm:"column:raw_response;type:jsonb" json:"raw_response"`
|
||||
RawResponseText string `gorm:"column:raw_response_text;type:text;not null;default:''" json:"raw_response_text"`
|
||||
RawTruncated bool `gorm:"column:raw_truncated;not null;default:false" json:"raw_truncated"`
|
||||
GatewayAttempts int `gorm:"column:gateway_attempts;not null;default:0" json:"gateway_attempts"`
|
||||
}
|
||||
|
||||
// CardTrafficCollectionFailure 卡流量采集失败记录:所有被采集的卡每次失败一条,按月分区,在线保留 2 个月。
|
||||
type CardTrafficCollectionFailure struct {
|
||||
ID uint `gorm:"column:id;primaryKey;autoIncrement" json:"id"`
|
||||
IotCardID uint `gorm:"column:iot_card_id;not null" json:"iot_card_id"`
|
||||
ICCID string `gorm:"column:iccid;type:varchar(30);not null;default:''" json:"iccid"`
|
||||
CarrierID uint `gorm:"column:carrier_id;not null;default:0" json:"carrier_id"`
|
||||
ObservedAt time.Time `gorm:"column:observed_at;primaryKey;not null" json:"observed_at"`
|
||||
ObservationID string `gorm:"column:observation_id;type:varchar(128);not null;default:''" json:"observation_id"`
|
||||
Source string `gorm:"column:source;type:varchar(32);not null;default:''" json:"source"`
|
||||
Scene string `gorm:"column:scene;type:varchar(64);not null;default:''" json:"scene"`
|
||||
Result string `gorm:"column:result;type:varchar(32);not null" json:"result"`
|
||||
ErrorCategory string `gorm:"column:error_category;type:varchar(30);not null;default:''" json:"error_category"`
|
||||
ProviderCode string `gorm:"column:provider_code;type:varchar(30);not null;default:''" json:"provider_code"`
|
||||
ProviderMessage string `gorm:"column:provider_message;type:varchar(500);not null;default:''" json:"provider_message"`
|
||||
DurationMS int `gorm:"column:duration_ms;not null;default:0" json:"duration_ms"`
|
||||
CollectionRaw
|
||||
CreatedAt time.Time `gorm:"column:created_at;not null;default:now()" json:"created_at"`
|
||||
}
|
||||
|
||||
// TableName 指定表名。
|
||||
func (CardTrafficCollectionFailure) TableName() string {
|
||||
return "tb_card_traffic_collection_failure"
|
||||
}
|
||||
|
||||
// PackageUsageAdjustment 套餐流量人工冲正流水:只新增,不修改、不删除。
|
||||
type PackageUsageAdjustment struct {
|
||||
ID uint `gorm:"column:id;primaryKey;autoIncrement" json:"id"`
|
||||
|
||||
@@ -27,7 +27,9 @@ type AssetResolveResponse struct {
|
||||
ActivationStatus int `json:"activation_status" description:"激活状态:0未激活 1已激活;设备需有生效中主套餐且任意绑定卡已实名"`
|
||||
ActivationStatusName string `json:"activation_status_name" description:"激活状态名称(中文)"`
|
||||
RealNameStatus int `json:"real_name_status" description:"实名状态:0未实名 1已实名"`
|
||||
RealNameAt *time.Time `json:"real_name_at" description:"最近一次完成实名的时间,未实名时为 null"`
|
||||
RealNameAt *time.Time `json:"real_name_at" description:"实名时间:上游返回的实名时间优先,否则为首次读到已实名的时间;未实名时为 null"`
|
||||
RealNameAtSource string `json:"real_name_at_source,omitempty" description:"实名时间来源(卡资产):upstream 上游返回 / first_observed 首次读到 / migrated 迁移沿用"`
|
||||
RealNameAtSourceName string `json:"real_name_at_source_name,omitempty" description:"实名时间来源中文名"`
|
||||
RealnamePolicy string `json:"realname_policy" description:"实名认证策略 (none:无需实名, before_order:先实名后充值/购买, after_order:先充值/购买后实名)"`
|
||||
CurrentPackage string `json:"current_package" description:"当前套餐名称(无套餐时为空)"`
|
||||
CurrentPackageUsageID *uint `json:"current_package_usage_id" description:"当前主套餐的套餐使用记录ID,无主套餐时为 null"`
|
||||
@@ -116,7 +118,9 @@ type BoundCardInfo struct {
|
||||
MSISDN string `json:"msisdn,omitempty" description:"手机号"`
|
||||
NetworkStatus int `json:"network_status" description:"网络状态:0停机 1开机"`
|
||||
RealNameStatus int `json:"real_name_status" description:"实名状态:0未实名 1已实名"`
|
||||
RealNameAt *time.Time `json:"real_name_at" description:"该卡最近一次完成实名的时间,未实名时为 null"`
|
||||
RealNameAt *time.Time `json:"real_name_at" description:"该卡实名时间:上游返回的实名时间优先,否则为首次读到已实名的时间;未实名时为 null"`
|
||||
RealNameAtSource string `json:"real_name_at_source,omitempty" description:"实名时间来源:upstream 上游返回 / first_observed 首次读到 / migrated 迁移沿用"`
|
||||
RealNameAtSourceName string `json:"real_name_at_source_name,omitempty" description:"实名时间来源中文名"`
|
||||
SlotPosition int `json:"slot_position,omitempty" description:"插槽位置"`
|
||||
IsCurrent bool `json:"is_current" description:"是否为当前使用的卡"`
|
||||
CarrierID uint `json:"carrier_id,omitempty" description:"运营商ID"`
|
||||
@@ -281,6 +285,8 @@ type PackageTrafficAdjustmentListRequest struct {
|
||||
PackageUsageID uint `path:"package_usage_id" description:"套餐使用记录ID" required:"true"`
|
||||
Page int `query:"page" validate:"omitempty,min=1" minimum:"1" description:"页码,默认 1"`
|
||||
PageSize int `query:"page_size" validate:"omitempty,min=1,max=100" minimum:"1" maximum:"100" description:"每页条数,默认 20"`
|
||||
StartTime string `query:"start_time" description:"开始时间(RFC3339 或 2006-01-02 15:04:05,上海时间),选填;与结束时间同时传,跨度不超过 31 天"`
|
||||
EndTime string `query:"end_time" description:"结束时间(不含),选填"`
|
||||
}
|
||||
|
||||
// PackageTrafficAdjustmentItem 冲正流水。
|
||||
@@ -296,6 +302,7 @@ type PackageTrafficAdjustmentItem struct {
|
||||
RefObservationID string `json:"ref_observation_id" description:"关联的采集 ID"`
|
||||
RefEventID string `json:"ref_event_id" description:"关联的流量事件 ID"`
|
||||
OperatorID uint `json:"operator_id" description:"操作人账号ID"`
|
||||
OperatorName string `json:"operator_name" description:"操作人账号用户名"`
|
||||
CreatedAt time.Time `json:"created_at" description:"冲正时间"`
|
||||
}
|
||||
|
||||
@@ -312,6 +319,11 @@ type CardTrafficCollectionListRequest struct {
|
||||
EndTime string `query:"end_time" validate:"required" required:"true" description:"结束时间(不含),最长跨度 31 天"`
|
||||
Page int `query:"page" validate:"omitempty,min=1" minimum:"1" description:"页码,默认 1"`
|
||||
PageSize int `query:"page_size" validate:"omitempty,min=1,max=200" minimum:"1" maximum:"200" description:"每页条数,默认 50"`
|
||||
Decision string `query:"decision" validate:"omitempty,max=32" description:"写入判断筛选(只作用于成功记录)"`
|
||||
Source string `query:"source" validate:"omitempty,max=32" description:"来源筛选"`
|
||||
Scene string `query:"scene" validate:"omitempty,max=64" description:"场景筛选"`
|
||||
// IncludeFailures 为 true 时合并采集失败记录,按采集时间倒序返回。
|
||||
IncludeFailures bool `query:"include_failures" description:"是否包含采集失败记录,默认 false"`
|
||||
}
|
||||
|
||||
// CardTrafficCollectionItem 卡流量采集记录。
|
||||
@@ -329,6 +341,13 @@ type CardTrafficCollectionItem struct {
|
||||
StaleGuarded *bool `json:"stale_guarded" description:"写入时是否触发重置日防旧值"`
|
||||
DeltaMB *float64 `json:"delta_mb" description:"写入时本次增量(MB)"`
|
||||
EventID string `json:"event_id" description:"流量事件 ID"`
|
||||
// RecordKind 区分成功表与失败表记录:success/failure。
|
||||
RecordKind string `json:"record_kind" description:"记录类型:success 采集成功,failure 采集失败"`
|
||||
ErrorCategory string `json:"error_category,omitempty" description:"错误类别(失败记录)"`
|
||||
ProviderCode string `json:"provider_code,omitempty" description:"上游返回码(失败记录)"`
|
||||
ProviderMessage string `json:"provider_message,omitempty" description:"上游返回信息或错误信息(失败记录)"`
|
||||
DurationMS int `json:"duration_ms,omitempty" description:"调用耗时毫秒(失败记录)"`
|
||||
GatewayRawItem
|
||||
}
|
||||
|
||||
// CardTrafficCollectionListResponse 卡流量采集记录分页结果。
|
||||
|
||||
114
internal/model/dto/card_realname_dto.go
Normal file
114
internal/model/dto/card_realname_dto.go
Normal file
@@ -0,0 +1,114 @@
|
||||
package dto
|
||||
|
||||
import "time"
|
||||
|
||||
// CardRealnameHistoryListRequest 查询单卡实名时间历史。
|
||||
type CardRealnameHistoryListRequest struct {
|
||||
ID uint `json:"-" path:"id" description:"IoT卡ID"`
|
||||
Page int `json:"page" query:"page" validate:"omitempty,min=1" minimum:"1" description:"页码"`
|
||||
PageSize int `json:"page_size" query:"page_size" validate:"omitempty,min=1,max=100" minimum:"1" maximum:"100" description:"每页数量"`
|
||||
}
|
||||
|
||||
// CardRealnameCurrentResponse 是卡当前实名时间。
|
||||
type CardRealnameCurrentResponse struct {
|
||||
CardID uint `json:"card_id" description:"IoT卡ID"`
|
||||
RealnameAt *time.Time `json:"realname_at" description:"当前实名时间:上游返回的实名时间优先,否则为首次读到已实名的时间"`
|
||||
RealnameAtSource string `json:"realname_at_source" description:"实名时间来源:upstream 上游返回 / first_observed 首次读到 / migrated 迁移沿用"`
|
||||
RealnameAtSourceName string `json:"realname_at_source_name" description:"实名时间来源中文名"`
|
||||
UpstreamRealnameAt *time.Time `json:"upstream_realname_at" description:"上游最近一次返回的实名时间"`
|
||||
FirstObservedAt *time.Time `json:"first_observed_at" description:"首次读到已实名的时间"`
|
||||
ResetPending bool `json:"reset_pending" description:"是否等待二次实名(仅后台展示)"`
|
||||
ResetAt *time.Time `json:"reset_at" description:"二次实名清除时间"`
|
||||
ResetBaselineAt *time.Time `json:"reset_baseline_at" description:"清除前的上游实名时间(新旧判定基准)"`
|
||||
ResetBatchID *uint `json:"reset_batch_id" description:"所属二次实名批次 ID"`
|
||||
}
|
||||
|
||||
// CardRealnameHistoryItem 是一条实名时间变化历史。
|
||||
type CardRealnameHistoryItem struct {
|
||||
ID uint `json:"id" description:"历史 ID"`
|
||||
CardID uint `json:"card_id" description:"IoT卡ID"`
|
||||
ICCID string `json:"iccid" description:"ICCID"`
|
||||
BeforeAt *time.Time `json:"before_at" description:"原实名时间"`
|
||||
AfterAt *time.Time `json:"after_at" description:"新实名时间"`
|
||||
AfterSource string `json:"after_source" description:"新实名时间来源"`
|
||||
AfterSourceName string `json:"after_source_name" description:"新实名时间来源中文名"`
|
||||
ChangeType string `json:"change_type" description:"变化类型:first 首次实名 / upstream_fix 上游更正 / reset 二次实名清除 / reset_completed 二次实名完成 / reset_reverted 二次实名撤销 / migrated 迁移补录"`
|
||||
ChangeTypeName string `json:"change_type_name" description:"变化类型中文名"`
|
||||
ObservationSource string `json:"observation_source" description:"观测来源:polling 轮询 / manual_sync 手动刷新 / carrier_callback 回调 / business_event 业务观测 / manual_override 人工 / migration 迁移 / package_silence 沉默期判定"`
|
||||
ObservationSourceName string `json:"observation_source_name" description:"观测来源中文名"`
|
||||
ResetBatchID *uint `json:"reset_batch_id" description:"关联二次实名批次 ID"`
|
||||
OperatorID uint `json:"operator_id" description:"操作人账号 ID(人工时)"`
|
||||
OperatorName string `json:"operator_name" description:"操作人名称"`
|
||||
ObservedAt time.Time `json:"observed_at" description:"发现时间"`
|
||||
CreatedAt time.Time `json:"created_at" description:"记录时间"`
|
||||
}
|
||||
|
||||
// CardRealnameHistoryResponse 是单卡实名记录:当前实名时间与历史分页。
|
||||
type CardRealnameHistoryResponse struct {
|
||||
Current CardRealnameCurrentResponse `json:"current" description:"当前实名时间"`
|
||||
Items []CardRealnameHistoryItem `json:"items" description:"实名时间历史(按时间倒序)"`
|
||||
Total int64 `json:"total" description:"历史总数"`
|
||||
Page int `json:"page" description:"页码"`
|
||||
PageSize int `json:"page_size" description:"每页数量"`
|
||||
}
|
||||
|
||||
// RealnameResetImportRequest 导入二次实名名单。
|
||||
type RealnameResetImportRequest struct {
|
||||
Identifiers []string `json:"identifiers" validate:"required,min=1,max=1000,dive,required,max=64" required:"true" description:"资产号列表:ICCID / 虚拟号 / IMEI,设备展开为其全部绑定卡,最多 1000 个"`
|
||||
Reason string `json:"reason" validate:"required,min=1,max=500" required:"true" description:"原因"`
|
||||
ImportFileKey string `json:"import_file_key" validate:"omitempty,max=500" description:"导入文件对象存储 Key(可选,留档)"`
|
||||
}
|
||||
|
||||
// RealnameResetItem 是二次实名批次的一行结果。
|
||||
type RealnameResetItem struct {
|
||||
RowNo int `json:"row_no" description:"行号(从 1 开始)"`
|
||||
Input string `json:"input" description:"导入的资产号"`
|
||||
CardID uint `json:"card_id,omitempty" description:"卡 ID"`
|
||||
ICCID string `json:"iccid,omitempty" description:"ICCID"`
|
||||
Result string `json:"result" description:"结果:pending 等待二次实名 / completed 已完成 / reverted 已撤销 / skipped 跳过 / failed 失败"`
|
||||
ResultName string `json:"result_name" description:"结果中文名"`
|
||||
Reason string `json:"reason,omitempty" description:"跳过或失败原因"`
|
||||
}
|
||||
|
||||
// RealnameResetBatchResponse 是二次实名批次。
|
||||
type RealnameResetBatchResponse struct {
|
||||
ID uint `json:"id" description:"批次 ID"`
|
||||
BatchNo string `json:"batch_no" description:"批次号"`
|
||||
Reason string `json:"reason" description:"原因"`
|
||||
ImportFileKey string `json:"import_file_key" description:"导入文件 Key"`
|
||||
TotalCount int `json:"total_count" description:"处理卡数(含跳过)"`
|
||||
SucceededCount int `json:"succeeded_count" description:"已清除卡数"`
|
||||
SkippedCount int `json:"skipped_count" description:"跳过或失败数"`
|
||||
CompletedCount int `json:"completed_count" description:"已完成二次实名卡数"`
|
||||
RevertedCount int `json:"reverted_count" description:"已撤销卡数"`
|
||||
PendingCount int `json:"pending_count" description:"仍在等待二次实名卡数"`
|
||||
OperatorID uint `json:"operator_id" description:"操作人账号 ID"`
|
||||
OperatorName string `json:"operator_name" description:"操作人"`
|
||||
CreatedAt time.Time `json:"created_at" description:"导入时间"`
|
||||
Items []RealnameResetItem `json:"items,omitempty" description:"逐行结果(详情返回)"`
|
||||
}
|
||||
|
||||
// RealnameResetBatchListRequest 查询二次实名批次。
|
||||
type RealnameResetBatchListRequest struct {
|
||||
BatchNo string `json:"batch_no" query:"batch_no" validate:"omitempty,max=40" description:"批次号"`
|
||||
Page int `json:"page" query:"page" validate:"omitempty,min=1" minimum:"1" description:"页码"`
|
||||
PageSize int `json:"page_size" query:"page_size" validate:"omitempty,min=1,max=100" minimum:"1" maximum:"100" description:"每页数量"`
|
||||
}
|
||||
|
||||
// RealnameResetBatchIDRequest 是批次路径参数。
|
||||
type RealnameResetBatchIDRequest struct {
|
||||
ID uint `json:"-" path:"id" description:"批次 ID"`
|
||||
}
|
||||
|
||||
// RealnameResetRevertRequest 撤销二次实名。
|
||||
type RealnameResetRevertRequest struct {
|
||||
ID uint `json:"-" path:"id" description:"批次 ID"`
|
||||
CardIDs []uint `json:"card_ids" validate:"omitempty,max=1000" description:"只撤销这些卡;为空撤销整批仍在等待的卡"`
|
||||
}
|
||||
|
||||
// RealnameResetRevertResponse 撤销结果。
|
||||
type RealnameResetRevertResponse struct {
|
||||
RevertedCount int `json:"reverted_count" description:"撤销成功卡数"`
|
||||
FailedCount int `json:"failed_count" description:"撤销失败卡数"`
|
||||
Failures []string `json:"failures,omitempty" description:"失败说明"`
|
||||
}
|
||||
@@ -140,6 +140,10 @@ type StopResumeRecordListRequest struct {
|
||||
Page int `json:"page" query:"page" validate:"omitempty,min=1" minimum:"1" description:"页码"`
|
||||
PageSize int `json:"page_size" query:"page_size" validate:"omitempty,min=1,max=100" minimum:"1" maximum:"100" description:"每页数量"`
|
||||
ICCID string `json:"iccid" query:"iccid" validate:"omitempty,max=30" maxLength:"30" description:"ICCID"`
|
||||
Identifier string `json:"identifier" query:"identifier" validate:"omitempty,max=50" maxLength:"50" description:"资产标识(虚拟号/ICCID/MSISDN,设备支持虚拟号/IMEI/SN,取其绑定卡)"`
|
||||
Scene string `json:"scene" query:"scene" validate:"omitempty,max=50" maxLength:"50" description:"场景"`
|
||||
Reason string `json:"reason" query:"reason" validate:"omitempty,max=50" maxLength:"50" description:"停机原因"`
|
||||
CommandID string `json:"command_id" query:"command_id" validate:"omitempty,max=64" maxLength:"64" description:"指令号(同一次停复机命令的多次尝试共用)"`
|
||||
CarrierID *uint `json:"carrier_id" query:"carrier_id" validate:"omitempty" description:"运营商账户ID"`
|
||||
Action string `json:"action" query:"action" validate:"omitempty,oneof=stop start" description:"动作 (stop:停机, start:复机)"`
|
||||
Source string `json:"source" query:"source" validate:"omitempty,max=50" maxLength:"50" description:"来源"`
|
||||
@@ -156,6 +160,9 @@ type CardStopResumeRecordListRequest struct {
|
||||
PageSize int `json:"page_size" query:"page_size" validate:"omitempty,min=1,max=100" minimum:"1" maximum:"100" description:"每页数量"`
|
||||
StartTime time.Time `json:"start_time" query:"start_time" description:"开始时间(RFC3339),为空取最近 31 天"`
|
||||
EndTime time.Time `json:"end_time" query:"end_time" description:"结束时间(RFC3339),为空取当前"`
|
||||
Action string `json:"action" query:"action" validate:"omitempty,oneof=stop start" description:"动作 (stop:停机, start:复机)"`
|
||||
Result string `json:"result" query:"result" validate:"omitempty,oneof=success failed unknown already_target skipped" description:"结果 (success:成功, failed:失败, unknown:结果未知, already_target:已是目标状态, skipped:跳过)"`
|
||||
Source string `json:"source" query:"source" validate:"omitempty,max=50" maxLength:"50" description:"来源"`
|
||||
}
|
||||
|
||||
// StopResumeRecordResponse 停复机记录响应
|
||||
|
||||
@@ -194,5 +194,8 @@ type PackageUsageDetailResponse struct {
|
||||
PackageUsageID uint `json:"package_usage_id" description:"套餐使用记录ID"`
|
||||
PackageName string `json:"package_name" description:"套餐名称"`
|
||||
Records []PackageUsageDailyRecordResponse `json:"records" description:"流量日记录列表"`
|
||||
TotalUsageMB int64 `json:"total_usage_mb" description:"总使用流量(MB)"`
|
||||
TotalUsageMB int64 `json:"total_usage_mb" description:"总使用流量(MB),为筛选范围内全部记录之和"`
|
||||
Total int64 `json:"total" description:"筛选范围内记录总数"`
|
||||
Page int `json:"page" description:"页码;未传 page_size 时为 0,返回全部记录"`
|
||||
PageSize int `json:"page_size" description:"每页条数;未传时为 0,返回全部记录"`
|
||||
}
|
||||
|
||||
@@ -115,6 +115,12 @@ type SilenceExtensionOption struct {
|
||||
// SilenceEligibilityResponse 延期资格(技术方案 §12.2),金额与月数全部由后端计算。
|
||||
type SilenceEligibilityResponse struct {
|
||||
PackageUsageID uint `json:"package_usage_id" description:"套餐记录 ID"`
|
||||
PackageName string `json:"package_name,omitempty" description:"套餐名称"`
|
||||
AssetIdentifier string `json:"asset_identifier,omitempty" description:"资产标识"`
|
||||
PurchasedAt *time.Time `json:"purchased_at,omitempty" description:"套餐订购时间(购买支付成功时间)"`
|
||||
ActivatedAt *time.Time `json:"activated_at,omitempty" description:"套餐生效时间(未实名激活时为空)"`
|
||||
ExpiresAt *time.Time `json:"expires_at,omitempty" description:"套餐到期时间(未实名激活时为空)"`
|
||||
SilenceDeadlineAt *time.Time `json:"silence_deadline_at,omitempty" description:"沉默期截止时间(截止日 23:59:59)"`
|
||||
SilenceStatus string `json:"silence_status" description:"沉默期状态(待实名但已到期的先判定为过期)"`
|
||||
CanExtend bool `json:"can_extend" description:"能否办理付费延期"`
|
||||
SpecialExtensionAvailable bool `json:"special_extension_available" description:"能否申请特殊延期(只要求套餐已过期)"`
|
||||
@@ -159,6 +165,7 @@ type SilenceOnlineOrderRequest struct {
|
||||
PackageUsageID uint `json:"package_usage_id" validate:"required,min=1" required:"true" description:"套餐记录 ID"`
|
||||
Days int `json:"days" validate:"required,min=1,max=3650" required:"true" description:"输入的延期天数"`
|
||||
PaymentMethod string `json:"payment_method" validate:"required,oneof=wechat alipay" required:"true" description:"支付方式:wechat / alipay(经商户池路由)"`
|
||||
AppType string `json:"app_type" validate:"omitempty,oneof=official_account miniapp" description:"H5 微信支付时的应用类型:official_account / miniapp;传入时在微信内直接拉起支付(JSAPI),返回 pay_config"`
|
||||
RequestID string `json:"request_id" validate:"required,min=1,max=64" required:"true" description:"下单幂等键"`
|
||||
EvidenceRefs []string `json:"evidence_refs" validate:"omitempty,max=10,dive,max=500" description:"客户申请记录或截图对象存储 Key(后台创建时填写)"`
|
||||
}
|
||||
@@ -178,51 +185,52 @@ type SilenceOfflineOrderRequest struct {
|
||||
|
||||
// SilenceExtensionOrderResponse 延期订单。
|
||||
type SilenceExtensionOrderResponse struct {
|
||||
ID uint `json:"id" description:"订单 ID"`
|
||||
OrderNo string `json:"order_no" description:"订单号"`
|
||||
BatchNo string `json:"batch_no,omitempty" description:"批次号"`
|
||||
PackageUsageID uint `json:"package_usage_id" description:"套餐记录 ID"`
|
||||
PackageID uint `json:"package_id" description:"套餐 ID"`
|
||||
PackageName string `json:"package_name" description:"套餐名称快照"`
|
||||
AssetType string `json:"asset_type" description:"资产类型 iot_card / device"`
|
||||
AssetID uint `json:"asset_id" description:"资产 ID"`
|
||||
AssetIdentifier string `json:"asset_identifier" description:"资产标识快照"`
|
||||
ShopID uint `json:"shop_id" description:"下单时资产所属店铺"`
|
||||
CustomerID *uint `json:"customer_id,omitempty" description:"H5 下单的客户"`
|
||||
Source string `json:"source" description:"来源:client / admin / offline"`
|
||||
SourceName string `json:"source_name" description:"来源名称"`
|
||||
InputDays int `json:"input_days" description:"输入天数"`
|
||||
Months int `json:"months" description:"计费月数"`
|
||||
ExtensionDays int `json:"extension_days" description:"计费 / 延长天数"`
|
||||
UnitPrice int64 `json:"unit_price" description:"单价(分/月)"`
|
||||
Amount int64 `json:"amount" description:"应付金额(分)"`
|
||||
PolicyName string `json:"policy_name" description:"政策名称快照"`
|
||||
BeforeDeadlineAt time.Time `json:"before_deadline_at" description:"下单时截止时间"`
|
||||
ExpectedDeadlineAt time.Time `json:"expected_deadline_at" description:"预计新截止时间"`
|
||||
Status string `json:"status" description:"状态:pending_payment/pending_approval/rejected/paid/completed/closed/exception/refunded"`
|
||||
StatusName string `json:"status_name" description:"状态名称"`
|
||||
PaymentMethod string `json:"payment_method" description:"支付方式:wechat/alipay/offline"`
|
||||
PaymentMerchantName string `json:"payment_merchant_name,omitempty" description:"收款商户名称(取已支付或已退款支付单快照)"`
|
||||
ThirdPartyTradeNo string `json:"third_party_trade_no,omitempty" description:"交易流水号"`
|
||||
PaymentNo string `json:"payment_no,omitempty" description:"支付单号"`
|
||||
QRContent string `json:"qr_content,omitempty" description:"支付内容(待支付时返回,前端渲染为二维码或跳转链接)"`
|
||||
OfflinePaymentMethodName string `json:"offline_payment_method_name,omitempty" description:"线下收款方式"`
|
||||
OfflineTradeNo string `json:"offline_trade_no,omitempty" description:"线下交易单号"`
|
||||
PaymentVoucherKeys []string `json:"payment_voucher_keys,omitempty" description:"线下收款凭证"`
|
||||
EvidenceRefs []string `json:"evidence_refs,omitempty" description:"申请依据"`
|
||||
ApprovalRequired bool `json:"approval_required" description:"是否需要审批"`
|
||||
ApprovalInstanceID *uint `json:"approval_instance_id,omitempty" description:"审批实例 ID"`
|
||||
PaidAmount *int64 `json:"paid_amount,omitempty" description:"实付金额(分)"`
|
||||
PaidAt *time.Time `json:"paid_at,omitempty" description:"支付时间"`
|
||||
ExpireAt *time.Time `json:"expire_at,omitempty" description:"支付截止时间"`
|
||||
CompletedAt *time.Time `json:"completed_at,omitempty" description:"延期生效时间"`
|
||||
ExceptionCode string `json:"exception_code,omitempty" description:"异常原因码"`
|
||||
ExceptionSummary string `json:"exception_summary,omitempty" description:"异常说明"`
|
||||
RefundNo string `json:"refund_no,omitempty" description:"原路退款单号(仅执行异常)"`
|
||||
RefundAmount *int64 `json:"refund_amount,omitempty" description:"退款金额"`
|
||||
RefundedAt *time.Time `json:"refunded_at,omitempty" description:"退款时间"`
|
||||
CreatedBy *uint `json:"created_by,omitempty" description:"后台创建人"`
|
||||
CreatedAt time.Time `json:"created_at" description:"创建时间"`
|
||||
ID uint `json:"id" description:"订单 ID"`
|
||||
OrderNo string `json:"order_no" description:"订单号"`
|
||||
BatchNo string `json:"batch_no,omitempty" description:"批次号"`
|
||||
PackageUsageID uint `json:"package_usage_id" description:"套餐记录 ID"`
|
||||
PackageID uint `json:"package_id" description:"套餐 ID"`
|
||||
PackageName string `json:"package_name" description:"套餐名称快照"`
|
||||
AssetType string `json:"asset_type" description:"资产类型 iot_card / device"`
|
||||
AssetID uint `json:"asset_id" description:"资产 ID"`
|
||||
AssetIdentifier string `json:"asset_identifier" description:"资产标识快照"`
|
||||
ShopID uint `json:"shop_id" description:"下单时资产所属店铺"`
|
||||
CustomerID *uint `json:"customer_id,omitempty" description:"H5 下单的客户"`
|
||||
Source string `json:"source" description:"来源:client / admin / offline"`
|
||||
SourceName string `json:"source_name" description:"来源名称"`
|
||||
InputDays int `json:"input_days" description:"输入天数"`
|
||||
Months int `json:"months" description:"计费月数"`
|
||||
ExtensionDays int `json:"extension_days" description:"计费 / 延长天数"`
|
||||
UnitPrice int64 `json:"unit_price" description:"单价(分/月)"`
|
||||
Amount int64 `json:"amount" description:"应付金额(分)"`
|
||||
PolicyName string `json:"policy_name" description:"政策名称快照"`
|
||||
BeforeDeadlineAt time.Time `json:"before_deadline_at" description:"下单时截止时间"`
|
||||
ExpectedDeadlineAt time.Time `json:"expected_deadline_at" description:"预计新截止时间"`
|
||||
Status string `json:"status" description:"状态:pending_payment/pending_approval/rejected/paid/completed/closed/exception/refunded"`
|
||||
StatusName string `json:"status_name" description:"状态名称"`
|
||||
PaymentMethod string `json:"payment_method" description:"支付方式:wechat/alipay/offline"`
|
||||
PaymentMerchantName string `json:"payment_merchant_name,omitempty" description:"收款商户名称(取已支付或已退款支付单快照)"`
|
||||
ThirdPartyTradeNo string `json:"third_party_trade_no,omitempty" description:"交易流水号"`
|
||||
PaymentNo string `json:"payment_no,omitempty" description:"支付单号"`
|
||||
QRContent string `json:"qr_content,omitempty" description:"支付内容(待支付时返回,前端渲染为二维码或跳转链接)"`
|
||||
PayConfig *ClientPayConfig `json:"pay_config,omitempty" description:"微信内直接支付(JSAPI)参数,H5 带 app_type 下微信单时返回,前端用它拉起支付"`
|
||||
OfflinePaymentMethodName string `json:"offline_payment_method_name,omitempty" description:"线下收款方式"`
|
||||
OfflineTradeNo string `json:"offline_trade_no,omitempty" description:"线下交易单号"`
|
||||
PaymentVoucherKeys []string `json:"payment_voucher_keys,omitempty" description:"线下收款凭证"`
|
||||
EvidenceRefs []string `json:"evidence_refs,omitempty" description:"申请依据"`
|
||||
ApprovalRequired bool `json:"approval_required" description:"是否需要审批"`
|
||||
ApprovalInstanceID *uint `json:"approval_instance_id,omitempty" description:"审批实例 ID"`
|
||||
PaidAmount *int64 `json:"paid_amount,omitempty" description:"实付金额(分)"`
|
||||
PaidAt *time.Time `json:"paid_at,omitempty" description:"支付时间"`
|
||||
ExpireAt *time.Time `json:"expire_at,omitempty" description:"支付截止时间"`
|
||||
CompletedAt *time.Time `json:"completed_at,omitempty" description:"延期生效时间"`
|
||||
ExceptionCode string `json:"exception_code,omitempty" description:"异常原因码"`
|
||||
ExceptionSummary string `json:"exception_summary,omitempty" description:"异常说明"`
|
||||
RefundNo string `json:"refund_no,omitempty" description:"原路退款单号(仅执行异常)"`
|
||||
RefundAmount *int64 `json:"refund_amount,omitempty" description:"退款金额"`
|
||||
RefundedAt *time.Time `json:"refunded_at,omitempty" description:"退款时间"`
|
||||
CreatedBy *uint `json:"created_by,omitempty" description:"后台创建人"`
|
||||
CreatedAt time.Time `json:"created_at" description:"创建时间"`
|
||||
}
|
||||
|
||||
// SilenceSpecialItem 特殊延期的一条明细。
|
||||
@@ -410,6 +418,13 @@ type SilenceIDPath struct {
|
||||
ID uint `json:"id" params:"id" path:"id" validate:"required,min=1" required:"true" description:"ID"`
|
||||
}
|
||||
|
||||
// SilenceOrderCancelRequest 作废待支付延期订单请求。
|
||||
type SilenceOrderCancelRequest struct {
|
||||
// ID 来自路径参数,由 handler 单独校验;这里不加 validate,否则解析请求体时一律报"必须大于 0"
|
||||
ID uint `json:"-" params:"id" path:"id" required:"true" description:"延期订单 ID"`
|
||||
Reason string `json:"reason" validate:"omitempty,max=200" maxLength:"200" description:"作废原因(选填)"`
|
||||
}
|
||||
|
||||
// SilenceRecordListRequest 沉默期流水查询请求。
|
||||
type SilenceRecordListRequest struct {
|
||||
PackageUsageID uint `json:"package_usage_id" query:"package_usage_id" validate:"required,min=1" required:"true" description:"套餐记录 ID"`
|
||||
|
||||
233
internal/model/dto/record_query_dto.go
Normal file
233
internal/model/dto/record_query_dto.go
Normal file
@@ -0,0 +1,233 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
)
|
||||
|
||||
// RecordRangeQuery 是记录查询的公共条件:资产标识选填(不传查全部),时间范围必填(跨度不超过 31 天),分页。
|
||||
type RecordRangeQuery struct {
|
||||
Identifier string `query:"identifier" validate:"omitempty,max=50" maxLength:"50" description:"资产标识(虚拟号/ICCID/MSISDN,设备支持 IMEI/SN);不传查全部"`
|
||||
StartTime string `query:"start_time" validate:"required" required:"true" description:"开始时间(RFC3339 或 2006-01-02 15:04:05,上海时间)"`
|
||||
EndTime string `query:"end_time" validate:"required" required:"true" description:"结束时间(不含),跨度不超过 31 天"`
|
||||
Page int `query:"page" validate:"omitempty,min=1" minimum:"1" description:"页码,默认 1"`
|
||||
PageSize int `query:"page_size" validate:"omitempty,min=1,max=100" minimum:"1" maximum:"100" description:"每页条数,默认 20,最大 100"`
|
||||
}
|
||||
|
||||
// RecordDateRangeQuery 是按日期查询的公共条件:资产标识选填,日期范围必填(含首尾,跨度不超过 31 天),分页。
|
||||
type RecordDateRangeQuery struct {
|
||||
Identifier string `query:"identifier" validate:"omitempty,max=50" maxLength:"50" description:"资产标识(虚拟号/ICCID/MSISDN,设备支持 IMEI/SN);不传查全部"`
|
||||
StartDate string `query:"start_date" validate:"required" required:"true" description:"开始日期(2006-01-02,含)"`
|
||||
EndDate string `query:"end_date" validate:"required" required:"true" description:"结束日期(2006-01-02,含),跨度不超过 31 天"`
|
||||
Page int `query:"page" validate:"omitempty,min=1" minimum:"1" description:"页码,默认 1"`
|
||||
PageSize int `query:"page_size" validate:"omitempty,min=1,max=100" minimum:"1" maximum:"100" description:"每页条数,默认 20,最大 100"`
|
||||
}
|
||||
|
||||
// GatewayRawItem 是采集记录保存的网关原始请求与响应。
|
||||
type GatewayRawItem struct {
|
||||
RawRequest json.RawMessage `json:"raw_request" description:"网关明文业务请求(加密前),未收集时为 null"`
|
||||
HTTPStatus *int `json:"http_status" description:"HTTP 状态码,未拿到响应时为 null"`
|
||||
GatewayCode *int `json:"gateway_code" description:"网关响应 code"`
|
||||
GatewayMsg string `json:"gateway_msg" description:"网关响应 msg"`
|
||||
GatewayTraceID string `json:"gateway_trace_id" description:"网关响应 trace_id"`
|
||||
RawResponse json.RawMessage `json:"raw_response" description:"网关原始响应体(JSON 且不超过 4KB 时)"`
|
||||
RawResponseText string `json:"raw_response_text" description:"网关原始响应体文本(非 JSON 或超过 4KB 截断时)"`
|
||||
RawTruncated bool `json:"raw_truncated" description:"原始响应是否被截断"`
|
||||
GatewayAttempts int `json:"gateway_attempts" description:"网关客户端内部 HTTP 尝试次数(原始数据为最后一次)"`
|
||||
}
|
||||
|
||||
// TrafficCollectionListRequest 采集成功记录列表请求。
|
||||
type TrafficCollectionListRequest struct {
|
||||
RecordRangeQuery
|
||||
CarrierID *uint `query:"carrier_id" validate:"omitempty,min=1" description:"运营商账户ID"`
|
||||
Decision string `query:"decision" validate:"omitempty,max=32" description:"写入判断:written/baseline/queue_not_full/slope_negative/out_of_order/settled_existing"`
|
||||
Source string `query:"source" validate:"omitempty,max=32" description:"来源:polling/manual_sync/business_event"`
|
||||
Scene string `query:"scene" validate:"omitempty,max=64" description:"场景"`
|
||||
HasDelta *bool `query:"has_delta" description:"是否产生增量:true 只看增量大于 0,false 只看没有增量"`
|
||||
StaleGuarded *bool `query:"stale_guarded" description:"是否触发重置日防旧值"`
|
||||
}
|
||||
|
||||
// TrafficCollectionRecordItem 采集成功记录。
|
||||
type TrafficCollectionRecordItem struct {
|
||||
CardTrafficCollectionItem
|
||||
IotCardID uint `json:"iot_card_id" description:"卡ID"`
|
||||
ICCID string `json:"iccid" description:"ICCID"`
|
||||
CarrierID uint `json:"carrier_id" description:"运营商账户ID(历史记录为 0)"`
|
||||
CarrierName string `json:"carrier_name" description:"运营商账户名称"`
|
||||
}
|
||||
|
||||
// TrafficCollectionRecordListResponse 采集成功记录分页结果。
|
||||
type TrafficCollectionRecordListResponse struct {
|
||||
Items []TrafficCollectionRecordItem `json:"items" description:"采集成功记录"`
|
||||
Total int64 `json:"total" description:"总数"`
|
||||
Page int `json:"page" description:"页码"`
|
||||
PageSize int `json:"page_size" description:"每页条数"`
|
||||
}
|
||||
|
||||
// TrafficCollectionFailureListRequest 采集失败记录列表请求。
|
||||
type TrafficCollectionFailureListRequest struct {
|
||||
RecordRangeQuery
|
||||
CarrierID *uint `query:"carrier_id" validate:"omitempty,min=1" description:"运营商账户ID"`
|
||||
Result string `query:"result" validate:"omitempty,oneof=failed rate_limited invalid_payload no_reading invalid_reading" description:"失败类型:failed/rate_limited/invalid_payload/no_reading/invalid_reading"`
|
||||
ErrorCategory string `query:"error_category" validate:"omitempty,max=30" description:"错误类别:timeout/network/http/invalid_response/upstream 等"`
|
||||
ProviderCode string `query:"provider_code" validate:"omitempty,max=30" description:"上游返回码"`
|
||||
Source string `query:"source" validate:"omitempty,max=32" description:"来源"`
|
||||
Scene string `query:"scene" validate:"omitempty,max=64" description:"场景"`
|
||||
}
|
||||
|
||||
// TrafficCollectionFailureItem 采集失败记录。
|
||||
type TrafficCollectionFailureItem struct {
|
||||
ID uint `json:"id" description:"记录ID"`
|
||||
IotCardID uint `json:"iot_card_id" description:"卡ID"`
|
||||
ICCID string `json:"iccid" description:"ICCID"`
|
||||
CarrierID uint `json:"carrier_id" description:"运营商账户ID"`
|
||||
CarrierName string `json:"carrier_name" description:"运营商账户名称"`
|
||||
ObservedAt time.Time `json:"observed_at" description:"采集时间"`
|
||||
ObservationID string `json:"observation_id" description:"采集 ID(等于对接日志 integration_id)"`
|
||||
Source string `json:"source" description:"来源"`
|
||||
Scene string `json:"scene" description:"场景"`
|
||||
Result string `json:"result" description:"失败类型"`
|
||||
ErrorCategory string `json:"error_category" description:"错误类别"`
|
||||
ProviderCode string `json:"provider_code" description:"上游返回码"`
|
||||
ProviderMessage string `json:"provider_message" description:"上游返回信息或错误信息"`
|
||||
DurationMS int `json:"duration_ms" description:"调用耗时(毫秒)"`
|
||||
GatewayRawItem
|
||||
}
|
||||
|
||||
// TrafficCollectionFailureListResponse 采集失败记录分页结果。
|
||||
type TrafficCollectionFailureListResponse struct {
|
||||
Items []TrafficCollectionFailureItem `json:"items" description:"采集失败记录"`
|
||||
Total int64 `json:"total" description:"总数"`
|
||||
Page int `json:"page" description:"页码"`
|
||||
PageSize int `json:"page_size" description:"每页条数"`
|
||||
}
|
||||
|
||||
// CardDailyUsageListRequest 卡日流量列表请求。
|
||||
type CardDailyUsageListRequest struct {
|
||||
RecordDateRangeQuery
|
||||
CarrierID *uint `query:"carrier_id" validate:"omitempty,min=1" description:"运营商账户ID"`
|
||||
MinUsageMB *float64 `query:"min_usage_mb" validate:"omitempty,min=0" description:"当日已结算增量下限(MB),用于排查异常大流量"`
|
||||
}
|
||||
|
||||
// CardDailyUsageItem 卡日流量(卡日快照 tb_card_flow_day)。
|
||||
type CardDailyUsageItem struct {
|
||||
ID uint `json:"id" description:"记录ID"`
|
||||
IotCardID uint `json:"iot_card_id" description:"卡ID"`
|
||||
ICCID string `json:"iccid" description:"ICCID"`
|
||||
CarrierID uint `json:"carrier_id" description:"运营商账户ID"`
|
||||
CarrierName string `json:"carrier_name" description:"运营商账户名称"`
|
||||
Date string `json:"date" description:"日期(上海)"`
|
||||
SettledMB float64 `json:"settled_mb" description:"当日已结算增量合计(MB),即当日用量"`
|
||||
MonthUsedMB float64 `json:"month_used_mb" description:"当日结束时的本月自然月累计(MB)"`
|
||||
VendorUsedMB float64 `json:"vendor_used_mb" description:"当天最后一次写入的运营商原始读数(MB)"`
|
||||
StaleGuarded bool `json:"stale_guarded" description:"当天是否触发重置日防旧值"`
|
||||
ObsCount int `json:"obs_count" description:"当天写入次数"`
|
||||
UpdatedAt time.Time `json:"updated_at" description:"更新时间"`
|
||||
}
|
||||
|
||||
// CardDailyUsageListResponse 卡日流量分页结果。
|
||||
type CardDailyUsageListResponse struct {
|
||||
Items []CardDailyUsageItem `json:"items" description:"卡日流量"`
|
||||
Total int64 `json:"total" description:"总数"`
|
||||
Page int `json:"page" description:"页码"`
|
||||
PageSize int `json:"page_size" description:"每页条数"`
|
||||
}
|
||||
|
||||
// PackageUsageDailyRecordListRequest 套餐日流量详单列表请求。
|
||||
type PackageUsageDailyRecordListRequest struct {
|
||||
RecordDateRangeQuery
|
||||
PackageUsageID *uint `query:"package_usage_id" validate:"omitempty,min=1" description:"套餐使用记录ID"`
|
||||
PackageID *uint `query:"package_id" validate:"omitempty,min=1" description:"套餐ID"`
|
||||
CarrierID *uint `query:"carrier_id" validate:"omitempty,min=1" description:"运营商账户ID(按卡所属账户)"`
|
||||
}
|
||||
|
||||
// PackageUsageDailyRecordItem 套餐日流量详单。
|
||||
type PackageUsageDailyRecordItem struct {
|
||||
ID uint `json:"id" description:"记录ID"`
|
||||
PackageUsageID uint `json:"package_usage_id" description:"套餐使用记录ID"`
|
||||
PackageID uint `json:"package_id" description:"套餐ID"`
|
||||
PackageName string `json:"package_name" description:"套餐名称(套餐使用记录快照)"`
|
||||
IotCardID uint `json:"iot_card_id" description:"卡ID,设备套餐为 0"`
|
||||
ICCID string `json:"iccid" description:"ICCID(卡套餐)"`
|
||||
DeviceID uint `json:"device_id" description:"设备ID,卡套餐为 0"`
|
||||
DeviceVirtualNo string `json:"device_virtual_no" description:"设备号(设备套餐)"`
|
||||
DeviceIMEI string `json:"device_imei" description:"设备 IMEI(设备套餐)"`
|
||||
Date string `json:"date" description:"日期"`
|
||||
DailyUsageMB int `json:"daily_usage_mb" description:"当日流量(MB)"`
|
||||
CumulativeUsageMB int64 `json:"cumulative_usage_mb" description:"截止当日累计(MB)"`
|
||||
UpdatedAt time.Time `json:"updated_at" description:"更新时间"`
|
||||
}
|
||||
|
||||
// PackageUsageDailyRecordListResponse 套餐日流量详单分页结果。
|
||||
type PackageUsageDailyRecordListResponse struct {
|
||||
Items []PackageUsageDailyRecordItem `json:"items" description:"套餐日流量详单"`
|
||||
Total int64 `json:"total" description:"总数"`
|
||||
Page int `json:"page" description:"页码"`
|
||||
PageSize int `json:"page_size" description:"每页条数"`
|
||||
}
|
||||
|
||||
// PackageTrafficAdjustmentQueryRequest 套餐流量冲正流水列表请求。
|
||||
type PackageTrafficAdjustmentQueryRequest struct {
|
||||
RecordRangeQuery
|
||||
PackageUsageID *uint `query:"package_usage_id" validate:"omitempty,min=1" description:"套餐使用记录ID"`
|
||||
OperatorID *uint `query:"operator_id" validate:"omitempty,min=1" description:"操作人账号ID"`
|
||||
Direction string `query:"direction" validate:"omitempty,oneof=deduct refund" description:"调整方向:deduct 补扣(增量为正),refund 退回(增量为负)"`
|
||||
}
|
||||
|
||||
// PackageTrafficAdjustmentRecordItem 冲正流水(跨卡列表)。
|
||||
type PackageTrafficAdjustmentRecordItem struct {
|
||||
PackageTrafficAdjustmentItem
|
||||
PackageName string `json:"package_name" description:"套餐名称(套餐使用记录快照)"`
|
||||
IotCardID uint `json:"iot_card_id" description:"卡ID"`
|
||||
ICCID string `json:"iccid" description:"ICCID(卡套餐)"`
|
||||
DeviceID uint `json:"device_id" description:"设备ID"`
|
||||
DeviceVirtualNo string `json:"device_virtual_no" description:"设备号(设备套餐)"`
|
||||
DeviceIMEI string `json:"device_imei" description:"设备 IMEI(设备套餐)"`
|
||||
}
|
||||
|
||||
// PackageTrafficAdjustmentRecordListResponse 冲正流水分页结果(跨卡列表)。
|
||||
type PackageTrafficAdjustmentRecordListResponse struct {
|
||||
Items []PackageTrafficAdjustmentRecordItem `json:"items" description:"冲正流水"`
|
||||
Total int64 `json:"total" description:"总数"`
|
||||
Page int `json:"page" description:"页码"`
|
||||
PageSize int `json:"page_size" description:"每页条数"`
|
||||
}
|
||||
|
||||
// RefundPostProcessAttemptListRequest 退款资产后处理尝试记录列表请求。
|
||||
type RefundPostProcessAttemptListRequest struct {
|
||||
RecordRangeQuery
|
||||
RefundID *uint `query:"refund_id" validate:"omitempty,min=1" description:"退款单ID"`
|
||||
RefundNo string `query:"refund_no" validate:"omitempty,max=64" description:"退款单号"`
|
||||
Step string `query:"step" validate:"omitempty,oneof=load invalidate activate check_main stop mark done" description:"处理步骤:load/invalidate/activate/check_main/stop/mark/done"`
|
||||
Result string `query:"result" validate:"omitempty,oneof=success failed" description:"结果:success/failed"`
|
||||
ErrorCode string `query:"error_code" validate:"omitempty,max=32" description:"错误码"`
|
||||
Trigger string `query:"trigger" validate:"omitempty,oneof=outbox manual" description:"触发方式:outbox(含补偿扫描)/manual(人工重试)"`
|
||||
}
|
||||
|
||||
// RefundPostProcessAttemptItem 退款资产后处理尝试记录。
|
||||
type RefundPostProcessAttemptItem struct {
|
||||
ID uint `json:"id" description:"记录ID"`
|
||||
RefundID uint `json:"refund_id" description:"退款单ID"`
|
||||
RefundNo string `json:"refund_no" description:"退款单号"`
|
||||
Step string `json:"step" description:"处理步骤(失败时为失败步骤,成功为 done)"`
|
||||
AssetType string `json:"asset_type" description:"资产类型"`
|
||||
AssetID uint `json:"asset_id" description:"资产ID"`
|
||||
ICCID string `json:"iccid" description:"ICCID(单卡资产)"`
|
||||
DeviceVirtualNo string `json:"device_virtual_no" description:"设备号(设备资产)"`
|
||||
DeviceIMEI string `json:"device_imei" description:"设备 IMEI(设备资产)"`
|
||||
Attempt int `json:"attempt" description:"尝试序号"`
|
||||
Trigger string `json:"trigger" description:"触发方式"`
|
||||
Result string `json:"result" description:"结果"`
|
||||
ErrorCode string `json:"error_code" description:"错误码"`
|
||||
ErrorMessage string `json:"error_message" description:"错误信息"`
|
||||
DurationMS int `json:"duration_ms" description:"耗时(毫秒)"`
|
||||
CreatedAt time.Time `json:"created_at" description:"记录时间"`
|
||||
}
|
||||
|
||||
// RefundPostProcessAttemptListResponse 退款资产后处理尝试记录分页结果。
|
||||
type RefundPostProcessAttemptListResponse struct {
|
||||
Items []RefundPostProcessAttemptItem `json:"items" description:"尝试记录"`
|
||||
Total int64 `json:"total" description:"总数"`
|
||||
Page int `json:"page" description:"页码"`
|
||||
PageSize int `json:"page_size" description:"每页条数"`
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
package dto
|
||||
|
||||
import "time"
|
||||
|
||||
// CreateRefundRequest 创建退款申请请求
|
||||
type CreateRefundRequest struct {
|
||||
OrderID uint `json:"order_id" validate:"required" required:"true" description:"关联订单ID"`
|
||||
@@ -60,6 +62,7 @@ type RefundListRequest struct {
|
||||
OrderID *uint `json:"order_id" query:"order_id" validate:"omitempty" description:"关联订单ID"`
|
||||
ShopID *uint `json:"shop_id" query:"shop_id" validate:"omitempty" description:"店铺ID"`
|
||||
AssetIdentifier string `json:"asset_identifier" query:"asset_identifier" validate:"omitempty,max=100" maxLength:"100" description:"资产标识精确检索(ICCID 或 设备虚拟号,非空时精确匹配)"`
|
||||
AssetPostStatus *int `json:"asset_post_status" query:"asset_post_status" validate:"omitempty,min=0,max=3" minimum:"0" maximum:"3" description:"资产后处理状态 (0:未开始, 1:待重试, 2:已完成, 3:需人工处理)"`
|
||||
}
|
||||
|
||||
// RefundResponse 退款申请详情响应
|
||||
@@ -116,6 +119,10 @@ type RefundResponse struct {
|
||||
Remark string `json:"remark,omitempty" description:"审批备注"`
|
||||
CommissionDeducted bool `json:"commission_deducted" description:"佣金是否已回扣"`
|
||||
AssetReset bool `json:"asset_reset" description:"退款后资产处理是否完成"`
|
||||
AssetPostStatus int `json:"asset_post_status" description:"资产后处理状态 (0:未开始, 1:待重试, 2:已完成, 3:需人工处理)"`
|
||||
AssetPostAttempts int `json:"asset_post_attempts" description:"资产后处理已尝试次数(自动重试上限 10 次)"`
|
||||
AssetPostLastError string `json:"asset_post_last_error" description:"资产后处理最后一次错误"`
|
||||
AssetPostNextAt *time.Time `json:"asset_post_next_at,omitempty" description:"资产后处理下次自动重试时间"`
|
||||
SubmitterID uint `json:"submitter_id" description:"提交人账号ID"`
|
||||
SubmitterName string `json:"submitter_name" description:"提交人账号名称"`
|
||||
ApprovalInstanceID *uint `json:"approval_instance_id,omitempty" description:"通用审批实例ID"`
|
||||
|
||||
67
internal/model/iot_card_realname.go
Normal file
67
internal/model/iot_card_realname.go
Normal file
@@ -0,0 +1,67 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gorm.io/datatypes"
|
||||
)
|
||||
|
||||
// IotCardRealname 是卡的当前实名记录(每卡一行)。
|
||||
// 实名状态 real_name_status 仍在 tb_iot_card;这里只记录实名时间及来源、二次实名状态。
|
||||
type IotCardRealname struct {
|
||||
ID uint `gorm:"column:id;primaryKey" json:"id"`
|
||||
CardID uint `gorm:"column:card_id;not null" json:"card_id"`
|
||||
RealnameAt *time.Time `gorm:"column:realname_at" json:"realname_at,omitempty"`
|
||||
RealnameAtSource string `gorm:"column:realname_at_source;type:varchar(20);not null;default:''" json:"realname_at_source"`
|
||||
UpstreamRealnameAt *time.Time `gorm:"column:upstream_realname_at" json:"upstream_realname_at,omitempty"`
|
||||
FirstObservedAt *time.Time `gorm:"column:first_observed_at" json:"first_observed_at,omitempty"`
|
||||
ResetStatus string `gorm:"column:reset_status;type:varchar(20);not null;default:'none'" json:"reset_status"`
|
||||
ResetAt *time.Time `gorm:"column:reset_at" json:"reset_at,omitempty"`
|
||||
ResetBaselineAt *time.Time `gorm:"column:reset_baseline_at" json:"reset_baseline_at,omitempty"`
|
||||
ResetBatchID *uint `gorm:"column:reset_batch_id" json:"reset_batch_id,omitempty"`
|
||||
CreatedAt time.Time `gorm:"column:created_at;not null;default:CURRENT_TIMESTAMP" json:"created_at"`
|
||||
UpdatedAt time.Time `gorm:"column:updated_at;not null;default:CURRENT_TIMESTAMP" json:"updated_at"`
|
||||
}
|
||||
|
||||
// TableName 指定表名。
|
||||
func (IotCardRealname) TableName() string { return "tb_iot_card_realname" }
|
||||
|
||||
// IotCardRealnameHistory 是卡实名时间变化历史(只追加)。
|
||||
type IotCardRealnameHistory struct {
|
||||
ID uint `gorm:"column:id;primaryKey" json:"id"`
|
||||
CardID uint `gorm:"column:card_id;not null" json:"card_id"`
|
||||
ICCID string `gorm:"column:iccid;type:varchar(20);not null;default:''" json:"iccid"`
|
||||
BeforeAt *time.Time `gorm:"column:before_at" json:"before_at,omitempty"`
|
||||
AfterAt *time.Time `gorm:"column:after_at" json:"after_at,omitempty"`
|
||||
AfterSource string `gorm:"column:after_source;type:varchar(20);not null;default:''" json:"after_source"`
|
||||
ChangeType string `gorm:"column:change_type;type:varchar(30);not null" json:"change_type"`
|
||||
ObservationSource string `gorm:"column:observation_source;type:varchar(30);not null;default:''" json:"observation_source"`
|
||||
ResetBatchID *uint `gorm:"column:reset_batch_id" json:"reset_batch_id,omitempty"`
|
||||
OperatorID uint `gorm:"column:operator_id;not null;default:0" json:"operator_id"`
|
||||
ObservedAt time.Time `gorm:"column:observed_at;not null" json:"observed_at"`
|
||||
CreatedAt time.Time `gorm:"column:created_at;not null;default:CURRENT_TIMESTAMP" json:"created_at"`
|
||||
}
|
||||
|
||||
// TableName 指定表名。
|
||||
func (IotCardRealnameHistory) TableName() string { return "tb_iot_card_realname_history" }
|
||||
|
||||
// IotCardRealnameResetBatch 是二次实名导入批次。
|
||||
type IotCardRealnameResetBatch struct {
|
||||
ID uint `gorm:"column:id;primaryKey" json:"id"`
|
||||
BatchNo string `gorm:"column:batch_no;type:varchar(40);not null" json:"batch_no"`
|
||||
ImportFileKey string `gorm:"column:import_file_key;type:varchar(500);not null;default:''" json:"import_file_key"`
|
||||
Reason string `gorm:"column:reason;type:varchar(500);not null;default:''" json:"reason"`
|
||||
TotalCount int `gorm:"column:total_count;not null;default:0" json:"total_count"`
|
||||
SucceededCount int `gorm:"column:succeeded_count;not null;default:0" json:"succeeded_count"`
|
||||
SkippedCount int `gorm:"column:skipped_count;not null;default:0" json:"skipped_count"`
|
||||
RevertedCount int `gorm:"column:reverted_count;not null;default:0" json:"reverted_count"`
|
||||
CompletedCount int `gorm:"column:completed_count;not null;default:0" json:"completed_count"`
|
||||
Items datatypes.JSON `gorm:"column:items;type:jsonb;not null;default:'[]'" json:"items"`
|
||||
OperatorID uint `gorm:"column:operator_id;not null;default:0" json:"operator_id"`
|
||||
OperatorName string `gorm:"column:operator_name;type:varchar(100);not null;default:''" json:"operator_name"`
|
||||
CreatedAt time.Time `gorm:"column:created_at;not null;default:CURRENT_TIMESTAMP" json:"created_at"`
|
||||
UpdatedAt time.Time `gorm:"column:updated_at;not null;default:CURRENT_TIMESTAMP" json:"updated_at"`
|
||||
}
|
||||
|
||||
// TableName 指定表名。
|
||||
func (IotCardRealnameResetBatch) TableName() string { return "tb_iot_card_realname_reset_batch" }
|
||||
@@ -77,6 +77,12 @@ type RefundRequest struct {
|
||||
// 后处理标记
|
||||
CommissionDeducted bool `gorm:"column:commission_deducted;not null;default:false;comment:佣金是否已回扣" json:"commission_deducted"`
|
||||
AssetReset bool `gorm:"column:asset_reset;not null;default:false;comment:退款后资产处理是否完成" json:"asset_reset"`
|
||||
|
||||
// 资产后处理重试状态(refactor-audit-log-persistence)
|
||||
AssetPostStatus int `gorm:"column:asset_post_status;type:smallint;not null;default:0;comment:资产后处理状态 0-未开始 1-待重试 2-已完成 3-需人工处理" json:"asset_post_status"`
|
||||
AssetPostAttempts int `gorm:"column:asset_post_attempts;type:int;not null;default:0;comment:资产后处理已尝试次数" json:"asset_post_attempts"`
|
||||
AssetPostLastError string `gorm:"column:asset_post_last_error;type:varchar(500);not null;default:'';comment:资产后处理最后一次错误摘要" json:"asset_post_last_error"`
|
||||
AssetPostNextAt *time.Time `gorm:"column:asset_post_next_at;comment:资产后处理下次自动重试时间" json:"asset_post_next_at,omitempty"`
|
||||
}
|
||||
|
||||
// TableName 指定表名
|
||||
@@ -136,3 +142,34 @@ func RefundActiveStatuses() []int {
|
||||
func RefundResubmittableStatuses() []int {
|
||||
return []int{RefundStatusRejected, RefundStatusReturned, RefundStatusChannelFailed, RefundStatusSubmissionFailed}
|
||||
}
|
||||
|
||||
// 退款资产后处理状态。
|
||||
const (
|
||||
RefundAssetPostNotStarted = 0 // 未开始
|
||||
RefundAssetPostRetryPending = 1 // 待重试
|
||||
RefundAssetPostCompleted = 2 // 已完成
|
||||
RefundAssetPostManualRequired = 3 // 需人工处理
|
||||
)
|
||||
|
||||
// RefundPostProcessAttempt 退款资产后处理逐次尝试记录,只新增不修改。
|
||||
type RefundPostProcessAttempt struct {
|
||||
ID uint `gorm:"column:id;primaryKey;autoIncrement" json:"id"`
|
||||
RefundID uint `gorm:"column:refund_id;not null" json:"refund_id"`
|
||||
RefundNo string `gorm:"column:refund_no;type:varchar(64);not null;default:''" json:"refund_no"`
|
||||
Step string `gorm:"column:step;type:varchar(32);not null" json:"step"`
|
||||
AssetType string `gorm:"column:asset_type;type:varchar(16);not null;default:''" json:"asset_type"`
|
||||
AssetID uint `gorm:"column:asset_id;not null;default:0" json:"asset_id"`
|
||||
ICCID string `gorm:"column:iccid;type:varchar(30);not null;default:''" json:"iccid"`
|
||||
Attempt int `gorm:"column:attempt;not null" json:"attempt"`
|
||||
Trigger string `gorm:"column:trigger;type:varchar(16);not null" json:"trigger"`
|
||||
Result string `gorm:"column:result;type:varchar(16);not null" json:"result"`
|
||||
ErrorCode string `gorm:"column:error_code;type:varchar(32);not null;default:''" json:"error_code"`
|
||||
ErrorMessage string `gorm:"column:error_message;type:varchar(500);not null;default:''" json:"error_message"`
|
||||
DurationMS int `gorm:"column:duration_ms;not null;default:0" json:"duration_ms"`
|
||||
CreatedAt time.Time `gorm:"column:created_at;type:timestamptz;not null;autoCreateTime" json:"created_at"`
|
||||
}
|
||||
|
||||
// TableName 指定退款资产后处理尝试记录表名。
|
||||
func (RefundPostProcessAttempt) TableName() string {
|
||||
return "tb_refund_post_process_attempt"
|
||||
}
|
||||
|
||||
@@ -110,6 +110,12 @@ func (d *Dispatcher) Ready(ctx context.Context) bool {
|
||||
return err == nil && state == InitStateDone
|
||||
}
|
||||
|
||||
// ingestPaused 判断入库积压是否已触发反压:置位时暂停领取新卡任务(停复机指令照常分发)。
|
||||
func (d *Dispatcher) ingestPaused(ctx context.Context) bool {
|
||||
exists, err := d.store.redis.Exists(ctx, constants.RedisPollingIngestPausedKey).Result()
|
||||
return err == nil && exists > 0
|
||||
}
|
||||
|
||||
func (d *Dispatcher) tick(ctx context.Context, interval time.Duration) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
@@ -118,7 +124,7 @@ func (d *Dispatcher) tick(ctx context.Context, interval time.Duration) {
|
||||
}()
|
||||
// 停复机指令与设备判断的分发只看停复机出口开关,不受 scheduler_mode 限制;卡任务只在新调度就绪时领取。
|
||||
stopResumeOn := d.settings.Current(ctx).StopResumeQueueEnabled
|
||||
cardsReady := d.Ready(ctx)
|
||||
cardsReady := d.Ready(ctx) && !d.ingestPaused(ctx)
|
||||
if !stopResumeOn && !cardsReady {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -27,6 +27,7 @@ func RegisterConfigDefinitions(registry *systemconfig.Registry, logger *zap.Logg
|
||||
return
|
||||
}
|
||||
minZero, minOne, maxSeconds, maxCount := int64(0), int64(1), int64(86400*7), int64(100000)
|
||||
maxDepth := int64(100000000)
|
||||
definitions := []systemconfig.Definition{
|
||||
{Key: constants.SystemConfigPollingSchedulerMode, Module: constants.SystemConfigModulePolling, ValueType: constants.SystemConfigTypeString,
|
||||
DefaultValue: constants.PollingSchedulerModeLegacy, Description: "卡轮询调度模式:legacy 旧分片调度,carrier 按运营商账户调度(整体切换)",
|
||||
@@ -61,6 +62,13 @@ func RegisterConfigDefinitions(registry *systemconfig.Registry, logger *zap.Logg
|
||||
DefaultValue: "5", Description: "停复机连续失败告警阈值", Min: &minOne, Max: &maxCount},
|
||||
{Key: constants.SystemConfigStopResumeStatusGrace, Module: constants.SystemConfigModulePolling, ValueType: constants.SystemConfigTypeInt,
|
||||
DefaultValue: "300", Description: "停复机成功后的状态保护窗口(秒):窗口内查卡状态返回操作前的状态视为上游滞后,不回写;0 不保护", Min: &minZero, Max: &maxSeconds},
|
||||
{Key: constants.SystemConfigPollingIngestMode, Module: constants.SystemConfigModulePolling, ValueType: constants.SystemConfigTypeString,
|
||||
DefaultValue: constants.PollingIngestModeSync, Description: "轮询观测入库模式:sync 卡任务内同步入库,async 只调网关并发布入库消息",
|
||||
EnumValues: []string{constants.PollingIngestModeSync, constants.PollingIngestModeAsync}},
|
||||
{Key: constants.SystemConfigPollingIngestAlertDepth, Module: constants.SystemConfigModulePolling, ValueType: constants.SystemConfigTypeInt,
|
||||
DefaultValue: strconv.Itoa(constants.PollingIngestDefaultAlertDepth), Description: "入库消息积压告警阈值(条)", Min: &minOne, Max: &maxDepth},
|
||||
{Key: constants.SystemConfigPollingIngestPauseDepth, Module: constants.SystemConfigModulePolling, ValueType: constants.SystemConfigTypeInt,
|
||||
DefaultValue: strconv.Itoa(constants.PollingIngestDefaultPauseDepth), Description: "入库消息积压反压阈值(条):超过时暂停派发新卡任务,降到一半以下恢复;须大于告警阈值", Min: &minOne, Max: &maxDepth},
|
||||
}
|
||||
for _, definition := range definitions {
|
||||
if _, exists := registry.Get(definition.Key); exists {
|
||||
@@ -205,6 +213,16 @@ type Settings struct {
|
||||
SRBackoff []time.Duration
|
||||
SRAlertFailCount int
|
||||
SRStatusGrace time.Duration
|
||||
|
||||
// 轮询观测入库(add-polling-async-ingest)。
|
||||
IngestMode string
|
||||
IngestAlertDepth int
|
||||
IngestPauseDepth int
|
||||
}
|
||||
|
||||
// IngestAsync 判断轮询观测是否按异步入库执行。
|
||||
func (s Settings) IngestAsync() bool {
|
||||
return s.IngestMode == constants.PollingIngestModeAsync
|
||||
}
|
||||
|
||||
// SRBackoffFor 返回停复机第 n 次连续失败(n 从 1 起)的退避间隔;超过序列长度取最后一项。
|
||||
@@ -297,6 +315,9 @@ func DefaultSettings() Settings {
|
||||
SRBackoff: []time.Duration{10 * time.Minute, 15 * time.Minute, 30 * time.Minute, time.Hour},
|
||||
SRAlertFailCount: 5,
|
||||
SRStatusGrace: 5 * time.Minute,
|
||||
IngestMode: constants.PollingIngestModeSync,
|
||||
IngestAlertDepth: constants.PollingIngestDefaultAlertDepth,
|
||||
IngestPauseDepth: constants.PollingIngestDefaultPauseDepth,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -421,6 +442,8 @@ func (p *SettingsProvider) load(ctx context.Context) (Settings, error) {
|
||||
{constants.SystemConfigStopResumeUnknownAlert, func(v int) { s.SRUnknownAlert = v }},
|
||||
{constants.SystemConfigStopResumeAlertFailCount, func(v int) { s.SRAlertFailCount = v }},
|
||||
{constants.SystemConfigStopResumeStatusGrace, func(v int) { s.SRStatusGrace = time.Duration(v) * time.Second }},
|
||||
{constants.SystemConfigPollingIngestAlertDepth, func(v int) { s.IngestAlertDepth = v }},
|
||||
{constants.SystemConfigPollingIngestPauseDepth, func(v int) { s.IngestPauseDepth = v }},
|
||||
}
|
||||
for _, item := range ints {
|
||||
raw, err := get(item.key)
|
||||
@@ -448,6 +471,16 @@ func (p *SettingsProvider) load(ctx context.Context) (Settings, error) {
|
||||
for _, value := range srBackoff {
|
||||
s.SRBackoff = append(s.SRBackoff, time.Duration(value)*time.Second)
|
||||
}
|
||||
if raw, err = get(constants.SystemConfigPollingIngestMode); err != nil {
|
||||
return s, err
|
||||
}
|
||||
s.IngestMode = raw
|
||||
if s.IngestPauseDepth <= s.IngestAlertDepth {
|
||||
// 反压阈值须大于告警阈值:配置不满足时按告警阈值的 2 倍执行并告警,避免还没告警就先停派发。
|
||||
p.logger.Warn("入库反压阈值不大于告警阈值,按告警阈值的 2 倍执行",
|
||||
zap.Int("alert_depth", s.IngestAlertDepth), zap.Int("pause_depth", s.IngestPauseDepth))
|
||||
s.IngestPauseDepth = s.IngestAlertDepth * 2
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -188,9 +188,8 @@ func (m *PollingConfigManager) lazyTierFacts(card *model.IotCard) func() TierFac
|
||||
return func() TierFacts {
|
||||
once.Do(func() {
|
||||
if m.tier != nil {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
facts = m.tier.Resolve(ctx, card)
|
||||
// 每次查询在解析器内单独计时,避免一张绑定设备的卡连查多次时共用一个超时。
|
||||
facts = m.tier.Resolve(context.Background(), card)
|
||||
}
|
||||
})
|
||||
return facts
|
||||
|
||||
@@ -156,6 +156,16 @@ func (m *PollingQueueManager) EnqueueManual(ctx context.Context, cardID uint, ta
|
||||
// 使用 RPUSH 与调度器的 LPopCount 组成先进先出;提示通道不是权威,丢失或缓存服务重启时
|
||||
// 库内活动优先项仍在,后续普通轮询执行按条件认领仍会执行,只退化为延迟一个普通轮询周期。
|
||||
func (m *PollingQueueManager) EnqueuePriority(ctx context.Context, cardID uint, taskType string) error {
|
||||
// 同时登记活动优先项索引(轮询步骤据此跳过无优先项卡的查库);recent 集合供索引重建时并入,避免重建期间漏掉新项。
|
||||
member := constants.PollingPriorityIndexMember(cardID, taskType)
|
||||
pipe := m.redis.Pipeline()
|
||||
pipe.SAdd(ctx, constants.RedisPollingPriorityActiveKey, member)
|
||||
pipe.SAdd(ctx, constants.RedisPollingPriorityRecentKey, member)
|
||||
pipe.Expire(ctx, constants.RedisPollingPriorityRecentKey, constants.PollingPriorityIndexRecentTTL)
|
||||
if _, err := pipe.Exec(ctx); err != nil {
|
||||
m.logger.Warn("登记活动优先项索引失败,轮询步骤将在索引重建后发现该项", zap.Uint("card_id", cardID),
|
||||
zap.String("task_type", taskType), zap.Error(err))
|
||||
}
|
||||
key := constants.RedisPollingPriorityQueueKey(taskType)
|
||||
return m.redis.RPush(ctx, key, fmt.Sprintf("%d", cardID)).Err()
|
||||
}
|
||||
|
||||
@@ -76,7 +76,7 @@ func (r *TierResolver) Prefill(ctx context.Context, cards []*model.IotCard) {
|
||||
}
|
||||
results := make(map[uint]TierFacts, len(cards))
|
||||
if len(standaloneIDs) > 0 {
|
||||
states, err := r.usage.PackageStatesByCarriers(ctx, constants.AssetTypeIotCard, standaloneIDs)
|
||||
states, err := r.packageStates(ctx, constants.AssetTypeIotCard, standaloneIDs)
|
||||
if err != nil {
|
||||
r.logger.Warn("批量查询卡套餐状态失败,相关卡本次不按套餐状态匹配", zap.Error(err))
|
||||
}
|
||||
@@ -87,7 +87,9 @@ func (r *TierResolver) Prefill(ctx context.Context, cards []*model.IotCard) {
|
||||
}
|
||||
}
|
||||
if len(boundCardIDs) > 0 && r.bindings != nil {
|
||||
bindings, err := r.bindings.GetActiveBindingsByCardIDs(ctx, boundCardIDs)
|
||||
bindCtx, cancel := context.WithTimeout(ctx, constants.PollingTierQueryTimeout)
|
||||
bindings, err := r.bindings.GetActiveBindingsByCardIDs(bindCtx, boundCardIDs)
|
||||
cancel()
|
||||
if err != nil {
|
||||
r.logger.Warn("批量查询卡绑定设备失败,相关卡本次不按套餐状态匹配", zap.Error(err))
|
||||
} else {
|
||||
@@ -97,8 +99,8 @@ func (r *TierResolver) Prefill(ctx context.Context, cards []*model.IotCard) {
|
||||
deviceOf[binding.IotCardID] = binding.DeviceID
|
||||
deviceIDs = append(deviceIDs, binding.DeviceID)
|
||||
}
|
||||
deviceStates, devErr := r.usage.PackageStatesByCarriers(ctx, constants.AssetTypeDevice, deviceIDs)
|
||||
cardStates, cardErr := r.usage.PackageStatesByCarriers(ctx, constants.AssetTypeIotCard, boundCardIDs)
|
||||
deviceStates, devErr := r.packageStates(ctx, constants.AssetTypeDevice, deviceIDs)
|
||||
cardStates, cardErr := r.packageStates(ctx, constants.AssetTypeIotCard, boundCardIDs)
|
||||
for _, id := range boundCardIDs {
|
||||
// 有有效设备绑定按设备计算;绑定已失效的卡按卡自身计算(与 resolvePackageCarrier 口径一致)。
|
||||
if deviceID, bound := deviceOf[id]; bound {
|
||||
@@ -111,17 +113,22 @@ func (r *TierResolver) Prefill(ctx context.Context, cards []*model.IotCard) {
|
||||
}
|
||||
}
|
||||
}
|
||||
// 只缓存查询成功的卡:查询失败的卡本次按未知处理,下次重新查询,不把"未知"留在缓存里。
|
||||
now := time.Now()
|
||||
r.mu.Lock()
|
||||
for _, card := range cards {
|
||||
if card == nil {
|
||||
continue
|
||||
}
|
||||
r.cache[card.ID] = tierCacheEntry{facts: results[card.ID], loadedAt: now}
|
||||
for id, facts := range results {
|
||||
r.cache[id] = tierCacheEntry{facts: facts, loadedAt: now}
|
||||
}
|
||||
r.mu.Unlock()
|
||||
}
|
||||
|
||||
// packageStates 以单独的超时查询一批载体的套餐状态,避免多次查询共用一个超时。
|
||||
func (r *TierResolver) packageStates(ctx context.Context, carrierType string, ids []uint) (map[uint]string, error) {
|
||||
queryCtx, cancel := context.WithTimeout(ctx, constants.PollingTierQueryTimeout)
|
||||
defer cancel()
|
||||
return r.usage.PackageStatesByCarriers(queryCtx, carrierType, ids)
|
||||
}
|
||||
|
||||
// Invalidate 清除某卡的分层事实缓存(套餐变化后可调用,未调用时最迟缓存过期后更新)。
|
||||
func (r *TierResolver) Invalidate(cardID uint) {
|
||||
if r == nil {
|
||||
|
||||
42
internal/query/cardrealname/current.go
Normal file
42
internal/query/cardrealname/current.go
Normal file
@@ -0,0 +1,42 @@
|
||||
// Package cardrealname 提供卡当前实名时间与实名时间历史的只读查询。
|
||||
package cardrealname
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/errors"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// Current 是卡当前实名时间及来源。
|
||||
type Current struct {
|
||||
RealnameAt *time.Time
|
||||
Source string
|
||||
}
|
||||
|
||||
// LoadCurrent 批量读取卡当前实名记录;没有记录的卡不在返回结果中。
|
||||
func LoadCurrent(ctx context.Context, db *gorm.DB, cardIDs []uint) (map[uint]Current, error) {
|
||||
result := make(map[uint]Current, len(cardIDs))
|
||||
if db == nil || len(cardIDs) == 0 {
|
||||
return result, nil
|
||||
}
|
||||
var rows []model.IotCardRealname
|
||||
if err := db.WithContext(ctx).Select("card_id", "realname_at", "realname_at_source").
|
||||
Where("card_id IN ?", cardIDs).Find(&rows).Error; err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询卡当前实名时间失败")
|
||||
}
|
||||
for _, row := range rows {
|
||||
result[row.CardID] = Current{RealnameAt: row.RealnameAt, Source: row.RealnameAtSource}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// ResolveRealnameAt 返回卡的实名时间:有当前实名记录用记录(可能为空,如等待二次实名),没有记录回退 first_realname_at。
|
||||
func ResolveRealnameAt(current map[uint]Current, cardID uint, fallback *time.Time) (*time.Time, string) {
|
||||
if value, ok := current[cardID]; ok {
|
||||
return value.RealnameAt, value.Source
|
||||
}
|
||||
return fallback, ""
|
||||
}
|
||||
269
internal/query/cardrealname/query.go
Normal file
269
internal/query/cardrealname/query.go
Normal file
@@ -0,0 +1,269 @@
|
||||
package cardrealname
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/bytedance/sonic"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
"github.com/break/junhong_cmp_fiber/internal/model/dto"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/errors"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/middleware"
|
||||
)
|
||||
|
||||
// Query 提供单卡实名记录与二次实名批次查询。
|
||||
type Query struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewQuery 创建实名记录查询。
|
||||
func NewQuery(db *gorm.DB) *Query {
|
||||
return &Query{db: db}
|
||||
}
|
||||
|
||||
// CardHistory 返回单卡当前实名时间与实名时间历史(按时间倒序分页);卡按当前账号数据范围可见。
|
||||
func (q *Query) CardHistory(ctx context.Context, req dto.CardRealnameHistoryListRequest) (*dto.CardRealnameHistoryResponse, error) {
|
||||
var card model.IotCard
|
||||
if err := middleware.ApplyShopFilter(ctx, q.db.WithContext(ctx).Select("id", "first_realname_at").Where("id = ?", req.ID)).
|
||||
First(&card).Error; err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return nil, errors.New(errors.CodeNotFound, "IoT 卡不存在")
|
||||
}
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询 IoT 卡失败")
|
||||
}
|
||||
page, size := normalizePage(req.Page, req.PageSize)
|
||||
resp := &dto.CardRealnameHistoryResponse{Current: dto.CardRealnameCurrentResponse{CardID: card.ID}, Page: page, PageSize: size}
|
||||
var record model.IotCardRealname
|
||||
err := q.db.WithContext(ctx).Where("card_id = ?", card.ID).Take(&record).Error
|
||||
switch {
|
||||
case err == nil:
|
||||
resp.Current = dto.CardRealnameCurrentResponse{
|
||||
CardID: card.ID, RealnameAt: record.RealnameAt, RealnameAtSource: record.RealnameAtSource,
|
||||
RealnameAtSourceName: constants.RealnameAtSourceName(record.RealnameAtSource),
|
||||
UpstreamRealnameAt: record.UpstreamRealnameAt, FirstObservedAt: record.FirstObservedAt,
|
||||
ResetPending: record.ResetStatus == constants.RealnameResetStatusPending, ResetAt: record.ResetAt,
|
||||
ResetBaselineAt: record.ResetBaselineAt, ResetBatchID: record.ResetBatchID,
|
||||
}
|
||||
case err == gorm.ErrRecordNotFound:
|
||||
resp.Current.RealnameAt = card.FirstRealnameAt
|
||||
default:
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询卡当前实名记录失败")
|
||||
}
|
||||
base := q.db.WithContext(ctx).Model(&model.IotCardRealnameHistory{}).Where("card_id = ?", card.ID)
|
||||
if err := base.Count(&resp.Total).Error; err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "统计卡实名时间历史失败")
|
||||
}
|
||||
var rows []model.IotCardRealnameHistory
|
||||
if err := base.Order("id DESC").Offset((page - 1) * size).Limit(size).Find(&rows).Error; err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询卡实名时间历史失败")
|
||||
}
|
||||
operators, err := q.operatorNames(ctx, rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp.Items = make([]dto.CardRealnameHistoryItem, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
resp.Items = append(resp.Items, dto.CardRealnameHistoryItem{
|
||||
ID: row.ID, CardID: row.CardID, ICCID: row.ICCID, BeforeAt: row.BeforeAt, AfterAt: row.AfterAt,
|
||||
AfterSource: row.AfterSource, AfterSourceName: constants.RealnameAtSourceName(row.AfterSource),
|
||||
ChangeType: row.ChangeType, ChangeTypeName: constants.RealnameChangeTypeName(row.ChangeType),
|
||||
ObservationSource: row.ObservationSource, ObservationSourceName: observationSourceName(row.ObservationSource),
|
||||
ResetBatchID: row.ResetBatchID, OperatorID: row.OperatorID, OperatorName: operators[row.OperatorID],
|
||||
ObservedAt: row.ObservedAt, CreatedAt: row.CreatedAt,
|
||||
})
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// ListResetBatches 分页查询二次实名批次(不含逐行结果)。
|
||||
func (q *Query) ListResetBatches(ctx context.Context, req dto.RealnameResetBatchListRequest) ([]dto.RealnameResetBatchResponse, int64, int, int, error) {
|
||||
if err := requirePlatform(ctx); err != nil {
|
||||
return nil, 0, 0, 0, err
|
||||
}
|
||||
page, size := normalizePage(req.Page, req.PageSize)
|
||||
base := q.db.WithContext(ctx).Model(&model.IotCardRealnameResetBatch{})
|
||||
if req.BatchNo != "" {
|
||||
base = base.Where("batch_no = ?", req.BatchNo)
|
||||
}
|
||||
var total int64
|
||||
if err := base.Count(&total).Error; err != nil {
|
||||
return nil, 0, 0, 0, errors.Wrap(errors.CodeDatabaseError, err, "统计二次实名批次失败")
|
||||
}
|
||||
var rows []model.IotCardRealnameResetBatch
|
||||
if err := base.Omit("items").Order("id DESC").Offset((page - 1) * size).Limit(size).Find(&rows).Error; err != nil {
|
||||
return nil, 0, 0, 0, errors.Wrap(errors.CodeDatabaseError, err, "查询二次实名批次失败")
|
||||
}
|
||||
pending, err := q.pendingCounts(ctx, batchIDs(rows))
|
||||
if err != nil {
|
||||
return nil, 0, 0, 0, err
|
||||
}
|
||||
list := make([]dto.RealnameResetBatchResponse, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
item := batchResponse(row)
|
||||
item.PendingCount = pending[row.ID]
|
||||
list = append(list, item)
|
||||
}
|
||||
return list, total, page, size, nil
|
||||
}
|
||||
|
||||
// GetResetBatch 查询二次实名批次详情,逐行结果按卡当前状态刷新为等待 / 已完成 / 已撤销。
|
||||
func (q *Query) GetResetBatch(ctx context.Context, id uint) (*dto.RealnameResetBatchResponse, error) {
|
||||
if err := requirePlatform(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var row model.IotCardRealnameResetBatch
|
||||
if err := q.db.WithContext(ctx).Where("id = ?", id).Take(&row).Error; err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return nil, errors.New(errors.CodeNotFound, "二次实名批次不存在")
|
||||
}
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询二次实名批次失败")
|
||||
}
|
||||
var items []dto.RealnameResetItem
|
||||
if len(row.Items) > 0 {
|
||||
if err := sonic.Unmarshal(row.Items, &items); err != nil {
|
||||
return nil, errors.Wrap(errors.CodeInternalError, err, "解析二次实名批次结果失败")
|
||||
}
|
||||
}
|
||||
finals, err := q.finalResults(ctx, row.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pending := 0
|
||||
for index := range items {
|
||||
if items[index].Result == constants.RealnameResetItemPending {
|
||||
if final, ok := finals[items[index].CardID]; ok {
|
||||
items[index].Result = final
|
||||
} else {
|
||||
pending++
|
||||
}
|
||||
}
|
||||
items[index].ResultName = constants.RealnameResetItemName(items[index].Result)
|
||||
}
|
||||
resp := batchResponse(row)
|
||||
resp.PendingCount = pending
|
||||
resp.Items = items
|
||||
return &resp, nil
|
||||
}
|
||||
|
||||
// finalResults 返回批次内已完成或已撤销的卡(以历史为准,同卡取最新一条)。
|
||||
func (q *Query) finalResults(ctx context.Context, batchID uint) (map[uint]string, error) {
|
||||
var rows []model.IotCardRealnameHistory
|
||||
if err := q.db.WithContext(ctx).Select("card_id", "change_type").
|
||||
Where("reset_batch_id = ? AND change_type IN ?", batchID,
|
||||
[]string{constants.RealnameChangeResetCompleted, constants.RealnameChangeResetReverted}).
|
||||
Order("id").Find(&rows).Error; err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询二次实名结果失败")
|
||||
}
|
||||
result := make(map[uint]string, len(rows))
|
||||
for _, row := range rows {
|
||||
if row.ChangeType == constants.RealnameChangeResetCompleted {
|
||||
result[row.CardID] = constants.RealnameResetItemCompleted
|
||||
} else {
|
||||
result[row.CardID] = constants.RealnameResetItemReverted
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (q *Query) pendingCounts(ctx context.Context, ids []uint) (map[uint]int, error) {
|
||||
result := make(map[uint]int, len(ids))
|
||||
if len(ids) == 0 {
|
||||
return result, nil
|
||||
}
|
||||
var rows []struct {
|
||||
BatchID uint `gorm:"column:reset_batch_id"`
|
||||
Count int `gorm:"column:count"`
|
||||
}
|
||||
if err := q.db.WithContext(ctx).Model(&model.IotCardRealname{}).Select("reset_batch_id, COUNT(*) AS count").
|
||||
Where("reset_batch_id IN ? AND reset_status = ?", ids, constants.RealnameResetStatusPending).
|
||||
Group("reset_batch_id").Scan(&rows).Error; err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "统计等待二次实名卡数失败")
|
||||
}
|
||||
for _, row := range rows {
|
||||
result[row.BatchID] = row.Count
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (q *Query) operatorNames(ctx context.Context, rows []model.IotCardRealnameHistory) (map[uint]string, error) {
|
||||
ids := make([]uint, 0)
|
||||
for _, row := range rows {
|
||||
if row.OperatorID > 0 {
|
||||
ids = append(ids, row.OperatorID)
|
||||
}
|
||||
}
|
||||
result := make(map[uint]string, len(ids))
|
||||
if len(ids) == 0 {
|
||||
return result, nil
|
||||
}
|
||||
var accounts []model.Account
|
||||
if err := q.db.WithContext(ctx).Select("id", "username").Where("id IN ?", ids).Find(&accounts).Error; err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询操作人失败")
|
||||
}
|
||||
for _, account := range accounts {
|
||||
result[account.ID] = account.Username
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func batchResponse(row model.IotCardRealnameResetBatch) dto.RealnameResetBatchResponse {
|
||||
return dto.RealnameResetBatchResponse{
|
||||
ID: row.ID, BatchNo: row.BatchNo, Reason: row.Reason, ImportFileKey: row.ImportFileKey,
|
||||
TotalCount: row.TotalCount, SucceededCount: row.SucceededCount, SkippedCount: row.SkippedCount,
|
||||
CompletedCount: row.CompletedCount, RevertedCount: row.RevertedCount,
|
||||
OperatorID: row.OperatorID, OperatorName: row.OperatorName, CreatedAt: row.CreatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
func batchIDs(rows []model.IotCardRealnameResetBatch) []uint {
|
||||
ids := make([]uint, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
ids = append(ids, row.ID)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
func requirePlatform(ctx context.Context) error {
|
||||
switch middleware.GetUserTypeFromContext(ctx) {
|
||||
case constants.UserTypeSuperAdmin, constants.UserTypePlatform:
|
||||
return nil
|
||||
default:
|
||||
return errors.New(errors.CodeForbidden, "仅平台账号可查看二次实名批次")
|
||||
}
|
||||
}
|
||||
|
||||
func normalizePage(page, size int) (int, int) {
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if size < 1 {
|
||||
size = 20
|
||||
}
|
||||
if size > 100 {
|
||||
size = 100
|
||||
}
|
||||
return page, size
|
||||
}
|
||||
|
||||
func observationSourceName(source string) string {
|
||||
switch source {
|
||||
case constants.CardObservationSourcePolling:
|
||||
return "轮询"
|
||||
case constants.CardObservationSourceManualSync:
|
||||
return "手动刷新"
|
||||
case constants.CardObservationSourceManualOverride:
|
||||
return "人工"
|
||||
case constants.CardObservationSourceCarrierCallback:
|
||||
return "运营商回调"
|
||||
case constants.CardObservationSourceBusinessEvent:
|
||||
return "业务观测"
|
||||
case "migration":
|
||||
return "上线迁移"
|
||||
case "package_silence":
|
||||
return "沉默期判定"
|
||||
default:
|
||||
return source
|
||||
}
|
||||
}
|
||||
@@ -125,7 +125,22 @@ func (q *Query) GetOrder(ctx context.Context, id uint, customerID uint) (*dto.Si
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items[0], nil
|
||||
item := items[0]
|
||||
// 待支付且未过支付截止的订单返回支付内容,前端据此展示二维码 / 继续支付;列表不返回。
|
||||
if order.Status == constants.SilenceOrderStatusPendingPayment && (order.ExpireAt == nil || time.Now().Before(*order.ExpireAt)) {
|
||||
var payment model.Payment
|
||||
err := q.db.WithContext(ctx).Select("payment_no", "qr_content").
|
||||
Where("order_type = ? AND order_id = ? AND status = ?", constants.PaymentOrderTypeSilenceExtension, order.ID, model.PaymentRecordStatusPending).
|
||||
Order("id DESC").First(&payment).Error
|
||||
if err != nil && err != gorm.ErrRecordNotFound {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询延期支付单失败")
|
||||
}
|
||||
if err == nil {
|
||||
packagesilenceapp.ApplyPaymentContent(item, payment.QRContent)
|
||||
item.PaymentNo = payment.PaymentNo
|
||||
}
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
|
||||
// OrderItems 批量补齐延期订单的支付单快照与批次号(列表、详情与导出共用)。
|
||||
|
||||
@@ -24,7 +24,7 @@ type StopRefusedFilter struct {
|
||||
type StopRefusedRow struct {
|
||||
ID uint
|
||||
CardID uint
|
||||
ICCID string
|
||||
ICCID string `gorm:"column:iccid"` // 显式列名:GORM 默认映射成 icc_id
|
||||
CarrierID uint
|
||||
CarrierName string
|
||||
DeviceID uint
|
||||
|
||||
20
internal/query/pollingalert/stop_refused_columns_test.go
Normal file
20
internal/query/pollingalert/stop_refused_columns_test.go
Normal file
@@ -0,0 +1,20 @@
|
||||
package pollingalert
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"gorm.io/gorm/schema"
|
||||
)
|
||||
|
||||
// GORM 默认把字段 ICCID 映射成 icc_id;查询选的是 a.iccid,必须显式指定列名,否则列表 ICCID 一直为空。
|
||||
func TestStopRefusedRowICCIDColumn(t *testing.T) {
|
||||
s, err := schema.Parse(&StopRefusedRow{}, &sync.Map{}, schema.NamingStrategy{})
|
||||
if err != nil {
|
||||
t.Fatalf("parse StopRefusedRow: %v", err)
|
||||
}
|
||||
field := s.LookUpField("ICCID")
|
||||
if field == nil || field.DBName != "iccid" {
|
||||
t.Fatalf("StopRefusedRow.ICCID column = %v, want iccid", field)
|
||||
}
|
||||
}
|
||||
29
internal/query/recorddisplay/columns_test.go
Normal file
29
internal/query/recorddisplay/columns_test.go
Normal file
@@ -0,0 +1,29 @@
|
||||
package recorddisplay
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"gorm.io/gorm/schema"
|
||||
)
|
||||
|
||||
// 防回归:不带 column tag 时 GORM 会把 ICCID 读成 icc_id 列。
|
||||
func TestDefaultNamingSplitsICCID(t *testing.T) {
|
||||
type untagged struct{ ICCID string }
|
||||
type tagged struct {
|
||||
ICCID string `gorm:"column:iccid"`
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
v any
|
||||
want string
|
||||
}{{"untagged", &untagged{}, "icc_id"}, {"tagged", &tagged{}, "iccid"}} {
|
||||
s, err := schema.Parse(tc.v, &sync.Map{}, schema.NamingStrategy{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := s.LookUpField("ICCID").DBName; got != tc.want {
|
||||
t.Fatalf("%s: DBName = %q, want %q", tc.name, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
143
internal/query/recorddisplay/lookup.go
Normal file
143
internal/query/recorddisplay/lookup.go
Normal file
@@ -0,0 +1,143 @@
|
||||
// Package recorddisplay 为记录查询列表补齐展示字段(ICCID、设备号、运营商名称、操作人)。
|
||||
//
|
||||
// 记录表只存内部 ID;列表先分页,再按当前页出现的 ID 批量查主键补齐,
|
||||
// 不在分页查询里关联,也不在记录表里冗余这些字段。查到的是当前值。
|
||||
package recorddisplay
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/errors"
|
||||
)
|
||||
|
||||
// Device 是设备展示字段。
|
||||
type Device struct {
|
||||
VirtualNo string
|
||||
IMEI string
|
||||
}
|
||||
|
||||
// Lookup 是当前页的展示字段字典;未找到的 ID 返回零值。
|
||||
type Lookup struct {
|
||||
iccids map[uint]string
|
||||
devices map[uint]Device
|
||||
carriers map[uint]string
|
||||
operators map[uint]string
|
||||
packages map[uint]string
|
||||
}
|
||||
|
||||
// Request 是需要补齐的 ID 集合(可重复、可含 0,内部去重并忽略 0)。
|
||||
type Request struct {
|
||||
CardIDs []uint
|
||||
DeviceIDs []uint
|
||||
CarrierIDs []uint
|
||||
OperatorIDs []uint
|
||||
// PackageUsageIDs 用于取套餐使用记录上的套餐名称快照。
|
||||
PackageUsageIDs []uint
|
||||
}
|
||||
|
||||
// Load 按 ID 批量查询展示字段:每类最多一条主键查询,已删除的资产同样返回(历史记录仍需显示)。
|
||||
func Load(ctx context.Context, db *gorm.DB, req Request) (*Lookup, error) {
|
||||
lookup := &Lookup{
|
||||
iccids: map[uint]string{}, devices: map[uint]Device{}, carriers: map[uint]string{}, operators: map[uint]string{},
|
||||
packages: map[uint]string{},
|
||||
}
|
||||
session := db.WithContext(ctx).Unscoped()
|
||||
|
||||
if ids := distinct(req.CardIDs); len(ids) > 0 {
|
||||
// 显式列名:GORM 默认把字段 ICCID 映射成 icc_id,不写 tag 会读不到值。
|
||||
var rows []struct {
|
||||
ID uint `gorm:"column:id"`
|
||||
ICCID string `gorm:"column:iccid"`
|
||||
}
|
||||
if err := session.Model(&model.IotCard{}).Select("id, iccid").Where("id IN ?", ids).Scan(&rows).Error; err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询卡展示信息失败")
|
||||
}
|
||||
for _, row := range rows {
|
||||
lookup.iccids[row.ID] = row.ICCID
|
||||
}
|
||||
}
|
||||
if ids := distinct(req.DeviceIDs); len(ids) > 0 {
|
||||
var rows []struct {
|
||||
ID uint `gorm:"column:id"`
|
||||
VirtualNo string `gorm:"column:virtual_no"`
|
||||
IMEI string `gorm:"column:imei"`
|
||||
}
|
||||
if err := session.Model(&model.Device{}).Select("id, virtual_no, imei").Where("id IN ?", ids).Scan(&rows).Error; err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询设备展示信息失败")
|
||||
}
|
||||
for _, row := range rows {
|
||||
lookup.devices[row.ID] = Device{VirtualNo: row.VirtualNo, IMEI: row.IMEI}
|
||||
}
|
||||
}
|
||||
if ids := distinct(req.CarrierIDs); len(ids) > 0 {
|
||||
var rows []struct {
|
||||
ID uint `gorm:"column:id"`
|
||||
CarrierName string `gorm:"column:carrier_name"`
|
||||
}
|
||||
if err := session.Model(&model.Carrier{}).Select("id, carrier_name").Where("id IN ?", ids).Scan(&rows).Error; err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询运营商账户展示信息失败")
|
||||
}
|
||||
for _, row := range rows {
|
||||
lookup.carriers[row.ID] = row.CarrierName
|
||||
}
|
||||
}
|
||||
if ids := distinct(req.OperatorIDs); len(ids) > 0 {
|
||||
var rows []struct {
|
||||
ID uint `gorm:"column:id"`
|
||||
Username string `gorm:"column:username"`
|
||||
}
|
||||
if err := session.Model(&model.Account{}).Select("id, username").Where("id IN ?", ids).Scan(&rows).Error; err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询操作人展示信息失败")
|
||||
}
|
||||
for _, row := range rows {
|
||||
lookup.operators[row.ID] = row.Username
|
||||
}
|
||||
}
|
||||
if ids := distinct(req.PackageUsageIDs); len(ids) > 0 {
|
||||
var rows []struct {
|
||||
ID uint `gorm:"column:id"`
|
||||
PackageName string `gorm:"column:package_name"`
|
||||
}
|
||||
if err := session.Model(&model.PackageUsage{}).Select("id, package_name").Where("id IN ?", ids).Scan(&rows).Error; err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询套餐名称失败")
|
||||
}
|
||||
for _, row := range rows {
|
||||
lookup.packages[row.ID] = row.PackageName
|
||||
}
|
||||
}
|
||||
return lookup, nil
|
||||
}
|
||||
|
||||
// ICCID 返回卡 ICCID。
|
||||
func (l *Lookup) ICCID(cardID uint) string { return l.iccids[cardID] }
|
||||
|
||||
// Device 返回设备号与 IMEI。
|
||||
func (l *Lookup) Device(deviceID uint) Device { return l.devices[deviceID] }
|
||||
|
||||
// CarrierName 返回运营商账户名称。
|
||||
func (l *Lookup) CarrierName(carrierID uint) string { return l.carriers[carrierID] }
|
||||
|
||||
// PackageName 返回套餐使用记录上的套餐名称快照。
|
||||
func (l *Lookup) PackageName(packageUsageID uint) string { return l.packages[packageUsageID] }
|
||||
|
||||
// OperatorName 返回操作人账号用户名。
|
||||
func (l *Lookup) OperatorName(accountID uint) string { return l.operators[accountID] }
|
||||
|
||||
func distinct(ids []uint) []uint {
|
||||
seen := make(map[uint]struct{}, len(ids))
|
||||
result := make([]uint, 0, len(ids))
|
||||
for _, id := range ids {
|
||||
if id == 0 {
|
||||
continue
|
||||
}
|
||||
if _, ok := seen[id]; ok {
|
||||
continue
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
result = append(result, id)
|
||||
}
|
||||
return result
|
||||
}
|
||||
50
internal/query/recorddisplay/lookup_test.go
Normal file
50
internal/query/recorddisplay/lookup_test.go
Normal file
@@ -0,0 +1,50 @@
|
||||
package recorddisplay
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDistinctSkipsZeroAndDuplicates(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
in []uint
|
||||
want []uint
|
||||
}{
|
||||
{name: "空", in: nil, want: []uint{}},
|
||||
{name: "只有 0", in: []uint{0, 0}, want: []uint{}},
|
||||
{name: "去重并保持顺序", in: []uint{3, 0, 1, 3, 2, 1}, want: []uint{3, 1, 2}},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := distinct(tt.in); !reflect.DeepEqual(got, tt.want) {
|
||||
t.Fatalf("distinct(%v) = %v, want %v", tt.in, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLookupMissingIDsReturnZeroValues(t *testing.T) {
|
||||
lookup := &Lookup{
|
||||
iccids: map[uint]string{1: "8986001"},
|
||||
devices: map[uint]Device{2: {VirtualNo: "60003081372", IMEI: "869555083099518"}},
|
||||
carriers: map[uint]string{},
|
||||
operators: map[uint]string{},
|
||||
packages: map[uint]string{},
|
||||
}
|
||||
if got := lookup.ICCID(1); got != "8986001" {
|
||||
t.Fatalf("ICCID(1) = %q", got)
|
||||
}
|
||||
if got := lookup.ICCID(9); got != "" {
|
||||
t.Fatalf("ICCID(9) = %q, want empty", got)
|
||||
}
|
||||
if got := lookup.Device(2); got.VirtualNo != "60003081372" || got.IMEI != "869555083099518" {
|
||||
t.Fatalf("Device(2) = %+v", got)
|
||||
}
|
||||
if got := lookup.Device(0); got != (Device{}) {
|
||||
t.Fatalf("Device(0) = %+v, want zero", got)
|
||||
}
|
||||
if lookup.CarrierName(5) != "" || lookup.OperatorName(5) != "" || lookup.PackageName(5) != "" {
|
||||
t.Fatal("missing IDs must return empty strings")
|
||||
}
|
||||
}
|
||||
@@ -154,6 +154,9 @@ func RegisterAdminRoutes(router fiber.Router, handlers *bootstrap.Handlers, midd
|
||||
if handlers.PollingMonitoring != nil {
|
||||
registerPollingMonitoringRoutes(authGroup, handlers.PollingMonitoring, doc, basePath)
|
||||
}
|
||||
if handlers.CardRealname != nil {
|
||||
registerCardRealnameRoutes(authGroup, handlers.CardRealname, doc, basePath)
|
||||
}
|
||||
if handlers.PollingAlert != nil {
|
||||
registerPollingAlertRoutes(authGroup, handlers.PollingAlert, doc, basePath)
|
||||
}
|
||||
@@ -188,6 +191,9 @@ func RegisterAdminRoutes(router fiber.Router, handlers *bootstrap.Handlers, midd
|
||||
if handlers.Refund != nil {
|
||||
registerRefundRoutes(authGroup, handlers.Refund, doc, basePath)
|
||||
}
|
||||
if handlers.Asset != nil && handlers.Refund != nil {
|
||||
registerRecordQueryRoutes(authGroup, handlers.Asset, handlers.Refund, doc, basePath)
|
||||
}
|
||||
if handlers.OrderPackageInvalidate != nil {
|
||||
registerOrderPackageInvalidateRoutes(authGroup, handlers.OrderPackageInvalidate, doc, basePath)
|
||||
}
|
||||
|
||||
38
internal/routes/card_realname.go
Normal file
38
internal/routes/card_realname.go
Normal file
@@ -0,0 +1,38 @@
|
||||
package routes
|
||||
|
||||
import (
|
||||
"github.com/gofiber/fiber/v2"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/handler/admin"
|
||||
"github.com/break/junhong_cmp_fiber/internal/model/dto"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/openapi"
|
||||
)
|
||||
|
||||
func registerCardRealnameRoutes(router fiber.Router, handler *admin.CardRealnameHandler, doc *openapi.Generator, basePath string) {
|
||||
tags := []string{"卡实名记录"}
|
||||
Register(router, doc, basePath, "GET", "/iot-cards/:id/realname-history", handler.CardHistory, RouteSpec{
|
||||
Summary: "查询单卡实名时间与历史",
|
||||
Description: "current 为当前实名时间:上游返回 archiveTime 时以它为准(来源 upstream),否则为首次读到已实名的时间(first_observed)," +
|
||||
"上线前已实名的卡沿用库里时间(migrated)。历史只在实名时间变化时记录,按时间倒序分页。卡按当前账号数据范围可见。",
|
||||
Tags: tags, Input: new(dto.CardRealnameHistoryListRequest), Output: new(dto.CardRealnameHistoryResponse), Auth: true,
|
||||
})
|
||||
Register(router, doc, basePath, "POST", "/realname-reset/batches", handler.ImportResetBatch, RouteSpec{
|
||||
Summary: "导入二次实名名单",
|
||||
Description: "仅平台账号,需 iot_card:realname_reset 权限。资产号为 ICCID / 虚拟号 / IMEI,设备展开为其全部绑定卡,最多 1000 个。" +
|
||||
"逐卡清除实名状态与实名时间;未实名、上游从未返回 archiveTime、已在等待的卡跳过并写明原因,不影响其他行。" +
|
||||
"之后上游 archiveTime 晚于清除前时间才算二次实名完成。C 端按普通未实名展示。",
|
||||
Tags: tags, Input: new(dto.RealnameResetImportRequest), Output: new(dto.RealnameResetBatchResponse), Auth: true,
|
||||
})
|
||||
Register(router, doc, basePath, "GET", "/realname-reset/batches", handler.ListResetBatches, RouteSpec{
|
||||
Summary: "二次实名批次列表", Description: "仅平台账号,按导入时间倒序分页。",
|
||||
Tags: tags, Input: new(dto.RealnameResetBatchListRequest), Output: new(dto.RealnameResetBatchResponse), Auth: true,
|
||||
})
|
||||
Register(router, doc, basePath, "GET", "/realname-reset/batches/:id", handler.GetResetBatch, RouteSpec{
|
||||
Summary: "二次实名批次详情", Description: "仅平台账号;逐行结果按卡当前状态显示等待二次实名 / 已完成 / 已撤销 / 跳过 / 失败。",
|
||||
Tags: tags, Input: new(dto.RealnameResetBatchIDRequest), Output: new(dto.RealnameResetBatchResponse), Auth: true,
|
||||
})
|
||||
Register(router, doc, basePath, "POST", "/realname-reset/batches/:id/revert", handler.RevertResetBatch, RouteSpec{
|
||||
Summary: "撤销二次实名", Description: "仅平台账号,需 iot_card:realname_reset 权限。card_ids 为空时撤销整批仍在等待的卡;卡恢复已实名、实名时间恢复为清除前时间。",
|
||||
Tags: tags, Input: new(dto.RealnameResetRevertRequest), Output: new(dto.RealnameResetRevertResponse), Auth: true,
|
||||
})
|
||||
}
|
||||
@@ -77,7 +77,14 @@ func registerPackageSilenceRoutes(router fiber.Router, handler *admin.PackageSil
|
||||
Tags: extTags, Input: new(dto.SilenceOrderListRequest), Output: new(dto.SilenceOrderPageResult), Auth: true,
|
||||
})
|
||||
Register(group, doc, path, "GET", "/orders/:id", handler.GetOrder, RouteSpec{
|
||||
Summary: "延期订单详情", Tags: extTags, Input: new(dto.SilenceIDPath), Output: new(dto.SilenceExtensionOrderResponse), Auth: true,
|
||||
Summary: "延期订单详情", Description: "待支付且未过支付截止的订单返回 qr_content,可继续扫码支付。",
|
||||
Tags: extTags, Input: new(dto.SilenceIDPath), Output: new(dto.SilenceExtensionOrderResponse), Auth: true,
|
||||
})
|
||||
Register(group, doc, path, "POST", "/orders/:id/close", handler.CloseOrder, RouteSpec{
|
||||
Summary: "作废待支付延期订单",
|
||||
Description: "需 package_silence:extend 权限,只能作废数据范围内待支付的在线订单。作废前先查单:渠道已支付则按支付成功办理延期并拒绝作废;" +
|
||||
"作废后同一套餐可重新下单,作废后才到达的支付进入异常并原路退款。",
|
||||
Tags: extTags, Input: new(dto.SilenceOrderCancelRequest), Output: new(dto.SilenceExtensionOrderResponse), Auth: true,
|
||||
})
|
||||
Register(group, doc, path, "POST", "/special", handler.SubmitSpecial, RouteSpec{
|
||||
Summary: "提交特殊延期(单个 / 批量)",
|
||||
@@ -130,7 +137,13 @@ func registerPersonalPackageSilenceRoutes(router fiber.Router, handler *apphandl
|
||||
Summary: "我的延期订单", Tags: tags, Input: new(dto.SilenceOrderListRequest), Output: new(dto.SilenceOrderPageResult), Auth: true,
|
||||
})
|
||||
Register(group, doc, path, "GET", "/orders/:id", handler.GetOrder, RouteSpec{
|
||||
Summary: "我的延期订单详情", Tags: tags, Input: new(dto.SilenceIDPath), Output: new(dto.SilenceExtensionOrderResponse), Auth: true,
|
||||
Summary: "我的延期订单详情", Description: "待支付且未过支付截止的订单返回 qr_content,可继续支付。",
|
||||
Tags: tags, Input: new(dto.SilenceIDPath), Output: new(dto.SilenceExtensionOrderResponse), Auth: true,
|
||||
})
|
||||
Register(group, doc, path, "POST", "/orders/:id/cancel", handler.CancelOrder, RouteSpec{
|
||||
Summary: "作废我的待支付延期订单",
|
||||
Description: "只能作废自己的待支付订单。作废前先查单:已支付则按支付成功办理延期并拒绝作废;作废后可重新下单。",
|
||||
Tags: tags, Input: new(dto.SilenceOrderCancelRequest), Output: new(dto.SilenceExtensionOrderResponse), Auth: true,
|
||||
})
|
||||
Register(group, doc, path, "GET", "/records", handler.ListRecords, RouteSpec{
|
||||
Summary: "套餐沉默期流水", Tags: tags, Input: new(dto.SilenceRecordListRequest), Output: new([]dto.SilenceRecordResponse), Auth: true,
|
||||
|
||||
@@ -14,10 +14,11 @@ func registerPackageUsageRoutes(router fiber.Router, handler *admin.PackageUsage
|
||||
groupPath := basePath + "/package-usage"
|
||||
|
||||
Register(packageUsage, doc, groupPath, "GET", "/:id/daily-records", handler.GetDailyRecords, RouteSpec{
|
||||
Summary: "获取套餐流量详单",
|
||||
Tags: []string{"套餐使用记录"},
|
||||
Input: new(dto.IDReq),
|
||||
Output: new(dto.PackageUsageDetailResponse),
|
||||
Auth: true,
|
||||
Summary: "获取套餐流量详单",
|
||||
Description: "查询参数:start_date、end_date(2006-01-02,选填);page、page_size(选填,page_size 最大 100)。传 page_size 时按日期倒序分页并返回 total/page/page_size,不传时按日期正序返回全部(兼容旧调用);total_usage_mb 为筛选范围内全部记录之和。",
|
||||
Tags: []string{"套餐使用记录"},
|
||||
Input: new(dto.IDReq),
|
||||
Output: new(dto.PackageUsageDetailResponse),
|
||||
Auth: true,
|
||||
})
|
||||
}
|
||||
|
||||
46
internal/routes/record_query.go
Normal file
46
internal/routes/record_query.go
Normal file
@@ -0,0 +1,46 @@
|
||||
package routes
|
||||
|
||||
import (
|
||||
"github.com/gofiber/fiber/v2"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/handler/admin"
|
||||
"github.com/break/junhong_cmp_fiber/internal/model/dto"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/openapi"
|
||||
)
|
||||
|
||||
// recordQueryDescription 是记录查询接口的公共说明。
|
||||
const recordQueryDescription = "identifier 选填:传入时只查该卡(设备取其绑定卡),解析不到资产返回空页;不传查全部,仅平台账号。" +
|
||||
"时间范围必填,跨度不超过 31 天;按记录时间倒序分页,每页默认 20、最大 100。"
|
||||
|
||||
func registerRecordQueryRoutes(router fiber.Router, asset *admin.AssetHandler, refund *admin.RefundHandler, doc *openapi.Generator, basePath string) {
|
||||
Register(router, doc, basePath, "GET", "/traffic-collections", asset.ListTrafficCollectionRecords, RouteSpec{
|
||||
Summary: "运营商流量采集成功记录",
|
||||
Description: recordQueryDescription + "只含读数有效的采集,带网关原始请求与响应;在线保留当月加最近 2 个整月。",
|
||||
Tags: []string{"记录查询"}, Input: new(dto.TrafficCollectionListRequest), Output: new(dto.TrafficCollectionRecordListResponse), Auth: true,
|
||||
})
|
||||
Register(router, doc, basePath, "GET", "/traffic-collection-failures", asset.ListTrafficCollectionFailures, RouteSpec{
|
||||
Summary: "运营商流量采集失败记录",
|
||||
Description: recordQueryDescription + "含失败、限流、响应无效、无读数、读数无效,带错误类别、上游返回与原始数据;observation_id 等于对接日志 integration_id。",
|
||||
Tags: []string{"记录查询"}, Input: new(dto.TrafficCollectionFailureListRequest), Output: new(dto.TrafficCollectionFailureListResponse), Auth: true,
|
||||
})
|
||||
Register(router, doc, basePath, "GET", "/card-daily-usages", asset.ListCardDailyUsages, RouteSpec{
|
||||
Summary: "卡日流量记录",
|
||||
Description: recordQueryDescription + "数据来自卡日快照(每卡每天一条);按日期范围(含首尾)查询;min_usage_mb 按当日已结算增量筛异常大流量。",
|
||||
Tags: []string{"记录查询"}, Input: new(dto.CardDailyUsageListRequest), Output: new(dto.CardDailyUsageListResponse), Auth: true,
|
||||
})
|
||||
Register(router, doc, basePath, "GET", "/package-usage-daily-records", asset.ListPackageUsageDailyRecords, RouteSpec{
|
||||
Summary: "套餐日流量详单记录",
|
||||
Description: recordQueryDescription + "按日期范围(含首尾)查询;设备标识同时匹配设备套餐与其绑定卡的套餐。",
|
||||
Tags: []string{"记录查询"}, Input: new(dto.PackageUsageDailyRecordListRequest), Output: new(dto.PackageUsageDailyRecordListResponse), Auth: true,
|
||||
})
|
||||
Register(router, doc, basePath, "GET", "/package-traffic-adjustments", asset.ListPackageTrafficAdjustmentRecords, RouteSpec{
|
||||
Summary: "套餐流量冲正流水记录",
|
||||
Description: recordQueryDescription + "direction=deduct 为补扣(增量为正),refund 为退回(增量为负)。",
|
||||
Tags: []string{"记录查询"}, Input: new(dto.PackageTrafficAdjustmentQueryRequest), Output: new(dto.PackageTrafficAdjustmentRecordListResponse), Auth: true,
|
||||
})
|
||||
Register(router, doc, basePath, "GET", "/refund-post-process-attempts", refund.ListAssetPostProcessAttempts, RouteSpec{
|
||||
Summary: "退款资产后处理尝试记录",
|
||||
Description: "仅平台账号。可按退款单 ID 或单号、资产标识、步骤、结果、错误码、触发方式筛选,不传条件查全部;时间范围必填,跨度不超过 31 天;按时间倒序分页,每页默认 20、最大 100。",
|
||||
Tags: []string{"记录查询"}, Input: new(dto.RefundPostProcessAttemptListRequest), Output: new(dto.RefundPostProcessAttemptListResponse), Auth: true,
|
||||
})
|
||||
}
|
||||
@@ -74,6 +74,10 @@ func registerRefundRoutes(router fiber.Router, handler *admin.RefundHandler, doc
|
||||
Summary: "恢复退款原审批提交", Description: "仅恢复最新退款审批实例的原提交事件,不创建新审批实例,不直接调用企业微信接口;审批提交结果未知时必须先由恢复任务确认。", Tags: []string{"退款管理"}, Input: new(dto.RefundIDRequest), Output: new(dto.RefundResponse), Auth: true,
|
||||
})
|
||||
|
||||
Register(refund, doc, groupPath, "POST", "/:id/asset-post-processing/retry", handler.RetryAssetPostProcessing, RouteSpec{
|
||||
Summary: "人工重试退款资产后处理", Description: "仅平台账号;仅对资产后处理状态为需人工处理(自动重试已达 10 次)的退款单发起,同步执行一次后处理并写尝试记录,返回最新退款详情;仍失败时返回错误并保留需人工处理状态。", Tags: []string{"退款管理"}, Input: new(dto.RefundIDRequest), Output: new(dto.RefundResponse), Auth: true,
|
||||
})
|
||||
|
||||
Register(refund, doc, groupPath, "POST", "/:id/approve", handler.Approve, RouteSpec{
|
||||
Summary: "审批通过退款申请",
|
||||
Tags: []string{"退款管理"},
|
||||
|
||||
436
internal/service/asset/record_query.go
Normal file
436
internal/service/asset/record_query.go
Normal file
@@ -0,0 +1,436 @@
|
||||
package asset
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
stderrors "errors"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/domain/cardflow"
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
"github.com/break/junhong_cmp_fiber/internal/model/dto"
|
||||
"github.com/break/junhong_cmp_fiber/internal/query/recorddisplay"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/errors"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/middleware"
|
||||
)
|
||||
|
||||
const (
|
||||
recordDefaultPageSize = 20
|
||||
recordMaxPageSize = 100
|
||||
recordDateLayout = "2006-01-02"
|
||||
)
|
||||
|
||||
// recordScope 是资产标识解析后的查询范围:all 为 true 表示不按资产过滤。
|
||||
type recordScope struct {
|
||||
all bool
|
||||
cardIDs []uint
|
||||
deviceID uint
|
||||
}
|
||||
|
||||
func (r recordScope) empty() bool { return !r.all && len(r.cardIDs) == 0 && r.deviceID == 0 }
|
||||
|
||||
// resolveRecordScope 把选填的资产标识解析为卡 ID(设备取其绑定卡);不传标识查全部时只允许平台账号。
|
||||
// 标识解析不到资产时返回空范围,调用方直接返回空页。
|
||||
func (s *Service) resolveRecordScope(ctx context.Context, identifier string) (recordScope, error) {
|
||||
if identifier == "" {
|
||||
userType := middleware.GetUserTypeFromContext(ctx)
|
||||
if userType != constants.UserTypeSuperAdmin && userType != constants.UserTypePlatform {
|
||||
return recordScope{}, errors.New(errors.CodeForbidden, "只有平台账号可以不带资产标识查询全部记录")
|
||||
}
|
||||
return recordScope{all: true}, nil
|
||||
}
|
||||
asset, err := s.Resolve(ctx, identifier, false)
|
||||
if err != nil {
|
||||
var appErr *errors.AppError
|
||||
if stderrors.As(err, &appErr) && appErr.Code == errors.CodeNotFound {
|
||||
return recordScope{}, nil
|
||||
}
|
||||
return recordScope{}, err
|
||||
}
|
||||
if asset.AssetType == "card" {
|
||||
return recordScope{cardIDs: []uint{asset.AssetID}}, nil
|
||||
}
|
||||
var cardIDs []uint
|
||||
if err := s.db.WithContext(ctx).Model(&model.DeviceSimBinding{}).
|
||||
Where("device_id = ? AND bind_status = ?", asset.AssetID, constants.BindStatusBound).
|
||||
Pluck("iot_card_id", &cardIDs).Error; err != nil {
|
||||
return recordScope{}, errors.Wrap(errors.CodeDatabaseError, err, "查询设备绑定卡失败")
|
||||
}
|
||||
return recordScope{cardIDs: cardIDs, deviceID: asset.AssetID}, nil
|
||||
}
|
||||
|
||||
// parseRecordTimeRange 解析必填时间范围(结束不含,跨度不超过 31 天)。
|
||||
func parseRecordTimeRange(start, end string) (time.Time, time.Time, error) {
|
||||
from, err := parseCollectionTime(start)
|
||||
if err != nil {
|
||||
return time.Time{}, time.Time{}, err
|
||||
}
|
||||
to, err := parseCollectionTime(end)
|
||||
if err != nil {
|
||||
return time.Time{}, time.Time{}, err
|
||||
}
|
||||
if !to.After(from) || to.Sub(from) > maxCollectionQuerySpan {
|
||||
return time.Time{}, time.Time{}, errors.New(errors.CodeInvalidParam, "结束时间必须晚于开始时间,且跨度不超过 31 天")
|
||||
}
|
||||
return from, to, nil
|
||||
}
|
||||
|
||||
// parseRecordDateRange 解析必填日期范围(含首尾,跨度不超过 31 天)。
|
||||
func parseRecordDateRange(start, end string) (time.Time, time.Time, error) {
|
||||
location := cardflow.ShanghaiDate(time.Now()).Location()
|
||||
from, err := time.ParseInLocation(recordDateLayout, start, location)
|
||||
if err != nil {
|
||||
return time.Time{}, time.Time{}, errors.New(errors.CodeInvalidParam, "开始日期格式无效,应为 2006-01-02")
|
||||
}
|
||||
to, err := time.ParseInLocation(recordDateLayout, end, location)
|
||||
if err != nil {
|
||||
return time.Time{}, time.Time{}, errors.New(errors.CodeInvalidParam, "结束日期格式无效,应为 2006-01-02")
|
||||
}
|
||||
if to.Before(from) || to.Sub(from) > maxCollectionQuerySpan {
|
||||
return time.Time{}, time.Time{}, errors.New(errors.CodeInvalidParam, "结束日期不能早于开始日期,且跨度不超过 31 天")
|
||||
}
|
||||
return from, to, nil
|
||||
}
|
||||
|
||||
func recordPage(page, size, maxSize int) (int, int) {
|
||||
if page <= 0 {
|
||||
page = 1
|
||||
}
|
||||
if size <= 0 {
|
||||
size = recordDefaultPageSize
|
||||
}
|
||||
if size > maxSize {
|
||||
size = maxSize
|
||||
}
|
||||
return page, size
|
||||
}
|
||||
|
||||
// pageQuery 统计总数后按排序取当前页。
|
||||
func pageQuery[T any](query *gorm.DB, order string, page, size int) ([]T, int64, error) {
|
||||
var total int64
|
||||
if err := query.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
rows := make([]T, 0, size)
|
||||
if total == 0 {
|
||||
return rows, 0, nil
|
||||
}
|
||||
err := query.Order(order).Offset((page - 1) * size).Limit(size).Find(&rows).Error
|
||||
return rows, total, err
|
||||
}
|
||||
|
||||
func gatewayRawItem(raw model.CollectionRaw) dto.GatewayRawItem {
|
||||
return dto.GatewayRawItem{
|
||||
RawRequest: json.RawMessage(raw.RawRequest), HTTPStatus: raw.HTTPStatus, GatewayCode: raw.GatewayCode,
|
||||
GatewayMsg: raw.GatewayMsg, GatewayTraceID: raw.GatewayTraceID, RawResponse: json.RawMessage(raw.RawResponse),
|
||||
RawResponseText: raw.RawResponseText, RawTruncated: raw.RawTruncated, GatewayAttempts: raw.GatewayAttempts,
|
||||
}
|
||||
}
|
||||
|
||||
func collectionSuccessItem(row model.CardTrafficCollection) dto.CardTrafficCollectionItem {
|
||||
return dto.CardTrafficCollectionItem{
|
||||
ID: row.ID, ObservedAt: row.ObservedAt, ObservationID: row.ObservationID, Source: row.Source,
|
||||
Scene: row.Scene, Result: row.Result, VendorUsedMB: row.VendorUsedMB, QueuePoints: json.RawMessage(row.QueuePoints),
|
||||
Decision: row.Decision, MonthUsedMB: row.MonthUsedMB, StaleGuarded: row.StaleGuarded,
|
||||
DeltaMB: row.DeltaMB, EventID: row.EventID, RecordKind: "success", GatewayRawItem: gatewayRawItem(row.CollectionRaw),
|
||||
}
|
||||
}
|
||||
|
||||
func collectionFailureItem(row model.CardTrafficCollectionFailure) dto.TrafficCollectionFailureItem {
|
||||
return dto.TrafficCollectionFailureItem{
|
||||
ID: row.ID, IotCardID: row.IotCardID, ICCID: row.ICCID, CarrierID: row.CarrierID, ObservedAt: row.ObservedAt,
|
||||
ObservationID: row.ObservationID, Source: row.Source, Scene: row.Scene, Result: row.Result,
|
||||
ErrorCategory: row.ErrorCategory, ProviderCode: row.ProviderCode, ProviderMessage: row.ProviderMessage,
|
||||
DurationMS: row.DurationMS, GatewayRawItem: gatewayRawItem(row.CollectionRaw),
|
||||
}
|
||||
}
|
||||
|
||||
// ListTrafficCollectionRecords 查询采集成功记录(可查单个也可查全部)。
|
||||
func (s *Service) ListTrafficCollectionRecords(ctx context.Context, req *dto.TrafficCollectionListRequest) (*dto.TrafficCollectionRecordListResponse, error) {
|
||||
from, to, err := parseRecordTimeRange(req.StartTime, req.EndTime)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
page, size := recordPage(req.Page, req.PageSize, recordMaxPageSize)
|
||||
resp := &dto.TrafficCollectionRecordListResponse{Items: []dto.TrafficCollectionRecordItem{}, Page: page, PageSize: size}
|
||||
scope, err := s.resolveRecordScope(ctx, req.Identifier)
|
||||
if err != nil || scope.empty() {
|
||||
return resp, err
|
||||
}
|
||||
query := s.db.WithContext(ctx).Model(&model.CardTrafficCollection{}).
|
||||
Where("observed_at >= ? AND observed_at < ? AND result = ?", from, to, constants.TrafficCollectionResultOK)
|
||||
if !scope.all {
|
||||
query = query.Where("iot_card_id IN ?", scope.cardIDs)
|
||||
}
|
||||
if req.CarrierID != nil {
|
||||
query = query.Where("carrier_id = ?", *req.CarrierID)
|
||||
}
|
||||
query = applyStringFilters(query, map[string]string{"decision": req.Decision, "source": req.Source, "scene": req.Scene})
|
||||
if req.HasDelta != nil {
|
||||
if *req.HasDelta {
|
||||
query = query.Where("delta_mb > 0")
|
||||
} else {
|
||||
query = query.Where("(delta_mb IS NULL OR delta_mb = 0)")
|
||||
}
|
||||
}
|
||||
if req.StaleGuarded != nil {
|
||||
query = query.Where("stale_guarded = ?", *req.StaleGuarded)
|
||||
}
|
||||
rows, total, err := pageQuery[model.CardTrafficCollection](query, "observed_at DESC, id DESC", page, size)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询采集成功记录失败")
|
||||
}
|
||||
successReq := recorddisplay.Request{}
|
||||
for _, row := range rows {
|
||||
successReq.CardIDs = append(successReq.CardIDs, row.IotCardID)
|
||||
successReq.CarrierIDs = append(successReq.CarrierIDs, row.CarrierID)
|
||||
}
|
||||
display, err := recorddisplay.Load(ctx, s.db, successReq)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, row := range rows {
|
||||
resp.Items = append(resp.Items, dto.TrafficCollectionRecordItem{
|
||||
CardTrafficCollectionItem: collectionSuccessItem(row), IotCardID: row.IotCardID, ICCID: display.ICCID(row.IotCardID),
|
||||
CarrierID: row.CarrierID, CarrierName: display.CarrierName(row.CarrierID),
|
||||
})
|
||||
}
|
||||
resp.Total = total
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// ListTrafficCollectionFailures 查询采集失败记录(可查单个也可查全部)。
|
||||
func (s *Service) ListTrafficCollectionFailures(ctx context.Context, req *dto.TrafficCollectionFailureListRequest) (*dto.TrafficCollectionFailureListResponse, error) {
|
||||
from, to, err := parseRecordTimeRange(req.StartTime, req.EndTime)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
page, size := recordPage(req.Page, req.PageSize, recordMaxPageSize)
|
||||
resp := &dto.TrafficCollectionFailureListResponse{Items: []dto.TrafficCollectionFailureItem{}, Page: page, PageSize: size}
|
||||
scope, err := s.resolveRecordScope(ctx, req.Identifier)
|
||||
if err != nil || scope.empty() {
|
||||
return resp, err
|
||||
}
|
||||
query := s.db.WithContext(ctx).Model(&model.CardTrafficCollectionFailure{}).Where("observed_at >= ? AND observed_at < ?", from, to)
|
||||
if !scope.all {
|
||||
query = query.Where("iot_card_id IN ?", scope.cardIDs)
|
||||
}
|
||||
if req.CarrierID != nil {
|
||||
query = query.Where("carrier_id = ?", *req.CarrierID)
|
||||
}
|
||||
query = applyStringFilters(query, map[string]string{
|
||||
"result": req.Result, "error_category": req.ErrorCategory, "provider_code": req.ProviderCode, "source": req.Source, "scene": req.Scene,
|
||||
})
|
||||
rows, total, err := pageQuery[model.CardTrafficCollectionFailure](query, "observed_at DESC, id DESC", page, size)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询采集失败记录失败")
|
||||
}
|
||||
carrierIDs := make([]uint, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
carrierIDs = append(carrierIDs, row.CarrierID)
|
||||
}
|
||||
display, err := recorddisplay.Load(ctx, s.db, recorddisplay.Request{CarrierIDs: carrierIDs})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, row := range rows {
|
||||
item := collectionFailureItem(row)
|
||||
item.CarrierName = display.CarrierName(row.CarrierID)
|
||||
resp.Items = append(resp.Items, item)
|
||||
}
|
||||
resp.Total = total
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// ListCardDailyUsages 查询卡日流量(可查单个也可查全部)。
|
||||
func (s *Service) ListCardDailyUsages(ctx context.Context, req *dto.CardDailyUsageListRequest) (*dto.CardDailyUsageListResponse, error) {
|
||||
from, to, err := parseRecordDateRange(req.StartDate, req.EndDate)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
page, size := recordPage(req.Page, req.PageSize, recordMaxPageSize)
|
||||
resp := &dto.CardDailyUsageListResponse{Items: []dto.CardDailyUsageItem{}, Page: page, PageSize: size}
|
||||
scope, err := s.resolveRecordScope(ctx, req.Identifier)
|
||||
if err != nil || scope.empty() {
|
||||
return resp, err
|
||||
}
|
||||
// 显式列名:GORM 默认把字段 ICCID 映射成 icc_id,不写 tag 时 ICCID 一直为空。
|
||||
type row struct {
|
||||
model.CardFlowDay
|
||||
ICCID string `gorm:"column:iccid"`
|
||||
CarrierID uint `gorm:"column:carrier_id"`
|
||||
}
|
||||
query := s.db.WithContext(ctx).Table("tb_card_flow_day AS u").
|
||||
Select("u.*, c.iccid, c.carrier_id").Joins("LEFT JOIN tb_iot_card c ON c.id = u.iot_card_id").
|
||||
Where("u.flow_date >= ? AND u.flow_date <= ?", from.Format(recordDateLayout), to.Format(recordDateLayout))
|
||||
if !scope.all {
|
||||
query = query.Where("u.iot_card_id IN ?", scope.cardIDs)
|
||||
}
|
||||
if req.CarrierID != nil {
|
||||
query = query.Where("c.carrier_id = ?", *req.CarrierID)
|
||||
}
|
||||
if req.MinUsageMB != nil {
|
||||
query = query.Where("u.settled_mb >= ?", *req.MinUsageMB)
|
||||
}
|
||||
rows, total, err := pageQuery[row](query, "u.flow_date DESC, u.id DESC", page, size)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询卡日流量失败")
|
||||
}
|
||||
carrierIDs := make([]uint, 0, len(rows))
|
||||
for _, item := range rows {
|
||||
carrierIDs = append(carrierIDs, item.CarrierID)
|
||||
}
|
||||
display, err := recorddisplay.Load(ctx, s.db, recorddisplay.Request{CarrierIDs: carrierIDs})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, item := range rows {
|
||||
resp.Items = append(resp.Items, dto.CardDailyUsageItem{
|
||||
ID: item.ID, IotCardID: item.IotCardID, ICCID: item.ICCID, CarrierID: item.CarrierID,
|
||||
CarrierName: display.CarrierName(item.CarrierID),
|
||||
Date: item.FlowDate.Format(recordDateLayout), SettledMB: item.SettledMB, MonthUsedMB: item.MonthUsedMB,
|
||||
VendorUsedMB: item.VendorUsedMB, StaleGuarded: item.StaleGuarded, ObsCount: item.ObsCount, UpdatedAt: item.UpdatedAt,
|
||||
})
|
||||
}
|
||||
resp.Total = total
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// ListPackageUsageDailyRecords 查询套餐日流量详单(可查单个也可查全部)。
|
||||
func (s *Service) ListPackageUsageDailyRecords(ctx context.Context, req *dto.PackageUsageDailyRecordListRequest) (*dto.PackageUsageDailyRecordListResponse, error) {
|
||||
from, to, err := parseRecordDateRange(req.StartDate, req.EndDate)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
page, size := recordPage(req.Page, req.PageSize, recordMaxPageSize)
|
||||
resp := &dto.PackageUsageDailyRecordListResponse{Items: []dto.PackageUsageDailyRecordItem{}, Page: page, PageSize: size}
|
||||
scope, err := s.resolveRecordScope(ctx, req.Identifier)
|
||||
if err != nil || scope.empty() {
|
||||
return resp, err
|
||||
}
|
||||
type row struct {
|
||||
model.PackageUsageDailyRecord
|
||||
PackageID uint `gorm:"column:package_id"`
|
||||
PackageName string `gorm:"column:package_name"`
|
||||
IotCardID uint `gorm:"column:iot_card_id"`
|
||||
DeviceID uint `gorm:"column:device_id"`
|
||||
}
|
||||
query := s.db.WithContext(ctx).Table("tb_package_usage_daily_record AS r").
|
||||
Select("r.*, pu.package_id, pu.package_name, COALESCE(pu.iot_card_id, 0) AS iot_card_id, COALESCE(pu.device_id, 0) AS device_id").
|
||||
Joins("JOIN tb_package_usage pu ON pu.id = r.package_usage_id").
|
||||
Where("r.date >= ? AND r.date <= ?", from.Format(recordDateLayout), to.Format(recordDateLayout))
|
||||
if !scope.all {
|
||||
if scope.deviceID > 0 {
|
||||
query = query.Where("(pu.device_id = ? OR pu.iot_card_id IN ?)", scope.deviceID, append([]uint{0}, scope.cardIDs...))
|
||||
} else {
|
||||
query = query.Where("pu.iot_card_id IN ?", scope.cardIDs)
|
||||
}
|
||||
}
|
||||
if req.PackageUsageID != nil {
|
||||
query = query.Where("r.package_usage_id = ?", *req.PackageUsageID)
|
||||
}
|
||||
if req.PackageID != nil {
|
||||
query = query.Where("pu.package_id = ?", *req.PackageID)
|
||||
}
|
||||
if req.CarrierID != nil {
|
||||
query = query.Where("pu.iot_card_id IN (SELECT id FROM tb_iot_card WHERE carrier_id = ?)", *req.CarrierID)
|
||||
}
|
||||
rows, total, err := pageQuery[row](query, "r.date DESC, r.id DESC", page, size)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询套餐日流量详单失败")
|
||||
}
|
||||
dailyReq := recorddisplay.Request{}
|
||||
for _, item := range rows {
|
||||
dailyReq.CardIDs = append(dailyReq.CardIDs, item.IotCardID)
|
||||
dailyReq.DeviceIDs = append(dailyReq.DeviceIDs, item.DeviceID)
|
||||
}
|
||||
display, err := recorddisplay.Load(ctx, s.db, dailyReq)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, item := range rows {
|
||||
device := display.Device(item.DeviceID)
|
||||
resp.Items = append(resp.Items, dto.PackageUsageDailyRecordItem{
|
||||
ID: item.ID, PackageUsageID: item.PackageUsageID, PackageID: item.PackageID, PackageName: item.PackageName,
|
||||
IotCardID: item.IotCardID, ICCID: display.ICCID(item.IotCardID),
|
||||
DeviceID: item.DeviceID, DeviceVirtualNo: device.VirtualNo, DeviceIMEI: device.IMEI, Date: item.Date.Format(recordDateLayout), DailyUsageMB: item.DailyUsageMB,
|
||||
CumulativeUsageMB: item.CumulativeUsageMB, UpdatedAt: item.UpdatedAt,
|
||||
})
|
||||
}
|
||||
resp.Total = total
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// ListPackageTrafficAdjustmentRecords 查询套餐流量冲正流水(可查单个也可查全部)。
|
||||
func (s *Service) ListPackageTrafficAdjustmentRecords(ctx context.Context, req *dto.PackageTrafficAdjustmentQueryRequest) (*dto.PackageTrafficAdjustmentRecordListResponse, error) {
|
||||
from, to, err := parseRecordTimeRange(req.StartTime, req.EndTime)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
page, size := recordPage(req.Page, req.PageSize, recordMaxPageSize)
|
||||
resp := &dto.PackageTrafficAdjustmentRecordListResponse{Items: []dto.PackageTrafficAdjustmentRecordItem{}, Page: page, PageSize: size}
|
||||
scope, err := s.resolveRecordScope(ctx, req.Identifier)
|
||||
if err != nil || scope.empty() {
|
||||
return resp, err
|
||||
}
|
||||
query := s.db.WithContext(ctx).Model(&model.PackageUsageAdjustment{}).Where("created_at >= ? AND created_at < ?", from, to)
|
||||
if !scope.all {
|
||||
if scope.deviceID > 0 {
|
||||
query = query.Where("(device_id = ? OR iot_card_id IN ?)", scope.deviceID, append([]uint{0}, scope.cardIDs...))
|
||||
} else {
|
||||
query = query.Where("iot_card_id IN ?", scope.cardIDs)
|
||||
}
|
||||
}
|
||||
if req.PackageUsageID != nil {
|
||||
query = query.Where("package_usage_id = ?", *req.PackageUsageID)
|
||||
}
|
||||
if req.OperatorID != nil {
|
||||
query = query.Where("operator_id = ?", *req.OperatorID)
|
||||
}
|
||||
switch req.Direction {
|
||||
case "deduct":
|
||||
query = query.Where("delta_mb > 0")
|
||||
case "refund":
|
||||
query = query.Where("delta_mb < 0")
|
||||
}
|
||||
rows, total, err := pageQuery[model.PackageUsageAdjustment](query, "created_at DESC, id DESC", page, size)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询套餐流量冲正流水失败")
|
||||
}
|
||||
adjReq := recorddisplay.Request{}
|
||||
for _, row := range rows {
|
||||
adjReq.CardIDs = append(adjReq.CardIDs, row.IotCardID)
|
||||
adjReq.DeviceIDs = append(adjReq.DeviceIDs, row.DeviceID)
|
||||
adjReq.OperatorIDs = append(adjReq.OperatorIDs, row.OperatorID)
|
||||
adjReq.PackageUsageIDs = append(adjReq.PackageUsageIDs, row.PackageUsageID)
|
||||
}
|
||||
display, err := recorddisplay.Load(ctx, s.db, adjReq)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, row := range rows {
|
||||
item := toTrafficAdjustmentItem(row)
|
||||
item.OperatorName = display.OperatorName(row.OperatorID)
|
||||
device := display.Device(row.DeviceID)
|
||||
resp.Items = append(resp.Items, dto.PackageTrafficAdjustmentRecordItem{
|
||||
PackageTrafficAdjustmentItem: item, PackageName: display.PackageName(row.PackageUsageID),
|
||||
IotCardID: row.IotCardID, ICCID: display.ICCID(row.IotCardID),
|
||||
DeviceID: row.DeviceID, DeviceVirtualNo: device.VirtualNo, DeviceIMEI: device.IMEI,
|
||||
})
|
||||
}
|
||||
resp.Total = total
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// applyStringFilters 对非空字符串条件追加等值过滤(列名为内部常量,不来自请求)。
|
||||
func applyStringFilters(query *gorm.DB, filters map[string]string) *gorm.DB {
|
||||
for column, value := range filters {
|
||||
if value != "" {
|
||||
query = query.Where(column+" = ?", value)
|
||||
}
|
||||
}
|
||||
return query
|
||||
}
|
||||
@@ -16,6 +16,7 @@ import (
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
"github.com/break/junhong_cmp_fiber/internal/model/dto"
|
||||
assetquery "github.com/break/junhong_cmp_fiber/internal/query/asset"
|
||||
"github.com/break/junhong_cmp_fiber/internal/query/cardrealname"
|
||||
packageexpiry "github.com/break/junhong_cmp_fiber/internal/query/packageexpiry"
|
||||
"github.com/break/junhong_cmp_fiber/internal/store/postgres"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
@@ -247,14 +248,21 @@ func (s *Service) buildDeviceResolveResponse(ctx context.Context, device *model.
|
||||
zap.Uints("card_ids", cardIDs),
|
||||
zap.Error(err))
|
||||
}
|
||||
currentRealname, realnameErr := cardrealname.LoadCurrent(ctx, s.db, cardIDs)
|
||||
if realnameErr != nil {
|
||||
return nil, realnameErr
|
||||
}
|
||||
for _, c := range cards {
|
||||
realnameAt, realnameSource := cardrealname.ResolveRealnameAt(currentRealname, c.ID, c.FirstRealnameAt)
|
||||
resp.Cards = append(resp.Cards, dto.BoundCardInfo{
|
||||
CardID: c.ID,
|
||||
ICCID: c.ICCID,
|
||||
MSISDN: c.MSISDN,
|
||||
NetworkStatus: c.NetworkStatus,
|
||||
RealNameStatus: c.RealNameStatus,
|
||||
RealNameAt: c.FirstRealnameAt,
|
||||
RealNameAt: realnameAt,
|
||||
RealNameAtSource: realnameSource,
|
||||
RealNameAtSourceName: constants.RealnameAtSourceName(realnameSource),
|
||||
SlotPosition: slotMap[c.ID],
|
||||
IsCurrent: isCurrentMap[c.ID],
|
||||
CarrierID: c.CarrierID,
|
||||
@@ -288,11 +296,12 @@ func (s *Service) buildDeviceResolveResponse(ctx context.Context, device *model.
|
||||
}
|
||||
// RealNameAt 取所有绑定卡中最早的实名时间
|
||||
for _, c := range cards {
|
||||
if c.FirstRealnameAt == nil {
|
||||
realnameAt, _ := cardrealname.ResolveRealnameAt(currentRealname, c.ID, c.FirstRealnameAt)
|
||||
if realnameAt == nil {
|
||||
continue
|
||||
}
|
||||
if resp.RealNameAt == nil || c.FirstRealnameAt.Before(*resp.RealNameAt) {
|
||||
t := *c.FirstRealnameAt
|
||||
if resp.RealNameAt == nil || realnameAt.Before(*resp.RealNameAt) {
|
||||
t := *realnameAt
|
||||
resp.RealNameAt = &t
|
||||
}
|
||||
}
|
||||
@@ -345,6 +354,11 @@ func (s *Service) resolveAssociatedPhones(ctx context.Context, assetType string,
|
||||
|
||||
// buildCardResolveResponse 构建卡类型的资产解析响应
|
||||
func (s *Service) buildCardResolveResponse(ctx context.Context, card *model.IotCard) (*dto.AssetResolveResponse, error) {
|
||||
currentRealname, err := cardrealname.LoadCurrent(ctx, s.db, []uint{card.ID})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
realnameAt, realnameSource := cardrealname.ResolveRealnameAt(currentRealname, card.ID, card.FirstRealnameAt)
|
||||
resp := &dto.AssetResolveResponse{
|
||||
AssetType: "card",
|
||||
AssetID: card.ID,
|
||||
@@ -359,7 +373,9 @@ func (s *Service) buildCardResolveResponse(ctx context.Context, card *model.IotC
|
||||
CreatedAt: card.CreatedAt,
|
||||
UpdatedAt: card.UpdatedAt,
|
||||
RealNameStatus: card.RealNameStatus,
|
||||
RealNameAt: card.FirstRealnameAt,
|
||||
RealNameAt: realnameAt,
|
||||
RealNameAtSource: realnameSource,
|
||||
RealNameAtSourceName: constants.RealnameAtSourceName(realnameSource),
|
||||
RealnamePolicy: card.RealnamePolicy,
|
||||
NetworkStatus: card.NetworkStatus,
|
||||
GatewayExtend: card.GatewayExtend,
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
stopresumedomain "github.com/break/junhong_cmp_fiber/internal/domain/stopresume"
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
"github.com/break/junhong_cmp_fiber/internal/model/dto"
|
||||
"github.com/break/junhong_cmp_fiber/internal/query/recorddisplay"
|
||||
"github.com/break/junhong_cmp_fiber/internal/store/postgres"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/errors"
|
||||
@@ -175,6 +176,13 @@ func (s *Service) ListPackageTrafficAdjustments(ctx context.Context, assetType s
|
||||
size = 20
|
||||
}
|
||||
query := s.db.WithContext(ctx).Model(&model.PackageUsageAdjustment{}).Where("package_usage_id = ?", req.PackageUsageID)
|
||||
if req.StartTime != "" || req.EndTime != "" {
|
||||
from, to, err := parseRecordTimeRange(req.StartTime, req.EndTime)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
query = query.Where("created_at >= ? AND created_at < ?", from, to)
|
||||
}
|
||||
var total int64
|
||||
if err := query.Count(&total).Error; err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询冲正流水失败")
|
||||
@@ -183,9 +191,19 @@ func (s *Service) ListPackageTrafficAdjustments(ctx context.Context, assetType s
|
||||
if err := query.Order("created_at DESC, id DESC").Offset((page - 1) * size).Limit(size).Find(&rows).Error; err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询冲正流水失败")
|
||||
}
|
||||
operatorIDs := make([]uint, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
operatorIDs = append(operatorIDs, row.OperatorID)
|
||||
}
|
||||
display, err := recorddisplay.Load(ctx, s.db, recorddisplay.Request{OperatorIDs: operatorIDs})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items := make([]dto.PackageTrafficAdjustmentItem, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
items = append(items, toTrafficAdjustmentItem(row))
|
||||
item := toTrafficAdjustmentItem(row)
|
||||
item.OperatorName = display.OperatorName(row.OperatorID)
|
||||
items = append(items, item)
|
||||
}
|
||||
return &dto.PackageTrafficAdjustmentListResponse{Items: items, Total: total}, nil
|
||||
}
|
||||
|
||||
@@ -2,12 +2,15 @@ package asset
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/domain/cardflow"
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
"github.com/break/junhong_cmp_fiber/internal/model/dto"
|
||||
"github.com/break/junhong_cmp_fiber/internal/store/postgres"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/errors"
|
||||
)
|
||||
|
||||
@@ -37,22 +40,72 @@ func (s *Service) ListCardTrafficCollections(ctx context.Context, cardID uint, r
|
||||
if size <= 0 {
|
||||
size = 50
|
||||
}
|
||||
rows, total, err := postgres.NewCardTrafficCollectionStore(s.db).List(ctx, postgres.CardTrafficCollectionQuery{
|
||||
CardID: cardID, From: from, To: to, Page: page, PageSize: size,
|
||||
})
|
||||
if err != nil {
|
||||
success := s.db.WithContext(ctx).Model(&model.CardTrafficCollection{}).
|
||||
Where("iot_card_id = ? AND observed_at >= ? AND observed_at < ? AND result = ?", cardID, from, to, constants.TrafficCollectionResultOK)
|
||||
success = applyStringFilters(success, map[string]string{"decision": req.Decision, "source": req.Source, "scene": req.Scene})
|
||||
if !req.IncludeFailures {
|
||||
rows, total, err := pageQuery[model.CardTrafficCollection](success, "observed_at DESC, id DESC", page, size)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询卡流量采集记录失败")
|
||||
}
|
||||
items := make([]dto.CardTrafficCollectionItem, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
items = append(items, collectionSuccessItem(row))
|
||||
}
|
||||
return &dto.CardTrafficCollectionListResponse{Items: items, Total: total}, nil
|
||||
}
|
||||
return s.listCardCollectionsWithFailures(ctx, success, cardID, from, to, req, page, size)
|
||||
}
|
||||
|
||||
// listCardCollectionsWithFailures 合并单卡的成功与失败记录,按采集时间倒序分页(单卡 31 天内数据量有限,取前 page*size 条归并)。
|
||||
func (s *Service) listCardCollectionsWithFailures(ctx context.Context, success *gorm.DB, cardID uint, from, to time.Time,
|
||||
req *dto.CardTrafficCollectionListRequest, page, size int) (*dto.CardTrafficCollectionListResponse, error) {
|
||||
failure := s.db.WithContext(ctx).Model(&model.CardTrafficCollectionFailure{}).
|
||||
Where("iot_card_id = ? AND observed_at >= ? AND observed_at < ?", cardID, from, to)
|
||||
failure = applyStringFilters(failure, map[string]string{"source": req.Source, "scene": req.Scene})
|
||||
var successTotal, failureTotal int64
|
||||
if err := success.Count(&successTotal).Error; err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询卡流量采集记录失败")
|
||||
}
|
||||
items := make([]dto.CardTrafficCollectionItem, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
items = append(items, dto.CardTrafficCollectionItem{
|
||||
ID: row.ID, ObservedAt: row.ObservedAt, ObservationID: row.ObservationID, Source: row.Source,
|
||||
Scene: row.Scene, Result: row.Result, VendorUsedMB: row.VendorUsedMB, QueuePoints: json.RawMessage(row.QueuePoints),
|
||||
Decision: row.Decision, MonthUsedMB: row.MonthUsedMB, StaleGuarded: row.StaleGuarded,
|
||||
DeltaMB: row.DeltaMB, EventID: row.EventID,
|
||||
if err := failure.Count(&failureTotal).Error; err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询卡流量采集失败记录失败")
|
||||
}
|
||||
window := page * size
|
||||
var successRows []model.CardTrafficCollection
|
||||
if err := success.Order("observed_at DESC, id DESC").Limit(window).Find(&successRows).Error; err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询卡流量采集记录失败")
|
||||
}
|
||||
var failureRows []model.CardTrafficCollectionFailure
|
||||
if err := failure.Order("observed_at DESC, id DESC").Limit(window).Find(&failureRows).Error; err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询卡流量采集失败记录失败")
|
||||
}
|
||||
merged := make([]dto.CardTrafficCollectionItem, 0, len(successRows)+len(failureRows))
|
||||
for _, row := range successRows {
|
||||
merged = append(merged, collectionSuccessItem(row))
|
||||
}
|
||||
for _, row := range failureRows {
|
||||
f := collectionFailureItem(row)
|
||||
merged = append(merged, dto.CardTrafficCollectionItem{
|
||||
ID: f.ID, ObservedAt: f.ObservedAt, ObservationID: f.ObservationID, Source: f.Source, Scene: f.Scene,
|
||||
Result: f.Result, RecordKind: "failure", ErrorCategory: f.ErrorCategory, ProviderCode: f.ProviderCode,
|
||||
ProviderMessage: f.ProviderMessage, DurationMS: f.DurationMS, GatewayRawItem: f.GatewayRawItem,
|
||||
})
|
||||
}
|
||||
return &dto.CardTrafficCollectionListResponse{Items: items, Total: total}, nil
|
||||
sort.SliceStable(merged, func(i, j int) bool {
|
||||
if !merged[i].ObservedAt.Equal(merged[j].ObservedAt) {
|
||||
return merged[i].ObservedAt.After(merged[j].ObservedAt)
|
||||
}
|
||||
return merged[i].ID > merged[j].ID
|
||||
})
|
||||
start := (page - 1) * size
|
||||
if start > len(merged) {
|
||||
start = len(merged)
|
||||
}
|
||||
end := start + size
|
||||
if end > len(merged) {
|
||||
end = len(merged)
|
||||
}
|
||||
return &dto.CardTrafficCollectionListResponse{Items: merged[start:end], Total: successTotal + failureTotal}, nil
|
||||
}
|
||||
|
||||
func parseCollectionTime(value string) (time.Time, error) {
|
||||
|
||||
@@ -182,3 +182,29 @@ func payFirstNonEmpty(values ...string) string {
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// CreateJSAPIPayConfig 为 C 端客户按已选定(已冻结)的商户配置创建微信 JSAPI 预下单,返回前端调起支付的参数。
|
||||
// 供套餐以外的 C 端在线支付复用(如沉默期延期):openid 取客户在当前应用(公众号 / 小程序)下的授权。
|
||||
func (s *Service) CreateJSAPIPayConfig(ctx context.Context, customerID uint, appType string, config *model.WechatConfig,
|
||||
paymentNo, description string, amount int64) (*dto.ClientPayConfig, error) {
|
||||
if config == nil {
|
||||
return nil, errors.New(errors.CodeNoPaymentConfig)
|
||||
}
|
||||
_, appID, err := s.loadWechatAuthorization(ctx, appType)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
openID, err := s.resolveCustomerOpenID(ctx, customerID, appID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
provider, err := s.newPaymentProvider(config, appID, appType)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result, err := provider.CreateJSAPIPayment(ctx, paymentNo, description, openID, int(amount))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return buildClientPayConfigFromResult(result), nil
|
||||
}
|
||||
|
||||
@@ -1590,7 +1590,7 @@ func (s *Service) refreshCardDataFromGateway(ctx context.Context, iccid string,
|
||||
requestID := requestIDFromContext(ctx)
|
||||
decision, applyErr := s.cardObservation.ApplyCardObservation(ctx, carddomain.RealnameObservation{
|
||||
CardID: card.ID,
|
||||
Verified: realnameResp.RealStatus,
|
||||
Verified: realnameResp.RealStatus, UpstreamRealnameAt: realnameResp.UpstreamRealnameAt(),
|
||||
Metadata: carddomain.ObservationMetadata{
|
||||
ObservationID: uuid.NewString(), Source: constants.CardObservationSourceManualSync,
|
||||
Scene: constants.CardObservationSceneManualRefresh, ObservedAt: syncTime,
|
||||
|
||||
@@ -3,6 +3,7 @@ package iot_card
|
||||
import (
|
||||
"context"
|
||||
stderrors "errors"
|
||||
"github.com/break/junhong_cmp_fiber/internal/infrastructure/gatewaylimit"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
@@ -52,6 +53,17 @@ func (s *StopResumeService) DecideCommand(ctx context.Context, cardID uint, scen
|
||||
return CommandDecision{Card: card, Action: decision.Action, Reason: decision.Reason}, nil
|
||||
}
|
||||
|
||||
// RecordCommandSkipped 为执行前结束、未调用上游的停复机指令写一条"跳过"停复机记录;记录写入失败只告警。
|
||||
func (s *StopResumeService) RecordCommandSkipped(ctx context.Context, card *model.IotCard, action, scene, reason, skipReason string) {
|
||||
if s.stopResumeRecorder == nil || card == nil {
|
||||
return
|
||||
}
|
||||
s.stopResumeRecorder.Record(ctx, gatewaylimit.StopResumeRecordInput{
|
||||
CardID: card.ID, ICCID: card.ICCID, CarrierID: card.CarrierID, Action: action,
|
||||
Source: commandSource(ctx), Scene: scene, Reason: reason, Attempt: 0, SkipReason: skipReason,
|
||||
})
|
||||
}
|
||||
|
||||
// ErrCommandBusy 表示该卡复机正在其他路径执行(持单卡复机锁),本次未调用上游。
|
||||
var ErrCommandBusy = stderrors.New("该卡复机正在执行中")
|
||||
|
||||
|
||||
@@ -36,7 +36,8 @@ func NewDailyRecordService(
|
||||
|
||||
// GetDailyRecords 任务 13.2-13.5: 查询套餐流量详单
|
||||
// 查询指定套餐使用记录的日流量明细
|
||||
func (s *DailyRecordService) GetDailyRecords(ctx context.Context, packageUsageID uint, startDate, endDate string) (*dto.PackageUsageDetailResponse, error) {
|
||||
// GetDailyRecords 查询套餐流量详单;page_size 大于 0 时按日期倒序分页,否则按日期正序返回全部(兼容旧调用)。
|
||||
func (s *DailyRecordService) GetDailyRecords(ctx context.Context, packageUsageID uint, startDate, endDate string, page, pageSize int) (*dto.PackageUsageDetailResponse, error) {
|
||||
// 查询套餐使用记录
|
||||
var usage model.PackageUsage
|
||||
if err := s.db.WithContext(ctx).First(&usage, packageUsageID).Error; err != nil {
|
||||
@@ -73,7 +74,27 @@ func (s *DailyRecordService) GetDailyRecords(ctx context.Context, packageUsageID
|
||||
query = query.Where("date <= ?", end)
|
||||
}
|
||||
|
||||
if err := query.Order("date ASC").Find(&records).Error; err != nil {
|
||||
var summary struct {
|
||||
Total int64
|
||||
Usage int64
|
||||
}
|
||||
if err := query.Session(&gorm.Session{}).Model(&model.PackageUsageDailyRecord{}).
|
||||
Select("count(*) AS total, COALESCE(sum(daily_usage_mb), 0) AS usage").Scan(&summary).Error; err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "统计日流量记录失败")
|
||||
}
|
||||
if pageSize > 0 {
|
||||
if pageSize > 100 {
|
||||
pageSize = 100
|
||||
}
|
||||
if page <= 0 {
|
||||
page = 1
|
||||
}
|
||||
query = query.Order("date DESC").Offset((page - 1) * pageSize).Limit(pageSize)
|
||||
} else {
|
||||
page = 0
|
||||
query = query.Order("date ASC")
|
||||
}
|
||||
if err := query.Find(&records).Error; err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询日流量记录失败")
|
||||
}
|
||||
|
||||
@@ -87,14 +108,17 @@ func (s *DailyRecordService) GetDailyRecords(ctx context.Context, packageUsageID
|
||||
DailyUsageMB: record.DailyUsageMB,
|
||||
CumulativeUsageMB: record.CumulativeUsageMB,
|
||||
}
|
||||
totalUsageMB += int64(record.DailyUsageMB)
|
||||
}
|
||||
totalUsageMB = summary.Usage
|
||||
|
||||
response := &dto.PackageUsageDetailResponse{
|
||||
PackageUsageID: packageUsageID,
|
||||
PackageName: pkg.PackageName,
|
||||
Records: recordResponses,
|
||||
TotalUsageMB: totalUsageMB,
|
||||
Total: summary.Total,
|
||||
Page: page,
|
||||
PageSize: pageSize,
|
||||
}
|
||||
|
||||
return response, nil
|
||||
|
||||
@@ -41,11 +41,19 @@ func (s *GatewayRateLimitService) ListStopResumeRecords(ctx context.Context, req
|
||||
return nil, errors.New(errors.CodeInvalidParam, "停复机记录查询参数不合法:时间跨度须大于 0 且不超过 31 天")
|
||||
}
|
||||
page, size := normalizePage(req.Page, req.PageSize)
|
||||
return s.listRecords(ctx, postgres.StopResumeRecordFilter{
|
||||
filter := postgres.StopResumeRecordFilter{
|
||||
ICCID: strings.TrimSpace(req.ICCID), CarrierID: req.CarrierID, Action: req.Action, Source: req.Source,
|
||||
Result: req.Result, ErrorCategory: req.ErrorCategory, StartTime: req.StartTime, EndTime: req.EndTime,
|
||||
Page: page, PageSize: size,
|
||||
})
|
||||
Scene: req.Scene, Reason: req.Reason, CommandID: strings.TrimSpace(req.CommandID), Page: page, PageSize: size,
|
||||
}
|
||||
if identifier := strings.TrimSpace(req.Identifier); identifier != "" {
|
||||
cardIDs, err := s.cardIDsByIdentifier(ctx, identifier)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
filter.CardIDs = cardIDs
|
||||
}
|
||||
return s.listRecords(ctx, filter)
|
||||
}
|
||||
|
||||
// ListCardStopResumeRecords 查询单卡停复机历史;未传时间默认最近 31 天。
|
||||
@@ -73,7 +81,29 @@ func (s *GatewayRateLimitService) ListCardStopResumeRecords(ctx context.Context,
|
||||
}
|
||||
page, size := normalizePage(req.Page, req.PageSize)
|
||||
cardID := req.ID
|
||||
return s.listRecords(ctx, postgres.StopResumeRecordFilter{CardID: &cardID, StartTime: start, EndTime: end, Page: page, PageSize: size})
|
||||
return s.listRecords(ctx, postgres.StopResumeRecordFilter{CardID: &cardID, StartTime: start, EndTime: end, Page: page, PageSize: size,
|
||||
Action: req.Action, Result: req.Result, Source: req.Source})
|
||||
}
|
||||
|
||||
// cardIDsByIdentifier 把资产标识解析为卡:卡按虚拟号、ICCID、MSISDN 匹配,设备按虚拟号、IMEI、SN 匹配后取其绑定卡。
|
||||
// 匹配不到时返回空切片(查询结果为空页)。
|
||||
func (s *GatewayRateLimitService) cardIDsByIdentifier(ctx context.Context, identifier string) ([]uint, error) {
|
||||
cardIDs := []uint{}
|
||||
if err := s.db.WithContext(ctx).Model(&model.IotCard{}).
|
||||
Where("iccid = ? OR virtual_no = ? OR msisdn = ?", identifier, identifier, identifier).
|
||||
Pluck("id", &cardIDs).Error; err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "按资产标识查询卡失败")
|
||||
}
|
||||
if len(cardIDs) > 0 {
|
||||
return cardIDs, nil
|
||||
}
|
||||
if err := s.db.WithContext(ctx).Model(&model.DeviceSimBinding{}).
|
||||
Joins("JOIN tb_device d ON d.id = tb_device_sim_binding.device_id AND d.deleted_at IS NULL").
|
||||
Where("(d.virtual_no = ? OR d.imei = ? OR d.sn = ?) AND tb_device_sim_binding.bind_status = ?", identifier, identifier, identifier, constants.BindStatusBound).
|
||||
Pluck("tb_device_sim_binding.iot_card_id", &cardIDs).Error; err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "按资产标识查询设备绑定卡失败")
|
||||
}
|
||||
return cardIDs, nil
|
||||
}
|
||||
|
||||
func (s *GatewayRateLimitService) listRecords(ctx context.Context, filter postgres.StopResumeRecordFilter) (*dto.StopResumeRecordPageResult, error) {
|
||||
|
||||
@@ -290,16 +290,4 @@ func (s *Service) ProcessCommissionDeduction(ctx context.Context, refundID uint)
|
||||
return s.clawbackCommission(ctx, refundID)
|
||||
}
|
||||
|
||||
func (s *Service) ProcessAssetPostProcessing(ctx context.Context, refundID uint) error {
|
||||
s.handleRefundAssetProcessing(ctx, refundID)
|
||||
var refund model.RefundRequest
|
||||
if err := s.db.WithContext(ctx).Select("asset_reset").First(&refund, refundID).Error; err != nil {
|
||||
return errors.Wrap(errors.CodeDatabaseError, err, "复核退款资产后处理状态失败")
|
||||
}
|
||||
if !refund.AssetReset {
|
||||
return errors.New(errors.CodeServiceUnavailable, "退款资产后处理尚未完成")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var _ approvalapp.BusinessDecisionHandler = (*Service)(nil)
|
||||
|
||||
108
internal/service/refund/asset_post_attempt_query.go
Normal file
108
internal/service/refund/asset_post_attempt_query.go
Normal file
@@ -0,0 +1,108 @@
|
||||
package refund
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/domain/cardflow"
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
"github.com/break/junhong_cmp_fiber/internal/model/dto"
|
||||
"github.com/break/junhong_cmp_fiber/internal/query/recorddisplay"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/errors"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/middleware"
|
||||
)
|
||||
|
||||
// attemptQueryMaxSpan 是尝试记录查询的最长时间跨度。
|
||||
const attemptQueryMaxSpan = 31 * 24 * time.Hour
|
||||
|
||||
var attemptTimeLayouts = []string{time.RFC3339, "2006-01-02 15:04:05", "2006-01-02"}
|
||||
|
||||
// ListAssetPostProcessAttempts 分页查询退款资产后处理尝试记录(仅平台账号;可查单张退款单或单个资产,也可查全部)。
|
||||
func (s *Service) ListAssetPostProcessAttempts(ctx context.Context, req *dto.RefundPostProcessAttemptListRequest) (*dto.RefundPostProcessAttemptListResponse, error) {
|
||||
userType := middleware.GetUserTypeFromContext(ctx)
|
||||
if userType != constants.UserTypeSuperAdmin && userType != constants.UserTypePlatform {
|
||||
return nil, errors.New(errors.CodeForbidden, "只有平台账号可以查询退款资产后处理尝试记录")
|
||||
}
|
||||
from, err := parseAttemptTime(req.StartTime)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
to, err := parseAttemptTime(req.EndTime)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !to.After(from) || to.Sub(from) > attemptQueryMaxSpan {
|
||||
return nil, errors.New(errors.CodeInvalidParam, "结束时间必须晚于开始时间,且跨度不超过 31 天")
|
||||
}
|
||||
page, size := req.Page, req.PageSize
|
||||
if page <= 0 {
|
||||
page = 1
|
||||
}
|
||||
if size <= 0 || size > 100 {
|
||||
size = 20
|
||||
}
|
||||
resp := &dto.RefundPostProcessAttemptListResponse{Items: []dto.RefundPostProcessAttemptItem{}, Page: page, PageSize: size}
|
||||
query := s.db.WithContext(ctx).Model(&model.RefundPostProcessAttempt{}).Where("created_at >= ? AND created_at < ?", from, to)
|
||||
if req.RefundID != nil {
|
||||
query = query.Where("refund_id = ?", *req.RefundID)
|
||||
}
|
||||
if refundNo := strings.TrimSpace(req.RefundNo); refundNo != "" {
|
||||
query = query.Where("refund_no = ?", refundNo)
|
||||
}
|
||||
if identifier := strings.TrimSpace(req.Identifier); identifier != "" {
|
||||
query = query.Where(`(iccid = ? OR (asset_type = 'iot_card' AND asset_id IN (SELECT id FROM tb_iot_card WHERE virtual_no = ? OR msisdn = ?))
|
||||
OR (asset_type = 'device' AND asset_id IN (SELECT id FROM tb_device WHERE virtual_no = ? OR imei = ? OR sn = ?)))`,
|
||||
identifier, identifier, identifier, identifier, identifier, identifier)
|
||||
}
|
||||
for column, value := range map[string]string{"step": req.Step, "result": req.Result, "error_code": req.ErrorCode, "trigger": req.Trigger} {
|
||||
if value != "" {
|
||||
query = query.Where(column+" = ?", value)
|
||||
}
|
||||
}
|
||||
var total int64
|
||||
if err := query.Count(&total).Error; err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询退款资产后处理尝试记录失败")
|
||||
}
|
||||
resp.Total = total
|
||||
if total == 0 {
|
||||
return resp, nil
|
||||
}
|
||||
var rows []model.RefundPostProcessAttempt
|
||||
if err := query.Order("created_at DESC, id DESC").Offset((page - 1) * size).Limit(size).Find(&rows).Error; err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询退款资产后处理尝试记录失败")
|
||||
}
|
||||
displayReq := recorddisplay.Request{}
|
||||
for _, row := range rows {
|
||||
if row.AssetType == constants.AssetTypeDevice {
|
||||
displayReq.DeviceIDs = append(displayReq.DeviceIDs, row.AssetID)
|
||||
}
|
||||
}
|
||||
display, err := recorddisplay.Load(ctx, s.db, displayReq)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, row := range rows {
|
||||
var device recorddisplay.Device
|
||||
if row.AssetType == constants.AssetTypeDevice {
|
||||
device = display.Device(row.AssetID)
|
||||
}
|
||||
resp.Items = append(resp.Items, dto.RefundPostProcessAttemptItem{
|
||||
ID: row.ID, RefundID: row.RefundID, RefundNo: row.RefundNo, Step: row.Step, AssetType: row.AssetType,
|
||||
AssetID: row.AssetID, ICCID: row.ICCID, DeviceVirtualNo: device.VirtualNo, DeviceIMEI: device.IMEI, Attempt: row.Attempt, Trigger: row.Trigger, Result: row.Result,
|
||||
ErrorCode: row.ErrorCode, ErrorMessage: row.ErrorMessage, DurationMS: row.DurationMS, CreatedAt: row.CreatedAt,
|
||||
})
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func parseAttemptTime(value string) (time.Time, error) {
|
||||
location := cardflow.ShanghaiDate(time.Now()).Location()
|
||||
for _, layout := range attemptTimeLayouts {
|
||||
if t, err := time.ParseInLocation(layout, value, location); err == nil {
|
||||
return t, nil
|
||||
}
|
||||
}
|
||||
return time.Time{}, errors.New(errors.CodeInvalidParam, "时间格式无效")
|
||||
}
|
||||
236
internal/service/refund/asset_post_processing.go
Normal file
236
internal/service/refund/asset_post_processing.go
Normal file
@@ -0,0 +1,236 @@
|
||||
package refund
|
||||
|
||||
import (
|
||||
"context"
|
||||
stderrors "errors"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/infrastructure/audit"
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
"github.com/break/junhong_cmp_fiber/internal/model/dto"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/auditcontext"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/errors"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/middleware"
|
||||
)
|
||||
|
||||
// assetPostErrorMessageMax 是尝试记录与退款单上错误摘要的最大长度(字符)。
|
||||
const assetPostErrorMessageMax = 500
|
||||
|
||||
// ProcessAssetPostProcessing 是 Outbox 投递(含补偿扫描重投)的退款资产后处理入口。
|
||||
// 后处理失败只更新重试状态并返回 nil,由补偿扫描按下次重试时间拉起,不靠 Outbox 自身重投;
|
||||
// 只有读写退款单本身失败时返回错误,交给 Outbox 重试。
|
||||
func (s *Service) ProcessAssetPostProcessing(ctx context.Context, refundID uint) error {
|
||||
return s.runAssetPostProcessing(ctx, refundID, constants.RefundPostTriggerOutbox)
|
||||
}
|
||||
|
||||
// RetryAssetPostProcessingByAdmin 是后台人工重试接口:仅平台账号,按详情可见范围定位后重试并返回最新详情。
|
||||
func (s *Service) RetryAssetPostProcessingByAdmin(ctx context.Context, refundID uint) (*dto.RefundResponse, error) {
|
||||
userType := middleware.GetUserTypeFromContext(ctx)
|
||||
if userType != constants.UserTypeSuperAdmin && userType != constants.UserTypePlatform {
|
||||
return nil, errors.New(errors.CodeForbidden, "只有平台账号可以重试退款资产后处理")
|
||||
}
|
||||
if _, err := s.refundStore.GetByID(ctx, refundID); err != nil {
|
||||
return nil, errors.New(errors.CodeNotFound, "退款申请不存在")
|
||||
}
|
||||
if err := s.RetryAssetPostProcessing(ctx, refundID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.GetByID(ctx, refundID)
|
||||
}
|
||||
|
||||
// RetryAssetPostProcessing 是人工重试入口,只允许对"需人工处理"的退款单发起。
|
||||
func (s *Service) RetryAssetPostProcessing(ctx context.Context, refundID uint) error {
|
||||
var refund model.RefundRequest
|
||||
if err := s.db.WithContext(ctx).Select("id", "status", "asset_reset", "asset_post_status").First(&refund, refundID).Error; err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return errors.New(errors.CodeNotFound, "退款单不存在")
|
||||
}
|
||||
return errors.Wrap(errors.CodeDatabaseError, err, "查询退款单失败")
|
||||
}
|
||||
if refund.AssetReset || refund.AssetPostStatus != model.RefundAssetPostManualRequired {
|
||||
return errors.New(errors.CodeInvalidStatus, "只有需人工处理的退款单可以重试资产后处理")
|
||||
}
|
||||
if err := s.runAssetPostProcessing(ctx, refundID, constants.RefundPostTriggerManual); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.db.WithContext(ctx).Select("asset_reset", "asset_post_last_error").First(&refund, refundID).Error; err != nil {
|
||||
return errors.Wrap(errors.CodeDatabaseError, err, "复核退款资产后处理状态失败")
|
||||
}
|
||||
if !refund.AssetReset {
|
||||
return errors.New(errors.CodeServiceUnavailable, "资产后处理仍未完成:"+refund.AssetPostLastError)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) runAssetPostProcessing(ctx context.Context, refundID uint, trigger string) error {
|
||||
var refund model.RefundRequest
|
||||
if err := s.db.WithContext(ctx).Where("id = ?", refundID).First(&refund).Error; err != nil {
|
||||
return errors.Wrap(errors.CodeDatabaseError, err, "查询退款单失败")
|
||||
}
|
||||
if refund.AssetReset {
|
||||
return nil
|
||||
}
|
||||
now := time.Now()
|
||||
if trigger == constants.RefundPostTriggerOutbox {
|
||||
if refund.AssetPostStatus == model.RefundAssetPostManualRequired {
|
||||
return nil
|
||||
}
|
||||
if refund.AssetPostNextAt != nil && refund.AssetPostNextAt.After(now) {
|
||||
return nil
|
||||
}
|
||||
ctx = auditcontext.With(ctx, auditcontext.Context{
|
||||
ActorKind: constants.AuditActorSystemTask, ActorID: constants.AuditActorIDRefundAssetPostProcessing,
|
||||
ActorName: "退款资产自动后处理任务", Source: constants.AuditSourceWorker, CorrelationID: refund.RefundNo,
|
||||
})
|
||||
}
|
||||
|
||||
// 先占用本次尝试序号,使完成审计能读到总尝试次数。
|
||||
attempt := refund.AssetPostAttempts + 1
|
||||
if err := s.db.WithContext(ctx).Model(&model.RefundRequest{}).Where("id = ?", refundID).
|
||||
Update("asset_post_attempts", attempt).Error; err != nil {
|
||||
return errors.Wrap(errors.CodeDatabaseError, err, "更新退款资产后处理次数失败")
|
||||
}
|
||||
refund.AssetPostAttempts = attempt
|
||||
|
||||
outcome := s.handleRefundAssetProcessing(ctx, &refund)
|
||||
record := s.recordAssetPostAttempt(ctx, &refund, outcome, attempt, trigger, time.Since(now))
|
||||
if outcome.Err == nil {
|
||||
return s.completeAssetPostProcessing(ctx, refundID)
|
||||
}
|
||||
return s.failAssetPostProcessing(ctx, &refund, outcome, attempt, trigger, record)
|
||||
}
|
||||
|
||||
func (s *Service) completeAssetPostProcessing(ctx context.Context, refundID uint) error {
|
||||
if err := s.db.WithContext(ctx).Model(&model.RefundRequest{}).Where("id = ?", refundID).Updates(map[string]any{
|
||||
"asset_post_status": model.RefundAssetPostCompleted, "asset_post_last_error": "", "asset_post_next_at": nil,
|
||||
}).Error; err != nil {
|
||||
return errors.Wrap(errors.CodeDatabaseError, err, "更新退款资产后处理状态失败")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) failAssetPostProcessing(
|
||||
ctx context.Context, refund *model.RefundRequest, outcome refundAssetOutcome, attempt int, trigger string, record *model.RefundPostProcessAttempt,
|
||||
) error {
|
||||
message := truncateRunes(outcome.Err.Error(), assetPostErrorMessageMax)
|
||||
updates := map[string]any{"asset_post_last_error": message}
|
||||
final := attempt >= constants.RefundPostMaxAttempts
|
||||
if final {
|
||||
updates["asset_post_status"] = model.RefundAssetPostManualRequired
|
||||
updates["asset_post_next_at"] = nil
|
||||
} else {
|
||||
updates["asset_post_status"] = model.RefundAssetPostRetryPending
|
||||
updates["asset_post_next_at"] = time.Now().Add(assetPostBackoff(attempt))
|
||||
}
|
||||
if err := s.db.WithContext(ctx).Model(&model.RefundRequest{}).Where("id = ?", refund.ID).Updates(updates).Error; err != nil {
|
||||
return errors.Wrap(errors.CodeDatabaseError, err, "更新退款资产后处理重试状态失败")
|
||||
}
|
||||
s.recordAssetPostFailureAudit(ctx, refund, outcome, attempt, record, final || trigger == constants.RefundPostTriggerManual)
|
||||
return nil
|
||||
}
|
||||
|
||||
// recordAssetPostFailureAudit 写后处理失败:中间失败只写应用日志,转人工或人工重试失败写审计结论。
|
||||
func (s *Service) recordAssetPostFailureAudit(
|
||||
ctx context.Context, refund *model.RefundRequest, outcome refundAssetOutcome, attempt int, record *model.RefundPostProcessAttempt, final bool,
|
||||
) {
|
||||
if s.auditWriter == nil || s.db == nil {
|
||||
return
|
||||
}
|
||||
primary := audit.RefundResource(refund, constants.AuditResourceRelationPrimary, constants.AuditResourceRoleRefundTarget)
|
||||
primary.SubjectVisibility = constants.AuditSubjectInternalOnly
|
||||
input := audit.AppendInput{
|
||||
EventID: "refund:" + strconv.FormatUint(uint64(refund.ID), 10) + ":asset-processed:failed:" + strconv.Itoa(attempt),
|
||||
ActionCode: constants.AuditActionRefundAssetProcessed, Summary: "退款资产后处理失败(" + outcome.Step + ")",
|
||||
ScopeType: constants.AuditScopePlatform, CorrelationID: refund.RefundNo, Resources: []audit.ResourceInput{primary},
|
||||
Final: final, Attempt: attempt,
|
||||
Metadata: map[string]any{"asset_post_attempts": attempt, "step": outcome.Step, "manual_required": attempt >= constants.RefundPostMaxAttempts},
|
||||
}
|
||||
if final {
|
||||
input.Summary = "退款资产后处理重试用尽,转人工处理(" + outcome.Step + ")"
|
||||
for key, value := range assetPostOutcomeMetadata(ctx, s.db, refund) {
|
||||
input.Metadata[key] = value
|
||||
}
|
||||
}
|
||||
if record != nil && record.ID > 0 {
|
||||
input.AttemptRecordID = strconv.FormatUint(uint64(record.ID), 10)
|
||||
}
|
||||
s.auditWriter.RecordFailure(ctx, s.db, input, outcome.Err)
|
||||
}
|
||||
|
||||
// recordAssetPostAttempt 写一条尝试记录;写入失败只告警,不影响后处理结果。
|
||||
func (s *Service) recordAssetPostAttempt(
|
||||
ctx context.Context, refund *model.RefundRequest, outcome refundAssetOutcome, attempt int, trigger string, duration time.Duration,
|
||||
) *model.RefundPostProcessAttempt {
|
||||
record := &model.RefundPostProcessAttempt{
|
||||
RefundID: refund.ID, RefundNo: refund.RefundNo, Step: outcome.Step, AssetType: outcome.AssetType, AssetID: outcome.AssetID,
|
||||
Attempt: attempt, Trigger: trigger, Result: constants.RefundPostResultSuccess, DurationMS: int(duration.Milliseconds()),
|
||||
}
|
||||
if outcome.AssetType == constants.AssetTypeIotCard && outcome.AssetID > 0 {
|
||||
var card model.IotCard
|
||||
if err := s.db.WithContext(ctx).Select("iccid").First(&card, outcome.AssetID).Error; err == nil {
|
||||
record.ICCID = card.ICCID
|
||||
}
|
||||
}
|
||||
if outcome.Err != nil {
|
||||
record.Result = constants.RefundPostResultFailed
|
||||
record.ErrorCode, record.ErrorMessage = assetPostErrorDetail(outcome.Err)
|
||||
}
|
||||
if err := s.db.WithContext(ctx).Create(record).Error; err != nil {
|
||||
s.logger.Warn("写退款资产后处理尝试记录失败", zap.Uint("refund_id", refund.ID), zap.Int("attempt", attempt), zap.Error(err))
|
||||
return nil
|
||||
}
|
||||
return record
|
||||
}
|
||||
|
||||
// assetPostOutcomeMetadata 返回结论审计需要的总尝试次数、首次失败时间与最后错误。
|
||||
func assetPostOutcomeMetadata(ctx context.Context, db *gorm.DB, refund *model.RefundRequest) map[string]any {
|
||||
metadata := map[string]any{"asset_post_attempts": refund.AssetPostAttempts}
|
||||
var first model.RefundPostProcessAttempt
|
||||
if err := db.WithContext(ctx).Where("refund_id = ? AND result = ?", refund.ID, constants.RefundPostResultFailed).
|
||||
Order("created_at ASC, id ASC").Limit(1).Find(&first).Error; err == nil && first.ID > 0 {
|
||||
metadata["first_failed_at"] = first.CreatedAt
|
||||
}
|
||||
var last model.RefundPostProcessAttempt
|
||||
if err := db.WithContext(ctx).Where("refund_id = ? AND result = ?", refund.ID, constants.RefundPostResultFailed).
|
||||
Order("created_at DESC, id DESC").Limit(1).Find(&last).Error; err == nil && last.ID > 0 {
|
||||
metadata["last_error_code"] = last.ErrorCode
|
||||
}
|
||||
return metadata
|
||||
}
|
||||
|
||||
// assetPostBackoff 返回第 attempt 次失败后的重试间隔:2^(attempt-1) 分钟,最长 1 小时。
|
||||
func assetPostBackoff(attempt int) time.Duration {
|
||||
if attempt < 1 {
|
||||
attempt = 1
|
||||
}
|
||||
if attempt > 7 {
|
||||
return constants.RefundPostMaxBackoff
|
||||
}
|
||||
delay := time.Duration(1<<(attempt-1)) * time.Minute
|
||||
if delay > constants.RefundPostMaxBackoff {
|
||||
return constants.RefundPostMaxBackoff
|
||||
}
|
||||
return delay
|
||||
}
|
||||
|
||||
func assetPostErrorDetail(err error) (string, string) {
|
||||
code := strconv.Itoa(errors.CodeInternalError)
|
||||
var appErr *errors.AppError
|
||||
if stderrors.As(err, &appErr) && appErr != nil {
|
||||
code = strconv.Itoa(appErr.Code)
|
||||
}
|
||||
return code, truncateRunes(err.Error(), assetPostErrorMessageMax)
|
||||
}
|
||||
|
||||
func truncateRunes(value string, limit int) string {
|
||||
runes := []rune(value)
|
||||
if len(runes) <= limit {
|
||||
return value
|
||||
}
|
||||
return string(runes[:limit])
|
||||
}
|
||||
@@ -71,15 +71,20 @@ func (s *Service) appendRefundAudit(
|
||||
resources = append(resources, chain...)
|
||||
}
|
||||
|
||||
metadata := map[string]any{
|
||||
"requested_refund_amount": refund.RequestedRefundAmount,
|
||||
"approved_refund_amount": refund.ApprovedRefundAmount,
|
||||
}
|
||||
if actionCode == constants.AuditActionRefundAssetProcessed {
|
||||
for key, value := range assetPostOutcomeMetadata(ctx, tx, &refund) {
|
||||
metadata[key] = value
|
||||
}
|
||||
}
|
||||
// 退款审计都是业务结论;对"只写结论"策略的动作(退款资产后处理)标记为最终结论。
|
||||
return s.auditWriter.Append(ctx, tx, audit.AppendInput{
|
||||
EventID: eventID, ActionCode: actionCode, Summary: summary,
|
||||
ScopeType: constants.AuditScopePlatform, Result: constants.AuditResultSuccess,
|
||||
CorrelationID: refund.RefundNo,
|
||||
Metadata: map[string]any{
|
||||
"requested_refund_amount": refund.RequestedRefundAmount,
|
||||
"approved_refund_amount": refund.ApprovedRefundAmount,
|
||||
},
|
||||
Resources: resources,
|
||||
CorrelationID: refund.RefundNo, Metadata: metadata, Resources: resources, Final: true,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -268,6 +268,7 @@ func (s *Service) List(ctx context.Context, req *dto.RefundListRequest) (*dto.Re
|
||||
OrderID: req.OrderID,
|
||||
ShopID: req.ShopID,
|
||||
AssetIdentifier: req.AssetIdentifier,
|
||||
AssetPostStatus: req.AssetPostStatus,
|
||||
}
|
||||
|
||||
requests, total, err := s.refundStore.List(ctx, opts, filters)
|
||||
@@ -1125,34 +1126,26 @@ func (s *Service) appendWithdrawalRejectAudit(
|
||||
return nil
|
||||
}
|
||||
|
||||
// refundAssetOutcome 是一次退款资产后处理的结果:失败时 Step 为失败步骤,Err 非空。
|
||||
type refundAssetOutcome struct {
|
||||
Step string
|
||||
AssetType string
|
||||
AssetID uint
|
||||
Err error
|
||||
}
|
||||
|
||||
// handleRefundAssetProcessing 幂等处理退款后的资产状态。
|
||||
// 包括退款套餐精准失效、尝试接续待生效主套餐和必要时停机;全部完成后才设置完成标记。
|
||||
func (s *Service) handleRefundAssetProcessing(ctx context.Context, refundID uint) {
|
||||
// 失败不在这里写审计,由 ProcessAssetPostProcessing 写尝试记录、更新重试状态并按"只写结论"写审计。
|
||||
func (s *Service) handleRefundAssetProcessing(ctx context.Context, refund *model.RefundRequest) refundAssetOutcome {
|
||||
logger := s.logger
|
||||
|
||||
// 查询退款单
|
||||
var refund model.RefundRequest
|
||||
if err := s.db.Where("id = ?", refundID).First(&refund).Error; err != nil {
|
||||
logger.Error("退款资产处理:查询退款单失败", zap.Uint("refund_id", refundID), zap.Error(err))
|
||||
return
|
||||
}
|
||||
if refund.AssetReset {
|
||||
return
|
||||
}
|
||||
ctx = auditcontext.With(ctx, auditcontext.Context{
|
||||
ActorKind: constants.AuditActorSystemTask, ActorID: constants.AuditActorIDRefundAssetPostProcessing,
|
||||
ActorName: "退款资产自动后处理任务", Source: constants.AuditSourceWorker, CorrelationID: refund.RefundNo,
|
||||
})
|
||||
refundID := refund.ID
|
||||
|
||||
// 查询关联订单
|
||||
var order model.Order
|
||||
if err := s.db.Where("id = ?", refund.OrderID).First(&order).Error; err != nil {
|
||||
s.recordRefundFailure(ctx, constants.AuditActionRefundAssetProcessed, "完成退款资产后处理失败", &refund, nil, err)
|
||||
if err := s.db.WithContext(ctx).Where("id = ?", refund.OrderID).First(&order).Error; err != nil {
|
||||
logger.Error("退款资产处理:查询订单失败", zap.Uint("refund_id", refundID), zap.Uint("order_id", refund.OrderID), zap.Error(err))
|
||||
return
|
||||
}
|
||||
recordFailure := func(err error) {
|
||||
s.recordRefundFailure(ctx, constants.AuditActionRefundAssetProcessed, "完成退款资产后处理失败", &refund, &order, err)
|
||||
return refundAssetOutcome{Step: constants.RefundPostStepLoad, Err: errors.Wrap(errors.CodeDatabaseError, err, "查询退款关联订单失败")}
|
||||
}
|
||||
|
||||
// 确定资产类型和 ID
|
||||
@@ -1161,37 +1154,32 @@ func (s *Service) handleRefundAssetProcessing(ctx context.Context, refundID uint
|
||||
switch order.OrderType {
|
||||
case model.OrderTypeSingleCard:
|
||||
if order.IotCardID == nil {
|
||||
recordFailure(errors.New(errors.CodeInternalError, "退款单卡订单缺少资产ID"))
|
||||
logger.Error("退款资产处理:单卡订单缺少 iot_card_id", zap.Uint("order_id", order.ID))
|
||||
return
|
||||
return refundAssetOutcome{Step: constants.RefundPostStepLoad, Err: errors.New(errors.CodeInternalError, "退款单卡订单缺少资产ID")}
|
||||
}
|
||||
assetType = "iot_card"
|
||||
assetID = *order.IotCardID
|
||||
case model.OrderTypeDevice:
|
||||
if order.DeviceID == nil {
|
||||
recordFailure(errors.New(errors.CodeInternalError, "退款设备订单缺少资产ID"))
|
||||
logger.Error("退款资产处理:设备订单缺少 device_id", zap.Uint("order_id", order.ID))
|
||||
return
|
||||
return refundAssetOutcome{Step: constants.RefundPostStepLoad, Err: errors.New(errors.CodeInternalError, "退款设备订单缺少资产ID")}
|
||||
}
|
||||
assetType = "device"
|
||||
assetID = *order.DeviceID
|
||||
default:
|
||||
recordFailure(errors.New(errors.CodeInvalidParam, "退款订单资产类型无效"))
|
||||
logger.Error("退款资产处理:未知订单类型", zap.String("order_type", order.OrderType))
|
||||
return
|
||||
return refundAssetOutcome{Step: constants.RefundPostStepLoad, Err: errors.New(errors.CodeInvalidParam, "退款订单资产类型无效")}
|
||||
}
|
||||
fail := func(step string, err error) refundAssetOutcome {
|
||||
return refundAssetOutcome{Step: step, AssetType: assetType, AssetID: assetID, Err: err}
|
||||
}
|
||||
|
||||
// 1. 按退款单精准失效套餐(仅处理本次退款订单关联套餐)
|
||||
if s.packageActivationService == nil {
|
||||
businessErr := errors.New(errors.CodeServiceUnavailable, "退款套餐处理能力未配置")
|
||||
recordFailure(businessErr)
|
||||
logger.Error("退款资产处理:套餐激活服务未注入",
|
||||
zap.Uint("refund_id", refund.ID),
|
||||
zap.Uint("order_id", order.ID))
|
||||
return
|
||||
logger.Error("退款资产处理:套餐激活服务未注入", zap.Uint("refund_id", refund.ID), zap.Uint("order_id", order.ID))
|
||||
return fail(constants.RefundPostStepInvalidate, errors.New(errors.CodeServiceUnavailable, "退款套餐处理能力未配置"))
|
||||
}
|
||||
if err := s.packageActivationService.InvalidatePackagesForRefund(ctx, assetType, assetID, order.ID, refund.ID, refund.RefundNo, refund.PackageUsageID); err != nil {
|
||||
recordFailure(err)
|
||||
fields := []zap.Field{
|
||||
zap.String("asset_type", assetType),
|
||||
zap.Uint("asset_id", assetID),
|
||||
@@ -1204,43 +1192,35 @@ func (s *Service) handleRefundAssetProcessing(ctx context.Context, refundID uint
|
||||
fields = append(fields, zap.Uint("package_usage_id", *refund.PackageUsageID))
|
||||
}
|
||||
logger.Error("退款资产处理:退款套餐精准失效失败", fields...)
|
||||
return
|
||||
return fail(constants.RefundPostStepInvalidate, err)
|
||||
}
|
||||
|
||||
// 2. 尝试按购买顺序接续待生效主套餐
|
||||
if _, err := s.packageActivationService.ActivateNextPendingMainPackage(ctx, assetType, assetID); err != nil {
|
||||
recordFailure(err)
|
||||
logger.Error("退款资产处理:接续激活待生效套餐失败",
|
||||
zap.String("asset_type", assetType),
|
||||
zap.Uint("asset_id", assetID),
|
||||
zap.Uint("refund_id", refund.ID),
|
||||
zap.Error(err))
|
||||
return
|
||||
zap.String("asset_type", assetType), zap.Uint("asset_id", assetID), zap.Uint("refund_id", refund.ID), zap.Error(err))
|
||||
return fail(constants.RefundPostStepActivate, err)
|
||||
}
|
||||
|
||||
hasActiveMain, err := s.packageActivationService.HasActiveMainPackage(ctx, assetType, assetID)
|
||||
if err != nil {
|
||||
recordFailure(err)
|
||||
logger.Error("退款资产处理:查询生效主套餐失败",
|
||||
zap.String("asset_type", assetType),
|
||||
zap.Uint("asset_id", assetID),
|
||||
zap.Uint("refund_id", refund.ID),
|
||||
zap.Error(err))
|
||||
return
|
||||
zap.String("asset_type", assetType), zap.Uint("asset_id", assetID), zap.Uint("refund_id", refund.ID), zap.Error(err))
|
||||
return fail(constants.RefundPostStepCheckMain, err)
|
||||
}
|
||||
if !hasActiveMain {
|
||||
// 3. 无可用主套餐时才停机;退款不再重置世代或重建钱包。
|
||||
if !s.stopAsset(ctx, assetType, assetID) {
|
||||
recordFailure(errors.New(errors.CodeServiceUnavailable, "退款资产停机处理失败"))
|
||||
return
|
||||
return fail(constants.RefundPostStepStop, errors.New(errors.CodeServiceUnavailable, "退款资产停机处理失败"))
|
||||
}
|
||||
}
|
||||
|
||||
// 4. 标记退款后资产处理已完成
|
||||
if err := s.markRefundAssetProcessed(ctx, refundID); err != nil {
|
||||
recordFailure(err)
|
||||
logger.Error("退款资产处理:更新处理标记失败", zap.Uint("refund_id", refundID), zap.Error(err))
|
||||
return fail(constants.RefundPostStepMark, err)
|
||||
}
|
||||
return refundAssetOutcome{Step: constants.RefundPostStepDone, AssetType: assetType, AssetID: assetID}
|
||||
}
|
||||
|
||||
// stopAsset 根据资产类型执行停机操作
|
||||
@@ -1396,6 +1376,10 @@ func buildRefundResponse(r *model.RefundRequest) *dto.RefundResponse {
|
||||
Remark: r.Remark,
|
||||
CommissionDeducted: r.CommissionDeducted,
|
||||
AssetReset: r.AssetReset,
|
||||
AssetPostStatus: r.AssetPostStatus,
|
||||
AssetPostAttempts: r.AssetPostAttempts,
|
||||
AssetPostLastError: r.AssetPostLastError,
|
||||
AssetPostNextAt: r.AssetPostNextAt,
|
||||
SubmitterID: r.Creator,
|
||||
ApprovalInstanceID: r.ApprovalInstanceID,
|
||||
Creator: r.Creator,
|
||||
|
||||
@@ -2,19 +2,12 @@ package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/domain/cardflow"
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
)
|
||||
|
||||
// collectionPartitionPrefix 是采集记录月分区表名前缀,后接 YYYYMM。
|
||||
const collectionPartitionPrefix = "tb_card_traffic_collection_"
|
||||
|
||||
// CardTrafficCollectionStore 卡流量采集记录存储。
|
||||
type CardTrafficCollectionStore struct {
|
||||
db *gorm.DB
|
||||
@@ -30,68 +23,17 @@ func (s *CardTrafficCollectionStore) Create(ctx context.Context, record *model.C
|
||||
return s.db.WithContext(ctx).Create(record).Error
|
||||
}
|
||||
|
||||
// CardTrafficCollectionQuery 是采集记录查询条件。
|
||||
type CardTrafficCollectionQuery struct {
|
||||
CardID uint
|
||||
From, To time.Time
|
||||
Page int
|
||||
PageSize int
|
||||
// CardTrafficCollectionFailureStore 卡流量采集失败记录存储。
|
||||
type CardTrafficCollectionFailureStore struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// List 按卡与采集时间范围分页查询采集记录,按采集时间倒序。
|
||||
func (s *CardTrafficCollectionStore) List(ctx context.Context, query CardTrafficCollectionQuery) ([]model.CardTrafficCollection, int64, error) {
|
||||
db := s.db.WithContext(ctx).Model(&model.CardTrafficCollection{}).
|
||||
Where("iot_card_id = ? AND observed_at >= ? AND observed_at < ?", query.CardID, query.From, query.To)
|
||||
var total int64
|
||||
if err := db.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
var rows []model.CardTrafficCollection
|
||||
err := db.Order("observed_at DESC, id DESC").Offset((query.Page - 1) * query.PageSize).Limit(query.PageSize).Find(&rows).Error
|
||||
return rows, total, err
|
||||
// NewCardTrafficCollectionFailureStore 创建采集失败记录存储。
|
||||
func NewCardTrafficCollectionFailureStore(db *gorm.DB) *CardTrafficCollectionFailureStore {
|
||||
return &CardTrafficCollectionFailureStore{db: db}
|
||||
}
|
||||
|
||||
// FindByObservationID 按采集 ID 查询采集记录。
|
||||
func (s *CardTrafficCollectionStore) FindByObservationID(ctx context.Context, observationID string) ([]model.CardTrafficCollection, error) {
|
||||
var rows []model.CardTrafficCollection
|
||||
err := s.db.WithContext(ctx).Where("observation_id = ?", observationID).Order("observed_at DESC").Find(&rows).Error
|
||||
return rows, err
|
||||
}
|
||||
|
||||
// MaintainPartitions 预建本月起 aheadMonths 个月的分区,并删除整月都早于保留期的分区。
|
||||
func (s *CardTrafficCollectionStore) MaintainPartitions(ctx context.Context, now time.Time, aheadMonths int, retentionDays int) error {
|
||||
monthStart := cardflow.MonthStart(now)
|
||||
for i := 0; i <= aheadMonths; i++ {
|
||||
from := monthStart.AddDate(0, i, 0)
|
||||
to := from.AddDate(0, 1, 0)
|
||||
sql := fmt.Sprintf(`CREATE TABLE IF NOT EXISTS %s%s PARTITION OF tb_card_traffic_collection FOR VALUES FROM ('%s') TO ('%s')`,
|
||||
collectionPartitionPrefix, from.Format("200601"), from.Format(time.RFC3339), to.Format(time.RFC3339))
|
||||
if err := s.db.WithContext(ctx).Exec(sql).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
cutoff := cardflow.ShanghaiDate(now).AddDate(0, 0, -retentionDays)
|
||||
var partitions []string
|
||||
if err := s.db.WithContext(ctx).Raw(`
|
||||
SELECT c.relname FROM pg_inherits i
|
||||
JOIN pg_class c ON c.oid = i.inhrelid
|
||||
JOIN pg_class p ON p.oid = i.inhparent
|
||||
WHERE p.relname = 'tb_card_traffic_collection'`).Scan(&partitions).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
for _, name := range partitions {
|
||||
if len(name) != len(collectionPartitionPrefix)+6 || !strings.HasPrefix(name, collectionPartitionPrefix) {
|
||||
continue
|
||||
}
|
||||
start, err := time.ParseInLocation("200601", name[len(collectionPartitionPrefix):], cutoff.Location())
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if !start.AddDate(0, 1, 0).After(cutoff) {
|
||||
if err := s.db.WithContext(ctx).Exec(fmt.Sprintf("DROP TABLE IF EXISTS %s", name)).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
// Create 写入一条采集失败记录。
|
||||
func (s *CardTrafficCollectionFailureStore) Create(ctx context.Context, record *model.CardTrafficCollectionFailure) error {
|
||||
return s.db.WithContext(ctx).Create(record).Error
|
||||
}
|
||||
|
||||
@@ -186,7 +186,11 @@ func NewCardStopResumeRecordStore(db *gorm.DB) *CardStopResumeRecordStore {
|
||||
// StopResumeRecordFilter 是停复机记录列表筛选条件;时间范围由调用方保证必填且有上限。
|
||||
type StopResumeRecordFilter struct {
|
||||
CardID *uint
|
||||
CardIDs []uint // 资产标识解析出的卡;非 nil 时按其过滤(空切片表示匹配不到任何卡)
|
||||
ICCID string
|
||||
Scene string
|
||||
Reason string
|
||||
CommandID string
|
||||
CarrierID *uint
|
||||
Action string
|
||||
Source string
|
||||
@@ -210,9 +214,24 @@ func (s *CardStopResumeRecordStore) List(ctx context.Context, filter StopResumeR
|
||||
if filter.CardID != nil {
|
||||
query = query.Where("card_id = ?", *filter.CardID)
|
||||
}
|
||||
if filter.CardIDs != nil {
|
||||
if len(filter.CardIDs) == 0 {
|
||||
return []model.CardStopResumeRecord{}, 0, nil
|
||||
}
|
||||
query = query.Where("card_id IN ?", filter.CardIDs)
|
||||
}
|
||||
if filter.ICCID != "" {
|
||||
query = query.Where("iccid = ?", filter.ICCID)
|
||||
}
|
||||
if filter.Scene != "" {
|
||||
query = query.Where("scene = ?", filter.Scene)
|
||||
}
|
||||
if filter.Reason != "" {
|
||||
query = query.Where("reason = ?", filter.Reason)
|
||||
}
|
||||
if filter.CommandID != "" {
|
||||
query = query.Where("command_id = ?", filter.CommandID)
|
||||
}
|
||||
if filter.CarrierID != nil {
|
||||
query = query.Where("carrier_id = ?", *filter.CarrierID)
|
||||
}
|
||||
|
||||
@@ -219,6 +219,23 @@ func (s *PollingPriorityItemStore) FindActive(ctx context.Context, cardID uint,
|
||||
return &item, nil
|
||||
}
|
||||
|
||||
// PollingPriorityActiveKey 是一个活动优先项的卡与任务类型。
|
||||
type PollingPriorityActiveKey struct {
|
||||
CardID uint `gorm:"column:card_id"`
|
||||
TaskType string `gorm:"column:task_type"`
|
||||
}
|
||||
|
||||
// ListActiveKeys 查询全部活动优先项的卡与任务类型,供轮询侧重建活动优先项索引。
|
||||
func (s *PollingPriorityItemStore) ListActiveKeys(ctx context.Context) ([]PollingPriorityActiveKey, error) {
|
||||
var keys []PollingPriorityActiveKey
|
||||
if err := s.db.WithContext(ctx).Model(&model.PollingPriorityItem{}).Distinct("card_id", "task_type").
|
||||
Where("status IN ?", []string{constants.PollingPriorityStatusPending, constants.PollingPriorityStatusProcessing}).
|
||||
Scan(&keys).Error; err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询活动优先轮询项索引失败")
|
||||
}
|
||||
return keys, nil
|
||||
}
|
||||
|
||||
// ListActiveByCards 批量查询指定卡在该任务类型下的活动优先项,供轮询执行前一次性探测。
|
||||
func (s *PollingPriorityItemStore) ListActiveByCards(ctx context.Context, cardIDs []uint, taskType string) ([]*model.PollingPriorityItem, error) {
|
||||
if len(cardIDs) == 0 || strings.TrimSpace(taskType) == "" {
|
||||
|
||||
@@ -16,6 +16,7 @@ type RefundListFilters struct {
|
||||
OrderID *uint `json:"order_id"`
|
||||
ShopID *uint `json:"shop_id"`
|
||||
AssetIdentifier string `json:"asset_identifier"`
|
||||
AssetPostStatus *int `json:"asset_post_status"`
|
||||
}
|
||||
|
||||
// RefundStore 退款申请数据访问层
|
||||
@@ -100,6 +101,9 @@ func (s *RefundStore) List(ctx context.Context, opts *store.QueryOptions, filter
|
||||
if filters.AssetIdentifier != "" {
|
||||
query = query.Where("tb_refund_request.asset_identifier = ?", filters.AssetIdentifier)
|
||||
}
|
||||
if filters.AssetPostStatus != nil {
|
||||
query = query.Where("tb_refund_request.asset_post_status = ?", *filters.AssetPostStatus)
|
||||
}
|
||||
}
|
||||
|
||||
if err := query.Count(&total).Error; err != nil {
|
||||
|
||||
@@ -124,7 +124,7 @@ func (e *CarrierCardExecutor) execute(ctx context.Context, msg carrierqueue.Card
|
||||
}
|
||||
return set, del
|
||||
}
|
||||
if !card.EnablePolling || (e.base.scopeChecker != nil && !e.base.scopeChecker.ShouldEnqueue(ctx, card)) {
|
||||
if !e.base.scopeAllowsCached(ctx, card) {
|
||||
e.removeCard(ctx, msg.CardID, msg.CarrierID)
|
||||
return set, del
|
||||
}
|
||||
@@ -143,7 +143,9 @@ func (e *CarrierCardExecutor) execute(ctx context.Context, msg carrierqueue.Card
|
||||
if lost.Load() || ctx.Err() != nil {
|
||||
break
|
||||
}
|
||||
if checkType == constants.CheckTypePackage && settings.SkipPackageAfterFlow && flowEvaluated {
|
||||
// 异步入库时流量评估发生在入库段,由其写入的评估标记表示套餐检查间隔内已触发过停复机评估。
|
||||
if checkType == constants.CheckTypePackage && settings.SkipPackageAfterFlow &&
|
||||
(flowEvaluated || e.base.flowEvaluatedRecently(ctx, msg.CardID)) {
|
||||
executed[checkType] = stepOK()
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"encoding/json"
|
||||
stderrors "errors"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"go.uber.org/zap"
|
||||
@@ -25,6 +26,7 @@ type StopResumeCommandService interface {
|
||||
ConfirmCommandState(ctx context.Context, card *model.IotCard, action, reason string) error
|
||||
EvaluateDeviceCommands(ctx context.Context, deviceID uint, scenes []string) error
|
||||
LegacyDeviceOpLocked(ctx context.Context, deviceID uint) bool
|
||||
RecordCommandSkipped(ctx context.Context, card *model.IotCard, action, scene, reason, skipReason string)
|
||||
}
|
||||
|
||||
// stopResumeTaskTimeout 是一条停复机指令的总执行时长上限(一次判断 + 一次网关调用)。
|
||||
@@ -148,6 +150,7 @@ func (e *StopResumeExecutor) execute(ctx context.Context, msg carrierqueue.StopR
|
||||
e.logger.Info("停复机指令执行前重新判断不再需要,结束指令", zap.Uint("card_id", msg.CardID),
|
||||
zap.String("action", cmd.Action), zap.String("decided", decision.Action), zap.Strings("scenes", cmd.Scenes))
|
||||
e.recovered(cmd, card)
|
||||
e.service.RecordCommandSkipped(ctx, card, cmd.Action, skipScene(cmd.Scenes), cmd.Reason, skipReason(card, cmd.Action, decision.Action))
|
||||
return srEnded()
|
||||
}
|
||||
if clearedPending {
|
||||
@@ -330,6 +333,33 @@ func (e *StopResumeExecutor) recovered(cmd carrierqueue.CommandState, card *mode
|
||||
}
|
||||
}
|
||||
|
||||
// 停复机指令执行前结束的原因(写入"跳过"停复机记录)。
|
||||
const (
|
||||
srSkipAlreadyTarget = "执行前已是目标状态"
|
||||
srSkipConditionNotMet = "执行前判断停复机条件不再满足"
|
||||
srSkipOppositeAction = "执行前判断需要相反动作"
|
||||
)
|
||||
|
||||
// skipReason 返回指令执行前结束的原因。
|
||||
func skipReason(card *model.IotCard, action, decided string) string {
|
||||
if card != nil && card.NetworkStatus == targetNetworkStatus(action) {
|
||||
return srSkipAlreadyTarget
|
||||
}
|
||||
if decided != "" {
|
||||
return srSkipOppositeAction
|
||||
}
|
||||
return srSkipConditionNotMet
|
||||
}
|
||||
|
||||
// skipScene 把指令的场景合并为记录的场景字段(列宽 50)。
|
||||
func skipScene(scenes []string) string {
|
||||
scene := strings.Join(scenes, ",")
|
||||
if len(scene) > 50 {
|
||||
return scene[:50]
|
||||
}
|
||||
return scene
|
||||
}
|
||||
|
||||
func targetNetworkStatus(action string) int {
|
||||
if action == constants.StopResumeActionStop {
|
||||
return constants.NetworkStatusOffline
|
||||
|
||||
154
internal/task/collection_batch_consumer.go
Normal file
154
internal/task/collection_batch_consumer.go
Normal file
@@ -0,0 +1,154 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
)
|
||||
|
||||
// collectionWriteTimeout 是一批采集记录写库的超时。
|
||||
const collectionWriteTimeout = 30 * time.Second
|
||||
|
||||
// CollectionBatchConsumer 消费采集记录消息(topic card.collection),攒满一批或等满 1 秒写一次库:
|
||||
// 写成功后整批确认,写失败整批延迟重投;重复记录由唯一索引忽略。写库只占一个连接。
|
||||
type CollectionBatchConsumer struct {
|
||||
db *gorm.DB
|
||||
batchSize int
|
||||
logger *zap.Logger
|
||||
items chan *collectionItem
|
||||
}
|
||||
|
||||
type collectionItem struct {
|
||||
msg CollectionMessage
|
||||
done chan error
|
||||
}
|
||||
|
||||
// NewCollectionBatchConsumer 创建采集记录批量消费者。
|
||||
func NewCollectionBatchConsumer(db *gorm.DB, batchSize int, logger *zap.Logger) *CollectionBatchConsumer {
|
||||
if batchSize <= 0 {
|
||||
batchSize = constants.PollingCollectionDefaultBatchSize
|
||||
}
|
||||
if logger == nil {
|
||||
logger = zap.NewNop()
|
||||
}
|
||||
return &CollectionBatchConsumer{db: db, batchSize: batchSize, logger: logger,
|
||||
items: make(chan *collectionItem, constants.PollingCollectionMaxInFlight)}
|
||||
}
|
||||
|
||||
// Start 启动攒批写库循环,ctx 结束时写完已缓冲的一批后退出。
|
||||
func (c *CollectionBatchConsumer) Start(ctx context.Context) {
|
||||
go c.run(ctx)
|
||||
}
|
||||
|
||||
// Handle 处理一条采集记录消息:交给攒批循环并等待本批写库结果。
|
||||
func (c *CollectionBatchConsumer) Handle(ctx context.Context, body []byte, attempts uint16, _ func()) time.Duration {
|
||||
var msg CollectionMessage
|
||||
if err := json.Unmarshal(body, &msg); err != nil || (msg.Success == nil && msg.Failure == nil) {
|
||||
c.logger.Warn("采集记录消息无效,丢弃", zap.ByteString("body", body))
|
||||
return 0
|
||||
}
|
||||
item := &collectionItem{msg: msg, done: make(chan error, 1)}
|
||||
select {
|
||||
case c.items <- item:
|
||||
case <-ctx.Done():
|
||||
return ingestRetryDelay(attempts)
|
||||
}
|
||||
select {
|
||||
case err := <-item.done:
|
||||
if err == nil {
|
||||
return 0
|
||||
}
|
||||
delay := ingestRetryDelay(attempts)
|
||||
if attempts >= constants.PollingIngestErrorLogFromAttempt {
|
||||
c.logger.Error("写采集记录持续失败,继续重投", zap.Uint16("attempts", attempts),
|
||||
zap.String("observation_id", collectionObservationID(msg)), zap.Duration("retry_after", delay), zap.Error(err))
|
||||
}
|
||||
return delay
|
||||
case <-ctx.Done():
|
||||
return ingestRetryDelay(attempts)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *CollectionBatchConsumer) run(ctx context.Context) {
|
||||
ticker := time.NewTicker(constants.PollingCollectionFlushInterval)
|
||||
defer ticker.Stop()
|
||||
batch := make([]*collectionItem, 0, c.batchSize)
|
||||
flush := func() {
|
||||
if len(batch) == 0 {
|
||||
return
|
||||
}
|
||||
c.flush(batch)
|
||||
batch = make([]*collectionItem, 0, c.batchSize)
|
||||
}
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
flush()
|
||||
return
|
||||
case item := <-c.items:
|
||||
batch = append(batch, item)
|
||||
if len(batch) >= c.batchSize {
|
||||
flush()
|
||||
}
|
||||
case <-ticker.C:
|
||||
flush()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// flush 一次写入一批成功记录与失败记录,并把结果通知本批每条消息。
|
||||
func (c *CollectionBatchConsumer) flush(batch []*collectionItem) {
|
||||
var successes []*model.CardTrafficCollection
|
||||
var failures []*model.CardTrafficCollectionFailure
|
||||
for _, item := range batch {
|
||||
if item.msg.Success != nil {
|
||||
successes = append(successes, item.msg.Success)
|
||||
}
|
||||
if item.msg.Failure != nil {
|
||||
failures = append(failures, item.msg.Failure)
|
||||
}
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), collectionWriteTimeout)
|
||||
defer cancel()
|
||||
err := c.write(ctx, successes, failures)
|
||||
if err != nil {
|
||||
c.logger.Warn("批量写采集记录失败,整批重投", zap.Int("success_rows", len(successes)),
|
||||
zap.Int("failure_rows", len(failures)), zap.Error(err))
|
||||
}
|
||||
for _, item := range batch {
|
||||
item.done <- err
|
||||
}
|
||||
}
|
||||
|
||||
func (c *CollectionBatchConsumer) write(ctx context.Context, successes []*model.CardTrafficCollection, failures []*model.CardTrafficCollectionFailure) error {
|
||||
return c.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
if len(successes) > 0 {
|
||||
if err := tx.Clauses(clause.OnConflict{DoNothing: true}).CreateInBatches(successes, len(successes)).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
if err := tx.Clauses(clause.OnConflict{DoNothing: true}).CreateInBatches(failures, len(failures)).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func collectionObservationID(msg CollectionMessage) string {
|
||||
if msg.Success != nil {
|
||||
return msg.Success.ObservationID
|
||||
}
|
||||
if msg.Failure != nil {
|
||||
return msg.Failure.ObservationID
|
||||
}
|
||||
return ""
|
||||
}
|
||||
177
internal/task/ingest_executor.go
Normal file
177
internal/task/ingest_executor.go
Normal file
@@ -0,0 +1,177 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
stderrors "errors"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"go.uber.org/zap"
|
||||
|
||||
cardapp "github.com/break/junhong_cmp_fiber/internal/application/cardobservation"
|
||||
carddomain "github.com/break/junhong_cmp_fiber/internal/domain/cardobservation"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/errors"
|
||||
)
|
||||
|
||||
// IngestExecutor 消费轮询观测入库消息(topic card.ingest):复用卡观测应用服务写库,按采集 ID 去重;
|
||||
// 可重试错误按退避延迟重投且不设次数上限,业务性错误记录后丢弃。
|
||||
type IngestExecutor struct {
|
||||
base *PollingBase
|
||||
observation *cardapp.Service
|
||||
timeout time.Duration
|
||||
// lastLagMS 是最近处理消息的发布到开始处理的等待时长,供积压监控读取。
|
||||
lastLagMS atomic.Int64
|
||||
}
|
||||
|
||||
// NewIngestExecutor 创建入库消费者。
|
||||
func NewIngestExecutor(base *PollingBase, observation *cardapp.Service, timeout time.Duration) *IngestExecutor {
|
||||
if timeout <= 0 {
|
||||
timeout = constants.PollingIngestDefaultTimeout
|
||||
}
|
||||
return &IngestExecutor{base: base, observation: observation, timeout: timeout}
|
||||
}
|
||||
|
||||
// LastLag 返回最近处理的入库消息从发布到开始处理的等待时长。
|
||||
func (e *IngestExecutor) LastLag() time.Duration {
|
||||
if e == nil {
|
||||
return 0
|
||||
}
|
||||
return time.Duration(e.lastLagMS.Load()) * time.Millisecond
|
||||
}
|
||||
|
||||
// Handle 处理一条入库消息,返回 0 表示确认,正数表示按该延迟重投。
|
||||
func (e *IngestExecutor) Handle(ctx context.Context, body []byte, attempts uint16, _ func()) time.Duration {
|
||||
var msg IngestMessage
|
||||
if err := json.Unmarshal(body, &msg); err != nil || !msg.valid() {
|
||||
e.base.logger.Warn("入库消息无效,丢弃", zap.ByteString("body", body))
|
||||
return 0
|
||||
}
|
||||
if !msg.PublishedAt.IsZero() {
|
||||
e.lastLagMS.Store(time.Since(msg.PublishedAt).Milliseconds())
|
||||
}
|
||||
if e.alreadyDone(ctx, msg.ObservationID) {
|
||||
return 0
|
||||
}
|
||||
taskCtx, cancel := context.WithTimeout(ctx, e.timeout)
|
||||
defer cancel()
|
||||
taskCtx = withPollingWorkerAuditContext(taskCtx, msg.TaskType, pollingPriorityTaskName(msg.TaskType), msg.ObservationID)
|
||||
changed, err := e.apply(taskCtx, msg)
|
||||
if err != nil {
|
||||
return e.onFailure(msg, attempts, err)
|
||||
}
|
||||
e.markDone(msg.ObservationID)
|
||||
if changed && msg.Kind == ingestKindTraffic {
|
||||
e.markFlowEvaluated(msg.CardID)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// apply 按观测类型调用卡观测应用服务,返回流量是否产生增量或跨月。
|
||||
func (e *IngestExecutor) apply(ctx context.Context, msg IngestMessage) (bool, error) {
|
||||
if e.observation == nil {
|
||||
return false, errors.New(errors.CodeInternalError, "卡观测能力未配置")
|
||||
}
|
||||
switch msg.Kind {
|
||||
case ingestKindTraffic:
|
||||
decision, err := e.observation.ApplyTrafficObservation(ctx, carddomain.TrafficObservation{
|
||||
CardID: msg.CardID, GatewayReadingMB: msg.Traffic.ReadingMB, ReadingResult: msg.Traffic.ReadingResult,
|
||||
ResetDay: msg.Traffic.ResetDay, Raw: msg.Raw, ICCID: msg.ICCID, CarrierID: msg.CarrierID,
|
||||
Failure: &carddomain.CollectionFailure{DurationMS: msg.Traffic.DurationMS},
|
||||
Metadata: msg.metadata(),
|
||||
})
|
||||
return decision.IncrementMB > 0 || decision.CrossMonth, err
|
||||
case ingestKindNetwork:
|
||||
_, err := e.observation.ApplyNetworkObservation(ctx, carddomain.NetworkObservation{
|
||||
CardID: msg.CardID, GatewayStatus: msg.Network.Status, GatewayExtend: msg.Network.Extend,
|
||||
GatewayIMEI: msg.Network.IMEI, Metadata: msg.metadata(),
|
||||
})
|
||||
return false, err
|
||||
case ingestKindRealname:
|
||||
_, err := e.observation.ApplyCardObservation(ctx, carddomain.RealnameObservation{
|
||||
CardID: msg.CardID, Verified: msg.Realname.Verified, UpstreamRealnameAt: msg.Realname.UpstreamRealnameAt, Metadata: msg.metadata(),
|
||||
})
|
||||
return false, err
|
||||
}
|
||||
return false, errors.New(errors.CodeInvalidParam, "未知的入库观测类型")
|
||||
}
|
||||
|
||||
// onFailure 业务性错误丢弃,其余按退避重投;第 10 次起每次重投记 ERROR。
|
||||
func (e *IngestExecutor) onFailure(msg IngestMessage, attempts uint16, err error) time.Duration {
|
||||
fields := []zap.Field{zap.String("kind", msg.Kind), zap.Uint("card_id", msg.CardID),
|
||||
zap.String("observation_id", msg.ObservationID), zap.Uint16("attempts", attempts), zap.Error(err)}
|
||||
if ingestBusinessError(err) {
|
||||
e.base.logger.Warn("入库遇到业务性错误,丢弃消息", fields...)
|
||||
return 0
|
||||
}
|
||||
delay := ingestRetryDelay(attempts)
|
||||
fields = append(fields, zap.Duration("retry_after", delay))
|
||||
if attempts >= constants.PollingIngestErrorLogFromAttempt {
|
||||
e.base.logger.Error("入库持续失败,继续重投", fields...)
|
||||
} else {
|
||||
e.base.logger.Warn("入库失败,延迟重投", fields...)
|
||||
}
|
||||
return delay
|
||||
}
|
||||
|
||||
// ingestBusinessError 判断错误是否为重试也不会成功的业务性错误(卡不存在、观测数据校验失败)。
|
||||
func ingestBusinessError(err error) bool {
|
||||
var appErr *errors.AppError
|
||||
if !stderrors.As(err, &appErr) {
|
||||
return false
|
||||
}
|
||||
switch appErr.Code {
|
||||
case errors.CodeNotFound, errors.CodeInvalidParam, errors.CodeInvalidStatus:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (e *IngestExecutor) alreadyDone(ctx context.Context, observationID string) bool {
|
||||
if e.base.redis == nil {
|
||||
return false
|
||||
}
|
||||
exists, err := e.base.redis.Exists(ctx, constants.RedisPollingIngestDoneKey(observationID)).Result()
|
||||
return err == nil && exists > 0
|
||||
}
|
||||
|
||||
func (e *IngestExecutor) markDone(observationID string) {
|
||||
if e.base.redis == nil {
|
||||
return
|
||||
}
|
||||
markCtx, cancel := pollingFallbackContext()
|
||||
defer cancel()
|
||||
if err := e.base.redis.Set(markCtx, constants.RedisPollingIngestDoneKey(observationID), "1", constants.PollingIngestDoneTTL).Err(); err != nil {
|
||||
e.base.logger.Warn("写入库已处理标记失败,重投时由业务幂等兜底", zap.String("observation_id", observationID), zap.Error(err))
|
||||
}
|
||||
}
|
||||
|
||||
// markFlowEvaluated 流量入库产生增量或跨月时写评估标记,有效期取该卡套餐检查间隔;套餐步骤据此跳过。
|
||||
func (e *IngestExecutor) markFlowEvaluated(cardID uint) {
|
||||
if e.base.redis == nil {
|
||||
return
|
||||
}
|
||||
markCtx, cancel := pollingFallbackContext()
|
||||
defer cancel()
|
||||
ttl := constants.PollingFlowEvaluatedFallbackTTL
|
||||
if card, err := e.base.getCardWithCache(markCtx, cardID); err == nil && e.base.configMgr != nil {
|
||||
info, ok := e.base.configMgr.MergedTaskIntervals(card)[constants.TaskTypePollingPackage]
|
||||
if !ok || info.Interval <= 0 {
|
||||
return
|
||||
}
|
||||
ttl = time.Duration(info.Interval) * time.Second
|
||||
}
|
||||
if err := e.base.redis.Set(markCtx, constants.RedisPollingFlowEvaluatedKey(cardID), "1", ttl).Err(); err != nil {
|
||||
e.base.logger.Debug("写流量评估标记失败", zap.Uint("card_id", cardID), zap.Error(err))
|
||||
}
|
||||
}
|
||||
|
||||
// flowEvaluatedRecently 判断入库段是否在套餐检查间隔内写过流量评估标记。
|
||||
func (b *PollingBase) flowEvaluatedRecently(ctx context.Context, cardID uint) bool {
|
||||
if b == nil || b.redis == nil {
|
||||
return false
|
||||
}
|
||||
exists, err := b.redis.Exists(ctx, constants.RedisPollingFlowEvaluatedKey(cardID)).Result()
|
||||
return err == nil && exists > 0
|
||||
}
|
||||
157
internal/task/ingest_message.go
Normal file
157
internal/task/ingest_message.go
Normal file
@@ -0,0 +1,157 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
carddomain "github.com/break/junhong_cmp_fiber/internal/domain/cardobservation"
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/errors"
|
||||
)
|
||||
|
||||
// 入库消息的观测类型。
|
||||
const (
|
||||
ingestKindTraffic = "traffic"
|
||||
ingestKindNetwork = "network"
|
||||
ingestKindRealname = "realname"
|
||||
)
|
||||
|
||||
// ingestRawResponseLimit 是入库消息携带原始响应的上限:比采集记录保存上限多 1 字节,使"超过 4KB 截断"判断不变,同时控制消息大小。
|
||||
const ingestRawResponseLimit = 4096 + 1
|
||||
|
||||
// IngestMessage 是一次轮询观测的入库消息(topic card.ingest)。采集时间取网关返回时刻,入库全程按它归属日期与判断新旧。
|
||||
type IngestMessage struct {
|
||||
Kind string `json:"kind"`
|
||||
CardID uint `json:"card_id"`
|
||||
CarrierID uint `json:"carrier_id"`
|
||||
ICCID string `json:"iccid"`
|
||||
ObservationID string `json:"observation_id"`
|
||||
ObservedAt time.Time `json:"observed_at"`
|
||||
Source string `json:"source"`
|
||||
Scene string `json:"scene"`
|
||||
CorrelationID string `json:"correlation_id"`
|
||||
// TaskType 是发起观测的轮询任务类型,入库时用于审计上下文与流量评估标记。
|
||||
TaskType string `json:"task_type"`
|
||||
Traffic *IngestTrafficPayload `json:"traffic,omitempty"`
|
||||
Network *IngestNetworkPayload `json:"network,omitempty"`
|
||||
Realname *IngestRealnamePayload `json:"realname,omitempty"`
|
||||
Raw *carddomain.GatewayRaw `json:"raw,omitempty"`
|
||||
PublishedAt time.Time `json:"published_at"`
|
||||
}
|
||||
|
||||
// IngestTrafficPayload 是流量观测内容。
|
||||
type IngestTrafficPayload struct {
|
||||
ReadingMB float64 `json:"reading_mb"`
|
||||
ReadingResult string `json:"reading_result"`
|
||||
ResetDay int `json:"reset_day"`
|
||||
DurationMS int `json:"duration_ms"`
|
||||
}
|
||||
|
||||
// IngestNetworkPayload 是网络状态观测内容。
|
||||
type IngestNetworkPayload struct {
|
||||
Status string `json:"status"`
|
||||
Extend string `json:"extend"`
|
||||
IMEI string `json:"imei"`
|
||||
}
|
||||
|
||||
// IngestRealnamePayload 是实名观测内容。
|
||||
type IngestRealnamePayload struct {
|
||||
Verified bool `json:"verified"`
|
||||
UpstreamRealnameAt *time.Time `json:"upstream_realname_at,omitempty"`
|
||||
}
|
||||
|
||||
// metadata 还原观测元数据。
|
||||
func (m IngestMessage) metadata() carddomain.ObservationMetadata {
|
||||
return carddomain.ObservationMetadata{
|
||||
ObservationID: m.ObservationID, Source: m.Source, Scene: m.Scene,
|
||||
ObservedAt: m.ObservedAt, CorrelationID: m.CorrelationID,
|
||||
}
|
||||
}
|
||||
|
||||
// valid 校验消息必需字段。
|
||||
func (m IngestMessage) valid() bool {
|
||||
if m.CardID == 0 || m.ObservationID == "" || m.ObservedAt.IsZero() {
|
||||
return false
|
||||
}
|
||||
switch m.Kind {
|
||||
case ingestKindTraffic:
|
||||
return m.Traffic != nil
|
||||
case ingestKindNetwork:
|
||||
return m.Network != nil
|
||||
case ingestKindRealname:
|
||||
return m.Realname != nil
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// CollectionMessage 是一条采集记录消息(topic card.collection),成功记录与失败记录二选一。
|
||||
type CollectionMessage struct {
|
||||
Success *model.CardTrafficCollection `json:"success,omitempty"`
|
||||
Failure *model.CardTrafficCollectionFailure `json:"failure,omitempty"`
|
||||
}
|
||||
|
||||
// MessagePublisher 发布 NSQ 消息。
|
||||
type MessagePublisher interface {
|
||||
Publish(topic string, body []byte) error
|
||||
}
|
||||
|
||||
// IngestPublisher 发布入库消息与采集记录消息。
|
||||
type IngestPublisher struct {
|
||||
producer MessagePublisher
|
||||
}
|
||||
|
||||
// NewIngestPublisher 创建入库消息发布器;producer 为 nil 时所有发布都返回错误,调用方降级同步入库。
|
||||
func NewIngestPublisher(producer MessagePublisher) *IngestPublisher {
|
||||
return &IngestPublisher{producer: producer}
|
||||
}
|
||||
|
||||
// PublishIngest 发布一条入库消息。
|
||||
func (p *IngestPublisher) PublishIngest(_ context.Context, msg IngestMessage) error {
|
||||
if p == nil || p.producer == nil {
|
||||
return errors.New(errors.CodeInternalError, "入库消息发布器未配置")
|
||||
}
|
||||
if msg.Raw != nil && len(msg.Raw.Response) > ingestRawResponseLimit {
|
||||
trimmed := *msg.Raw
|
||||
trimmed.Response = trimmed.Response[:ingestRawResponseLimit]
|
||||
msg.Raw = &trimmed
|
||||
}
|
||||
msg.PublishedAt = time.Now()
|
||||
body, err := json.Marshal(msg)
|
||||
if err != nil {
|
||||
return errors.Wrap(errors.CodeInternalError, err, "编码入库消息失败")
|
||||
}
|
||||
if err := p.producer.Publish(constants.NSQCardIngestTopic, body); err != nil {
|
||||
return errors.Wrap(errors.CodeInternalError, err, "发布入库消息失败")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// PublishCollection 发布一条采集记录消息,实现卡观测服务的 CollectionSink。
|
||||
func (p *IngestPublisher) PublishCollection(_ context.Context, success *model.CardTrafficCollection, failure *model.CardTrafficCollectionFailure) error {
|
||||
if p == nil || p.producer == nil {
|
||||
return errors.New(errors.CodeInternalError, "采集记录消息发布器未配置")
|
||||
}
|
||||
body, err := json.Marshal(CollectionMessage{Success: success, Failure: failure})
|
||||
if err != nil {
|
||||
return errors.Wrap(errors.CodeInternalError, err, "编码采集记录消息失败")
|
||||
}
|
||||
if err := p.producer.Publish(constants.NSQCardCollectionTopic, body); err != nil {
|
||||
return errors.Wrap(errors.CodeInternalError, err, "发布采集记录消息失败")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ingestRetryDelay 返回第 attempts 次投递失败后的重投延迟;超过序列长度取最后一项,不设次数上限。
|
||||
func ingestRetryDelay(attempts uint16) time.Duration {
|
||||
delays := constants.PollingIngestRetryDelays
|
||||
index := int(attempts) - 1
|
||||
if index < 0 {
|
||||
index = 0
|
||||
}
|
||||
if index >= len(delays) {
|
||||
index = len(delays) - 1
|
||||
}
|
||||
return delays[index]
|
||||
}
|
||||
@@ -73,6 +73,10 @@ type PollingBase struct {
|
||||
rateLimitedDelay func() time.Duration // 卡网关调用被运营商账户限流后的固定重入队延迟
|
||||
errorClassifier ErrorClassifier // 上游错误分类(按运营商账户调度的失败退避与告警使用)
|
||||
schedulerMode SchedulerModeReader // 当前调度模式;carrier 时旧 Asynq 轮询任务直接结束
|
||||
ingest *IngestPublisher // 入库消息发布器;为 nil 时轮询步骤同步入库
|
||||
ingestAsync func(ctx context.Context) bool
|
||||
scopeCache scopeCache
|
||||
resetDays resetDayCache
|
||||
}
|
||||
|
||||
// SetRateLimitedDelay 设置被运营商账户限流后的重入队延迟来源(受控系统配置,即时生效)。
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user