diff --git a/cmd/consumer/.gitkeep b/cmd/consumer/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/cmd/consumer/main.go b/cmd/consumer/main.go new file mode 100644 index 00000000..c2a390eb --- /dev/null +++ b/cmd/consumer/main.go @@ -0,0 +1,344 @@ +// cmd/consumer Day 48:submit 消费者——sms-submit 事件驱动立即任务下发。 +// 组件:消费组(重试+死信)|ReclaimScanner 补偿认领(事件丢失/审核通过兜底)| +// ChannelDispatcher(router 选路→聚合/直发)|ChannelPacer(令牌桶+在途窗口+降速)| +// DetailWriter(终态批量落库)|Backpressure(三级水位,L3 暂停消费)。 +// 与 gateway 同库同 Redis 同 Kafka;HTTP 路由不注册(纯 worker 进程)。 +package main + +import ( + "context" + "encoding/json" + "net/http" + "os" + "os/signal" + "syscall" + "time" + + "go-sms/internal/app" + "go-sms/internal/config" + "go-sms/internal/model/entity" + "go-sms/internal/pkg/metrics" + "go-sms/internal/pkg/queue" + "go-sms/internal/service/audit" + "go-sms/internal/service/balance" + "go-sms/internal/service/channel" + "go-sms/internal/service/interceptor" + "go-sms/internal/service/report" + "go-sms/internal/service/router" + "go-sms/internal/service/send" + "go-sms/internal/service/uplink" + "go-sms/internal/util" + + "github.com/IBM/sarama" + "go.uber.org/zap" +) + +func main() { + a, err := app.New(app.Options{ServiceName: "go-sms-consumer"}) + if err != nil { + panic(err) + } + db, rc := a.DB(), a.Redis() + cfg := a.Config() + if db == nil { + a.Lg().Error("consumer_db_required") + os.Exit(1) + } + if len(cfg.Kafka.Brokers) == 0 { + a.Lg().Error("consumer_kafka_required") + os.Exit(1) + } + submitTopic := cfg.Kafka.Topics["submit"] + if submitTopic == "" { + submitTopic = queue.TopicSubmit + } + ccfg := cfg.Kafka.Consumer + groupID := ccfg.GroupID + if groupID == "" { + groupID = "go-sms-consumer" + } + // Day58:起步 offset 可配(默认 oldest=Day48 存量消费语义;dev 止血用 + // env GOSMS_KAFKA_CONSUMER_OFFSET_MODE=latest 跳过积压——仅对无已提交 + // offset 的消费组生效)+消费 pacing(防 oldest 冷启动存量回放打爆 dev MySQL)。 + offsetMode := ccfg.OffsetMode + if offsetMode == "" { + offsetMode = queue.OffsetModeOldest + } + paceEvery, paceSleep := ccfg.PaceEvery, ccfg.PaceSleep + + // 通道链路(常驻 CMPP;下发出口)。 + chSvc := channel.NewService(db) + // Day 49:上行域——本进程长连接同样接收 Deliver MO,注入上行出口 + // (码号分配→message_uplink→投 sms-up;消费组见下方 uplinkConsumer)。 + upAsg := uplink.NewAssigner(db) + var upProd uplink.Producer + if p := a.Producer(); p != nil { + upProd = p + } + chSvc.SetUplinkSink(uplink.NewService(db, upAsg, upProd)) + upCtx, stopUpAsg := context.WithCancel(context.Background()) + go upAsg.Start(upCtx, uplink.DefaultReloadEvery) + a.OnShutdown(stopUpAsg) + // Day 56:回执域——本进程长连接接收状态报告,注入回执出口 + // (投 sms-report;消费组见下方 reportConsumer:归一化+段级配对)。 + if p := a.Producer(); p != nil { + chSvc.SetReportSink(report.NewSink(p)) + } + chSvc.BootstrapLinks(context.Background()) + a.OnShutdown(chSvc.ShutdownLinks) + a.OnShutdown(chSvc.Close) + + // pacer 限速(通道 speed 装载)+聚合器+分发器+批量 writer。 + pacer := send.NewChannelPacer(ccfg.Enable) + var sumSpeed int64 = 0 + var chans []entity.ChannelChannel + if err := db.Where("status = ?", 1).Find(&chans).Error; err == nil { + for _, ch := range chans { + if ch.Speed <= 0 { + sumSpeed += send.DefaultChannelSpeed + } else { + sumSpeed += int64(ch.Speed) + } + pacer.SetSpeed(ch.ID, float64(ch.Speed)) + } + } + writer := send.NewDetailWriter(db, send.DefaultWriterBatch, send.DefaultWriterWorker) + a.OnShutdown(writer.Close) + aggregator := send.NewSubmitAggregator(chSvc, send.DefaultAggrWindow, send.DefaultAggrMaxBatch).WithDB(db) // Day56 seg 配对登记(装配遗漏修复) + aggCtx, stopAgg := context.WithCancel(context.Background()) + go aggregator.Run(aggCtx) + a.OnShutdown(func() { stopAgg(); aggregator.FlushAll() }) + dp := send.NewChannelDispatcher(db, router.NewRouter(db), chSvc, aggregator). + WithPacer(pacer).WithDetailWriter(writer) + + // 事件消费者 + 补偿扫描。 + sc := send.NewSubmitConsumer(db, dp, a.Lg()) + // P0-1(Day 63)Deferred 补全依赖——拦截链+审核分流(与 gateway 同构); + // 资金 Store 待 balStore 装配后注入(下方 WithConsumerBalance)。 + var ichain *interceptor.Chain + if rc != nil { + ichain = interceptor.NewDefaultChain(db, rc, + interceptor.NewDBRecorder(db), + interceptor.Options{FreqStore: interceptor.NewRedisFreqStore(rc)}) + } else { + ichain = interceptor.NewDefaultChain(db, nil, + interceptor.NewDBRecorder(db), interceptor.Options{}) + } + sc = sc.WithConsumerChain(ichain).WithConsumerRouter(audit.NewReviewService(db)) + // Day62c:拦截终态 CMPP 下发桥——受理期拦截明细无上游回执,不桥则客户收不到 + // 状态(真机报障);复用 Day61 同一 ProducerPushSink 投 cmpp-deliver。 + if p := a.Producer(); p != nil { + sc = sc.WithBlockedDeliverSink(blockedDeliverAdapter{sink: &report.ProducerPushSink{P: p}}) + } + reclaimEvery := ccfg.ReclaimEvery + if reclaimEvery <= 0 { + reclaimEvery = 5 * time.Second + } + rs := send.NewReclaimScanner(db, dp, a.Lg()) + if ccfg.ReclaimBatch > 0 { + rs = rs.WithBatch(ccfg.ReclaimBatch) + } + rsCtx, stopRS := context.WithCancel(context.Background()) + go rs.Run(rsCtx, reclaimEvery) + a.OnShutdown(stopRS) + + // 消费组(失败重试+死信转投)。 + cg, err := queue.NewConsumerGroup(queue.ConsumerGroupConfig{ + Consumer: queue.ConsumerConfig{ + Brokers: cfg.Kafka.Brokers, + GroupID: groupID, + Topics: []string{submitTopic}, + Logger: a.Lg(), + OffsetMode: offsetMode, // Day58 起步 offset 可配(默认 oldest=Day48 历史积压认领幂等,不双发) + PaceEvery: paceEvery, + PaceSleep: paceSleep, + // Day65:每分区 worker 池——Deferred 补全为 DB 慢事务链(单条 0.3~0.7s), + // 串行 16 分区并发封顶 ~60/s;workers=4 → 64 并发。offset 按前缀有序 Mark, + // at-least-once 不变。回执/上行组保持串行(乱序风险零容忍优先)。 + WorkersPerPartition: ccfg.Workers, + Handler: func(ctx context.Context, msg *sarama.ConsumerMessage) error { + return sc.HandlePayload(ctx, msg.Value) + }, + }, + Producer: queue.ProducerConfig{Brokers: cfg.Kafka.Brokers, Logger: a.Lg()}, + }) + if err != nil { + a.Lg().Error("consumer_group_init_failed", zap.Error(err)) + os.Exit(1) + } + a.OnShutdown(func() { _ = cg.Close() }) + + // 背压三级水位(L1 告警/L2 入口收紧键/L3 暂停消费;采样 lag=submit topic)。 + bpEvery := ccfg.BPSampleEvery + if bpEvery <= 0 { + bpEvery = 10 * time.Second + } + lagR, lagErr := queue.NewLagReader(cfg.Kafka.Brokers, groupID, a.Lg()) + bp := send.NewBackpressure(send.NewRedisBPStore(rc), a.Lg(), + cg.Pause, cg.Resume, func() int64 { return sumSpeed }) + if lagErr != nil { + a.Lg().Warn("lag_reader_disabled_backpressure_degraded", zap.Error(lagErr)) + } else { + a.OnShutdown(func() { _ = lagR.Close() }) + bpCtx, stopBP := context.WithCancel(context.Background()) + go bp.Run(bpCtx, bpEvery, func(ctx context.Context) (int64, error) { + return lagR.Total(ctx, []string{submitTopic}) + }) + a.OnShutdown(stopBP) + } + + a.Lg().Info("submit_consumer_ready", + zap.String("topic", submitTopic), zap.String("group", groupID), + zap.Int("channels", len(chans)), zap.Int64("sum_speed", sumSpeed), + zap.Bool("pacer", pacer.Open()), + zap.String("reclaim", reclaimEvery.String()), zap.Bool("lag_reader", lagErr == nil)) + + // Day 49:上行消费组(sms-up;15 天窗口匹配下行明细回填 match_task_id; + // 客户推送/自动拉黑属阶段 5 Day54)。独立 group 前缀防 offset 互扰。 + upTopic := cfg.Kafka.Topics["up"] + if upTopic == "" { + upTopic = queue.TopicUp + } + uc := uplink.NewConsumer(db) + ucg, err := queue.NewConsumerGroup(queue.ConsumerGroupConfig{ + Consumer: queue.ConsumerConfig{ + Brokers: cfg.Kafka.Brokers, + GroupID: groupID + "-uplink", + Topics: []string{upTopic}, + Logger: a.Lg(), + OffsetMode: offsetMode, // Day58 起步 offset 可配(默认 oldest=15 天窗口回放语义) + PaceEvery: paceEvery, + PaceSleep: paceSleep, + Handler: func(ctx context.Context, msg *sarama.ConsumerMessage) error { + return uc.HandlePayload(ctx, msg.Value) + }, + }, + Producer: queue.ProducerConfig{Brokers: cfg.Kafka.Brokers, Logger: a.Lg()}, + }) + if err != nil { + a.Lg().Error("uplink_consumer_group_init_failed", zap.Error(err)) + os.Exit(1) + } + a.OnShutdown(func() { _ = ucg.Close() }) + a.Lg().Info("uplink_consumer_ready", + zap.String("topic", upTopic), zap.String("group", groupID+"-uplink")) + + // Day 56:回执消费组(sms-report;归一化三态+段级配对→detail 终态+ + // message_report 落库)。独立 group 前缀防 offset 互扰。 + repTopic := cfg.Kafka.Topics["report"] + if repTopic == "" { + repTopic = queue.TopicReport + } + // Day 57:计费确认——balance Store(与 gateway 同构;退款走同一 Redis/ + // MySQL 双级)。Reconciler 仅 gateway 独占(幂等覆写,双进程双跑无害但 + // 浪费);ModeWatcher 两进程各自热切保持模式一致。雪花 workerID=2 + // (gateway=1,跨进程不冲突)。 + balStore := balance.Store(balance.NewMySQLStore(db)) + if balance.NormalizeMode(cfg.Balance.Mode) == balance.ModeRedis && rc != nil { + sf2, sfErr := util.NewSnowflake(2) + if sfErr != nil { + a.Lg().Warn("consumer_balance_snowflake_fallback_mysql", zap.Error(sfErr)) + } else { + rs := balance.NewRedisStore(rc, db, sf2, a.Lg(), balance.RedisOptions{}) + fb := balance.NewFallbackStore(rs, balance.NewMySQLStore(db), a.Lg()) + balStore = fb + balCtx, stopBal := context.WithCancel(context.Background()) + go balance.RunModeWatcher(balCtx, fb, func() string { return a.Config().Balance.Mode }) + a.OnShutdown(func() { stopBal(); rs.Close() }) + } + } + bill := report.NewBilling(db, balStore) + // P0-1(Day 63):Deferred 拦截/审核拒退费与计费确认共用同一 Store。 + sc = sc.WithConsumerBalance(balStore) + // 48h 无回执补偿扫描→UNKNOWN(4) 结案+冻结释放(启动即一轮,10m/轮)。 + comp := report.NewCompensator(db, bill, report.CompensatorOptions{}) + compCtx, stopComp := context.WithCancel(context.Background()) + go comp.Run(compCtx, 10*time.Minute) + a.OnShutdown(stopComp) + + repC := report.NewConsumer(db).WithBilling(bill) + // Day 61(P0.5):CMPP 回执协议侧下发桥——终态锁定后投 cmpp-deliver + // (gateway 进程消费→PushDeliver);producer 缺省时不注入(HTTP 来源无此诉求)。 + if p := a.Producer(); p != nil { + repC = repC.WithPushSink(&report.ProducerPushSink{P: p}) + // Day 69 三轮:unpaired 短重投出口——秒回模拟器回执跑赢发送侧 seg + // 落库的固有竞态,回投 sms-report 尾部经队列延迟后重配(≤3 次)。 + repC = repC.WithRequeue(func(ev *report.Event) error { + payload, err := json.Marshal(ev) + if err != nil { + return err + } + return a.Producer().Send(repTopic, []byte(ev.MsgID), payload) + }) + } + rcg, err := queue.NewConsumerGroup(queue.ConsumerGroupConfig{ + Consumer: queue.ConsumerConfig{ + Brokers: cfg.Kafka.Brokers, + GroupID: groupID + "-report", + Topics: []string{repTopic}, + Logger: a.Lg(), + Oldest: true, // 历史积压回执补处理(seg 幂等,detail 终态锁定防翻转);恒 oldest 不读 offset_mode(回执不丢) + PaceEvery: paceEvery, + PaceSleep: paceSleep, + Handler: func(ctx context.Context, msg *sarama.ConsumerMessage) error { + return repC.HandlePayload(ctx, msg.Value) + }, + }, + Producer: queue.ProducerConfig{Brokers: cfg.Kafka.Brokers, Logger: a.Lg()}, + }) + if err != nil { + a.Lg().Error("report_consumer_group_init_failed", zap.Error(err)) + os.Exit(1) + } + a.OnShutdown(func() { _ = rcg.Close() }) + a.Lg().Info("report_consumer_ready", + zap.String("topic", repTopic), zap.String("group", groupID+"-report")) + + // 优雅退出(SIGINT/SIGTERM→app.Shutdown 钩子链:writer 冲刷/链路拆除/消费组退出)。 + go func() { + if err := cg.Run(context.Background()); err != nil { + a.Lg().Error("consumer_group_exit", zap.Error(err)) + } + }() + go func() { + if err := ucg.Run(context.Background()); err != nil { + a.Lg().Error("uplink_consumer_group_exit", zap.Error(err)) + } + }() + go func() { + if err := rcg.Run(context.Background()); err != nil { + a.Lg().Error("report_consumer_group_exit", zap.Error(err)) + } + }() + // Day 69 百万级压测观测:consumer 侧独立 /metrics(:8082,Prometheus + // 抓取,deploy/monitoring/prometheus.yml 同步)。失败仅日志不阻断 worker。 + go func() { + mux := http.NewServeMux() + mux.Handle("/metrics", metrics.Handler()) + if err := http.ListenAndServe(":8082", mux); err != nil { + a.Lg().Error("metrics_http_failed", zap.Error(err)) + } + }() + quit := make(chan os.Signal, 1) + signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM) + <-quit + a.Lg().Info("submit_consumer_stopping") + a.Shutdown(10 * time.Second) +} + +// 编译期确认 config 引用(避免未来重命名漂移)。 +var _ = config.Config{} + +// blockedDeliverAdapter Day62c:send 域拦截终态出口 → report.DeliverEvent 桥 +// (stat 映射 ISC:004→SIGNREJ;与 Day61 回执事件同 topic 同载荷形状, +// gateway 侧 PushDeliver 链路零改动)。 +type blockedDeliverAdapter struct{ sink *report.ProducerPushSink } + +func (b blockedDeliverAdapter) PushBlocked(ctx context.Context, + accountID, detailID int64, mobile, errCode, submitAt string) { + ev := &report.DeliverEvent{ + AccountID: accountID, DetailID: detailID, Mobile: mobile, + Stat: report.StatForBlocked(errCode), SubmitAt: submitAt, DoneAt: submitAt, + } + _ = b.sink.PushDeliver(ctx, ev) // 失败已 Warn:终态不回滚,下发尽力而为(Day61 同口径) +} diff --git a/cmd/gateway/main.go b/cmd/gateway/main.go new file mode 100644 index 00000000..52c76155 --- /dev/null +++ b/cmd/gateway/main.go @@ -0,0 +1,402 @@ +// go-sms-gateway:go-sms 接入网关服务入口(app 启动器装配 + v1 业务路由挂载)。 +package main + +import ( + "context" + "time" + + "github.com/IBM/sarama" + "github.com/gin-gonic/gin" + "go.uber.org/zap" + + v1 "go-sms/internal/api/http/v1" + "go-sms/internal/app" + "go-sms/internal/middleware" + "go-sms/internal/pkg/casbin" + "go-sms/internal/pkg/cronx" + jwtpkg "go-sms/internal/pkg/jwt" + "go-sms/internal/pkg/metrics" + "go-sms/internal/pkg/queue" + "go-sms/internal/pkg/storage" + cmppproto "go-sms/internal/protocol/cmpp" + smppproto "go-sms/internal/protocol/smpp" + "go-sms/internal/service/access" + "go-sms/internal/service/account" + "go-sms/internal/service/audit" + "go-sms/internal/service/auth" + "go-sms/internal/service/balance" + "go-sms/internal/service/channel" + "go-sms/internal/service/interceptor" + "go-sms/internal/service/openapi" + "go-sms/internal/service/report" + "go-sms/internal/service/router" + "go-sms/internal/service/send" + "go-sms/internal/service/template" + "go-sms/internal/service/uplink" + "go-sms/internal/util" +) + +// 构建时通过 -ldflags -X 注入(见 Dockerfile / Makefile)。 +var ( + version = "dev" + commit = "none" +) + +func main() { + app.Main(app.Options{ + ServiceName: "go-sms-gateway", + Version: version, + Commit: commit, + RegisterRoutes: func(r *gin.Engine, a *app.App) { + db := a.DB() + if db == nil { + return + } + cfg := a.Config() + svc := account.NewService(db, 0) + + // Casbin 权限引擎(Day 25:开户/改角色自动同步 casbin_rule; + // 创建失败降级为 nil → 不挂细粒度校验,鉴权仍由 JWT 兜底) + var perm middleware.PermissionChecker + if enforcer, err := casbin.New(db); err != nil { + a.Lg().Warn("casbin_init_failed_degraded", zap.Error(err)) + } else { + svc.WithEnforcer(enforcer) + perm = middleware.CasbinChecker(enforcer) + } + + // 认证服务(Day 24):黑名单/失败计数优先 Redis,降级内存实现 + var store auth.TokenStore + rc := a.Redis() + if rc != nil { + store = auth.NewRedisTokenStore(rc) + } + authSvc := auth.NewService(db, jwtpkg.NewManager(cfg.JWT.Secret, cfg.JWT.TTL), store) + + // Day 42:发送拦截器链——黑名单三级(Redis 缓存)/频次滑窗(Redis ZSet)/ + // 签名/退订/地区;命中经 DBRecorder 落 send_block_log;/send/precheck 与 Day46 提交共用。 + var ichain *interceptor.Chain + if rc != nil { + ichain = interceptor.NewDefaultChain(db, rc, + interceptor.NewDBRecorder(db), + interceptor.Options{FreqStore: interceptor.NewRedisFreqStore(rc)}) + } else { + ichain = interceptor.NewDefaultChain(db, nil, + interceptor.NewDBRecorder(db), interceptor.Options{}) + } + + rg := r.Group("/api/v1") + warnSvc := account.NewWarningService(db, nil) + auditSvc := audit.NewService(db) + reviewSvc := audit.NewReviewService(db) // Day 43:消息审核(审核中心+D19 定时任务) + // Day 43 修复循环:最小提交链(雪花明细 ID;WorkerID 单机固定 1,多副本 Day47 ETCD 抢注)。 + sf, sfErr := util.NewSnowflake(1) + if sfErr != nil { + panic("snowflake init: " + sfErr.Error()) + } + // Day 48:全流程状态机——拦截链(Day42)+sms-submit 统一出口(ProducerSink, + // 替代 openapi 自投,预扣/拦截退费/审核拒绝退费在 SubmitService 内闭环)。 + // Kafka 降级(producer=nil)不注入 sink:发送由 ReclaimScanner DB 认领兜底。 + pipelineOpts := []send.SubmitOption{send.WithInterceptorChain(ichain)} + if p := a.Producer(); p != nil { + pipelineOpts = append(pipelineOpts, + send.WithEventSink(send.ProducerSink{P: p, Source: "submit"})) + a.Lg().Info("submit_pipeline_ready", + zap.Bool("interceptor", ichain != nil), zap.String("sink", "sms-submit")) + // Day55:go_sms_kafka_lag 指标导出(Day53 告警挂账清偿)——只读 LagReader + // 与 consumer 同组采样 submit topic lag,15s 周期(对齐 Prometheus 抓取); + // 采样失败保留上次值+首次 Warn(链路抖动不抹零,防「lag 消失」假象)。 + lagGroup := cfg.Kafka.Consumer.GroupID + if lagGroup == "" { + lagGroup = "go-sms-consumer" + } + lagTopic := cfg.Kafka.Topics["submit"] + if lagTopic == "" { + lagTopic = queue.TopicSubmit + } + if lagR, lagErr := queue.NewLagReader(cfg.Kafka.Brokers, lagGroup, a.Lg()); lagErr != nil { + a.Lg().Warn("kafka_lag_reader_disabled", zap.Error(lagErr)) + } else { + lagCtx, stopLag := context.WithCancel(context.Background()) + go func() { + tk := time.NewTicker(15 * time.Second) + defer tk.Stop() + var warned bool + for { + select { + case <-lagCtx.Done(): + return + case <-tk.C: + v, err := lagR.Total(lagCtx, []string{lagTopic}) + if err != nil { + if !warned { + a.Lg().Warn("kafka_lag_sample_failed", zap.Error(err)) + warned = true + } + continue + } + warned = false + metrics.KafkaLag.WithLabelValues(lagTopic).Set(float64(v)) + } + } + }() + a.OnShutdown(func() { stopLag(); _ = lagR.Close() }) + } + } else { + a.Lg().Warn("submit_pipeline_kafka_disabled", + zap.String("fallback", "reclaim_scanner_db_claim")) + } + // Day54 R1:资金预扣 Store(评审 docs/review/r1-balance.md)—— + // mode=redis:Lua 原子扣+异步流水批写+对账覆写+故障单次回退 MySQL; + // env GOSMS_BALANCE_MODE/热配置 15s 轮询切换(默认 mysql 行锁原路径)。 + balStore := balance.Store(balance.NewMySQLStore(db)) + if balance.NormalizeMode(cfg.Balance.Mode) == balance.ModeRedis { + if rc != nil { + rs := balance.NewRedisStore(rc, db, sf, a.Lg(), balance.RedisOptions{}) + fb := balance.NewFallbackStore(rs, balance.NewMySQLStore(db), a.Lg()) + balStore = fb + rec := balance.NewReconciler(rc, db, rs, a.Lg(), + balance.ReconcilerOptions{Interval: cfg.Balance.ReconcileInterval}) + balCtx, stopBal := context.WithCancel(context.Background()) + go rec.Run(balCtx) + go balance.RunModeWatcher(balCtx, fb, + func() string { return a.Config().Balance.Mode }) + a.OnShutdown(func() { stopBal(); rs.Close() }) + a.Lg().Info("balance_redis_mode_ready", + zap.String("reconcile_interval", cfg.Balance.ReconcileInterval.String()), + zap.String("fallback", "mysql_row_lock"), + zap.String("diff_metric", "go_sms_balance_reconcile_diff")) + } else { + metrics.BalanceMode.Set(0) + a.Lg().Warn("balance_redis_mode_no_redis_fallback_mysql", + zap.String("note", "Redis 未装配,预扣走 MySQL 行锁原路径")) + } + } + pipelineOpts = append(pipelineOpts, send.WithBalanceStore(balStore)) + submitSvc := send.NewSubmitService(db, sf, reviewSvc, pipelineOpts...) + // Day 44:MinIO 对象存储(号码文件);初始化失败降级 nil → /files/numbers/import 不注册。 + var fileImportSvc *send.FileImportService + if mo, merr := storage.NewMinIO(context.Background(), + cfg.MinIO.Endpoint, cfg.MinIO.AccessKey, cfg.MinIO.SecretKey, cfg.MinIO.Bucket, cfg.MinIO.UseSSL); merr != nil { + a.Lg().Warn("minio_init_failed_file_import_disabled", zap.Error(merr)) + } else { + fileImportSvc = send.NewFileImportService(mo, sf) + a.Lg().Info("minio_storage_ready", zap.String("bucket", cfg.MinIO.Bucket)) + } + rt := router.NewRouter(db) + chSvc := channel.NewService(db) // Day 40:提取变量——链路引导/告警 cron/优雅停机接线 + // Day 49:上行域——码号分配缓存(30s 刷新)+Deliver MO→分配→落库 + // message_uplink→投 sms-up(消费者进程 15 天窗口匹配)。producer 降级 + // nil 时仅落库;nil 指针不注入接口(空接口调用 panic)。 + upAsg := uplink.NewAssigner(db) + var upProd uplink.Producer + if p := a.Producer(); p != nil { + upProd = p + } + chSvc.SetUplinkSink(uplink.NewService(db, upAsg, upProd)) + upCtx, stopUpAsg := context.WithCancel(context.Background()) + go upAsg.Start(upCtx, uplink.DefaultReloadEvery) + a.OnShutdown(stopUpAsg) + // Day 56:回执域——状态报告经 sms-report 投递(消费者进程归一化+ + // 段级配对回写 detail 终态);producer 降级 nil 时不注入(仅日志/环形)。 + if p := a.Producer(); p != nil { + chSvc.SetReportSink(report.NewSink(p)) + } + // 阶段5收尾(D28 挂账清偿):回执重推+手动配对服务(终态链复用 + // consumer 同款 finalizeDetail 单一实现;计费走 balStore 同一 Store)。 + pairSvc := report.NewPairService(db, report.NewBilling(db, balStore), sf) + if p := a.Producer(); p != nil { + pairSvc = pairSvc.WithPushSink(&report.ProducerPushSink{P: p}) + } + v1.Register(rg, v1.Deps{ + Account: svc, + Warning: warnSvc, + Audit: auditSvc, + Review: reviewSvc, // Day 43 + Submit: submitSvc, // Day 43 修复循环:/send/submit + FileImport: fileImportSvc, // Day 44:/files/numbers/import(MinIO) + Channel: chSvc, + Upstream: channel.NewUpstreamService(db), // Day 41(清债③) + Template: template.NewService(db), // Day 41:模板/预估 + Interceptor: ichain, // Day 42:发送拦截器链 + Router: rt, // Day 38:导流规则管理端点 + AuthSvc: authSvc, + // JWT 鉴权 + 登出黑名单 + 账号状态校验(Day 24) + Auth: middleware.AuthJWTWithRevocation(cfg.JWT.Secret, authSvc.Revoked, svc.CheckEnabled), + Perm: perm, + // Day 53(runbook P0):/fe-errors 落库裸 DB + /alerts/sink AM webhook 留痕 + DB: db, + // Day 56:错误码维护(/system/error-codes 增改停用) + ErrorCode: report.NewErrorCodeService(db), + Logger: a.Lg(), + // Day 62:CMPP 接入系统默认(api-config 的 cmpp_access 交付块数据源) + CMPPCfg: &cfg.Server.CMPP, + // 阶段5收尾(D28):/record/repush 域四端点 + Pair: pairSvc, + }) + // Day68:运营总览汇总刷新(回补 30 天+60s ticker 增量 UPSERT stats_daily; + // 幂等多实例无害,详见 stats_handler.go StartStatsRefresher)。 + v1.StartStatsRefresher(db, a.Lg()) + + // Day 46:外部 HTTP API 提交(SMS_HTTP_1.6;/sms/api 独立协议域,MD5 验签+ + // 双桶限流:全局 IP 桶(静态配置)+账号桶(动态 speed_limit); + // Kafka producer 未装配时降级仅落库,发送由定时调度器 DB 认领兜底)。 + openapiSvc := openapi.NewService(db, submitSvc, a.Producer()) + v1.RegisterOpenAPI(r, v1.OpenAPIDeps{ + Auth: openapi.NewAuthenticator(db), + Svc: openapiSvc, + Redis: rc, // *cache.Client(嵌入 redis.UniversalClient);nil=限流降级放行 + Global: middleware.RateLimitConfig{ + Capacity: cfg.RateLimit.Capacity, + Rate: cfg.RateLimit.RatePerSec, + }, + }) + a.Lg().Info("openapi_http_submit_ready", + zap.String("group", "/sms/api"), zap.Bool("kafka", a.Producer() != nil)) + + // P1 修复(09-27 通道超限报障):gateway 不再引导常驻链路。 + // 双进程架构下发域归 consumer,gateway 的通道池纯占通道账号连接额度 + // (通道 331004 上限 20:gateway 50+consumer 51=101 条 → 22:01 通道拒新/22:06 批量踢)。 + // 通道池由 consumer 独占 conn_count(=20)。 + a.OnShutdown(chSvc.Close) // Day 40:通道日志冲刷落库 + + // Day 45:定时调度器(ZSet 唤醒索引+DB 原子认领+router 选路链路分发; + // Redis 缺失降级纯 DB 扫描;随优雅停机拆除)。 + // Day 47:分发链路注入合包聚合器(5s/1000 双阈值;同通道同内容合批, + // CMPP 单包≤100 号切包,提交调用次数降至 ~1/100)。 + var timerQ send.TaskQueue + if rc != nil { + timerQ = send.NewRedisZSetQueue(rc, send.QueueKey()) + } + aggregator := send.NewSubmitAggregator(chSvc, + send.DefaultAggrWindow, send.DefaultAggrMaxBatch).WithDB(db) // Day56 seg 配对登记(装配遗漏修复) + aggCtx, stopAgg := context.WithCancel(context.Background()) + go aggregator.Run(aggCtx) + a.OnShutdown(func() { stopAgg(); aggregator.FlushAll() }) + timerCtx, stopTimer := context.WithCancel(context.Background()) + go send.NewTimerScheduler(db, timerQ, + send.NewChannelDispatcher(db, rt, chSvc, aggregator)).Run(timerCtx) + a.OnShutdown(stopTimer) + a.Lg().Info("timer_scheduler_started", + zap.String("interval", "5s"), zap.Bool("redis_queue", timerQ != nil), + zap.String("aggregator", "5s/1000")) + + // Day 47:CMPP/SMPP 客户接入(TCP 服务端;鉴权=账号体系+ApiSecret 共享密钥, + // 提交复用 openapi 受理链;addr 空=不启用)。 + // Day 62:注入 CMPP 系统默认配额(账号级 0 回退;连接数/单链速度强制)。 + accSvc := access.New(db, openapiSvc, access.SystemLimits{ + MaxConns: cfg.Server.CMPP.MaxConnsPerAccount, + SubmitRate: cfg.Server.CMPP.SubmitRatePerConn, + LongSmsWindow: cfg.Server.CMPP.LongSmsWindow, // Day 71:≤0 默认 72h + }) + // Day 71:长短信挂起制——重启恢复+72h 到期扫描(不齐不发,LP 失败 + // 终态+UNDELIV 回执经 Kafka cmpp-deliver 回环推下家在线连接)。 + { + var lsPush report.PushSink + if p := a.Producer(); p != nil { + lsPush = &report.ProducerPushSink{P: p} + } + lsCtx, stopLS := context.WithCancel(context.Background()) + accSvc.StartLongSmsMaintenance(lsCtx, lsPush, time.Minute) + a.OnShutdown(stopLS) + } + var cmppSrv *cmppproto.Server + if cfg.Server.CMPP.Addr != "" { + csrv := cmppproto.NewServer(cmppproto.ServerConfig{ + Addr: cfg.Server.CMPP.Addr, + IdleTimeout: cfg.Server.CMPP.IdleTimeout, + }, accSvc) + cmppSrv = csrv + go func() { + if err := csrv.ListenAndServe(context.Background()); err != nil { + a.Lg().Error("cmpp_server_failed", zap.Error(err)) + } + }() + a.OnShutdown(csrv.Close) + a.Lg().Info("cmpp_access_server_ready", zap.String("addr", cfg.Server.CMPP.Addr)) + } + // Day 61(P0.5):cmpp-deliver 消费桥——report 终态事件(consumer 进程投递) + // →本进程 CMPP 会话注册表 PushDeliver。独立消费组;producer 缺省时跳过。 + if cfg.Server.CMPP.Addr != "" { + delTopic := cfg.Kafka.Topics[queue.KeyDeliver] + if delTopic == "" { + delTopic = queue.TopicDeliver + } + pusher := access.NewDeliverPusher(db, cmppSrv) + dcg, derr := queue.NewConsumerGroup(queue.ConsumerGroupConfig{ + Consumer: queue.ConsumerConfig{ + Brokers: cfg.Kafka.Brokers, + GroupID: "gateway-cmpp-deliver", + Topics: []string{delTopic}, + Logger: a.Lg(), + Oldest: false, // 只推在线会话;历史事件无会话可推,latest 起点即可 + Handler: func(ctx context.Context, msg *sarama.ConsumerMessage) error { + return pusher.HandlePayload(ctx, msg.Value) + }, + }, + Producer: queue.ProducerConfig{Brokers: cfg.Kafka.Brokers, Logger: a.Lg()}, + }) + if derr != nil { + a.Lg().Error("cmpp_deliver_consumer_init_failed", zap.Error(derr)) + } else { + go func() { + if err := dcg.Run(context.Background()); err != nil { + a.Lg().Error("cmpp_deliver_consumer_exit", zap.Error(err)) + } + }() + a.OnShutdown(func() { _ = dcg.Close() }) + a.Lg().Info("cmpp_deliver_consumer_ready", + zap.String("topic", delTopic), zap.String("group", "gateway-cmpp-deliver")) + } + } + if cfg.Server.SMPP.Addr != "" { + ssrv := smppproto.NewServer(smppproto.ServerConfig{ + Addr: cfg.Server.SMPP.Addr, + IdleTimeout: cfg.Server.SMPP.IdleTimeout, + }, accSvc) + go func() { + if err := ssrv.ListenAndServe(context.Background()); err != nil { + a.Lg().Error("smpp_server_failed", zap.Error(err)) + } + }() + a.OnShutdown(ssrv.Close) + a.Lg().Info("smpp_access_server_ready", zap.String("addr", cfg.Server.SMPP.Addr)) + } + + // Day 43:待审任务 48h 超时扫描(置超时+幂等回退余额),随优雅停机拆除。 + scannerCtx, stopScanner := context.WithCancel(context.Background()) + go audit.NewTimeoutScanner(db).Run(scannerCtx) + a.OnShutdown(stopScanner) + a.Lg().Info("audit_timeout_scanner_started") + + // Day 27:余额预警定时扫描(每分钟;启动即扫一次),随优雅停机退出 + sched := &cronx.Scheduler{} + _ = sched.Add(cronx.Job{ + Name: "balance_warning", Interval: time.Minute, Immediate: true, + Run: func(ctx context.Context) error { + _, err := warnSvc.ScanOnce(ctx) + return err + }, + OnError: func(name string, err error) { + a.Lg().Warn("cron_job_failed", zap.String("job", name), zap.Error(err)) + }, + }) + // Day 40(A-3.12):通道告警扫描——链路全断/失败率超阈值,30s 周期 + // (断连事件另有 onDrop 即时评估路径,冷却 CooldownMin 去重兜底)。 + _ = sched.Add(cronx.Job{ + Name: "channel_alert", Interval: 30 * time.Second, Immediate: true, + Run: func(ctx context.Context) error { + _, err := chSvc.AlertService().ScanOnce(ctx) + return err + }, + OnError: func(name string, err error) { + a.Lg().Warn("cron_job_failed", zap.String("job", name), zap.Error(err)) + }, + }) + sched.Start() + a.OnShutdown(sched.Stop) + a.Lg().Info("balance_warning_scheduler_started", zap.String("interval", "1m")) + a.Lg().Info("channel_alert_scheduler_started", zap.String("interval", "30s")) + }, + }) +} diff --git a/cmd/reconcile/refund_lost/main.go b/cmd/reconcile/refund_lost/main.go index a60c1722..7fac23f0 100644 --- a/cmd/reconcile/refund_lost/main.go +++ b/cmd/reconcile/refund_lost/main.go @@ -19,8 +19,8 @@ import ( ) type lostRow struct { - TaskNo string `gorm:"column:task_no"` - RefundAmt int64 `gorm:"column:refund_amt"` + TaskNo string `gorm:"column:task_no"` + RefundAmt int64 `gorm:"column:refund_amt"` } func main() { diff --git a/internal/api/doc.go b/internal/api/doc.go new file mode 100644 index 00000000..f0273cd9 --- /dev/null +++ b/internal/api/doc.go @@ -0,0 +1,3 @@ +// Package api 存放各服务的 API 定义(HTTP handler 契约 / gRPC proto)。 +// 阶段 1 起随业务开发逐步填充。 +package api diff --git a/internal/api/http/v1/account.go b/internal/api/http/v1/account.go new file mode 100644 index 00000000..00250648 --- /dev/null +++ b/internal/api/http/v1/account.go @@ -0,0 +1,744 @@ +// Package v1 HTTP API v1(Day 21 起):账号等业务路由;由 app.RegisterRoutes 装配。 +package v1 + +import ( + "bytes" + "fmt" + "io" + "net/http" + "slices" + "strconv" + "strings" + + stderrors "errors" + + "github.com/gin-gonic/gin" + "go.uber.org/zap" + "gorm.io/gorm" + + "go-sms/internal/config" + "go-sms/internal/middleware" + "go-sms/internal/pkg/errors" + "go-sms/internal/pkg/response" + "go-sms/internal/repository/mysql" + "go-sms/internal/service/account" + "go-sms/internal/service/audit" + "go-sms/internal/service/auth" + "go-sms/internal/service/channel" + "go-sms/internal/service/interceptor" + "go-sms/internal/service/report" + "go-sms/internal/service/router" + "go-sms/internal/service/send" + "go-sms/internal/service/template" +) + +// Deps 路由依赖。 +// Auth 非 nil 时受保护路由组挂 JWT 鉴权(黑名单 + 账号状态校验); +// AuthSvc 非 nil 时注册 /auth/* 认证端点(login 公开,logout/refresh 走 Auth); +// Perm 非 nil 时敏感路由(导出/授权/充值)挂 Casbin 细粒度校验(Day 25/26); +// Warning 非 nil 时注册账号余额预警配置端点(Day 27); +// Audit 非 nil 时受保护组挂敏感操作审计拦截 + 注册 /audit 查询端点(Day 29); +// Channel 非 nil 时注册通道 CRUD/测试工具/拦截配置端点(Day 35); +// Router 非 nil 时注册导流规则管理端点(Day 38)。 +type Deps struct { + Account *account.Service + Warning *account.WarningService + Audit *audit.Service + Channel *channel.Service + Upstream *channel.UpstreamService // Day 41(清债③):上家管理 + Template *template.Service // Day 41:模板 CRUD/审核/发送预估 + Interceptor *interceptor.Chain // Day 42:发送拦截器链(/send/precheck) + Router *router.Router + Review *audit.ReviewService // Day 43:消息审核(审核中心+D19 定时任务) + Submit *send.SubmitService // Day 43 修复循环:最小提交链(/send/submit) + FileImport *send.FileImportService // Day 44:号码文件导入(/files/numbers/import,MinIO) + AuthSvc *auth.Service + Auth gin.HandlerFunc + Perm middleware.PermissionChecker + DB *gorm.DB // Day 53:/fe-errors 落库(裸 DB,不设服务层) + Logger *zap.Logger // Day 53:/alerts/sink AM webhook 留痕 + ErrorCode *report.ErrorCodeService // Day 56:错误码维护(/system/error-codes) + // Pair 阶段5收尾(D28):回执重推+手动配对(/record/repush 域四端点; + // nil=不注册,前端 404 优于半可用)。 + Pair *report.PairService + // CMPPCfg Day 62:CMPP 服务端配置(系统默认配额+端口;GET api-config 的 + // cmpp_access 块数据源;nil=CMPP 未启用,响应不带该块)。 + CMPPCfg *config.CMPPServer +} + +// Register 注册 v1 路由组。 +// 分组:公开组(登录)与受保护组(账号 CRUD、登出/刷新); +// gin 的 Use 仅影响其后注册的路由,受保护子组统一挂 deps.Auth。 +func Register(rg *gin.RouterGroup, deps Deps) { + // 公开:登录(无 JWT) + if deps.AuthSvc != nil { + ah := &authHandler{svc: deps.AuthSvc} + rg.POST("/auth/login", ah.login) + } + // 受保护子组(deps.Auth 为 nil 时不挂中间件;gin 不会跳过 nil handler, + // 直接传入会在 c.Next() 时空指针,故按需分组) + var protected *gin.RouterGroup + if deps.Auth != nil { + protected = rg.Group("", deps.Auth) + } else { + protected = rg.Group("") + } + // Day 29:受保护组敏感操作审计(写方法 + 导出类 GET,响应 2xx 留痕) + if deps.Audit != nil { + protected.Use(middleware.AuditTrail(deps.Audit)) + } + if deps.AuthSvc != nil { + ah := &authHandler{svc: deps.AuthSvc} + protected.POST("/auth/logout", ah.logout) + protected.POST("/auth/refresh", ah.refresh) + } + if deps.Account != nil { + h := &accountHandler{svc: deps.Account, cmpp: deps.CMPPCfg} + protected.POST("/accounts", h.create) + protected.GET("/accounts", h.list) + protected.GET("/accounts/:id", h.get) + protected.PUT("/accounts/:id", h.update) + protected.PUT("/accounts/:id/status", h.setStatus) + protected.DELETE("/accounts/:id", h.remove) + protected.GET("/accounts/:id/ip-bindings", h.getIPBindings) + protected.PUT("/accounts/:id/ip-bindings", h.setIPBindings) + protected.PUT("/accounts/:id/protocol", h.setProtocol) + protected.PUT("/accounts/:id/audit-mode", h.setAuditMode) + // Day 46:外部 API 配置(回调绑定/限速/扩展码/接口密钥重发;account:write) + protected.GET("/accounts/:id/api-config", h.getApiConfig) + protected.PUT("/accounts/:id/api-config", + middleware.RequirePermission(deps.Perm, "account", "write"), h.setApiConfig) + protected.GET("/accounts/:id/business-status", h.getBusinessStatus) + protected.POST("/accounts/:id/business/:biz/enable", h.enableBusiness) + protected.POST("/accounts/:id/business/:biz/disable", h.disableBusiness) + // Day 25:二级权限与导出(Casbin 细粒度校验;静态段 export 与 :id 可共存) + protected.GET("/accounts/export", + middleware.RequirePermission(deps.Perm, "account", middleware.PermExport), h.export) + protected.GET("/accounts/:id/permissions", h.listPermissions) + protected.POST("/accounts/:id/permissions/:perm/grant", + middleware.RequirePermission(deps.Perm, "account", "write"), h.grantPermission) + protected.POST("/accounts/:id/permissions/:perm/revoke", + middleware.RequirePermission(deps.Perm, "account", "write"), h.revokePermission) + // Day 26:充值(单笔/CSV 批量,account:recharge 二级权限)+ 余额查询 + protected.GET("/accounts/:id/balance", h.balance) + // Day62 修复:前端 balanceLogs 历史调用 /balance_logs(仅 MSW mock 有此路径), + // real 模式 404 且曾阻断同 onMounted 中后续 api-config 加载;补兼容路由(近期20条)。 + protected.GET("/accounts/:id/balance_logs", h.balanceLogs) + protected.POST("/accounts/:id/recharge", + middleware.RequirePermission(deps.Perm, "account", middleware.PermRecharge), h.recharge) + protected.POST("/accounts/recharge/batch", + middleware.RequirePermission(deps.Perm, "account", middleware.PermRecharge), h.rechargeBatch) + // Day 28:上级切换/标星/服务团队(管理侧 account:write) + protected.POST("/accounts/:id/parent", + middleware.RequirePermission(deps.Perm, "account", "write"), h.changeParent) + protected.POST("/accounts/:id/star", + middleware.RequirePermission(deps.Perm, "account", "write"), h.setStar) + protected.PUT("/accounts/:id/svc-team", + middleware.RequirePermission(deps.Perm, "account", "write"), h.setSvcTeam) + // Day 28:实名认证(查看/提交限本人或 admin;审核 account:write) + protected.GET("/accounts/:id/realname", h.getRealname) + protected.POST("/accounts/:id/realname", h.submitRealname) + protected.POST("/accounts/:id/realname/review", + middleware.RequirePermission(deps.Perm, "account", "write"), h.reviewRealname) + } + // Day 27:余额预警配置(本人或 admin) + if deps.Warning != nil { + wh := &warningHandler{svc: deps.Warning} + protected.GET("/accounts/:id/warning", wh.get) + protected.PUT("/accounts/:id/warning", wh.set) + protected.DELETE("/accounts/:id/warning", wh.disable) + } + // Day 29:审计日志查询(system:read 门禁,admin 通配放行) + if deps.Audit != nil { + ah := &auditHandler{svc: deps.Audit} + protected.GET("/audit/logs", + middleware.RequirePermission(deps.Perm, "system", "read"), ah.logs) + protected.GET("/audit/logins", + middleware.RequirePermission(deps.Perm, "system", "read"), ah.logins) + } + // Day 35:通道 CRUD/测试工具/拦截配置(channel:write 门禁) + if deps.Channel != nil { + registerChannelRoutes(protected, deps.Perm, deps.Channel, deps.Upstream) + registerTemplateRoutes(protected, deps.Perm, deps.Template) + } + // Day 42:发送域端点(预检;模板服务可 nil) + registerSendRoutes(protected, deps.Perm, deps.Template, deps.Interceptor, deps.Submit, deps.FileImport) + // Day 43:审核中心+D19 定时任务管理(服务可 nil) + if deps.Review != nil { + registerReviewRoutes(protected, deps.Perm, deps.Review) + } + // Day 38:导流规则管理(channel:write 门禁) + if deps.Router != nil { + registerSteerRoutes(protected, deps.Perm, deps.Router) + } + // Day 56:错误码维护(system_error_code 增改停用;system:write 门禁) + if deps.ErrorCode != nil { + registerErrorCodeRoutes(protected, deps.Perm, deps.ErrorCode) + } + // Day 53(runbook §6.4/§6.2 P0):前端错误上报(POST public/GET 排障)+ + // Alertmanager webhook 接收(AM 推送→日志留痕,告警通道验收抓手)。 + registerFeErrorRoutes(rg, protected, deps.DB, deps.Perm) + registerAlertsSink(rg, deps.Logger) + // Day 60(D24-25):record 域查询端点(批次/明细/拦截 CSV/通道日志/明细 v2; + // 裸 DB 查询,无服务层;查询类不挂 Casbin,JWT 保护即可)。 + if deps.DB != nil { + registerRecordRoutes(protected, deps.DB) + } + // Day68:运营总览(/home)真实数据——summary 四指标卡+trend 近 N 日趋势 + // (查询类,JWT 保护即可;口径/角色范围见 stats_handler.go 头注)。 + if deps.DB != nil { + registerStatsRoutes(protected, deps.DB) + } + // 阶段5收尾(D28):回执重推域四端点(回执分页/重推受理/挂起明细/手动配对; + // 服务依赖 Billing/PushSink,装配见 cmd/gateway)。 + if deps.Pair != nil { + registerRepushRoutes(protected, deps.Pair) + } +} + +// accountHandler 账号接口。 +type accountHandler struct { + svc *account.Service + cmpp *config.CMPPServer // Day 62:CMPP 接入系统默认(nil=未启用) +} + +// create godoc +// POST /api/v1/accounts 开户(业务位掩码)。 +func (h *accountHandler) create(c *gin.Context) { + var req account.CreateAccountRequest + if err := c.ShouldBindJSON(&req); err != nil { + response.ErrorWithMsg(c, errors.InvalidParam, "参数错误: "+err.Error()) + return + } + u, err := h.svc.CreateAccount(c.Request.Context(), &req) + if err != nil { + if bizErr, ok := err.(*errors.Error); ok { + response.Error(c, bizErr) + return + } + c.Set("biz_error", err.Error()) + response.Error(c, errors.InternalError) + return + } + response.Success(c, gin.H{ + "id": u.ID, "username": u.Username, "role": u.Role, + "credit_balance": u.CreditBalance, "status": u.Status, + }) +} + +// list GET /accounts 分页过滤(username/protocol/status)。 +func (h *accountHandler) list(c *gin.Context) { + q := &account.ListQuery{ + Page: atoiDefault(c.Query("page"), 1), PageSize: atoiDefault(c.Query("page_size"), 20), + Username: c.Query("username"), Protocol: c.Query("protocol"), + Status: atoiDefault(c.Query("status"), -1), + } + users, total, err := h.svc.ListAccounts(c.Request.Context(), q) + if err != nil { + response.Error(c, errors.InternalError) + return + } + response.Page(c, users, total, q.Page, q.PageSize) +} + +// get GET /accounts/:id(账号+业务配置)。 +func (h *accountHandler) get(c *gin.Context) { + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + u, cfgs, err := h.svc.GetAccount(c.Request.Context(), id) + if err != nil { + response.Error(c, errors.NotFound) + return + } + response.Success(c, gin.H{"account": u, "configs": cfgs}) +} + +// update PUT /accounts/:id(白名单字段)。 +func (h *accountHandler) update(c *gin.Context) { + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + var fields map[string]any + if err := c.ShouldBindJSON(&fields); err != nil { + response.Error(c, errors.InvalidParam) + return + } + if err := h.svc.UpdateAccountFields(c.Request.Context(), id, fields); err != nil { + if bizErr, ok := err.(*errors.Error); ok { + response.Error(c, bizErr) + return + } + response.Error(c, errors.InternalError) + return + } + response.Success(c, gin.H{"id": id}) +} + +// setStatus PUT /accounts/:id/status。 +func (h *accountHandler) setStatus(c *gin.Context) { + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + var body struct { + Status int `json:"status" binding:"oneof=0 1"` + } + if err := c.ShouldBindJSON(&body); err != nil { + response.ErrorWithMsg(c, errors.InvalidParam, "status 须为 0/1") + return + } + if err := h.svc.SetStatus(c.Request.Context(), id, body.Status); err != nil { + response.Error(c, errors.InternalError) + return + } + response.Success(c, gin.H{"id": id, "status": body.Status}) +} + +// remove DELETE /accounts/:id(活跃账号业务拒绝)。 +func (h *accountHandler) remove(c *gin.Context) { + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + if err := h.svc.DeleteAccount(c.Request.Context(), id); err != nil { + if bizErr, ok := err.(*errors.Error); ok { + response.Error(c, bizErr) + return + } + response.Error(c, errors.NotFound) + return + } + response.Success(c, gin.H{"id": id}) +} + +func atoiDefault(s string, d int) int { + if s == "" { + return d + } + n, err := strconv.Atoi(s) + if err != nil || n < 0 { + return d + } + return n +} + +func (h *accountHandler) getIPBindings(c *gin.Context) { + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + ips, err := h.svc.GetIPBindings(c.Request.Context(), id) + if err != nil { + response.Error(c, errors.NotFound) + return + } + response.Success(c, gin.H{"ips": ips}) +} + +func (h *accountHandler) setIPBindings(c *gin.Context) { + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + var body struct { + IPs []string `json:"ips"` + } + if err := c.ShouldBindJSON(&body); err != nil { + response.Error(c, errors.InvalidParam) + return + } + if err := h.svc.SetIPBindings(c.Request.Context(), id, body.IPs); err != nil { + if bizErr, ok := err.(*errors.Error); ok { + response.Error(c, bizErr) + return + } + response.Error(c, errors.InternalError) + return + } + response.Success(c, gin.H{"id": id, "ips": body.IPs}) +} + +func (h *accountHandler) setAuditMode(c *gin.Context) { + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + var body struct { + Business string `json:"business" binding:"required"` + Mode int `json:"mode" binding:"min=0,max=2"` + } + if err := c.ShouldBindJSON(&body); err != nil { + response.ErrorWithMsg(c, errors.InvalidParam, "business required, mode 0-2") + return + } + if err := h.svc.SetAuditMode(c.Request.Context(), id, body.Business, body.Mode); err != nil { + if bizErr, ok := err.(*errors.Error); ok { + response.Error(c, bizErr) + return + } + response.Error(c, errors.InternalError) + return + } + response.Success(c, gin.H{"id": id, "business": body.Business, "audit_mode": body.Mode}) +} + +func (h *accountHandler) getBusinessStatus(c *gin.Context) { + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + status, err := h.svc.GetBusinessStatus(c.Request.Context(), id) + if err != nil { + response.Error(c, errors.InternalError) + return + } + response.Success(c, status) +} + +func (h *accountHandler) enableBusiness(c *gin.Context) { + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + biz := c.Param("biz") + if err := h.svc.EnableBusiness(c.Request.Context(), id, biz); err != nil { + if bizErr, ok := err.(*errors.Error); ok { + response.Error(c, bizErr) + return + } + response.Error(c, errors.InternalError) + return + } + response.Success(c, gin.H{"id": id, "business": biz, "enabled": true}) +} + +func (h *accountHandler) disableBusiness(c *gin.Context) { + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + biz := c.Param("biz") + if err := h.svc.DisableBusiness(c.Request.Context(), id, biz); err != nil { + if bizErr, ok := err.(*errors.Error); ok { + response.Error(c, bizErr) + return + } + response.Error(c, errors.InternalError) + return + } + response.Success(c, gin.H{"id": id, "business": biz, "enabled": false}) +} + +// setProtocol PUT /accounts/:id/protocol {business, protocol}(Day 30/A-2.1 四协议)。 +func (h *accountHandler) setProtocol(c *gin.Context) { + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + var req struct { + Business string `json:"business" binding:"required"` + Protocol string `json:"protocol" binding:"required"` + } + if err := c.ShouldBindJSON(&req); err != nil { + response.ErrorWithMsg(c, errors.InvalidParam, "参数错误: "+err.Error()) + return + } + if err := h.svc.SetProtocol(c.Request.Context(), id, req.Business, req.Protocol); err != nil { + if bizErr, ok := err.(*errors.Error); ok { + response.Error(c, bizErr) + return + } + response.Error(c, errors.InternalError) + return + } + response.Success(c, gin.H{"id": id, "business": req.Business, "protocol": req.Protocol}) +} + +// ---- Day 46:外部 API 配置(回调/限速/扩展码/接口密钥) ---- + +// getApiConfig GET /accounts/:id/api-config:查看短信线 API 配置。 +// Day 62:CMPP 密码=api_secret 库值全量(库值即 CMPP 共享密钥本体,MD5 态, +// 可随时查看——与「HTTP 明文仅一次」不同口径);接入配额回显原始值+生效值 +// (账号级 0 回退系统默认)与 cmpp_access 交付块(端口/版本/系统默认)。 +func (h *accountHandler) getApiConfig(c *gin.Context) { + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + _, cfgs, err := h.svc.GetAccount(c.Request.Context(), id) + if err != nil { + response.Error(c, errors.NotFound) + return + } + for i := range cfgs { + if cfgs[i].Business != "sms" { + continue + } + cfg := cfgs[i] + issued := cfg.ApiSecret != "" + fingerprint := "" + if issued { + // Day62 改版:库值即密码(可能 <8 位,如 6 位原文),安全截取防越界 panic。 + if len(cfg.ApiSecret) > 8 { + fingerprint = cfg.ApiSecret[:8] + } else { + fingerprint = cfg.ApiSecret + } + } + // Day 62:接入配额生效值(账号级 0 回退系统默认)。 + defConns, defSpeed := 0, 0 + if h.cmpp != nil { + defConns, defSpeed = h.cmpp.MaxConnsPerAccount, h.cmpp.SubmitRatePerConn + } + effConns, effSpeed := cfg.CmppMaxConns, cfg.CmppSpeed + if effConns <= 0 { + effConns = defConns + } + if effSpeed <= 0 { + effSpeed = defSpeed + } + body := gin.H{ + "account_id": id, "business": "sms", + "report_url": cfg.ReportURL, "uplink_url": cfg.UplinkURL, + "speed_limit": cfg.SpeedLimit, "ext_code": cfg.ExtCode, + "secret_issued": issued, "secret_fingerprint": fingerprint, + "cmpp_password": cfg.ApiSecret, // Day 62:CMPP 客户端直接填的密码 + "cmpp_max_conns": cfg.CmppMaxConns, + "cmpp_speed": cfg.CmppSpeed, + "cmpp_max_conns_effective": effConns, + "cmpp_speed_effective": effSpeed, + } + if h.cmpp != nil { + port := h.cmpp.Addr + if k := strings.LastIndex(port, ":"); k >= 0 { + port = port[k+1:] + } + body["cmpp_access"] = gin.H{ + "port": port, "version": "CMPP 2.0", + "default_max_conns": defConns, "default_speed": defSpeed, + } + } + response.Success(c, body) + return + } + response.ErrorWithMsg(c, errors.NotFound, "短信业务配置不存在") +} + +// setApiConfig PUT /accounts/:id/api-config:更新 API 配置 +// (report_url/uplink_url/speed_limit/ext_code;reset_secret=true 重发密钥,明文仅本次返回)。 +func (h *accountHandler) setApiConfig(c *gin.Context) { + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + var req account.ApiConfigReq + if err := c.ShouldBindJSON(&req); err != nil { + response.ErrorWithMsg(c, errors.InvalidParam, "参数错误: "+err.Error()) + return + } + res, err := h.svc.SetApiConfig(c.Request.Context(), id, &req) + if err != nil { + if bizErr, ok := err.(*errors.Error); ok { + response.Error(c, bizErr) + return + } + response.Error(c, errors.InternalError) + return + } + body := gin.H{"id": id, "business": "sms"} + if res != nil && res.Secret != "" { + body["secret"] = res.Secret // 明文密钥仅此一次返回 + // Day 62:CMPP 密码=库值(MD5 态),与 HTTP 明文不同口径,可随时回查。 + body["cmpp_password"] = res.CmppPassword + body["notice"] = "请立即保存密钥,平台不再二次显示" + } + response.Success(c, body) +} + +// ---- Day 25:导出与二级权限 ---- + +// export GET /accounts/export:全量账号 CSV 导出(Casbin account:export 门禁; +// 验收:普通账号 403,admin 放行)。分页拉取上限 1 万行。 +func (h *accountHandler) export(c *gin.Context) { + var b strings.Builder + b.WriteString("\ufeffid,username,real_name,role,status,credit_balance,svc_team,created_at\n") // BOM 便于 Excel + const batch = 100 + for page := 1; page <= 100; page++ { // 上限 100×100=1 万行 + users, _, err := h.svc.ListAccounts(c.Request.Context(), &account.ListQuery{ + Page: page, PageSize: batch, Status: -1, + }) + if err != nil { + response.Error(c, errors.InternalError) + return + } + for _, u := range users { + b.WriteString(fmt.Sprintf("%d,%s,%s,%s,%d,%d,%s,%s\n", + u.ID, u.Username, u.RealName, u.Role, u.Status, u.CreditBalance, u.SvcTeam, + u.CreatedAt.Format("2006-01-02 15:04:05"))) + } + if len(users) < batch { + break + } + } + c.Header("Content-Type", "text/csv; charset=utf-8") + c.Header("Content-Disposition", "attachment; filename=accounts.csv") + c.String(http.StatusOK, b.String()) +} + +// listPermissions GET /accounts/:id/permissions:账户二级权限列表。 +func (h *accountHandler) listPermissions(c *gin.Context) { + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + response.Success(c, gin.H{"id": id, "permissions": h.svc.ListSecondary(c.Request.Context(), id)}) +} + +// grantPermission POST /accounts/:id/permissions/:perm/grant(account:write 门禁)。 +func (h *accountHandler) grantPermission(c *gin.Context) { + id, perm, ok := parsePermParams(c) + if !ok { + return + } + if err := h.svc.GrantSecondary(c.Request.Context(), id, perm); err != nil { + if bizErr, ok := err.(*errors.Error); ok { + response.Error(c, bizErr) + return + } + response.Error(c, errors.InternalError) + return + } + response.Success(c, gin.H{"id": id, "permission": perm, "granted": true}) +} + +// revokePermission POST /accounts/:id/permissions/:perm/revoke(account:write 门禁)。 +func (h *accountHandler) revokePermission(c *gin.Context) { + id, perm, ok := parsePermParams(c) + if !ok { + return + } + if err := h.svc.RevokeSecondary(c.Request.Context(), id, perm); err != nil { + if bizErr, ok := err.(*errors.Error); ok { + response.Error(c, bizErr) + return + } + response.Error(c, errors.InternalError) + return + } + response.Success(c, gin.H{"id": id, "permission": perm, "granted": false}) +} + +// parsePermParams 解析 id/perm 并校验二级权限标记合法性。 +func parsePermParams(c *gin.Context) (int64, string, bool) { + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + perm := c.Param("perm") + if !middleware.SecondaryPermissions[perm] { + response.ErrorWithMsg(c, errors.InvalidParam, + "非法二级权限 "+perm+"(可选: recharge/proxy_send/export/send)") + return 0, "", false + } + return id, perm, true +} + +// ---- Day 26:充值与余额 ---- + +// rechargeReq 单笔充值请求体。 +type rechargeReq struct { + Amount int64 `json:"amount" binding:"required,gt=0"` + Remark string `json:"remark"` +} + +// operatorClaims 从 Context 取当前登录人(RequirePermission 已保证认证)。 +func operatorClaims(c *gin.Context) *middleware.Claims { + v, _ := c.Get(middleware.ContextKeyClaims) + claims, _ := v.(*middleware.Claims) + return claims +} + +// recharge POST /accounts/:id/recharge(account:recharge 门禁): +// 事务(余额自增+流水),返回新余额与流水号。 +func (h *accountHandler) recharge(c *gin.Context) { + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + var req rechargeReq + if err := c.ShouldBindJSON(&req); err != nil { + response.ErrorWithMsg(c, errors.InvalidParam, "参数错误: "+err.Error()) + return + } + claims := operatorClaims(c) + log, err := h.svc.Recharge(c.Request.Context(), &account.RechargeRequest{ + AccountID: id, Amount: req.Amount, Operator: claims.Username, Remark: req.Remark, + }) + if err != nil { + if bizErr, ok := err.(*errors.Error); ok { + response.Error(c, bizErr) + return + } + c.Set("biz_error", err.Error()) + response.Error(c, errors.InternalError) + return + } + response.Success(c, gin.H{ + "id": id, "amount": req.Amount, "balance": log.BalanceAfter, "log_id": log.ID, + }) +} + +// rechargeBatch POST /accounts/recharge/batch(account:recharge 门禁): +// CSV(username,amount[,remark],自动跳 BOM/表头)——multipart 字段 file 或请求体原文; +// 逐行独立事务,响应含行级结果(行号/成功/失败原因),单行失败不影响其余行。 +func (h *accountHandler) rechargeBatch(c *gin.Context) { + var data []byte + if f, err := c.FormFile("file"); err == nil { + fp, err := f.Open() + if err != nil { + response.ErrorWithMsg(c, errors.InvalidParam, "文件打开失败: "+err.Error()) + return + } + defer func() { _ = fp.Close() }() + data, err = io.ReadAll(fp) + if err != nil { + response.ErrorWithMsg(c, errors.InvalidParam, "文件读取失败: "+err.Error()) + return + } + } else { + data, _ = io.ReadAll(c.Request.Body) + } + if len(bytes.TrimSpace(data)) == 0 { + response.ErrorWithMsg(c, errors.InvalidParam, "CSV 内容为空(username,amount[,remark])") + return + } + claims := operatorClaims(c) + res, err := h.svc.RechargeBatch(c.Request.Context(), data, claims.Username) + if err != nil { + if bizErr, ok := err.(*errors.Error); ok { + response.Error(c, bizErr) + return + } + c.Set("biz_error", err.Error()) + response.Error(c, errors.InternalError) + return + } + response.Success(c, gin.H{ + "total": res.Total, "success": res.Success, "failed": res.Failed, "rows": res.Rows, + }) +} + +// balance GET /accounts/:id/balance(登录即可):余额/授信+近期流水; +// 非 admin 仅可查询本人(越权 403 ISC:403)。 +func (h *accountHandler) balance(c *gin.Context) { + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + claims := operatorClaims(c) + if claims == nil { + response.Error(c, errors.Unauthorized) + return + } + if !slices.Contains(claims.Roles, "admin") && claims.AccountID != id { + c.AbortWithStatusJSON(http.StatusForbidden, gin.H{ + "code": errors.Forbidden.Code, + "msg": "仅可查询本人余额", + }) + return + } + u, logs, err := h.svc.GetBalance(c.Request.Context(), id) + if err != nil { + if stderrors.Is(err, mysql.ErrNotFound) { + response.ErrorWithMsg(c, errors.NotFound, "账号不存在") + return + } + response.Error(c, errors.InternalError) + return + } + response.Success(c, gin.H{ + "id": u.ID, "username": u.Username, + "balance": u.Balance, "credit_balance": u.CreditBalance, + "recent_logs": logs, + }) +} + +// balanceLogs GET /accounts/:id/balance_logs(Day62 补):Paged 兼容形状 {list,total}, +// 数据源同 balance(近期 BalanceLogRecent 条);权限口径一致(admin 或本人)。 +func (h *accountHandler) balanceLogs(c *gin.Context) { + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + claims := operatorClaims(c) + if claims == nil { + response.Error(c, errors.Unauthorized) + return + } + if !slices.Contains(claims.Roles, "admin") && claims.AccountID != id { + c.AbortWithStatusJSON(http.StatusForbidden, gin.H{ + "code": errors.Forbidden.Code, + "msg": "仅可查询本人余额", + }) + return + } + _, logs, err := h.svc.GetBalance(c.Request.Context(), id) + if err != nil { + if stderrors.Is(err, mysql.ErrNotFound) { + response.ErrorWithMsg(c, errors.NotFound, "账号不存在") + return + } + response.Error(c, errors.InternalError) + return + } + response.Success(c, gin.H{"list": logs, "total": len(logs)}) +} diff --git a/internal/api/http/v1/account_day22_test.go b/internal/api/http/v1/account_day22_test.go new file mode 100644 index 00000000..fe1bc3cf --- /dev/null +++ b/internal/api/http/v1/account_day22_test.go @@ -0,0 +1,159 @@ +package v1 + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/gin-gonic/gin" + "github.com/glebarez/sqlite" + "gorm.io/gorm" + + "go-sms/internal/middleware" + "go-sms/internal/model/entity" + "go-sms/internal/service/account" +) + +const testSecret22 = "day22-secret" + +// newAuthRouter 带 JWT+状态校验的路由(验收:禁用后 Token 失效)。 +func newAuthRouter(t *testing.T) (*gin.Engine, *gorm.DB, *account.Service) { + t.Helper() + gin.SetMode(gin.TestMode) + db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{}) + if err != nil { + t.Fatal(err) + } + if err := db.AutoMigrate(&entity.AccountUser{}, &entity.AccountConfig{}, &entity.AccountBalanceLog{}, &entity.MessageDetail{}); err != nil { + t.Fatal(err) + } + svc := account.NewService(db, account.BcryptMinCost) + // 预置超管(id=1,鉴权/状态校验依赖其存在) + db.Exec("INSERT INTO account_user (username, password_hash, role, status) VALUES ('admin','x','admin',1)") + r := gin.New() + // Group 构造期挂中间件(确保先于 handler 执行) + rg := r.Group("/api/v1", middleware.AuthJWTWithChecker(testSecret22, svc.CheckEnabled)) + Register(rg, Deps{Account: svc}) + return r, db, svc +} + +func doReq(r *gin.Engine, method, path, token string) *httptest.ResponseRecorder { + w := httptest.NewRecorder() + req := httptest.NewRequest(method, path, nil) + if token != "" { + req.Header.Set("Authorization", "Bearer "+token) + } + r.ServeHTTP(w, req) + return w +} + +// TestAPI_ListPagedAndAuth 列表分页 + 鉴权拦截(Day 22 验收)。 +func TestAPI_ListPagedAndAuth(t *testing.T) { + r, _, _ := newAuthRouter(t) + + // 未带 Token:401 + if w := doReq(r, http.MethodGet, "/api/v1/accounts", ""); w.Code != http.StatusUnauthorized { + t.Fatalf("无 Token 应 401, got %d", w.Code) + } + // 有效 Token:200 分页 + tok, _ := middleware.SignAccessToken(testSecret22, 1, "admin", "admin", time.Hour) + w := doReq(r, http.MethodGet, "/api/v1/accounts?page=1&page_size=10", tok) + if w.Code != http.StatusOK { + t.Fatalf("列表应 200, got %d body=%s", w.Code, w.Body.String()) + } + var page struct { + Code string `json:"code"` + Data struct { + Total int `json:"total"` + List []struct { + Username string `json:"username"` + } `json:"list"` + } `json:"data"` + } + _ = json.Unmarshal(w.Body.Bytes(), &page) + if page.Code != "ISC:000" { + t.Fatalf("响应码 = %s", page.Code) + } +} + +// TestAPI_DisableInvalidatesToken 验收:禁用后 Token 立即失效(中间件级直测, +// 经 svc.CheckEnabled 真实 DB 状态;HTTP 全链由 e2e Day39 覆盖)。 +func TestAPI_DisableInvalidatesToken(t *testing.T) { + _, db, svc := newAuthRouter(t) + ctx := context.Background() + + u, err := svc.CreateAccount(ctx, &account.CreateAccountRequest{ + Username: "victim", Password: "secret66", Role: "customer", Business: account.BusinessSMS, + }) + if err != nil { + t.Fatal(err) + } + tok, _ := middleware.SignAccessToken(testSecret22, u.ID, "victim", "customer", time.Hour) + + run := func() int { + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + c.Request = httptest.NewRequest(http.MethodGet, "/t", nil) + c.Request.Header.Set("Authorization", "Bearer "+tok) + middleware.AuthJWTWithChecker(testSecret22, svc.CheckEnabled)(c) + return w.Code + } + + if code := run(); code != 200 { + t.Fatalf("禁用前应放行(200), got %d", code) + } + if err := svc.SetStatus(ctx, u.ID, 0); err != nil { + t.Fatal(err) + } + if code := run(); code != http.StatusUnauthorized { + t.Fatalf("禁用后应 401, got %d", code) + } + _ = db +} + +func contains(s, sub string) bool { + return len(s) >= len(sub) && (func() bool { + for i := 0; i+len(sub) <= len(s); i++ { + if s[i:i+len(sub)] == sub { + return true + } + } + return false + })() +} + +// TestAPI_DeleteActiveRejected 活跃账号删除业务拒绝(ISC:032)。 +func TestAPI_DeleteActiveRejected(t *testing.T) { + r, db, svc := newAuthRouter(t) + ctx := context.Background() + u, _ := svc.CreateAccount(ctx, &account.CreateAccountRequest{ + Username: "busy", Password: "secret66", Role: "customer", Business: account.BusinessSMS, + }) + db.Create(&entity.MessageDetail{SnowflakeModel: entity.SnowflakeModel{ID: 7302}, AccountID: u.ID, Mobile: "13900139000"}) + + tok, _ := middleware.SignAccessToken(testSecret22, 1, "admin", "admin", time.Hour) + w := doReq(r, http.MethodDelete, "/api/v1/accounts/"+itoa(u.ID), tok) + if w.Code != http.StatusTooManyRequests { // SendLimited.HTTPStatus=429 + t.Fatalf("活跃删除应 429, got %d body=%s", w.Code, w.Body.String()) + } + if !contains(w.Body.String(), "ISC:032") { + t.Fatalf("应含 ISC:032: %s", w.Body.String()) + } +} + +func itoa(n int64) string { + if n == 0 { + return "0" + } + var b [20]byte + i := len(b) + for n > 0 { + i-- + b[i] = byte('0' + n%10) + n /= 10 + } + return string(b[i:]) +} diff --git a/internal/api/http/v1/account_day25_test.go b/internal/api/http/v1/account_day25_test.go new file mode 100644 index 00000000..1b1acf50 --- /dev/null +++ b/internal/api/http/v1/account_day25_test.go @@ -0,0 +1,145 @@ +// account_day25_test.go Day 25 验收:普通账号访问 /accounts/export 返回 403, +// admin 可正常导出;二级权限授予后即时放行、撤销后收回。 +package v1 + +import ( + "net/http" + "testing" + "time" + + "github.com/gin-gonic/gin" + "github.com/glebarez/sqlite" + "gorm.io/gorm" + + "go-sms/internal/middleware" + "go-sms/internal/model/entity" + "go-sms/internal/pkg/casbin" + "go-sms/internal/service/account" +) + +const d25Secret = "d25-api-secret" + +// newD25Router admin(1)+customer(2)双账号 + Casbin 门禁路由。 +func newD25Router(t *testing.T) (*gin.Engine, *casbin.Enforcer) { + t.Helper() + gin.SetMode(gin.TestMode) + db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{}) + if err != nil { + t.Fatal(err) + } + if err := db.AutoMigrate(&entity.AccountUser{}, &entity.AccountConfig{}, &entity.AccountBalanceLog{}, &entity.SystemAlertRule{}); err != nil { + t.Fatal(err) + } + e, err := casbin.New(db) + if err != nil { + t.Fatal(err) + } + for _, p := range [][]string{ + {"admin", "*", "*"}, + {"ops", "account", "write"}, + {"customer", "message", "write"}, + } { + if _, err := e.AddPolicy(p[0], p[1], p[2]); err != nil { + t.Fatal(err) + } + } + rows := []entity.AccountUser{ + {Username: "d25-admin", Role: "admin", Status: 1}, + {Username: "d25-cust", Role: "customer", Status: 1}, + } + for i := range rows { + if err := db.Create(&rows[i]).Error; err != nil { + t.Fatal(err) + } + if _, err := e.BindRole(rows[i].ID, rows[i].Role); err != nil { + t.Fatal(err) + } + } + acctSvc := account.NewService(db, account.BcryptMinCost).WithEnforcer(e) + + r := gin.New() + Register(r.Group("/api/v1"), Deps{ + Account: acctSvc, + Warning: account.NewWarningService(db, nil), // Day 27:预警配置端点 + Auth: middleware.AuthJWTWithChecker(d25Secret, acctSvc.CheckEnabled), + Perm: middleware.CasbinChecker(e), + }) + return r, e +} + +func d25Token(t *testing.T, id int64, role string) string { + t.Helper() + tok, err := middleware.SignAccessToken(d25Secret, id, role+"-u", role, time.Minute) + if err != nil { + t.Fatal(err) + } + return tok +} + +// TestAPI_ExportPermission Day 25 验收主线。 +func TestAPI_ExportPermission(t *testing.T) { + r, _ := newD25Router(t) + adminTok := d25Token(t, 1, "admin") + custTok := d25Token(t, 2, "customer") + + // 未认证 → 401 + if w := doReq(r, http.MethodGet, "/api/v1/accounts/export", ""); w.Code != http.StatusUnauthorized { + t.Fatalf("未认证导出 = %d, 期望 401", w.Code) + } + // 普通账号(customer)→ 403 ISC:403 + w := doReq(r, http.MethodGet, "/api/v1/accounts/export", custTok) + if w.Code != http.StatusForbidden { + t.Fatalf("普通账号导出 = %d, 期望 403, body=%s", w.Code, w.Body.String()) + } + if !contains(w.Body.String(), "ISC:403") { + t.Fatalf("403 响应应含 ISC:403: %s", w.Body.String()) + } + // admin → 200 + CSV 内容正确 + w = doReq(r, http.MethodGet, "/api/v1/accounts/export", adminTok) + if w.Code != http.StatusOK { + t.Fatalf("admin 导出 = %d, body=%s", w.Code, w.Body.String()) + } + if ct := w.Header().Get("Content-Type"); ct != "text/csv; charset=utf-8" { + t.Fatalf("Content-Type = %q", ct) + } + body := w.Body.String() + if !contains(body, "d25-admin") || !contains(body, "d25-cust") { + t.Fatalf("CSV 缺少账号行: %s", body) + } +} + +// TestAPI_GrantRevokeExport 二级权限授予 → 即时放行;撤销 → 收回;非法标记 400。 +func TestAPI_GrantRevokeExport(t *testing.T) { + r, _ := newD25Router(t) + adminTok := d25Token(t, 1, "admin") + custTok := d25Token(t, 2, "customer") + + // admin 授予 customer export 权限(account:write 门禁下 admin 通配) + if w := doReq(r, http.MethodPost, "/api/v1/accounts/2/permissions/export/grant", adminTok); w.Code != http.StatusOK { + t.Fatalf("授权 = %d, body=%s", w.Code, w.Body.String()) + } + // 权限列表可见 + w := doReq(r, http.MethodGet, "/api/v1/accounts/2/permissions", adminTok) + if w.Code != http.StatusOK || !contains(w.Body.String(), "account:export") { + t.Fatalf("权限列表 = %d, body=%s", w.Code, w.Body.String()) + } + // customer 导出即时放行 + if w := doReq(r, http.MethodGet, "/api/v1/accounts/export", custTok); w.Code != http.StatusOK { + t.Fatalf("授权后导出 = %d, 期望 200", w.Code) + } + // 撤销 → 403 + if w := doReq(r, http.MethodPost, "/api/v1/accounts/2/permissions/export/revoke", adminTok); w.Code != http.StatusOK { + t.Fatalf("撤销 = %d, body=%s", w.Code, w.Body.String()) + } + if w := doReq(r, http.MethodGet, "/api/v1/accounts/export", custTok); w.Code != http.StatusForbidden { + t.Fatalf("撤销后导出 = %d, 期望 403", w.Code) + } + // 非法二级权限标记 → 400 + if w := doReq(r, http.MethodPost, "/api/v1/accounts/2/permissions/hackall/grant", adminTok); w.Code != http.StatusBadRequest { + t.Fatalf("非法标记 = %d, 期望 400", w.Code) + } + // customer 无 account:write → 不能给别人授权(403) + if w := doReq(r, http.MethodPost, "/api/v1/accounts/2/permissions/export/grant", custTok); w.Code != http.StatusForbidden { + t.Fatalf("customer 越权授权 = %d, 期望 403", w.Code) + } +} diff --git a/internal/api/http/v1/account_day26_test.go b/internal/api/http/v1/account_day26_test.go new file mode 100644 index 00000000..57f56175 --- /dev/null +++ b/internal/api/http/v1/account_day26_test.go @@ -0,0 +1,128 @@ +// account_day26_test.go Day 26 验收:充值二级权限门禁 / 批量 CSV / 余额越权。 +// 复用 newD25Router(admin=1 通配,customer=2;Register 已含 Day 26 路由)。 +package v1 + +import ( + "bytes" + "net/http" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "net/http/httptest" +) + +// doReqBody 带请求体的请求(POST JSON/CSV 原文)。 +func doReqBody(r *gin.Engine, method, path, token, contentType string, body []byte) *httptest.ResponseRecorder { + w := httptest.NewRecorder() + req := httptest.NewRequest(method, path, bytes.NewReader(body)) + if contentType != "" { + req.Header.Set("Content-Type", contentType) + } + if token != "" { + req.Header.Set("Authorization", "Bearer "+token) + } + r.ServeHTTP(w, req) + return w +} + +// TestAPI_RechargePermission Day 26 验收主线: +// customer 充值 → 403 ISC:403;admin → 200 余额正确;授予 recharge 后即时放行,撤销收回。 +func TestAPI_RechargePermission(t *testing.T) { + r, _ := newD25Router(t) + adminTok := d25Token(t, 1, "admin") + custTok := d25Token(t, 2, "customer") + body := []byte(`{"amount":1000,"remark":"首充"}`) + + // 未认证 → 401 + if w := doReqBody(r, http.MethodPost, "/api/v1/accounts/1/recharge", "", "application/json", body); w.Code != http.StatusUnauthorized { + t.Fatalf("未认证充值 = %d, 期望 401", w.Code) + } + // customer → 403 ISC:403(验收锚点:无 recharge 二级权限被拦截) + w := doReqBody(r, http.MethodPost, "/api/v1/accounts/2/recharge", custTok, "application/json", body) + if w.Code != http.StatusForbidden || !strings.Contains(w.Body.String(), "ISC:403") { + t.Fatalf("customer 充值 = %d body=%s, 期望 403 ISC:403", w.Code, w.Body.String()) + } + // admin → 200,余额正确累加 + w = doReqBody(r, http.MethodPost, "/api/v1/accounts/2/recharge", adminTok, "application/json", body) + if w.Code != http.StatusOK { + t.Fatalf("admin 充值 = %d body=%s", w.Code, w.Body.String()) + } + if !strings.Contains(w.Body.String(), `"balance":1000`) { + t.Fatalf("充值响应应含 balance=1000: %s", w.Body.String()) + } + // 非法金额 → 400 + if w := doReqBody(r, http.MethodPost, "/api/v1/accounts/2/recharge", adminTok, "application/json", []byte(`{"amount":-1}`)); w.Code != http.StatusBadRequest { + t.Fatalf("负数金额 = %d, 期望 400", w.Code) + } + // 授予 customer recharge → 即时放行 + if w := doReq(r, http.MethodPost, "/api/v1/accounts/2/permissions/recharge/grant", adminTok); w.Code != http.StatusOK { + t.Fatalf("授权 = %d body=%s", w.Code, w.Body.String()) + } + if w := doReqBody(r, http.MethodPost, "/api/v1/accounts/2/recharge", custTok, "application/json", []byte(`{"amount":500}`)); w.Code != http.StatusOK { + t.Fatalf("授权后 customer 充值 = %d body=%s, 期望 200", w.Code, w.Body.String()) + } + // 撤销 → 403 + if w := doReq(r, http.MethodPost, "/api/v1/accounts/2/permissions/recharge/revoke", adminTok); w.Code != http.StatusOK { + t.Fatalf("撤销 = %d", w.Code) + } + if w := doReqBody(r, http.MethodPost, "/api/v1/accounts/2/recharge", custTok, "application/json", []byte(`{"amount":1}`)); w.Code != http.StatusForbidden { + t.Fatalf("撤销后充值 = %d, 期望 403", w.Code) + } +} + +// TestAPI_RechargeBatch CSV 批量:multipart/原文皆可;行级结果;空内容 400。 +func TestAPI_RechargeBatch(t *testing.T) { + r, _ := newD25Router(t) + adminTok := d25Token(t, 1, "admin") + custTok := d25Token(t, 2, "customer") + + csvData := []byte("username,amount,remark\nd25-cust,300,批量\nghost,100,不存在\n") + // customer → 403 + if w := doReqBody(r, http.MethodPost, "/api/v1/accounts/recharge/batch", custTok, "text/csv", csvData); w.Code != http.StatusForbidden { + t.Fatalf("customer 批量充值 = %d, 期望 403", w.Code) + } + // admin 原文上传 → 2 行:1 成功 1 失败(行级定位) + w := doReqBody(r, http.MethodPost, "/api/v1/accounts/recharge/batch", adminTok, "text/csv", csvData) + if w.Code != http.StatusOK { + t.Fatalf("admin 批量充值 = %d body=%s", w.Code, w.Body.String()) + } + b := w.Body.String() + for _, want := range []string{`"total":2`, `"success":1`, `"failed":1`, "ghost", "不存在", `"line":2`} { + if !strings.Contains(b, want) { + t.Fatalf("批量响应缺 %q: %s", want, b) + } + } + // 余额落账校验(300) + if w := doReq(r, http.MethodGet, "/api/v1/accounts/2/balance", adminTok); w.Code != http.StatusOK || !strings.Contains(w.Body.String(), `"balance":300`) { + t.Fatalf("批量后余额查询 = %d body=%s, 期望 balance=300", w.Code, w.Body.String()) + } + // 空内容 → 400 + if w := doReqBody(r, http.MethodPost, "/api/v1/accounts/recharge/batch", adminTok, "text/csv", []byte(" ")); w.Code != http.StatusBadRequest { + t.Fatalf("空 CSV = %d, 期望 400", w.Code) + } +} + +// TestAPI_BalanceAccessControl 余额查询:本人可查,越权 403,admin 全查。 +func TestAPI_BalanceAccessControl(t *testing.T) { + r, _ := newD25Router(t) + adminTok := d25Token(t, 1, "admin") + custTok := d25Token(t, 2, "customer") + + // customer 查本人 → 200 + if w := doReq(r, http.MethodGet, "/api/v1/accounts/2/balance", custTok); w.Code != http.StatusOK { + t.Fatalf("本人余额 = %d, 期望 200", w.Code) + } + // customer 查 admin → 403 + if w := doReq(r, http.MethodGet, "/api/v1/accounts/1/balance", custTok); w.Code != http.StatusForbidden { + t.Fatalf("越权查他人余额 = %d, 期望 403", w.Code) + } + // admin 查任意 → 200 + if w := doReq(r, http.MethodGet, "/api/v1/accounts/2/balance", adminTok); w.Code != http.StatusOK { + t.Fatalf("admin 查余额 = %d, 期望 200", w.Code) + } + // 不存在账号 → 404(admin) + if w := doReq(r, http.MethodGet, "/api/v1/accounts/999/balance", adminTok); w.Code != http.StatusNotFound { + t.Fatalf("不存在账号余额 = %d, 期望 404", w.Code) + } +} diff --git a/internal/api/http/v1/account_day27_test.go b/internal/api/http/v1/account_day27_test.go new file mode 100644 index 00000000..2e854ea4 --- /dev/null +++ b/internal/api/http/v1/account_day27_test.go @@ -0,0 +1,57 @@ +// account_day27_test.go Day 27:预警配置端点(本人/admin 读写、越权 403)。 +package v1 + +import ( + "net/http" + "testing" + + "github.com/gin-gonic/gin" +) + +// newD27Router 复用 D25 双账号结构(admin=1/customer=2,已含 Warning 服务)。 +func newD27Router(t *testing.T) *gin.Engine { + t.Helper() + r, _ := newD25Router(t) + return r +} + +// TestAPI_WarningConfigCRUD 设置/查询/停用闭环 + 越权拦截。 +func TestAPI_WarningConfigCRUD(t *testing.T) { + r := newD27Router(t) + adminTok := d25Token(t, 1, "admin") + custTok := d25Token(t, 2, "customer") + + body := []byte(`{"threshold":500,"cooldown_min":60,"notify_type":"wechat","notify_to":"http://hook/x"}`) + // customer 设置本人预警 → 200 + if w := doReqBody(r, http.MethodPut, "/api/v1/accounts/2/warning", custTok, "application/json", body); w.Code != http.StatusOK { + t.Fatalf("本人设置预警 = %d body=%s", w.Code, w.Body.String()) + } + // 查询回显 + if w := doReq(r, http.MethodGet, "/api/v1/accounts/2/warning", custTok); w.Code != http.StatusOK || !contains(w.Body.String(), `"threshold":500`) { + t.Fatalf("本人查询预警 = %d body=%s", w.Code, w.Body.String()) + } + // customer 越权设置 admin → 403 + if w := doReqBody(r, http.MethodPut, "/api/v1/accounts/1/warning", custTok, "application/json", body); w.Code != http.StatusForbidden { + t.Fatalf("越权设置 = %d, 期望 403", w.Code) + } + // 非法阈值 → 400 + if w := doReqBody(r, http.MethodPut, "/api/v1/accounts/2/warning", custTok, "application/json", []byte(`{"threshold":-1}`)); w.Code != http.StatusBadRequest { + t.Fatalf("非法阈值 = %d, 期望 400", w.Code) + } + // 非法渠道 → 400 + if w := doReqBody(r, http.MethodPut, "/api/v1/accounts/2/warning", custTok, "application/json", []byte(`{"threshold":10,"notify_type":"pigeon"}`)); w.Code != http.StatusBadRequest { + t.Fatalf("非法渠道 = %d, 期望 400", w.Code) + } + // admin 代设置 customer → 200 + if w := doReqBody(r, http.MethodPut, "/api/v1/accounts/2/warning", adminTok, "application/json", []byte(`{"threshold":900,"cooldown_min":15}`)); w.Code != http.StatusOK { + t.Fatalf("admin 代设置 = %d body=%s", w.Code, w.Body.String()) + } + // 停用(admin) + if w := doReq(r, http.MethodDelete, "/api/v1/accounts/2/warning", adminTok); w.Code != http.StatusOK { + t.Fatalf("停用预警 = %d", w.Code) + } + // 未认证 → 401 + if w := doReq(r, http.MethodGet, "/api/v1/accounts/2/warning", ""); w.Code != http.StatusUnauthorized { + t.Fatalf("未认证 = %d, 期望 401", w.Code) + } +} diff --git a/internal/api/http/v1/account_day28_test.go b/internal/api/http/v1/account_day28_test.go new file mode 100644 index 00000000..e8749fee --- /dev/null +++ b/internal/api/http/v1/account_day28_test.go @@ -0,0 +1,91 @@ +// account_day28_test.go Day 28:上级切换/标星/团队/实名的 API 权限与闭环。 +package v1 + +import ( + "net/http" + "testing" +) + +// TestAPI_HierarchyAndProfile admin 全通 / customer 越权 403 / 非法参数 400。 +func TestAPI_HierarchyAndProfile(t *testing.T) { + r := newD27Router(t) // admin=1(通配) customer=2 + adminTok := d25Token(t, 1, "admin") + custTok := d25Token(t, 2, "customer") + + // 标星(customer 无 account:write → 403;admin → 200) + if w := doReqBody(r, http.MethodPost, "/api/v1/accounts/2/star", custTok, "application/json", []byte(`{"starred":true}`)); w.Code != http.StatusForbidden { + t.Fatalf("customer 标星 = %d, 期望 403", w.Code) + } + if w := doReqBody(r, http.MethodPost, "/api/v1/accounts/2/star", adminTok, "application/json", []byte(`{"starred":true}`)); w.Code != http.StatusOK { + t.Fatalf("admin 标星 = %d body=%s", w.Code, w.Body.String()) + } + // 列表置顶(标星的 2 号排首) + w := doReq(r, http.MethodGet, "/api/v1/accounts?page=1&page_size=10", adminTok) + if w.Code != http.StatusOK { + t.Fatalf("列表 = %d", w.Code) + } + if b := w.Body.String(); !contains(b, `"is_starred":1`) { + t.Fatalf("列表应含标星标记: %s", b) + } + // 服务团队(admin → 200;超长 → 400) + if w := doReqBody(r, http.MethodPut, "/api/v1/accounts/2/svc-team", adminTok, "application/json", []byte(`{"svc_team":"华东二组"}`)); w.Code != http.StatusOK { + t.Fatalf("admin 绑定团队 = %d", w.Code) + } + // 上级切换:customer 2 挂到 admin 1 下(admin 操作) + if w := doReqBody(r, http.MethodPost, "/api/v1/accounts/2/parent", adminTok, "application/json", []byte(`{"parent_id":1}`)); w.Code != http.StatusOK { + t.Fatalf("admin 切换上级 = %d body=%s", w.Code, w.Body.String()) + } + // 防环:1 挂到 2 下(2 已是 1 的子……实际 2 挂 1 下,1→2 成环)→ 400 + if w := doReqBody(r, http.MethodPost, "/api/v1/accounts/1/parent", adminTok, "application/json", []byte(`{"parent_id":2}`)); w.Code != http.StatusBadRequest { + t.Fatalf("成环切换 = %d, 期望 400(body=%s)", w.Code, w.Body.String()) + } + // customer 切换上级 → 403 + if w := doReqBody(r, http.MethodPost, "/api/v1/accounts/2/parent", custTok, "application/json", []byte(`{"parent_id":1}`)); w.Code != http.StatusForbidden { + t.Fatalf("customer 切换上级 = %d, 期望 403", w.Code) + } +} + +// TestAPI_RealnameFlow 实名提交(本人)→ 审核(admin)→ 查询脱敏;越权 403。 +func TestAPI_RealnameFlow(t *testing.T) { + r := newD27Router(t) + adminTok := d25Token(t, 1, "admin") + custTok := d25Token(t, 2, "customer") + body := []byte(`{"real_name":"张三","id_card":"350203199001011234"}`) + + // customer 提交本人 → 200 + if w := doReqBody(r, http.MethodPost, "/api/v1/accounts/2/realname", custTok, "application/json", body); w.Code != http.StatusOK { + t.Fatalf("本人提交实名 = %d body=%s", w.Code, w.Body.String()) + } + // 越权:customer 给 admin(1) 提交 → 403 + if w := doReqBody(r, http.MethodPost, "/api/v1/accounts/1/realname", custTok, "application/json", body); w.Code != http.StatusForbidden { + t.Fatalf("越权提交 = %d, 期望 403", w.Code) + } + // 本人查询 → 脱敏(不含完整证件号) + w := doReq(r, http.MethodGet, "/api/v1/accounts/2/realname", custTok) + if w.Code != http.StatusOK { + t.Fatalf("查询实名 = %d", w.Code) + } + if b := w.Body.String(); contains(b, "350203199001011234") || !contains(b, "3502") { + t.Fatalf("证件号应脱敏: %s", b) + } + // customer 审核 → 403(account:write) + if w := doReqBody(r, http.MethodPost, "/api/v1/accounts/2/realname/review", custTok, "application/json", []byte(`{"approve":true}`)); w.Code != http.StatusForbidden { + t.Fatalf("customer 审核 = %d, 期望 403", w.Code) + } + // admin 审核通过 → 200 状态 1 + if w := doReqBody(r, http.MethodPost, "/api/v1/accounts/2/realname/review", adminTok, "application/json", []byte(`{"approve":true}`)); w.Code != http.StatusOK || !contains(w.Body.String(), `"status":1`) { + t.Fatalf("admin 审核 = %d body=%s", w.Code, w.Body.String()) + } + // 终态再审核 → 400(状态机) + if w := doReqBody(r, http.MethodPost, "/api/v1/accounts/2/realname/review", adminTok, "application/json", []byte(`{"approve":true}`)); w.Code != http.StatusBadRequest { + t.Fatalf("终态再审核 = %d, 期望 400", w.Code) + } + // 已通过再提交 → 400 + if w := doReqBody(r, http.MethodPost, "/api/v1/accounts/2/realname", custTok, "application/json", body); w.Code != http.StatusBadRequest { + t.Fatalf("已通过再提交 = %d, 期望 400", w.Code) + } + // 未认证 → 401 + if w := doReq(r, http.MethodGet, "/api/v1/accounts/2/realname", ""); w.Code != http.StatusUnauthorized { + t.Fatalf("未认证 = %d, 期望 401", w.Code) + } +} diff --git a/internal/api/http/v1/account_day29_test.go b/internal/api/http/v1/account_day29_test.go new file mode 100644 index 00000000..a3f9bfcf --- /dev/null +++ b/internal/api/http/v1/account_day29_test.go @@ -0,0 +1,107 @@ +// account_day29_test.go Day 29:审计查询 API(system:read 门禁)+ 拦截器联动。 +package v1 + +import ( + "net/http" + "testing" + + "go-sms/internal/service/audit" + + "github.com/gin-gonic/gin" + "github.com/glebarez/sqlite" + "gorm.io/gorm" + + "go-sms/internal/middleware" + "go-sms/internal/model/entity" + "go-sms/internal/pkg/casbin" + "go-sms/internal/service/account" +) + +// newD29Router 双账号 + 审计装配(拦截器 + 查询端点)。 +func newD29Router(t *testing.T) *gin.Engine { + t.Helper() + gin.SetMode(gin.TestMode) + db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{}) + if err != nil { + t.Fatal(err) + } + if err := db.AutoMigrate(&entity.AccountUser{}, &entity.AccountConfig{}, &entity.AccountBalanceLog{}, + &entity.SystemAlertRule{}, &entity.SystemOperateLog{}, &entity.SystemLoginLog{}); err != nil { + t.Fatal(err) + } + e, err := casbin.New(db) + if err != nil { + t.Fatal(err) + } + for _, p := range [][]string{{"admin", "*", "*"}, {"customer", "message", "write"}} { + if _, err := e.AddPolicy(p[0], p[1], p[2]); err != nil { + t.Fatal(err) + } + } + rows := []entity.AccountUser{ + {Username: "d29-admin", Role: "admin", Status: 1}, + {Username: "d29-cust", Role: "customer", Status: 1}, + } + for i := range rows { + if err := db.Create(&rows[i]).Error; err != nil { + t.Fatal(err) + } + if _, err := e.BindRole(rows[i].ID, rows[i].Role); err != nil { + t.Fatal(err) + } + } + acctSvc := account.NewService(db, account.BcryptMinCost).WithEnforcer(e) + auditSvc := audit.NewService(db) + + r := gin.New() + Register(r.Group("/api/v1"), Deps{ + Account: acctSvc, + Warning: account.NewWarningService(db, nil), + Audit: auditSvc, + Auth: middleware.AuthJWTWithChecker(d25Secret, acctSvc.CheckEnabled), + Perm: middleware.CasbinChecker(e), + }) + return r +} + +// TestAPI_AuditLogsQuery admin 触发写操作留痕 → 查询可见;customer 403。 +func TestAPI_AuditLogsQuery(t *testing.T) { + r := newD29Router(t) + adminTok := d25Token(t, 1, "admin") + custTok := d25Token(t, 2, "customer") + + // admin 充值(写操作 → 拦截器留痕) + if w := doReqBody(r, http.MethodPost, "/api/v1/accounts/2/recharge", adminTok, "application/json", []byte(`{"amount":50}`)); w.Code != http.StatusOK { + t.Fatalf("充值 = %d body=%s", w.Code, w.Body.String()) + } + // customer 查询审计 → 403(无 system:read) + if w := doReq(r, http.MethodGet, "/api/v1/audit/logs", custTok); w.Code != http.StatusForbidden { + t.Fatalf("customer 查审计 = %d, 期望 403", w.Code) + } + // admin 查询 → 200 且含充值动作留痕 + w := doReq(r, http.MethodGet, "/api/v1/audit/logs?module=account&action=recharge:post", adminTok) + if w.Code != http.StatusOK { + t.Fatalf("admin 查审计 = %d body=%s", w.Code, w.Body.String()) + } + if b := w.Body.String(); !contains(b, `"total":1`) || !contains(b, "recharge:post") || !contains(b, "admin-u") { + t.Fatalf("审计应含充值留痕: %s", b) + } + // GET 审计本身是普通 GET:不留痕(过滤条件查无) + if w := doReq(r, http.MethodGet, "/api/v1/audit/logs?action=logs:get", adminTok); w.Code != http.StatusOK || !contains(w.Body.String(), `"total":0`) { + t.Fatalf("查询自身不应留痕: %s", w.Body.String()) + } +} + +// TestAPI_AuditLoginsQuery 登录审计查询。 +func TestAPI_AuditLoginsQuery(t *testing.T) { + r := newD29Router(t) + adminTok := d25Token(t, 1, "admin") + // customer → 403 + if w := doReq(r, http.MethodGet, "/api/v1/audit/logins", d25Token(t, 2, "customer")); w.Code != http.StatusForbidden { + t.Fatalf("customer 查登录审计 = %d, 期望 403", w.Code) + } + // admin → 200 + if w := doReq(r, http.MethodGet, "/api/v1/audit/logins", adminTok); w.Code != http.StatusOK { + t.Fatalf("admin 查登录审计 = %d", w.Code) + } +} diff --git a/internal/api/http/v1/account_day30_test.go b/internal/api/http/v1/account_day30_test.go new file mode 100644 index 00000000..6f4f7df4 --- /dev/null +++ b/internal/api/http/v1/account_day30_test.go @@ -0,0 +1,231 @@ +// account_day30_test.go Day 30:阶段 2 验收全量回归(A-2.1~A-2.13)。 +// 以真实 HTTP 请求串联全部端点,等价 Postman 集合;证据映射见 docs/phase2-review.md。 +package v1 + +import ( + "context" + "encoding/json" + "net/http" + "testing" + "time" + + "github.com/gin-gonic/gin" + "github.com/glebarez/sqlite" + "golang.org/x/crypto/bcrypt" + "gorm.io/gorm" + + "go-sms/internal/middleware" + "go-sms/internal/model/entity" + "go-sms/internal/pkg/casbin" + jwtpkg "go-sms/internal/pkg/jwt" + "go-sms/internal/service/account" + "go-sms/internal/service/audit" + "go-sms/internal/service/auth" +) + +// e2eEnv 阶段 2 全量环境。 +type e2eEnv struct { + r *gin.Engine + db *gorm.DB + acct *account.Service + authSvc *auth.Service +} + +func newE2E(t *testing.T) *e2eEnv { + t.Helper() + gin.SetMode(gin.TestMode) + db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{}) + if err != nil { + t.Fatal(err) + } + if sqlDB, e := db.DB(); e == nil { + sqlDB.SetMaxOpenConns(1) + } + if err := db.AutoMigrate(&entity.AccountUser{}, &entity.AccountConfig{}, &entity.MessageDetail{}, + &entity.AccountBalanceLog{}, &entity.SystemAlertRule{}, &entity.SystemOperateLog{}, + &entity.SystemLoginLog{}); err != nil { + t.Fatal(err) + } + e, err := casbin.New(db) + if err != nil { + t.Fatal(err) + } + for _, p := range [][]string{{"admin", "*", "*"}, {"customer", "message", "write"}} { + if _, err := e.AddPolicy(p[0], p[1], p[2]); err != nil { + t.Fatal(err) + } + } + hash, _ := bcrypt.GenerateFromPassword([]byte("secret66"), bcrypt.MinCost) + admin := &entity.AccountUser{Username: "e2e-admin", PasswordHash: string(hash), Role: "admin", Status: 1} + cust := &entity.AccountUser{Username: "e2e-cust", PasswordHash: string(hash), Role: "customer", Status: 1} + if err := db.Create(admin).Error; err != nil { + t.Fatal(err) + } + if _, err := e.BindRole(admin.ID, "admin"); err != nil { + t.Fatal(err) + } + if err := db.Create(cust).Error; err != nil { + t.Fatal(err) + } + if _, err := e.BindRole(cust.ID, "customer"); err != nil { + t.Fatal(err) + } + acctSvc := account.NewService(db, account.BcryptMinCost).WithEnforcer(e) + authSvc := auth.NewService(db, jwtpkg.NewManager(d25Secret, time.Hour), nil) + env := &e2eEnv{db: db, acct: acctSvc, authSvc: authSvc} + r := gin.New() + auditSvc := audit.NewService(db) + Register(r.Group("/api/v1"), Deps{ + Account: acctSvc, + Warning: account.NewWarningService(db, nil), + Audit: auditSvc, + Auth: middleware.AuthJWTWithChecker(d25Secret, acctSvc.CheckEnabled), + AuthSvc: authSvc, + Perm: middleware.CasbinChecker(e), + }) + env.r = r + return env +} + +// loginE2E 真实登录拿 token(A-2.7)。 +func (env *e2eEnv) login(t *testing.T, username, password string) (string, int) { + t.Helper() + w := doReqBody(env.r, http.MethodPost, "/api/v1/auth/login", "", "application/json", + []byte(`{"username":"`+username+`","password":"`+password+`"}`)) + var resp struct { + Data struct { + Token string `json:"token"` + } `json:"data"` + } + tok := "" + if err := json.Unmarshal(w.Body.Bytes(), &resp); err == nil { + tok = resp.Data.Token + } + return tok, w.Code +} + +// TestPhase2E2E_AccountSystem A-2.1/2.2/2.3/2.4/2.7。 +func TestPhase2E2E_AccountSystem(t *testing.T) { + env := newE2E(t) + // A-2.7 正确密码登录返 JWT + tok, code := env.login(t, "e2e-admin", "secret66") + if code != http.StatusOK || tok == "" { + t.Fatalf("登录 = %d token空=%v", code, tok == "") + } + // A-2.1 开户 + 四协议 + w := doReqBody(env.r, http.MethodPost, "/api/v1/accounts", tok, "application/json", + []byte(`{"username":"e2e-u1","password":"secret66","role":"customer","business":3}`)) + if w.Code != http.StatusOK { + t.Fatalf("开户 = %d body=%s", w.Code, w.Body.String()) + } + for _, p := range []string{"http", "cmpp", "smpp", "web"} { + if w := doReqBody(env.r, http.MethodPut, "/api/v1/accounts/3/protocol", tok, "application/json", + []byte(`{"business":"sms","protocol":"`+p+`"}`)); w.Code != http.StatusOK { + t.Fatalf("协议 %s = %d body=%s", p, w.Code, w.Body.String()) + } + } + // A-2.2 业务线独立生效(business=3 → sms+intl) + w = doReq(env.r, http.MethodGet, "/api/v1/accounts/3/business-status", tok) + if w.Code != http.StatusOK || !contains(w.Body.String(), `"sms":true`) || !contains(w.Body.String(), `"intl":true`) { + t.Fatalf("业务线状态 = %d %s", w.Code, w.Body.String()) + } + // A-2.3 IP 白名单:非白名单 IP 拒绝 + if w := doReqBody(env.r, http.MethodPut, "/api/v1/accounts/3/ip-bindings", tok, "application/json", + []byte(`{"ips":["10.9.9.9"]}`)); w.Code != http.StatusOK { + t.Fatalf("设置白名单 = %d", w.Code) + } + ok, err := env.acct.CheckIPAllowed(context.Background(), 3, "1.2.3.4") + if err != nil || ok { + t.Fatalf("非白名单 IP 应拒绝: ok=%v err=%v", ok, err) + } + // A-2.4 审核模式切换(0→2) + if w := doReqBody(env.r, http.MethodPut, "/api/v1/accounts/3/audit-mode", tok, "application/json", + []byte(`{"business":"sms","mode":2}`)); w.Code != http.StatusOK { + t.Fatalf("审核模式 = %d body=%s", w.Code, w.Body.String()) + } + _, cfgs, _ := env.acct.GetAccount(context.Background(), 3) + smsMode := int8(-1) + for _, c := range cfgs { + if c.Business == "sms" { + smsMode = c.AuditMode + } + } + if smsMode != 2 { + t.Fatalf("审核模式未生效: sms mode=%d cfgs=%+v", smsMode, cfgs) + } +} + +// TestPhase2E2E_PermissionAndFunds A-2.5/2.6/2.8/2.9/2.10/2.11。 +func TestPhase2E2E_PermissionAndFunds(t *testing.T) { + env := newE2E(t) + adminTok, _ := env.login(t, "e2e-admin", "secret66") + custTok, _ := env.login(t, "e2e-cust", "secret66") + + // A-2.5 角色隔离:customer 访问审计(管理面)→ 403 + if w := doReq(env.r, http.MethodGet, "/api/v1/audit/logs", custTok); w.Code != http.StatusForbidden { + t.Fatalf("角色隔离 = %d, 期望 403", w.Code) + } + // A-2.6 二级权限:无 recharge 充值 → 403;授予 → 200 + if w := doReqBody(env.r, http.MethodPost, "/api/v1/accounts/2/recharge", custTok, "application/json", + []byte(`{"amount":10}`)); w.Code != http.StatusForbidden { + t.Fatalf("无权限充值 = %d, 期望 403", w.Code) + } + if w := doReq(env.r, http.MethodPost, "/api/v1/accounts/2/permissions/recharge/grant", adminTok); w.Code != http.StatusOK { + t.Fatalf("授权 = %d", w.Code) + } + if w := doReqBody(env.r, http.MethodPost, "/api/v1/accounts/2/recharge", custTok, "application/json", + []byte(`{"amount":10}`)); w.Code != http.StatusOK { + t.Fatalf("授权后充值 = %d", w.Code) + } + // A-2.8 admin 充值 100 → 余额 110(10+100) + if w := doReqBody(env.r, http.MethodPost, "/api/v1/accounts/2/recharge", adminTok, "application/json", + []byte(`{"amount":100}`)); w.Code != http.StatusOK { + t.Fatalf("admin 充值 = %d", w.Code) + } + w := doReq(env.r, http.MethodGet, "/api/v1/accounts/2/balance", custTok) + if !contains(w.Body.String(), `"balance":110`) { + t.Fatalf("余额应 110: %s", w.Body.String()) + } + // A-2.9 预警配置就绪(阈值高于余额;触发链路见 day27 单测) + if w := doReqBody(env.r, http.MethodPut, "/api/v1/accounts/2/warning", custTok, "application/json", + []byte(`{"threshold":500}`)); w.Code != http.StatusOK { + t.Fatalf("预警配置 = %d", w.Code) + } + // A-2.10 删除限制:有发送记录不可删 + if err := env.db.Create(&entity.MessageDetail{AccountID: 2, Mobile: "13800000000"}).Error; err != nil { + t.Fatal(err) + } + if w := doReq(env.r, http.MethodDelete, "/api/v1/accounts/2", adminTok); !contains(w.Body.String(), "不可删除") { + t.Fatalf("删除守卫 = %d body=%s", w.Code, w.Body.String()) + } + // A-2.11 导出仅 admin + if w := doReq(env.r, http.MethodGet, "/api/v1/accounts/export", custTok); w.Code != http.StatusForbidden { + t.Fatalf("customer 导出 = %d, 期望 403", w.Code) + } + if w := doReq(env.r, http.MethodGet, "/api/v1/accounts/export", adminTok); w.Code != http.StatusOK { + t.Fatalf("admin 导出 = %d", w.Code) + } +} + +// TestPhase2E2E_RealnameAndAudit A-2.12/2.13 + 操作留痕。 +func TestPhase2E2E_RealnameAndAudit(t *testing.T) { + env := newE2E(t) + adminTok, _ := env.login(t, "e2e-admin", "secret66") + // A-2.13 登录审计:失败+成功各留痕 + _, _ = env.login(t, "e2e-cust", "wrong-pass") + _, _ = env.login(t, "e2e-cust", "secret66") + w := doReq(env.r, http.MethodGet, "/api/v1/audit/logins?username=e2e-cust", adminTok) + if w.Code != http.StatusOK || !contains(w.Body.String(), `"total":2`) { + t.Fatalf("登录审计 = %d %s", w.Code, w.Body.String()) + } + // A-2.12 实名流转:提交 → 通过 → 状态更新 + custTok, _ := env.login(t, "e2e-cust", "secret66") + if w := doReqBody(env.r, http.MethodPost, "/api/v1/accounts/2/realname", custTok, "application/json", + []byte(`{"real_name":"李四","id_card":"350203199001019999"}`)); w.Code != http.StatusOK { + t.Fatalf("实名提交 = %d body=%s", w.Code, w.Body.String()) + } + if w := doReqBody(env.r, http.MethodPost, "/api/v1/accounts/2/realname/review", adminTok, "application/json", + []byte(`{"approve":true}`)); w.Code != http.StatusOK || !contains(w.Body.String(), `"status":1`) { + t.Fatalf("实名审核 = %d %s", w.Code, w.Body.String()) + } +} diff --git a/internal/api/http/v1/account_test.go b/internal/api/http/v1/account_test.go new file mode 100644 index 00000000..0b60fc83 --- /dev/null +++ b/internal/api/http/v1/account_test.go @@ -0,0 +1,103 @@ +package v1 + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + + "github.com/gin-gonic/gin" + "github.com/glebarez/sqlite" + "gorm.io/gorm" + + "go-sms/internal/model/entity" + "go-sms/internal/service/account" +) + +// newTestRouter 内存库 + v1 路由。 +func newTestRouter(t *testing.T) (*gin.Engine, *gorm.DB) { + t.Helper() + gin.SetMode(gin.TestMode) + db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{}) + if err != nil { + t.Fatal(err) + } + if err := db.AutoMigrate(&entity.AccountUser{}, &entity.AccountConfig{}, &entity.AccountBalanceLog{}); err != nil { + t.Fatal(err) + } + r := gin.New() + Register(r.Group("/api/v1"), Deps{Account: account.NewService(db, account.BcryptMinCost)}) + return r, db +} + +func postJSON(r *gin.Engine, path string, body any) *httptest.ResponseRecorder { + raw, _ := json.Marshal(body) + w := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, path, bytes.NewReader(raw)) + req.Header.Set("Content-Type", "application/json") + r.ServeHTTP(w, req) + return w +} + +// TestAPI_CreateAccount 验收:POST /api/v1/accounts 创建成功,库内记录正确。 +func TestAPI_CreateAccount(t *testing.T) { + r, db := newTestRouter(t) + w := postJSON(r, "/api/v1/accounts", map[string]any{ + "username": "api-cust", "password": "secret66", "role": "customer", + "business": 1, "credit_balance": 500, + }) + if w.Code != http.StatusOK { + t.Fatalf("状态码 = %d, body=%s", w.Code, w.Body.String()) + } + var resp struct { + Code string `json:"code"` + Data struct { + ID int64 `json:"id"` + } `json:"data"` + } + if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil { + t.Fatal(err) + } + if resp.Code != "ISC:000" || resp.Data.ID == 0 { + t.Fatalf("响应 = %s", w.Body.String()) + } + // DB 记录:密码哈希非明文 + 配置行存在 + var u entity.AccountUser + if err := db.First(&u, resp.Data.ID).Error; err != nil { + t.Fatal(err) + } + if u.PasswordHash == "secret66" || !account.VerifyPassword(u.PasswordHash, "secret66") { + t.Fatalf("密码未 bcrypt: %q", u.PasswordHash) + } + var n int64 + db.Model(&entity.AccountConfig{}).Where("account_id = ?", u.ID).Count(&n) + if n != 1 { + t.Fatalf("配置行 = %d", n) + } +} + +// TestAPI_CreateAccount_Duplicate 重复创建返回 ISC:400。 +func TestAPI_CreateAccount_Duplicate(t *testing.T) { + r, _ := newTestRouter(t) + body := map[string]any{"username": "dup", "password": "secret66", "role": "customer", "business": 1} + if w := postJSON(r, "/api/v1/accounts", body); w.Code != 200 { + t.Fatalf("首次创建应 200, got %d", w.Code) + } + w := postJSON(r, "/api/v1/accounts", body) + if w.Code != http.StatusBadRequest { + t.Fatalf("重复创建应 400, got %d", w.Code) + } + if !bytes.Contains(w.Body.Bytes(), []byte("ISC:400")) { + t.Fatalf("响应应含 ISC:400: %s", w.Body.String()) + } +} + +// TestAPI_CreateAccount_BadPayload 参数缺失 400。 +func TestAPI_CreateAccount_BadPayload(t *testing.T) { + r, _ := newTestRouter(t) + w := postJSON(r, "/api/v1/accounts", map[string]any{"username": "x"}) // 缺 password/role/business + if w.Code != http.StatusBadRequest { + t.Fatalf("缺参应 400, got %d", w.Code) + } +} diff --git a/internal/api/http/v1/alertsink_handler.go b/internal/api/http/v1/alertsink_handler.go new file mode 100644 index 00000000..4803e860 --- /dev/null +++ b/internal/api/http/v1/alertsink_handler.go @@ -0,0 +1,86 @@ +// alertsink_handler.go Day 53(runbook §6.2 P0):Alertmanager webhook 接收端点。 +// - POST /alerts/sink(public;生产须内网/白名单——AM 与网关同部署域) +// +// 链路:Prometheus 规则评估 → Alertmanager 分组/静默/抑制 → webhook 推送本端点 +// → Error/Warn 级结构化日志(runbook §2 定位入口)+ 可选回填通道告警留痕。 +// 验收口径(Day53):注入 firing 告警 → 网关日志 alerts_sink_alert_received 出现 = 通道通。 +package v1 + +import ( + "encoding/json" + "io" + "strings" + "time" + + "github.com/gin-gonic/gin" + "go.uber.org/zap" +) + +// amWebhookBody Alertmanager webhook 通用告警格式(v0.27 实测字段)。 +type amWebhookBody struct { + Receiver string `json:"receiver"` + Status string `json:"status"` // firing|resolved + Alerts []struct { + Status string `json:"status"` + Labels map[string]string `json:"labels"` // alertname/severity/route... + Annotations struct { + Summary string `json:"summary"` + Discovery string `json:"description"` + } `json:"annotations"` + StartsAt time.Time `json:"startsAt"` + EndsAt time.Time `json:"endsAt"` + } `json:"alerts"` +} + +const alertsSinkMaxBody = 1 << 20 // 1MB:AM 分组推送上限保护 + +type alertsSinkHandler struct{ lg *zap.Logger } + +// registerAlertsSink 挂载 AM webhook 接收(public:AM 不携带 JWT)。 +func registerAlertsSink(rg *gin.RouterGroup, lg *zap.Logger) { + if lg == nil { + return + } + h := &alertsSinkHandler{lg: lg} + rg.POST("/alerts/sink", h.sink) +} + +// sink POST /alerts/sink:逐条留痕;P0=Error 级(电话/强提醒语义对齐 runbook §0), +// 其余 Warn;resolved 状态降为 Info(恢复知会)。 +func (h *alertsSinkHandler) sink(c *gin.Context) { + raw, err := io.ReadAll(io.LimitReader(c.Request.Body, alertsSinkMaxBody)) + if err != nil || len(raw) == 0 { + c.JSON(200, gin.H{}) + return + } + var body amWebhookBody + if err := json.Unmarshal(raw, &body); err != nil { + h.lg.Warn("alerts_sink_bad_payload", zap.Error(err), zap.Int("bytes", len(raw))) + c.JSON(200, gin.H{}) + return + } + for i := range body.Alerts { + a := body.Alerts[i] + name := a.Labels["alertname"] + sev := strings.ToUpper(a.Labels["severity"]) + fields := []zap.Field{ + zap.String("alert", name), + zap.String("severity", sev), + zap.String("status", a.Status), + zap.String("route", a.Labels["route"]), + zap.String("summary", a.Annotations.Summary), + zap.String("description", a.Annotations.Discovery), + zap.Time("starts_at", a.StartsAt), + zap.Int("group_alerts", len(body.Alerts)), + } + switch { + case a.Status == "resolved": + h.lg.Info("alerts_sink_alert_received", fields...) + case sev == "P0": + h.lg.Error("alerts_sink_alert_received", fields...) + default: + h.lg.Warn("alerts_sink_alert_received", fields...) + } + } + c.JSON(200, gin.H{}) +} diff --git a/internal/api/http/v1/audit_handler.go b/internal/api/http/v1/audit_handler.go new file mode 100644 index 00000000..ea288eec --- /dev/null +++ b/internal/api/http/v1/audit_handler.go @@ -0,0 +1,87 @@ +// audit_handler.go Day 29:审计日志查询端点(system:read 门禁)。 +package v1 + +import ( + "strconv" + "time" + + "github.com/gin-gonic/gin" + + "go-sms/internal/pkg/errors" + "go-sms/internal/pkg/response" + "go-sms/internal/service/audit" +) + +// auditHandler 审计接口。 +type auditHandler struct{ svc *audit.Service } + +// logs GET /audit/logs:操作日志(操作人/账号/模块/动作/IP/时间范围过滤)。 +func (h *auditHandler) logs(c *gin.Context) { + q := &audit.OperateQuery{ + Page: intQuery(c, "page", 1), PageSize: intQuery(c, "page_size", 20), + Operator: c.Query("operator"), Module: c.Query("module"), + Action: c.Query("action"), IP: c.Query("ip"), + } + if v, err := strconv.ParseInt(c.Query("account_id"), 10, 64); err == nil && v > 0 { + q.AccountID = v + } + if t, err := parseTimeParam(c.Query("start")); err == nil { + q.Start = t + } + if t, err := parseTimeParam(c.Query("end")); err == nil { + q.End = t + } + logs, total, err := h.svc.Query(c.Request.Context(), q) + if err != nil { + response.Error(c, errors.InternalError) + return + } + response.Success(c, gin.H{"total": total, "list": logs}) +} + +// logins GET /audit/logins:登录审计(用户名/IP/仅失败/时间范围过滤)。 +func (h *auditHandler) logins(c *gin.Context) { + q := &audit.LoginQuery{ + Page: intQuery(c, "page", 1), PageSize: intQuery(c, "page_size", 20), + Username: c.Query("username"), IP: c.Query("ip"), + OnlyFailed: c.Query("only_failed") == "1", + } + if t, err := parseTimeParam(c.Query("start")); err == nil { + q.Start = t + } + if t, err := parseTimeParam(c.Query("end")); err == nil { + q.End = t + } + logs, total, err := h.svc.QueryLogin(c.Request.Context(), q) + if err != nil { + response.Error(c, errors.InternalError) + return + } + response.Success(c, gin.H{"total": total, "list": logs}) +} + +// intQuery 整型查询参数(缺省 def)。 +func intQuery(c *gin.Context, key string, def int) int { + if v, err := strconv.Atoi(c.Query(key)); err == nil && v > 0 { + return v + } + return def +} + +// parseTimeParam 时间参数(2006-01-02 或 2006-01-02 15:04:05)。 +func parseTimeParam(s string) (*time.Time, error) { + if s == "" { + return nil, errEmptyParam + } + for _, layout := range []string{"2006-01-02 15:04:05", "2006-01-02"} { + if t, err := time.ParseInLocation(layout, s, time.Local); err == nil { + return &t, nil + } + } + return nil, errBadTime +} + +var ( + errEmptyParam = errors.InvalidParam.WithMsg("空时间参数") + errBadTime = errors.InvalidParam.WithMsg("时间格式应为 2006-01-02[ 15:04:05]") +) diff --git a/internal/api/http/v1/auth.go b/internal/api/http/v1/auth.go new file mode 100644 index 00000000..1c6e5e55 --- /dev/null +++ b/internal/api/http/v1/auth.go @@ -0,0 +1,64 @@ +// auth.go 认证接口(Day 24):POST /auth/login(公开)、/auth/logout、/auth/refresh(受保护)。 +package v1 + +import ( + "github.com/gin-gonic/gin" + + "go-sms/internal/middleware" + "go-sms/internal/pkg/errors" + "go-sms/internal/pkg/response" + "go-sms/internal/service/auth" +) + +// authHandler 认证接口。 +type authHandler struct { + svc *auth.Service +} + +// login POST /api/v1/auth/login(公开,无需 JWT)。 +func (h *authHandler) login(c *gin.Context) { + var req auth.LoginRequest + if err := c.ShouldBindJSON(&req); err != nil { + response.ErrorWithMsg(c, errors.InvalidParam, "参数错误: "+err.Error()) + return + } + res, err := h.svc.Login(c.Request.Context(), req.Username, req.Password, c.ClientIP()) + if err != nil { + if bizErr, ok := err.(*errors.Error); ok { + response.Error(c, bizErr) + return + } + response.Error(c, errors.InternalError) + return + } + response.Success(c, res) +} + +// logout POST /api/v1/auth/logout:当前令牌写入黑名单(TTL=剩余有效期)。 +func (h *authHandler) logout(c *gin.Context) { + if err := h.svc.Logout(c.Request.Context(), middleware.BearerToken(c)); err != nil { + if bizErr, ok := err.(*errors.Error); ok { + response.Error(c, bizErr) + return + } + response.Error(c, errors.InternalError) + return + } + response.Success(c, gin.H{"revoked": true}) +} + +// refresh POST /api/v1/auth/refresh:旧令牌作废并签发新令牌(轮换)。 +func (h *authHandler) refresh(c *gin.Context) { + v, _ := c.Get(middleware.ContextKeyClaims) + claims, _ := v.(*middleware.Claims) + res, err := h.svc.Refresh(c.Request.Context(), middleware.BearerToken(c), claims) + if err != nil { + if bizErr, ok := err.(*errors.Error); ok { + response.Error(c, bizErr) + return + } + response.Error(c, errors.InternalError) + return + } + response.Success(c, res) +} diff --git a/internal/api/http/v1/auth_test.go b/internal/api/http/v1/auth_test.go new file mode 100644 index 00000000..742aa601 --- /dev/null +++ b/internal/api/http/v1/auth_test.go @@ -0,0 +1,178 @@ +// auth_test.go 认证端点全链路测试(Day 24 验收): +// 登录 → 受保护接口 → 登出即失效 → 刷新轮换 → 锁定。 +package v1 + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "strconv" + "testing" + "time" + + "github.com/gin-gonic/gin" + "github.com/glebarez/sqlite" + "golang.org/x/crypto/bcrypt" + "gorm.io/gorm" + + "go-sms/internal/middleware" + "go-sms/internal/model/entity" + jwtpkg "go-sms/internal/pkg/jwt" + "go-sms/internal/service/account" + "go-sms/internal/service/auth" +) + +const d24Secret = "d24-api-secret" + +// newAuthRouter 装配带认证中间件的完整 v1 路由。 +func newD24Router(t *testing.T) (*gin.Engine, *gorm.DB) { + t.Helper() + gin.SetMode(gin.TestMode) + db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{}) + if err != nil { + t.Fatal(err) + } + if err := db.AutoMigrate(&entity.AccountUser{}, &entity.AccountConfig{}, &entity.AccountBalanceLog{}); err != nil { + t.Fatal(err) + } + acctSvc := account.NewService(db, account.BcryptMinCost) + authSvc := auth.NewService(db, jwtpkg.NewManager(d24Secret, time.Hour), auth.NewMemoryTokenStore()) + + r := gin.New() + Register(r.Group("/api/v1"), Deps{ + Account: acctSvc, + AuthSvc: authSvc, + Auth: middleware.AuthJWTWithRevocation(d24Secret, authSvc.Revoked, acctSvc.CheckEnabled), + }) + // 种子账号 + hash, _ := bcrypt.GenerateFromPassword([]byte("secret66"), bcrypt.MinCost) + if err := db.Create(&entity.AccountUser{ + Username: "d24-api", PasswordHash: string(hash), Role: "ops", Status: 1, + }).Error; err != nil { + t.Fatal(err) + } + return r, db +} + +// doReq 通用请求:可选 Bearer 令牌与 JSON 体。 +func doJSON(r *gin.Engine, method, path, token string, body any) *httptest.ResponseRecorder { + raw, _ := json.Marshal(body) + w := httptest.NewRecorder() + req := httptest.NewRequest(method, path, bytes.NewReader(raw)) + req.Header.Set("Content-Type", "application/json") + if token != "" { + req.Header.Set("Authorization", "Bearer "+token) + } + r.ServeHTTP(w, req) + return w +} + +// loginOK 登录成功并返回令牌。 +func loginOK(t *testing.T, r *gin.Engine) string { + t.Helper() + w := doJSON(r, http.MethodPost, "/api/v1/auth/login", "", map[string]string{ + "username": "d24-api", "password": "secret66", + }) + if w.Code != http.StatusOK { + t.Fatalf("登录 = %d, body=%s", w.Code, w.Body.String()) + } + var resp struct { + Data struct { + Token string `json:"token"` + } `json:"data"` + } + if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil { + t.Fatal(err) + } + if resp.Data.Token == "" { + t.Fatalf("未返回 token: %s", w.Body.String()) + } + return resp.Data.Token +} + +// TestAPI_AuthFlow 验收主线:登录可用 → 受保护接口放行 → 登出后同一令牌 401。 +func TestAPI_AuthFlow(t *testing.T) { + r, db := newD24Router(t) + var u entity.AccountUser + if err := db.Where("username = ?", "d24-api").First(&u).Error; err != nil { + t.Fatal(err) + } + + // 登录前:受保护接口 401 + if w := doJSON(r, http.MethodGet, "/api/v1/accounts/1", "", nil); w.Code != http.StatusUnauthorized { + t.Fatalf("未登录访问 = %d, 期望 401", w.Code) + } + token := loginOK(t, r) + // 登录后:放行 + if w := doJSON(r, http.MethodGet, "/api/v1/accounts/"+strconv.FormatInt(u.ID, 10), token, nil); w.Code != http.StatusOK { + t.Fatalf("登录后访问 = %d, body=%s", w.Code, w.Body.String()) + } + // 登出 + if w := doJSON(r, http.MethodPost, "/api/v1/auth/logout", token, nil); w.Code != http.StatusOK { + t.Fatalf("登出 = %d, body=%s", w.Code, w.Body.String()) + } + // 登出后:同一令牌立即失效 + if w := doJSON(r, http.MethodGet, "/api/v1/accounts/"+strconv.FormatInt(u.ID, 10), token, nil); w.Code != http.StatusUnauthorized { + t.Fatalf("登出后访问 = %d, 期望 401(令牌已注销)", w.Code) + } +} + +// TestAPI_AuthRefresh 刷新:旧令牌作废,新令牌可用。 +func TestAPI_AuthRefresh(t *testing.T) { + r, _ := newD24Router(t) + old := loginOK(t, r) + + w := doJSON(r, http.MethodPost, "/api/v1/auth/refresh", old, nil) + if w.Code != http.StatusOK { + t.Fatalf("刷新 = %d, body=%s", w.Code, w.Body.String()) + } + var resp struct { + Data struct { + Token string `json:"token"` + } `json:"data"` + } + if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil { + t.Fatal(err) + } + if resp.Data.Token == "" || resp.Data.Token == old { + t.Fatalf("新令牌异常: %s", w.Body.String()) + } + // 旧令牌 401,新令牌 200 + if w := doJSON(r, http.MethodGet, "/api/v1/accounts", old, nil); w.Code != http.StatusUnauthorized { + t.Fatalf("旧令牌 = %d, 期望 401", w.Code) + } + if w := doJSON(r, http.MethodGet, "/api/v1/accounts", resp.Data.Token, nil); w.Code != http.StatusOK { + t.Fatalf("新令牌 = %d, 期望 200", w.Code) + } +} + +// TestAPI_AuthLogin_Locked 验收:错误密码 5 次后第 5 次即 429,正确密码也被拒。 +func TestAPI_AuthLogin_Locked(t *testing.T) { + r, _ := newD24Router(t) + body := map[string]string{"username": "d24-api", "password": "wrong-pass"} + + for i := 1; i <= 4; i++ { + if w := doJSON(r, http.MethodPost, "/api/v1/auth/login", "", body); w.Code != http.StatusUnauthorized { + t.Fatalf("第 %d 次错误密码 = %d, 期望 401", i, w.Code) + } + } + if w := doJSON(r, http.MethodPost, "/api/v1/auth/login", "", body); w.Code != http.StatusTooManyRequests { + t.Fatalf("第 5 次 = %d, 期望 429 锁定, body=%s", w.Code, w.Body.String()) + } + w := doJSON(r, http.MethodPost, "/api/v1/auth/login", "", map[string]string{ + "username": "d24-api", "password": "secret66", + }) + if w.Code != http.StatusTooManyRequests { + t.Fatalf("锁定期内正确密码 = %d, 期望 429", w.Code) + } +} + +// TestAPI_AuthLogin_BadRequest 缺参 400。 +func TestAPI_AuthLogin_BadRequest(t *testing.T) { + r, _ := newD24Router(t) + w := doJSON(r, http.MethodPost, "/api/v1/auth/login", "", map[string]string{"username": "x"}) + if w.Code != http.StatusBadRequest { + t.Fatalf("缺参 = %d, 期望 400", w.Code) + } +} diff --git a/internal/api/http/v1/channel_day35_test.go b/internal/api/http/v1/channel_day35_test.go new file mode 100644 index 00000000..20825bd9 --- /dev/null +++ b/internal/api/http/v1/channel_day35_test.go @@ -0,0 +1,211 @@ +// channel_day35_test.go Day 35:通道路由——CRUD/测试工具/拦截(channel:write 门禁)。 +package v1 + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/gin-gonic/gin" + "github.com/glebarez/sqlite" + "gorm.io/gorm" + + "go-sms/internal/middleware" + "go-sms/internal/model/entity" + "go-sms/internal/pkg/casbin" + "go-sms/internal/service/account" + "go-sms/internal/service/audit" + "go-sms/internal/service/channel" + "go-sms/internal/service/template" +) + +// newD35Router 双账号(admin 通配/customer)+ 通道服务。 +func newD35Router(t *testing.T) *gin.Engine { + t.Helper() + gin.SetMode(gin.TestMode) + db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{}) + if err != nil { + t.Fatal(err) + } + if sqlDB, e := db.DB(); e == nil { + sqlDB.SetMaxOpenConns(1) + } + if err := db.AutoMigrate(&entity.AccountUser{}, &entity.AccountConfig{}, &entity.AccountBalanceLog{}, + &entity.SystemAlertRule{}, &entity.SystemOperateLog{}, &entity.SystemLoginLog{}, + &entity.ChannelChannel{}, &entity.ChannelGroup{}, &entity.ChannelGroupItem{}, &entity.ChannelLog{}, + &entity.TemplateSMS{}); err != nil { + t.Fatal(err) + } + e, err := casbin.New(db) + if err != nil { + t.Fatal(err) + } + for _, p := range [][]string{{"admin", "*", "*"}, {"customer", "message", "write"}} { + if _, err := e.AddPolicy(p[0], p[1], p[2]); err != nil { + t.Fatal(err) + } + } + rows := []entity.AccountUser{ + {Username: "d35-admin", Role: "admin", Status: 1}, + {Username: "d35-cust", Role: "customer", Status: 1}, + } + for i := range rows { + if err := db.Create(&rows[i]).Error; err != nil { + t.Fatal(err) + } + if _, err := e.BindRole(rows[i].ID, rows[i].Role); err != nil { + t.Fatal(err) + } + } + acctSvc := account.NewService(db, account.BcryptMinCost).WithEnforcer(e) + r := gin.New() + Register(r.Group("/api/v1"), Deps{ + Account: acctSvc, + Warning: account.NewWarningService(db, nil), + Audit: audit.NewService(db), + Channel: channel.NewService(db), + Template: template.NewService(db), // Day 41:模板/预估(customer 角色有 message:write 策略) + Auth: middleware.AuthJWTWithChecker(d25Secret, acctSvc.CheckEnabled), + Perm: middleware.CasbinChecker(e), + }) + return r +} + +// TestAPI_ChannelCRUDAndTest admin 全通 / customer 403 / 测试工具返回 MsgID / 拦截配置。 +func TestAPI_ChannelCRUDAndTest(t *testing.T) { + r := newD35Router(t) + adminTok := d25Token(t, 1, "admin") + custTok := d25Token(t, 2, "customer") + + body := []byte(`{"name":"测试通道","code":"api-ch-1","protocol":"http","host":"http://nonexistent-upstream"}`) + // customer 创建 → 403 + if w := doReqBody(r, http.MethodPost, "/api/v1/channels", custTok, "application/json", body); w.Code != http.StatusForbidden { + t.Fatalf("customer 创建通道 = %d, 期望 403", w.Code) + } + // admin 创建 → 200 + if w := doReqBody(r, http.MethodPost, "/api/v1/channels", adminTok, "application/json", body); w.Code != http.StatusOK { + t.Fatalf("admin 创建 = %d body=%s", w.Code, w.Body.String()) + } + // 重复 code → 400 + if w := doReqBody(r, http.MethodPost, "/api/v1/channels", adminTok, "application/json", body); w.Code != http.StatusBadRequest { + t.Fatalf("重复 code = %d", w.Code) + } + // 列表 + if w := doReq(r, http.MethodGet, "/api/v1/channels?protocol=http&status=1", adminTok); w.Code != http.StatusOK || !contains(w.Body.String(), `"total":1`) { + t.Fatalf("列表 = %d %s", w.Code, w.Body.String()) + } + // 详情 + if w := doReq(r, http.MethodGet, "/api/v1/channels/1", adminTok); w.Code != http.StatusOK || !contains(w.Body.String(), "api-ch-1") { + t.Fatalf("详情 = %d", w.Code) + } + // 拦截配置:set + get + ic := []byte(`{"night_limit":1,"day_limit":100,"block_regions":"新疆"}`) + if w := doReqBody(r, http.MethodPut, "/api/v1/channels/1/intercept", adminTok, "application/json", ic); w.Code != http.StatusOK { + t.Fatalf("拦截配置 = %d body=%s", w.Code, w.Body.String()) + } + if w := doReq(r, http.MethodGet, "/api/v1/channels/1/intercept", adminTok); w.Code != http.StatusOK || !contains(w.Body.String(), "新疆") { + t.Fatalf("拦截查询 = %d %s", w.Code, w.Body.String()) + } + // 测试工具(上游不可达 → 错误但非 panic;停用后 400) + if w := doReqBody(r, http.MethodPost, "/api/v1/channels/1/test", adminTok, "application/json", + []byte(`{"mobile":"13800001111","content":"t"}`)); w.Code != http.StatusOK { + // 不可达上游返回 500/错误——此处验证链路与参数校验;不视为失败 + t.Logf("测试工具(不可达上游)= %d(预期错误)", w.Code) + } + // 缺参 → 400 + if w := doReqBody(r, http.MethodPost, "/api/v1/channels/1/test", adminTok, "application/json", []byte(`{}`)); w.Code != http.StatusBadRequest { + t.Fatalf("缺参 = %d", w.Code) + } + // 删除守卫:启用中拒删 + if w := doReq(r, http.MethodDelete, "/api/v1/channels/1", adminTok); w.Code != http.StatusBadRequest { + t.Fatalf("启用删除 = %d", w.Code) + } +} + +// TestAPI_ChannelGroupAndItems 通道组 CRUD/成员管理/权限/守卫。 +func TestAPI_ChannelGroupAndItems(t *testing.T) { + r := newD35Router(t) + adminTok := d25Token(t, 1, "admin") + custTok := d25Token(t, 2, "customer") + + // customer 建组 → 403 + if w := doReqBody(r, http.MethodPost, "/api/v1/channel-groups", custTok, "application/json", []byte(`{"name":"g"}`)); w.Code != http.StatusForbidden { + t.Fatalf("customer 建组 = %d", w.Code) + } + // admin 建组 → 200 + if w := doReqBody(r, http.MethodPost, "/api/v1/channel-groups", adminTok, "application/json", []byte(`{"name":"主路由组"}`)); w.Code != http.StatusOK { + t.Fatalf("建组 = %d %s", w.Code, w.Body.String()) + } + // 建两通道 + 成员(权重 7/3) + for _, body := range []string{ + `{"name":"甲","code":"ga","protocol":"http","host":"http://a"}`, + `{"name":"乙","code":"gb","protocol":"http","host":"http://b"}`, + } { + if w := doReqBody(r, http.MethodPost, "/api/v1/channels", adminTok, "application/json", []byte(body)); w.Code != http.StatusOK { + t.Fatalf("建通道 = %d", w.Code) + } + } + if w := doReqBody(r, http.MethodPost, "/api/v1/channel-groups/1/items", adminTok, "application/json", + []byte(`{"channel_id":1,"step":3,"weight":7}`)); w.Code != http.StatusOK { + t.Fatalf("加成员 = %d %s", w.Code, w.Body.String()) + } + // 非法 step/权重 → 400 + if w := doReqBody(r, http.MethodPost, "/api/v1/channel-groups/1/items", adminTok, "application/json", + []byte(`{"channel_id":2,"step":3,"weight":0}`)); w.Code != http.StatusBadRequest { + t.Fatalf("weight=0 = %d", w.Code) + } + if w := doReqBody(r, http.MethodPost, "/api/v1/channel-groups/1/items", adminTok, "application/json", + []byte(`{"channel_id":2,"step":9}`)); w.Code != http.StatusBadRequest { + t.Fatalf("step=9 = %d", w.Code) + } + if w := doReqBody(r, http.MethodPost, "/api/v1/channel-groups/1/items", adminTok, "application/json", + []byte(`{"channel_id":2,"step":3,"weight":3}`)); w.Code != http.StatusOK { + t.Fatalf("乙成员 = %d", w.Code) + } + // 组详情含成员(权重 7/3 可见) + if w := doReq(r, http.MethodGet, "/api/v1/channel-groups/1", adminTok); w.Code != http.StatusOK || + !contains(w.Body.String(), `"weight":7`) || !contains(w.Body.String(), `"weight":3`) { + t.Fatalf("组详情 = %d %s", w.Code, w.Body.String()) + } + // 通道删除守卫:被组引用拒删 + _ = doReqBody(r, http.MethodPut, "/api/v1/channels/1/status", adminTok, "application/json", []byte(`{"status":0}`)) + if w := doReq(r, http.MethodDelete, "/api/v1/channels/1", adminTok); w.Code != http.StatusBadRequest || !contains(w.Body.String(), "引用") { + t.Fatalf("引用守卫 = %d %s", w.Code, w.Body.String()) + } + // 移除成员后组可删 + if w := doReq(r, http.MethodDelete, "/api/v1/channel-groups/1/items/1", adminTok); w.Code != http.StatusOK { + t.Fatalf("移除成员 = %d", w.Code) + } + if w := doReq(r, http.MethodDelete, "/api/v1/channel-groups/1/items/2", adminTok); w.Code != http.StatusOK { + t.Fatalf("移除成员2 = %d", w.Code) + } + if w := doReq(r, http.MethodDelete, "/api/v1/channel-groups/1", adminTok); w.Code != http.StatusOK { + t.Fatalf("删组 = %d %s", w.Code, w.Body.String()) + } +} + +// newUpstream35 可达上游(httpadapter 契约)。 +func newUpstream35(t *testing.T) *httptest.Server { + t.Helper() + return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write([]byte(`{"code":0,"msg":"ok","data":{"message_id":"up-35"}}`)) + })) +} + +// TestAPI_ChannelTestWithUpstream http 通道 + 可达上游:测试工具返回 MsgID(闭环)。 +func TestAPI_ChannelTestWithUpstream(t *testing.T) { + r := newD35Router(t) + adminTok := d25Token(t, 1, "admin") + up := newUpstream35(t) + defer up.Close() + + if w := doReqBody(r, http.MethodPost, "/api/v1/channels", adminTok, "application/json", + []byte(`{"name":"ok","code":"api-ch-2","protocol":"http","host":"`+up.URL+`"}`)); w.Code != http.StatusOK { + t.Fatalf("创建 = %d", w.Code) + } + w := doReqBody(r, http.MethodPost, "/api/v1/channels/1/test", adminTok, "application/json", + []byte(`{"mobile":"13800001111","content":"验证"}`)) + if w.Code != http.StatusOK || !contains(w.Body.String(), "up-35") { + t.Fatalf("测试工具 = %d %s", w.Code, w.Body.String()) + } +} diff --git a/internal/api/http/v1/channel_day39_test.go b/internal/api/http/v1/channel_day39_test.go new file mode 100644 index 00000000..b45efefc --- /dev/null +++ b/internal/api/http/v1/channel_day39_test.go @@ -0,0 +1,40 @@ +// channel_day39_test.go Day 39:链路状态/回执复核端点(发送真实性 WEB 验收)。 +package v1 + +import ( + "net/http" + "strings" + "testing" +) + +// TestAPI_LinkStatusAndReceipts link-status(未建链 running=false)/receipts(空列表)/404。 +func TestAPI_LinkStatusAndReceipts(t *testing.T) { + r := newD35Router(t) + adminTok := d25Token(t, 1, "admin") + + // 建一条 http 通道(未建链)。 + w := doReqBody(r, http.MethodPost, "/api/v1/channels", adminTok, "application/json", + []byte(`{"name":"d39","code":"d39-ch","protocol":"http","host":"http://127.0.0.1:1"}`)) + if w.Code != http.StatusOK { + t.Fatalf("创建通道 = %d: %s", w.Code, w.Body.String()) + } + // link-status:未建链 → running=false 视图。 + w = doReq(r, http.MethodGet, "/api/v1/channels/1/link-status", adminTok) + if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), `"running":false`) { + t.Fatalf("link-status = %d: %s", w.Code, w.Body.String()) + } + // receipts:空列表。 + w = doReq(r, http.MethodGet, "/api/v1/channels/1/receipts?limit=10", adminTok) + if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), `"list":[]`) { + t.Fatalf("receipts = %d: %s", w.Code, w.Body.String()) + } + // 不存在通道 → 404 业务错误。 + w = doReq(r, http.MethodGet, "/api/v1/channels/999/link-status", adminTok) + if w.Code != http.StatusNotFound { + t.Fatalf("999 link-status = %d, 期望 404", w.Code) + } + w = doReq(r, http.MethodGet, "/api/v1/channels/999/receipts", adminTok) + if w.Code != http.StatusNotFound { + t.Fatalf("999 receipts = %d, 期望 404", w.Code) + } +} diff --git a/internal/api/http/v1/channel_day40_test.go b/internal/api/http/v1/channel_day40_test.go new file mode 100644 index 00000000..000704dc --- /dev/null +++ b/internal/api/http/v1/channel_day40_test.go @@ -0,0 +1,51 @@ +// channel_day40_test.go Day 40:监控快照/WS 升级/通道日志端点(A-3.13/A-3.14 WEB 验收)。 +package v1 + +import ( + "net/http" + "strings" + "testing" +) + +// TestAPI_MonitorSnapshotAndLogs 验收:monitor 快照(数组)/logs 空列表/kind 过滤/未知通道 404。 +func TestAPI_MonitorSnapshotAndLogs(t *testing.T) { + r := newD35Router(t) + adminTok := d25Token(t, 1, "admin") + + // 建一条通道。 + w := doReqBody(r, http.MethodPost, "/api/v1/channels", adminTok, "application/json", + []byte(`{"name":"d40","code":"d40-ch","protocol":"http","host":"http://127.0.0.1:1"}`)) + if w.Code != http.StatusOK { + t.Fatalf("创建通道 = %d: %s", w.Code, w.Body.String()) + } + // monitor 快照:含通道 1 的视图(HTTP 轮询口径,与 WS 帧同构)。 + w = doReq(r, http.MethodGet, "/api/v1/channels/monitor", adminTok) + if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), `"channel_id":1`) { + t.Fatalf("monitor = %d: %s", w.Code, w.Body.String()) + } + // logs:空列表。 + w = doReq(r, http.MethodGet, "/api/v1/channels/1/logs", adminTok) + if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), `"list":[]`) { + t.Fatalf("logs = %d: %s", w.Code, w.Body.String()) + } + // kind 过滤参数路径。 + w = doReq(r, http.MethodGet, "/api/v1/channels/1/logs?kind=disconnect&page=1&page_size=10", adminTok) + if w.Code != http.StatusOK { + t.Fatalf("logs 过滤 = %d: %s", w.Code, w.Body.String()) + } + // 未知通道 → 404。 + w = doReq(r, http.MethodGet, "/api/v1/channels/999/logs", adminTok) + if w.Code != http.StatusNotFound { + t.Fatalf("999 logs = %d 期望 404", w.Code) + } +} + +// TestAPI_MonitorWS WS 握手守卫:非 WS 升级请求 → 400(升级器拒绝)。 +func TestAPI_MonitorWS(t *testing.T) { + r := newD35Router(t) + tok := d25Token(t, 1, "admin") + w := doReq(r, http.MethodGet, "/api/v1/channels/monitor/ws", tok) + if w.Code != http.StatusBadRequest { + t.Fatalf("非 WS 握手应 400: %d", w.Code) + } +} diff --git a/internal/api/http/v1/channel_handler.go b/internal/api/http/v1/channel_handler.go new file mode 100644 index 00000000..990b1e98 --- /dev/null +++ b/internal/api/http/v1/channel_handler.go @@ -0,0 +1,388 @@ +// channel_handler.go Day 35:通道 CRUD/测试工具/拦截配置端点。 +package v1 + +import ( + "strconv" + "time" + + "github.com/gin-gonic/gin" + + "go-sms/internal/middleware" + "go-sms/internal/pkg/errors" + "go-sms/internal/pkg/response" + "go-sms/internal/service/channel" + "go-sms/internal/service/channel/pool" +) + +// channelHandler 通道接口。 +type channelHandler struct{ svc *channel.Service } + +// registerChannelRoutes 注册通道路由(channel:write 门禁)。 +func registerChannelRoutes(protected *gin.RouterGroup, perm middleware.PermissionChecker, svc *channel.Service, ups *channel.UpstreamService) { + h := &channelHandler{svc: svc} + gate := func(obj, act string) gin.HandlerFunc { + return middleware.RequirePermission(perm, obj, act) + } + protected.POST("/channels", gate("channel", "write"), h.create) + protected.GET("/channels", h.list) + // Day 40:实时监控(WS 2s)+通道日志(A-3.13/A-3.14)——静态段须先于 /channels/:id 注册, + // 否则 gin 树将 monitor 吞入 :id 参数段(h.get("monitor") 404)。 + registerMonitorRoutes(protected, svc) + // Day 41(清债③):上家管理——同样须先于 /channels/:id(静态段优先)。 + if ups != nil { + uh := &upstreamHandler{svc: ups} + protected.GET("/channels/upstreams", uh.list) + protected.POST("/channels/upstreams", gate("channel", "write"), uh.create) + protected.PUT("/channels/upstreams/:id", gate("channel", "write"), uh.update) + protected.DELETE("/channels/upstreams/:id", gate("channel", "write"), uh.remove) + } + protected.GET("/channels/:id", h.get) + protected.PUT("/channels/:id", gate("channel", "write"), h.update) + protected.PUT("/channels/:id/status", gate("channel", "write"), h.setStatus) + protected.DELETE("/channels/:id", gate("channel", "write"), h.remove) + protected.POST("/channels/:id/test", gate("channel", "write"), h.test) + protected.GET("/channels/:id/intercept", h.getIntercept) + protected.PUT("/channels/:id/intercept", gate("channel", "write"), h.setIntercept) + // Day 38:价格时间线(分时成本价) + protected.POST("/channels/:id/prices", gate("channel", "write"), h.setPrice) + protected.GET("/channels/:id/prices", h.listPrices) + protected.GET("/channels/:id/prices/current", h.currentPrice) + protected.DELETE("/channels/:id/prices/:pid", gate("channel", "write"), h.removePrice) + // Day 39:链路状态与回执复核(发送真实性 WEB 验收,数据源自内存) + protected.GET("/channels/:id/link-status", h.linkStatus) + protected.GET("/channels/:id/receipts", h.linkReceipts) + // Day 36:通道组与成员(channel:write) + protected.POST("/channel-groups", gate("channel", "write"), h.createGroup) + protected.GET("/channel-groups", h.listGroups) + protected.GET("/channel-groups/:id", h.getGroup) + protected.PUT("/channel-groups/:id", gate("channel", "write"), h.updateGroup) + protected.DELETE("/channel-groups/:id", gate("channel", "write"), h.removeGroup) + protected.POST("/channel-groups/:id/items", gate("channel", "write"), h.addItem) + protected.DELETE("/channel-groups/:id/items/:itemId", gate("channel", "write"), h.removeItem) +} + +// createGroup POST /channel-groups {name}。 +func (h *channelHandler) createGroup(c *gin.Context) { + var req struct { + Name string `json:"name" binding:"required"` + } + if err := c.ShouldBindJSON(&req); err != nil { + response.ErrorWithMsg(c, errors.InvalidParam, "参数错误: "+err.Error()) + return + } + g, err := h.svc.CreateGroup(c.Request.Context(), req.Name) + if err != nil { + bizResp(c, err) + return + } + response.Success(c, gin.H{"id": g.ID, "name": g.Name, "status": g.Status}) +} + +// listGroups GET /channel-groups。 +func (h *channelHandler) listGroups(c *gin.Context) { + list, err := h.svc.ListGroups(c.Request.Context()) + if err != nil { + bizResp(c, err) + return + } + response.Success(c, gin.H{"total": len(list), "list": list}) +} + +// getGroup GET /channel-groups/:id(含成员与通道摘要)。 +func (h *channelHandler) getGroup(c *gin.Context) { + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + d, err := h.svc.GetGroup(c.Request.Context(), id) + if err != nil { + bizResp(c, err) + return + } + response.Success(c, d) +} + +// updateGroup PUT /channel-groups/:id。 +func (h *channelHandler) updateGroup(c *gin.Context) { + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + var fields map[string]any + if err := c.ShouldBindJSON(&fields); err != nil { + response.ErrorWithMsg(c, errors.InvalidParam, "参数错误: "+err.Error()) + return + } + if err := h.svc.UpdateGroup(c.Request.Context(), id, fields); err != nil { + bizResp(c, err) + return + } + response.Success(c, gin.H{"id": id}) +} + +// removeGroup DELETE /channel-groups/:id(须先清空成员)。 +func (h *channelHandler) removeGroup(c *gin.Context) { + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + if err := h.svc.DeleteGroup(c.Request.Context(), id); err != nil { + bizResp(c, err) + return + } + response.Success(c, gin.H{"id": id, "deleted": true}) +} + +// addItem POST /channel-groups/:id/items。 +func (h *channelHandler) addItem(c *gin.Context) { + gid, _ := strconv.ParseInt(c.Param("id"), 10, 64) + var req channel.AddItemReq + if err := c.ShouldBindJSON(&req); err != nil { + response.ErrorWithMsg(c, errors.InvalidParam, "参数错误: "+err.Error()) + return + } + it, err := h.svc.AddItem(c.Request.Context(), gid, &req) + if err != nil { + bizResp(c, err) + return + } + response.Success(c, it) +} + +// removeItem DELETE /channel-groups/:id/items/:itemId。 +func (h *channelHandler) removeItem(c *gin.Context) { + gid, _ := strconv.ParseInt(c.Param("id"), 10, 64) + itemID, _ := strconv.ParseInt(c.Param("itemId"), 10, 64) + if err := h.svc.RemoveItem(c.Request.Context(), gid, itemID); err != nil { + bizResp(c, err) + return + } + response.Success(c, gin.H{"id": itemID, "deleted": true}) +} + +// bizResp 业务错误透传。 +func bizResp(c *gin.Context, err error) { + if bizErr, ok := err.(*errors.Error); ok { + response.Error(c, bizErr) + return + } + c.Set("biz_error", err.Error()) + response.Error(c, errors.InternalError) +} + +// create POST /channels:创建通道。 +func (h *channelHandler) create(c *gin.Context) { + var req channel.CreateReq + if err := c.ShouldBindJSON(&req); err != nil { + response.ErrorWithMsg(c, errors.InvalidParam, "参数错误: "+err.Error()) + return + } + ch, err := h.svc.Create(c.Request.Context(), &req) + if err != nil { + bizResp(c, err) + return + } + response.Success(c, gin.H{"id": ch.ID, "code": ch.Code, "protocol": ch.Protocol, "status": ch.Status}) +} + +// list GET /channels:分页过滤(name/protocol/status)。 +func (h *channelHandler) list(c *gin.Context) { + q := &channel.ListQuery{ + Page: intQuery(c, "page", 1), PageSize: intQuery(c, "page_size", 20), + Name: c.Query("name"), Protocol: c.Query("protocol"), + } + if v := c.Query("status"); v != "" { + st, _ := strconv.Atoi(v) + q.Status = int8(st) + } else { + q.Status = -1 + } + list, total, err := h.svc.List(c.Request.Context(), q) + if err != nil { + bizResp(c, err) + return + } + response.Success(c, gin.H{"total": total, "list": list}) +} + +// get GET /channels/:id。 +func (h *channelHandler) get(c *gin.Context) { + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + ch, err := h.svc.Get(c.Request.Context(), id) + if err != nil { + bizResp(c, err) + return + } + response.Success(c, ch) +} + +// update PUT /channels/:id:白名单字段。 +func (h *channelHandler) update(c *gin.Context) { + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + var fields map[string]any + if err := c.ShouldBindJSON(&fields); err != nil { + response.ErrorWithMsg(c, errors.InvalidParam, "参数错误: "+err.Error()) + return + } + if err := h.svc.Update(c.Request.Context(), id, fields); err != nil { + bizResp(c, err) + return + } + response.Success(c, gin.H{"id": id}) +} + +// setStatus PUT /channels/:id/status {status}。 +func (h *channelHandler) setStatus(c *gin.Context) { + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + var req struct { + Status int8 `json:"status"` + } + if err := c.ShouldBindJSON(&req); err != nil { + response.ErrorWithMsg(c, errors.InvalidParam, "参数错误: "+err.Error()) + return + } + if err := h.svc.SetStatus(c.Request.Context(), id, req.Status); err != nil { + bizResp(c, err) + return + } + response.Success(c, gin.H{"id": id, "status": req.Status}) +} + +// remove DELETE /channels/:id(须先停用)。 +func (h *channelHandler) remove(c *gin.Context) { + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + if err := h.svc.Delete(c.Request.Context(), id); err != nil { + bizResp(c, err) + return + } + response.Success(c, gin.H{"id": id, "deleted": true}) +} + +// test POST /channels/:id/test {mobile, content}:测试工具(真实发送,返回上游 MsgID)。 +func (h *channelHandler) test(c *gin.Context) { + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + var req struct { + Mobile string `json:"mobile" binding:"required"` + Content string `json:"content" binding:"required"` + } + if err := c.ShouldBindJSON(&req); err != nil { + response.ErrorWithMsg(c, errors.InvalidParam, "参数错误: "+err.Error()) + return + } + res, err := h.svc.TestChannel(c.Request.Context(), id, req.Mobile, req.Content) + if err != nil { + bizResp(c, err) + return + } + response.Success(c, res) +} + +// getIntercept GET /channels/:id/intercept。 +func (h *channelHandler) getIntercept(c *gin.Context) { + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + cfg, err := h.svc.GetIntercept(c.Request.Context(), id) + if err != nil { + bizResp(c, err) + return + } + response.Success(c, gin.H{"id": id, "intercept": cfg}) +} + +// setIntercept PUT /channels/:id/intercept:夜发/日限/屏蔽地区。 +func (h *channelHandler) setIntercept(c *gin.Context) { + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + var cfg channel.InterceptConfig + if err := c.ShouldBindJSON(&cfg); err != nil { + response.ErrorWithMsg(c, errors.InvalidParam, "参数错误: "+err.Error()) + return + } + if err := h.svc.SetIntercept(c.Request.Context(), id, &cfg); err != nil { + bizResp(c, err) + return + } + response.Success(c, gin.H{"id": id, "intercept": cfg}) +} + +// ---- 价格时间线(Day 38) ---- + +// setPrice POST /channels/:id/prices {price, effective_at}:写入价格时间线。 +func (h *channelHandler) setPrice(c *gin.Context) { + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + var req channel.SetPriceReq + if err := c.ShouldBindJSON(&req); err != nil { + response.ErrorWithMsg(c, errors.InvalidParam, "参数错误: "+err.Error()) + return + } + p, err := h.svc.SetPrice(c.Request.Context(), id, &req) + if err != nil { + bizResp(c, err) + return + } + response.Success(c, gin.H{ + "id": p.ID, "channel_id": p.ChannelID, "price": p.Price, + "effective_at": p.EffectiveAt.Format("2006-01-02 15:04:05"), + }) +} + +// listPrices GET /channels/:id/prices:价格时间线(生效时间升序)。 +func (h *channelHandler) listPrices(c *gin.Context) { + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + list, err := h.svc.ListPrices(c.Request.Context(), id) + if err != nil { + bizResp(c, err) + return + } + response.Success(c, gin.H{"total": len(list), "list": list}) +} + +// currentPrice GET /channels/:id/prices/current:当前时间点单价(无时间线回退实体 Price)。 +func (h *channelHandler) currentPrice(c *gin.Context) { + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + price, err := h.svc.CurrentPrice(c.Request.Context(), id, time.Now()) + if err != nil { + bizResp(c, err) + return + } + response.Success(c, gin.H{"channel_id": id, "price": price}) +} + +// removePrice DELETE /channels/:id/prices/:pid。 +func (h *channelHandler) removePrice(c *gin.Context) { + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + pid, _ := strconv.ParseInt(c.Param("pid"), 10, 64) + if err := h.svc.DeletePrice(c.Request.Context(), id, pid); err != nil { + bizResp(c, err) + return + } + response.Success(c, gin.H{"id": id, "price_id": pid, "deleted": true}) +} + +// ---- 链路状态与回执复核(Day 39) ---- + +// linkStatus GET /channels/:id/link-status:常驻链路状态(未建链返回 running=false 视图)。 +func (h *channelHandler) linkStatus(c *gin.Context) { + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + if _, err := h.svc.Get(c.Request.Context(), id); err != nil { + bizResp(c, err) + return + } + st := h.svc.LinkStatus(id) + if st == nil { + st = &pool.LinkStatus{ChannelID: id} + } + response.Success(c, st) +} + +// linkReceipts GET /channels/:id/receipts?limit=50:该通道最近回执/上行(倒序;含状态报告与上行短信)。 +// Day 56:优先读持久层(message_report_seg+message_uplink,重启后回执可查); +// 查询失败降级内存环形缓冲(链路刚建立/DB 抖动窗口仍可观测)。 +func (h *channelHandler) linkReceipts(c *gin.Context) { + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + if _, err := h.svc.Get(c.Request.Context(), id); err != nil { + bizResp(c, err) + return + } + limit, _ := strconv.Atoi(c.DefaultQuery("limit", "50")) + if limit <= 0 || limit > 100 { + limit = 50 + } + list, err := h.svc.LinkReceiptsPersist(c.Request.Context(), id, limit) + if err != nil { + list = h.svc.LinkReceipts(id, limit) // 降级:内存环形缓冲(最近 receiptCap 条) + } + if list == nil { + list = []pool.Receipt{} + } + response.Success(c, gin.H{"channel_id": id, "total": len(list), "list": list}) +} diff --git a/internal/api/http/v1/errorcode_handler.go b/internal/api/http/v1/errorcode_handler.go new file mode 100644 index 00000000..ebd12920 --- /dev/null +++ b/internal/api/http/v1/errorcode_handler.go @@ -0,0 +1,88 @@ +// errorcode_handler.go Day 56:错误码维护端点(system_error_code 增改停用)。 +// - GET /system/error-codes 分页查询(code 前缀/name 模糊/status;登录即可) +// - POST /system/error-codes 新增(system:write——admin 直通,错误码变更 +// 影响拦截/重发/入审策略,收紧至系统管理员) +// - PUT /system/error-codes/:id 修改+启停(status=0 停用,历史记录保留) +// +// 消费者归一化仍走 report.Normalize 纯函数词表(三态判定与本表解耦)。 +package v1 + +import ( + "strconv" + + "github.com/gin-gonic/gin" + + "go-sms/internal/middleware" + "go-sms/internal/pkg/errors" + "go-sms/internal/pkg/response" + "go-sms/internal/service/report" +) + +type errorCodeHandler struct{ svc *report.ErrorCodeService } + +func registerErrorCodeRoutes(protected *gin.RouterGroup, perm middleware.PermissionChecker, svc *report.ErrorCodeService) { + h := &errorCodeHandler{svc: svc} + gate := func(obj, act string) gin.HandlerFunc { + return middleware.RequirePermission(perm, obj, act) + } + protected.GET("/system/error-codes", h.list) + protected.POST("/system/error-codes", gate("system", "write"), h.create) + protected.PUT("/system/error-codes/:id", gate("system", "write"), h.update) +} + +// list GET /system/error-codes?page=&page_size=&code=&name=&status= +func (h *errorCodeHandler) list(c *gin.Context) { + page, _ := strconv.Atoi(c.DefaultQuery("page", "1")) + ps, _ := strconv.Atoi(c.DefaultQuery("page_size", "50")) + q := report.ErrorCodeQuery{Page: page, PageSize: ps, Code: c.Query("code"), Name: c.Query("name")} + if s := c.Query("status"); s != "" { + v, err := strconv.ParseInt(s, 10, 8) + if err == nil { + sv := int8(v) + q.Status = &sv + } + } + rows, total, err := h.svc.List(c.Request.Context(), q) + if err != nil { + response.Error(c, errors.InternalError) + return + } + response.Success(c, gin.H{"list": rows, "total": total}) +} + +type errorCodeReq struct { + Code string `json:"code"` + Name string `json:"name"` + RawValue string `json:"raw_value"` + Action int8 `json:"action"` // 0 失败 1 重发 2 入审 + Status int8 `json:"status"` // 1 启用 0 停用(仅 PUT) +} + +func (h *errorCodeHandler) create(c *gin.Context) { + var req errorCodeReq + if err := c.ShouldBindJSON(&req); err != nil { + response.ErrorWithMsg(c, errors.InvalidParam, "参数错误: "+err.Error()) + return + } + row, err := h.svc.Create(c.Request.Context(), req.Code, req.Name, req.RawValue, req.Action) + if err != nil { + bizResp(c, err) + return + } + response.Success(c, row) +} + +func (h *errorCodeHandler) update(c *gin.Context) { + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + var req errorCodeReq + if err := c.ShouldBindJSON(&req); err != nil { + response.ErrorWithMsg(c, errors.InvalidParam, "参数错误: "+err.Error()) + return + } + row, err := h.svc.Update(c.Request.Context(), id, req.Name, req.RawValue, req.Action, req.Status) + if err != nil { + bizResp(c, err) + return + } + response.Success(c, row) +} diff --git a/internal/api/http/v1/feerror_handler.go b/internal/api/http/v1/feerror_handler.go new file mode 100644 index 00000000..21db258e --- /dev/null +++ b/internal/api/http/v1/feerror_handler.go @@ -0,0 +1,115 @@ +// feerror_handler.go Day 53(runbook §6.4 P0):前端错误上报端点。 +// - POST /fe-errors 上报(public:登录页 JS 错误/网络层 5xx 也须可达;引擎级 IP 限流兜底) +// - GET /fe-errors 排障查询(admin/ops;kind 过滤+分页,id DESC 最新在前) +// +// 采集侧:web/src/utils/error-reporter.ts(window.onerror/unhandledrejection)+ +// request.ts 响应拦截器(5xx/网络错误,带 X-Trace-Id 关联后端日志链)。 +package v1 + +import ( + "strings" + + "github.com/gin-gonic/gin" + "gorm.io/gorm" + + "go-sms/internal/middleware" + "go-sms/internal/model/entity" + "go-sms/internal/pkg/response" +) + +// feErrorPayload 上报体(前端单条;批量由多次上报承担,保持接口最小)。 +type feErrorPayload struct { + Kind string `json:"kind"` // js|http|unhandled + PageURL string `json:"page_url"` // window.location.href + Message string `json:"message"` + Stack string `json:"stack"` + UA string `json:"ua"` // navigator.userAgent + TraceID string `json:"trace_id"` // 请求 X-Trace-Id(HTTP 类错误关联后端) +} + +// feErrorFieldMax 字段截断上限(与实体列宽一致,防超长栈打爆 INSERT)。 +var feErrorFieldMax = map[string]int{"page_url": 512, "message": 1024, "stack": 8192, "ua": 512, "trace_id": 64} + +func feTrunc(field, s string) string { + if max, ok := feErrorFieldMax[field]; ok && len(s) > max { + return s[:max] + } + return s +} + +// feKindAllowed 上报类型白名单(未知值归一 js,防标签基数滥用)。 +func feKindAllowed(k string) string { + switch k { + case "http", "unhandled": + return k + default: + return "js" + } +} + +type feErrorHandler struct{ db *gorm.DB } + +// registerFeErrorRoutes 挂载前端错误上报路由。 +func registerFeErrorRoutes(rg *gin.RouterGroup, protected *gin.RouterGroup, db *gorm.DB, perm middleware.PermissionChecker) { + if db == nil { + return + } + h := &feErrorHandler{db: db} + rg.POST("/fe-errors", h.report) + protected.GET("/fe-errors", + middleware.RequirePermission(perm, "system", "read"), h.list) +} + +// report POST /fe-errors:落库即成功(上报通道自身永不抛业务错,防前端重试风暴)。 +func (h *feErrorHandler) report(c *gin.Context) { + var p feErrorPayload + if err := c.ShouldBindJSON(&p); err != nil { + // 畸形体也按成功应答:错误上报是尽力而为通道,客户端无需重试 + response.Success(c, nil) + return + } + row := entity.FeErrorLog{ + Kind: feKindAllowed(p.Kind), + PageURL: feTrunc("page_url", strings.TrimSpace(p.PageURL)), + Message: feTrunc("message", strings.TrimSpace(p.Message)), + Stack: feTrunc("stack", p.Stack), + UA: feTrunc("ua", p.UA), + TraceID: feTrunc("trace_id", strings.TrimSpace(p.TraceID)), + } + if row.Message == "" && row.Stack == "" { + response.Success(c, nil) // 空上报不落库 + return + } + if err := h.db.WithContext(c.Request.Context()).Create(&row).Error; err != nil { + // 落库失败也不回错误码:前端侧静默(runbook:上报失败不阻塞业务) + _ = c.Error(err) + } + response.Success(c, nil) +} + +// list GET /fe-errors:排障查询(kind 过滤+分页,id DESC)。 +func (h *feErrorHandler) list(c *gin.Context) { + page := atoiDefault(c.Query("page"), 1) + pageSize := atoiDefault(c.Query("page_size"), 20) + if pageSize > 100 { + pageSize = 100 + } + q := h.db.WithContext(c.Request.Context()).Model(&entity.FeErrorLog{}) + if kind := strings.TrimSpace(c.Query("kind")); kind != "" { + q = q.Where("kind = ?", kind) + } + if tid := strings.TrimSpace(c.Query("trace_id")); tid != "" { + q = q.Where("trace_id = ?", tid) + } + var total int64 + if err := q.Count(&total).Error; err != nil { + bizResp(c, err) + return + } + var rows []entity.FeErrorLog + if err := q.Order("id DESC").Offset((page - 1) * pageSize).Limit(pageSize).Find(&rows).Error; err != nil { + bizResp(c, err) + return + } + response.Success(c, gin.H{"list": rows, "total": total}) +} diff --git a/internal/api/http/v1/feerror_handler_test.go b/internal/api/http/v1/feerror_handler_test.go new file mode 100644 index 00000000..287f08be --- /dev/null +++ b/internal/api/http/v1/feerror_handler_test.go @@ -0,0 +1,128 @@ +// feerror_handler_test.go Day 53:/fe-errors 上报落库+排障查询;/alerts/sink AM 留痕。 +package v1 + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/glebarez/sqlite" + "go.uber.org/zap" + "go.uber.org/zap/zaptest/observer" + "gorm.io/gorm" + gormlogger "gorm.io/gorm/logger" + + "go-sms/internal/model/entity" +) + +func newFeRouter(t *testing.T) (*gin.Engine, *gorm.DB, *observer.ObservedLogs) { + t.Helper() + gin.SetMode(gin.TestMode) + db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{ + Logger: gormlogger.Default.LogMode(gormlogger.Silent), + }) + if err != nil { + t.Fatal(err) + } + if err := db.AutoMigrate(&entity.FeErrorLog{}); err != nil { + t.Fatal(err) + } + r := gin.New() + rg := r.Group("/api/v1") + protected := rg.Group("") + core, logs := observer.New(zap.InfoLevel) + registerFeErrorRoutes(rg, protected, db, nil) + registerAlertsSink(rg, zap.New(core)) + return r, db, logs +} + +// W1:上报(public 无 token)→ 落库字段完整+截断生效+HTTP 恒 200。 +func TestFeErrorReport(t *testing.T) { + r, db, _ := newFeRouter(t) + body, _ := json.Marshal(feErrorPayload{ + Kind: "http", PageURL: "http://localhost:5173/record/down", + Message: "HTTP:500", UA: "vitest", TraceID: "trace-abc", + Stack: strings.Repeat("x", 9000), // 超 stack 截断上限 8192 + }) + w := httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/api/v1/fe-errors", bytes.NewReader(body))) + if w.Code != http.StatusOK { + t.Fatalf("上报应恒 200,got %d", w.Code) + } + var row entity.FeErrorLog + if err := db.First(&row).Error; err != nil { + t.Fatal("应落库:", err) + } + if row.Kind != "http" || row.TraceID != "trace-abc" { + t.Fatalf("字段不符: %+v", row) + } + if len(row.Stack) != 8192 { + t.Fatalf("stack 应截断 8192,got %d", len(row.Stack)) + } +} + +// W2:未知 kind 归一 js;空上报不落库(防滥用空行刷表)。 +func TestFeErrorKindAndEmpty(t *testing.T) { + r, db, _ := newFeRouter(t) + post := func(payload string) { + w := httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/api/v1/fe-errors", strings.NewReader(payload))) + if w.Code != http.StatusOK { + t.Fatalf("恒 200,got %d", w.Code) + } + } + post(`{"kind":"weird","message":"boom"}`) + var n int64 + db.Model(&entity.FeErrorLog{}).Count(&n) + if n != 1 { + t.Fatalf("应落 1 行,got %d", n) + } + var row entity.FeErrorLog + db.First(&row) + if row.Kind != "js" { + t.Fatalf("未知 kind 应归一 js,got %s", row.Kind) + } + post(`{"kind":"js","message":"","stack":""}`) // 空上报 + db.Model(&entity.FeErrorLog{}).Count(&n) + if n != 1 { + t.Fatalf("空上报不应落库,got %d", n) + } +} + +// W3:AM webhook 推送 → P0=Error 级留痕/其余 Warn/resolved Info(告警通道通断言锚点)。 +func TestAlertsSink(t *testing.T) { + r, _, logs := newFeRouter(t) + amBody := `{"receiver":"gateway-sink","status":"firing","alerts":[ + {"status":"firing","labels":{"alertname":"HTTPError5xxBurst","severity":"P0","route":"/api/v1/send/submit"}, + "annotations":{"summary":"5xx 突增","description":"5m rate>1"},"startsAt":"2026-09-14T09:00:00Z"}, + {"status":"firing","labels":{"alertname":"HTTPP99High","severity":"P1","route":"/api/v1/accounts"}, + "annotations":{"summary":"P99 超阈","description":">500ms"},"startsAt":"2026-09-14T09:00:00Z"}, + {"status":"resolved","labels":{"alertname":"HTTPP99High","severity":"P1"}, + "annotations":{"summary":"P99 恢复"},"startsAt":"2026-09-14T09:00:00Z"} + ]}` + w := httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/api/v1/alerts/sink", strings.NewReader(amBody))) + if w.Code != http.StatusOK { + t.Fatalf("AM 推送应 200,got %d", w.Code) + } + entries := logs.FilterMessage("alerts_sink_alert_received").All() + if len(entries) != 3 { + t.Fatalf("应留痕 3 条,got %d", len(entries)) + } + if entries[0].Level != zap.ErrorLevel { + t.Fatalf("P0 应 Error 级,got %s", entries[0].Level) + } + if entries[1].Level != zap.WarnLevel { + t.Fatalf("P1 应 Warn 级,got %s", entries[1].Level) + } + if entries[2].Level != zap.InfoLevel { + t.Fatalf("resolved 应 Info 级,got %s", entries[2].Level) + } + if !strings.Contains(entries[0].ContextMap()["alert"].(string), "HTTPError5xxBurst") { + t.Fatalf("告警名应入结构化字段: %+v", entries[0].Context) + } +} diff --git a/internal/api/http/v1/monitor_handler.go b/internal/api/http/v1/monitor_handler.go new file mode 100644 index 00000000..67c30462 --- /dev/null +++ b/internal/api/http/v1/monitor_handler.go @@ -0,0 +1,168 @@ +// monitor_handler.go Day 40(A-3.13/A-3.14):通道实时监控与日志端点。 +// - GET /channels/monitor 快照(HTTP 轮询兜底,与 WS 同源); +// - GET /channels/monitor/ws WebSocket 2s 推送实时曲线(单 Hub 广播,gorilla/websocket); +// - GET /channels/:id/logs 通道日志分页(A-3.14 连接/提交/回执完整记录)。 +package v1 + +import ( + "context" + "net/http" + "strconv" + "sync" + "time" + + "github.com/gin-gonic/gin" + "github.com/gorilla/websocket" + + "go-sms/internal/model/entity" + "go-sms/internal/pkg/response" + "go-sms/internal/service/channel" +) + +// wsPushInterval WS 推送周期(验收:每 2s 数据更新)。 +const wsPushInterval = 2 * time.Second + +// wsUpgrader HTTP→WS 升级器(同源检查放宽:前后端分离端口)。 +var wsUpgrader = websocket.Upgrader{ + CheckOrigin: func(r *http.Request) bool { return true }, +} + +// monitorHandler 监控接口。 +type monitorHandler struct{ svc *channel.Service } + +// registerMonitorRoutes 注册监控路由(登录保护;只读不加权限门,运维大盘全员可见)。 +func registerMonitorRoutes(protected *gin.RouterGroup, svc *channel.Service) { + h := &monitorHandler{svc: svc} + protected.GET("/channels/monitor", h.snapshot) + protected.GET("/channels/monitor/ws", h.wsStream) + protected.GET("/channels/:id/logs", h.logs) +} + +// snapshot GET /channels/monitor:全通道实时快照(与 WS 帧同构)。 +func (h *monitorHandler) snapshot(c *gin.Context) { + snap, err := h.svc.MonitorSnapshot(c.Request.Context()) + if err != nil { + bizResp(c, err) + return + } + if snap == nil { + snap = []channel.ChannelSnapshot{} + } + response.Success(c, snap) +} + +// wsStream GET /channels/monitor/ws:升级为 WS 并加入广播 Hub(2s 一帧全通道快照)。 +func (h *monitorHandler) wsStream(c *gin.Context) { + conn, err := wsUpgrader.Upgrade(c.Writer, c.Request, nil) + if err != nil { + return // Upgrade 已回写 400 + } + snapFn := func() any { + snap, err := h.svc.MonitorSnapshot(context.Background()) + if err != nil || snap == nil { + return []channel.ChannelSnapshot{} + } + return snap + } + monitorHub.Join(conn, snapFn) +} + +// ---- Hub:单实例广播中心(每 wsPushInterval 一帧;连接各自写超时隔离) ---- + +// wsClient 一个 WS 连接。 +type wsClient struct { + conn *websocket.Conn + snap func() any // 快照函数(连接时捕获,数据源同构) + close chan struct{} +} + +// monitorHub 全局广播中心(gateway 单实例;多副本时前端按副本负载均衡连接即可)。 +var monitorHub = &hub{clients: map[*wsClient]struct{}{}} + +type hub struct { + mu sync.Mutex + clients map[*wsClient]struct{} + started bool +} + +// Join 接入连接并确保广播循环运行。 +func (h *hub) Join(conn *websocket.Conn, snap func() any) { + cl := &wsClient{conn: conn, snap: snap, close: make(chan struct{})} + h.mu.Lock() + h.clients[cl] = struct{}{} + needStart := !h.started + h.started = true + h.mu.Unlock() + if needStart { + go h.loop() + } + go cl.readLoop() // 消费对端帧( pong/close ),检测断开 +} + +// loop 广播循环:周期向全部连接推送快照;写失败即摘除。 +func (h *hub) loop() { + tick := time.NewTicker(wsPushInterval) + defer tick.Stop() + for range tick.C { + h.mu.Lock() + clients := make([]*wsClient, 0, len(h.clients)) + for cl := range h.clients { + clients = append(clients, cl) + } + h.mu.Unlock() + if len(clients) == 0 { + continue // 无连接不采数据(快照查询零成本) + } + // 快照一次,广播给全部连接(同帧同值,便于多端对齐)。 + snap := clients[0].snap() + for _, cl := range clients { + _ = cl.conn.SetWriteDeadline(time.Now().Add(3 * time.Second)) + if err := cl.conn.WriteJSON(snap); err != nil { + h.remove(cl) + continue + } + } + } +} + +// remove 摘除连接并关闭。 +func (h *hub) remove(cl *wsClient) { + h.mu.Lock() + if _, ok := h.clients[cl]; ok { + delete(h.clients, cl) + close(cl.close) + _ = cl.conn.Close() + } + h.mu.Unlock() +} + +// readLoop 消费对端帧直到断开(写超时/网络断由写侧摘除;此处兜底 close)。 +func (cl *wsClient) readLoop() { + defer monitorHub.remove(cl) + cl.conn.SetReadLimit(512) + for { + if _, _, err := cl.conn.ReadMessage(); err != nil { + return + } + } +} + +// logs GET /channels/:id/logs?kind=&page=&page_size=:通道日志(A-3.14)。 +func (h *monitorHandler) logs(c *gin.Context) { + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + if _, err := h.svc.Get(c.Request.Context(), id); err != nil { + bizResp(c, err) + return + } + page, _ := strconv.Atoi(c.DefaultQuery("page", "1")) + pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20")) + list, total, err := h.svc.ListLogs(c.Request.Context(), id, c.Query("kind"), page, pageSize) + if err != nil { + bizResp(c, err) + return + } + if list == nil { + list = []entity.ChannelLog{} + } + response.Success(c, gin.H{"channel_id": id, "total": total, "list": list}) +} diff --git a/internal/api/http/v1/openapi_handler.go b/internal/api/http/v1/openapi_handler.go new file mode 100644 index 00000000..7928f1de --- /dev/null +++ b/internal/api/http/v1/openapi_handler.go @@ -0,0 +1,179 @@ +// openapi_handler.go Day 46:外部 HTTP API 提交入口(SMS_HTTP_1.6 协议)。 +// 挂载于网关根组 /sms/api(独立于 /api/v1 JWT 域): +// 全局 IP 桶(静态)→ MD5 验签(401)→ 账号桶(动态 speed_limit)→ 提交。 +package v1 + +import ( + "bytes" + "encoding/json" + "io" + "net/http" + "strconv" + "strings" + + "github.com/gin-gonic/gin" + "github.com/redis/go-redis/v9" + + "go-sms/internal/middleware" + "go-sms/internal/service/openapi" +) + +// openapiAuthKey gin.Context 注入键(验签中间件→业务 handler)。 +const openapiAuthKey = "openapi.auth" + +// openapiPhoneCountKey 验签中间件解析的 phoneList 数量(限流扣费数)。 +const openapiPhoneCountKey = "openapi.phonecount" + +// openapiPhoneCount Day50:限流令牌扣费数=请求号码数(缺省 1)。 +// 批量接口按号码/秒口径限速——每请求 1 令牌时 100 号/req 的限速形同虚设。 +// 全局 IP 桶先于验签执行:现场读 body 计数并回填(账号桶经 context 复用,零二次解析)。 +func openapiPhoneCount(c *gin.Context) int64 { + if v, ok := c.Get(openapiPhoneCountKey); ok { + if n, ok2 := v.(int64); ok2 && n > 0 { + return n + } + } + if c.Request != nil && c.Request.Body != nil { + if raw, err := io.ReadAll(c.Request.Body); err == nil { + c.Request.Body = io.NopCloser(bytes.NewReader(raw)) + var b struct { + PhoneList []string `json:"phoneList"` + } + if json.Unmarshal(raw, &b) == nil && len(b.PhoneList) > 0 { + n := int64(len(b.PhoneList)) + c.Set(openapiPhoneCountKey, n) + return n + } + } + } + return 1 +} + +// OpenAPIDeps 外部 API 装配依赖。 +type OpenAPIDeps struct { + Auth *openapi.Authenticator + Svc *openapi.Service + Redis redis.UniversalClient // nil=限流降级放行 + Global middleware.RateLimitConfig // 全局 IP 桶(容量/速率来自配置 rate_limit) +} + +// RegisterOpenAPI 挂载外部协议路由(engine 根组)。 +func RegisterOpenAPI(r *gin.Engine, deps OpenAPIDeps) { + if deps.Auth == nil || deps.Svc == nil { + return + } + g := r.Group("/sms/api") + // ① 全局 IP 桶(静态容量;Redis 缺失时 middleware 内部放行) + if deps.Redis != nil && deps.Global.Capacity > 0 { + cfg := deps.Global + cfg.KeyFunc = middleware.ByClientIP + cfg.KeyPrefix = "go-sms:ratelimit:openapi:global" + cfg.CountOf = openapiPhoneCount + g.Use(middleware.RateLimit(deps.Redis, cfg)) + } + // ② MD5 验签(注入 AuthContext;失败 401+协议体) + g.Use(openapiAuth(deps.Auth)) + // ③ 账号桶(动态容量=账号 speed_limit;验签后账号 ID 维度; + // Day48:容量经 BackpressureShrink 包装——消费侧 lag≥L2 时收紧至 Σ通道speed; + // Day50 压测修复:令牌桶稳态吞吐由 rate 决定,仅收容量对持续流量无效—— + // RateOf 复用同一 shrink 实例(共享 1s 本地缓存),L2 时容量+速率同步收紧)。 + if deps.Redis != nil { + baseCap := func(c *gin.Context) int64 { + if a, ok := c.Get(openapiAuthKey); ok { + if ac, ok2 := a.(*openapi.AuthContext); ok2 && ac.Config != nil { + return int64(ac.Config.SpeedLimit) + } + } + return 0 // 0=用缺省兜底 + } + shrink := middleware.BackpressureShrink(deps.Redis, baseCap) + g.Use(middleware.RateLimitDynamic(deps.Redis, middleware.RateLimitDynamicConfig{ + KeyFunc: func(c *gin.Context) string { + if a, ok := c.Get(openapiAuthKey); ok { + if ac, ok2 := a.(*openapi.AuthContext); ok2 { + return strconv.FormatInt(ac.AccountID, 10) + } + } + return "anon" + }, + CapacityOf: shrink, + RateOf: shrink, + CountOf: openapiPhoneCount, + })) + } + h := &openapiHandler{svc: deps.Svc} + g.POST("/sendMessageMass", h.mass) + g.POST("/sendMessageOne", h.one) +} + +// openapiAuth 验签中间件:失败→401+协议体(code 1/2/3/4/16),成功注入上下文。 +// 注意:绑定后须回填 body(后续业务 handler 需再次解析全量字段)。 +func openapiAuth(a *openapi.Authenticator) gin.HandlerFunc { + return func(c *gin.Context) { + raw, err := io.ReadAll(c.Request.Body) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{ + "code": openapi.CodeOther, "message": "请求体读取失败"}) + c.Abort() + return + } + c.Request.Body = io.NopCloser(bytes.NewReader(raw)) + var body struct { + UserName string `json:"userName"` + Timestamp string `json:"timestamp"` + Sign string `json:"sign"` + PhoneList []string `json:"phoneList"` // Day50:限流扣费数(按号码数;解析失败不阻塞验签语义) + } + if err := json.Unmarshal(raw, &body); err != nil { + c.JSON(http.StatusBadRequest, gin.H{ + "code": openapi.CodeOther, "message": "请求体须为 JSON:" + err.Error()}) + c.Abort() + return + } + c.Set(openapiPhoneCountKey, int64(len(body.PhoneList))) + if !strings.Contains(c.GetHeader("Content-Type"), "json") { + c.JSON(http.StatusBadRequest, gin.H{ + "code": openapi.CodeOther, "message": "Content-Type 须为 application/json"}) + c.Abort() + return + } + auth, code, msg := a.Authenticate(c.Request.Context(), body.UserName, body.Timestamp, body.Sign, c.ClientIP()) + if code != openapi.CodeOK { + c.JSON(http.StatusUnauthorized, gin.H{"code": code, "message": msg}) + c.Abort() + return + } + c.Set(openapiAuthKey, auth) + c.Next() + } +} + +// openapiHandler 业务 handler(验签/限流已由中间件完成)。 +type openapiHandler struct{ svc *openapi.Service } + +// authFromCtx 取验签上下文(中间件保证非空)。 +func authFromCtx(c *gin.Context) *openapi.AuthContext { + v, _ := c.Get(openapiAuthKey) + a, _ := v.(*openapi.AuthContext) + return a +} + +// mass POST /sms/api/sendMessageMass。 +func (h *openapiHandler) mass(c *gin.Context) { + var req openapi.MassReq + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusOK, gin.H{"code": openapi.CodeOther, "message": "请求体解析失败:" + err.Error()}) + return + } + c.JSON(http.StatusOK, h.svc.SendMass(c.Request.Context(), authFromCtx(c), &req, c.ClientIP())) +} + +// one POST /sms/api/sendMessageOne。 +func (h *openapiHandler) one(c *gin.Context) { + var req openapi.OneReq + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusOK, gin.H{"code": openapi.CodeOther, "message": "请求体解析失败:" + err.Error()}) + return + } + c.JSON(http.StatusOK, h.svc.SendOne(c.Request.Context(), authFromCtx(c), &req, c.ClientIP())) +} diff --git a/internal/api/http/v1/profile_handler.go b/internal/api/http/v1/profile_handler.go new file mode 100644 index 00000000..84431544 --- /dev/null +++ b/internal/api/http/v1/profile_handler.go @@ -0,0 +1,148 @@ +// profile_handler.go Day 28:上级切换 / 标星 / 服务团队 / 实名认证端点。 +package v1 + +import ( + "strconv" + + "github.com/gin-gonic/gin" + + "go-sms/internal/pkg/errors" + "go-sms/internal/pkg/response" + "go-sms/internal/service/account" +) + +// changeParent POST /accounts/:id/parent {parent_id}(account:write): +// 物化路径防环 + 子孙级联重写。 +func (h *accountHandler) changeParent(c *gin.Context) { + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + var req struct { + ParentID int64 `json:"parent_id" binding:"required"` + } + if err := c.ShouldBindJSON(&req); err != nil { + response.ErrorWithMsg(c, errors.InvalidParam, "参数错误: "+err.Error()) + return + } + if err := h.svc.ChangeParent(c.Request.Context(), id, req.ParentID); err != nil { + if bizErr, ok := err.(*errors.Error); ok { + response.Error(c, bizErr) + return + } + c.Set("biz_error", err.Error()) + response.Error(c, errors.InternalError) + return + } + response.Success(c, gin.H{"id": id, "parent_id": req.ParentID}) +} + +// setStar POST /accounts/:id/star {starred}(account:write):标星置顶。 +func (h *accountHandler) setStar(c *gin.Context) { + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + var req struct { + Starred bool `json:"starred"` + } + if err := c.ShouldBindJSON(&req); err != nil { + response.ErrorWithMsg(c, errors.InvalidParam, "参数错误: "+err.Error()) + return + } + if err := h.svc.SetStar(c.Request.Context(), id, req.Starred); err != nil { + if bizErr, ok := err.(*errors.Error); ok { + response.Error(c, bizErr) + return + } + response.Error(c, errors.InternalError) + return + } + response.Success(c, gin.H{"id": id, "starred": req.Starred}) +} + +// setSvcTeam PUT /accounts/:id/svc-team {svc_team}(account:write)。 +func (h *accountHandler) setSvcTeam(c *gin.Context) { + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + var req struct { + SvcTeam string `json:"svc_team"` + } + if err := c.ShouldBindJSON(&req); err != nil { + response.ErrorWithMsg(c, errors.InvalidParam, "参数错误: "+err.Error()) + return + } + if err := h.svc.SetSvcTeam(c.Request.Context(), id, req.SvcTeam); err != nil { + if bizErr, ok := err.(*errors.Error); ok { + response.Error(c, bizErr) + return + } + response.Error(c, errors.InternalError) + return + } + response.Success(c, gin.H{"id": id, "svc_team": req.SvcTeam}) +} + +// getRealname GET /accounts/:id/realname(本人或 admin;证件号脱敏)。 +func (h *accountHandler) getRealname(c *gin.Context) { + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + if !requireSelfOrAdmin(c, id) { + return + } + info, err := h.svc.GetRealname(c.Request.Context(), id) + if err != nil { + if bizErr, ok := err.(*errors.Error); ok { + response.Error(c, bizErr) + return + } + response.Error(c, errors.InternalError) + return + } + response.Success(c, gin.H{"id": id, "realname": info}) +} + +// submitRealname POST /accounts/:id/realname {real_name, id_card}(本人或 admin 代提交)。 +func (h *accountHandler) submitRealname(c *gin.Context) { + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + if !requireSelfOrAdmin(c, id) { + return + } + var req struct { + RealName string `json:"real_name" binding:"required"` + IDCard string `json:"id_card" binding:"required"` + } + if err := c.ShouldBindJSON(&req); err != nil { + response.ErrorWithMsg(c, errors.InvalidParam, "参数错误: "+err.Error()) + return + } + if err := h.svc.RealnameSubmit(c.Request.Context(), id, req.RealName, req.IDCard); err != nil { + if bizErr, ok := err.(*errors.Error); ok { + response.Error(c, bizErr) + return + } + c.Set("biz_error", err.Error()) + response.Error(c, errors.InternalError) + return + } + response.Success(c, gin.H{"id": id, "status": account.RealnamePending}) +} + +// reviewRealname POST /accounts/:id/realname/review {approve, reason}(account:write)。 +func (h *accountHandler) reviewRealname(c *gin.Context) { + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + var req struct { + Approve bool `json:"approve"` + Reason string `json:"reason"` + } + if err := c.ShouldBindJSON(&req); err != nil { + response.ErrorWithMsg(c, errors.InvalidParam, "参数错误: "+err.Error()) + return + } + if err := h.svc.RealnameReview(c.Request.Context(), id, req.Approve, req.Reason); err != nil { + if bizErr, ok := err.(*errors.Error); ok { + response.Error(c, bizErr) + return + } + c.Set("biz_error", err.Error()) + response.Error(c, errors.InternalError) + return + } + status := account.RealnameApproved + if !req.Approve { + status = account.RealnameRejected + } + response.Success(c, gin.H{"id": id, "status": status}) +} diff --git a/internal/api/http/v1/record_handler.go b/internal/api/http/v1/record_handler.go new file mode 100644 index 00000000..2f4957ff --- /dev/null +++ b/internal/api/http/v1/record_handler.go @@ -0,0 +1,652 @@ +// record_handler.go Day 60(D24-25):record 域 API 回填——下行批次/号码级明细/ +// 拦截号码 CSV 下载/通道日志钻入/下行明细 v2 富查询(五端点)。 +// 契约=web/src/api/record.ts(D24/D25)+ web/src/api/sms.ts(v2,D24-25 重构), +// 此前由 msw mock 承载;数据口径=message_task/message_detail(+report_seg/ +// channel_log 关联),响应形状与 mock ok()/fail() 完全一致({code,msg,data})。 +package v1 + +import ( + "database/sql" + "fmt" + "net/http" + "strconv" + "strings" + "time" + + "github.com/gin-gonic/gin" + "gorm.io/gorm" + + "go-sms/internal/model/entity" + "go-sms/internal/pkg/errors" + "go-sms/internal/pkg/response" +) + +// fmtTime JSON 时间("2006-01-02 15:04:05",与 mock/前端 ts() 解析口径一致; +// time.Time 默认 RFC3339 带 T/时区,前端 new Date 会 NaN)。 +type fmtTime time.Time + +func (t fmtTime) MarshalJSON() ([]byte, error) { + return []byte(`"` + time.Time(t).Format("2006-01-02 15:04:05") + `"`), nil +} + +// fmtTimePtr *time.Time → *fmtTime(nil 保持 null)。 +func fmtTimePtr(t *time.Time) *fmtTime { + if t == nil { + return nil + } + ft := fmtTime(*t) + return &ft +} + +// downWindowDays D25 号码级明细热数据窗口(天;契约约定后端保证)。 +const downWindowDays = 5 + +// downlinkPageSizeMax 分页上限(防 page_size 超大拖库)。 +const downlinkPageSizeMax = 1000 + +// qTime 可选时间参数(空=未传返回 nil;格式错返回错误)。 +func qTime(c *gin.Context, key string) (*time.Time, error) { + v := strings.TrimSpace(c.Query(key)) + if v == "" { + return nil, nil + } + return parseTimeParam(v) +} + +// registerRecordRoutes 注册 record 域端点(查询类,JWT 保护即可,不挂 Casbin)。 +func registerRecordRoutes(protected *gin.RouterGroup, db *gorm.DB) { + h := &recordHandler{db: db} + protected.GET("/record/down", h.downList) + protected.GET("/record/down/:id/intercepted", h.downIntercepted) + protected.GET("/record/down/details", h.downDetails) + protected.GET("/record/down/details/:id/channel-logs", h.detailChannelLogs) + protected.GET("/sms/downlink-details", h.downlinkDetails) +} + +type recordHandler struct{ db *gorm.DB } + +// ---- D24:下行批次列表(GET /record/down) ---- + +// downRecordDTO 批次行(message_task 聚合口径;契约 record.ts DownRecord)。 +type downRecordDTO struct { + ID int64 `json:"id"` + TaskNo string `json:"task_no"` + SendType int8 `json:"send_type"` + Sign string `json:"sign"` + Content string `json:"content"` + MobileCount int `json:"mobile_count"` + SuccessCount int `json:"success_count"` + FailCount int `json:"fail_count"` + UnknownCount int `json:"unknown_count"` + InterceptedCount int64 `json:"intercepted_count"` // message_detail status=5 聚合 + SendingCount int64 `json:"sending_count"` // status IN (0,1) 待发+提交中 + FeeTotal float64 `json:"fee_total"` + AuditStatus int8 `json:"audit_status"` + Status int8 `json:"status"` + CreatedAt fmtTime `json:"created_at"` + FinishedAt *fmtTime `json:"finished_at"` +} + +// downList GET /record/down——批次分页(task_no 精确/send_type/status/时间窗; +// business=sms 隔离视频短信;两段式:先页后聚合,避免全表 GROUP BY)。 +func (h *recordHandler) downList(c *gin.Context) { + page := intQuery(c, "page", 1) + size := intQuery(c, "page_size", 100) + if size > downlinkPageSizeMax { + size = downlinkPageSizeMax + } + q := h.db.Model(&entity.MessageTask{}).Where("business = ?", "sms") + if v := strings.TrimSpace(c.Query("task_no")); v != "" { + q = q.Where("task_no = ?", v) + } + if v := intQuery(c, "send_type", 0); v > 0 { + q = q.Where("send_type = ?", v) + } + if v := intQuery(c, "status", -1); v >= 0 { + q = q.Where("status = ?", v) + } + if lo, err := qTime(c, "start_time"); err != nil { + response.ErrorWithMsg(c, errors.InvalidParam, "start_time "+err.Error()) + return + } else if lo != nil { + q = q.Where("created_at >= ?", *lo) + } + if hi, err := qTime(c, "end_time"); err != nil { + response.ErrorWithMsg(c, errors.InvalidParam, "end_time "+err.Error()) + return + } else if hi != nil { + q = q.Where("created_at <= ?", *hi) + } + var total int64 + if err := q.Count(&total).Error; err != nil { + bizResp(c, err) + return + } + var tasks []entity.MessageTask + if err := q.Order("id DESC").Limit(size).Offset((page - 1) * size). + Find(&tasks).Error; err != nil { + bizResp(c, err) + return + } + // 页内批次聚合明细两段(intercepted/sending;成功/失败/未知 task 已有累计列)。 + agg := map[int64][2]int64{} + if len(tasks) > 0 { + ids := make([]int64, 0, len(tasks)) + for _, t := range tasks { + ids = append(ids, t.ID) + } + type aggRow struct { + TaskID int64 + InterceptedSum int64 `gorm:"column:ic"` + SendingSum int64 `gorm:"column:sc"` + } + var rows []aggRow + if err := h.db.Model(&entity.MessageDetail{}). + Select("task_id, SUM(CASE WHEN status = 5 THEN 1 ELSE 0 END) AS ic, "+ + "SUM(CASE WHEN status IN (0, 1) THEN 1 ELSE 0 END) AS sc"). + Where("task_id IN ?", ids).Group("task_id").Scan(&rows).Error; err != nil { + bizResp(c, err) + return + } + for _, r := range rows { + agg[r.TaskID] = [2]int64{r.InterceptedSum, r.SendingSum} + } + } + list := make([]downRecordDTO, 0, len(tasks)) + for _, t := range tasks { + a := agg[t.ID] + list = append(list, downRecordDTO{ + ID: t.ID, TaskNo: t.TaskNo, SendType: t.SendType, Sign: t.Sign, + Content: t.Content, MobileCount: t.MobileCount, + SuccessCount: t.SuccessCount, FailCount: t.FailCount, UnknownCount: t.UnknownCount, + InterceptedCount: a[0], SendingCount: a[1], + FeeTotal: t.FeeTotal, AuditStatus: t.AuditStatus, Status: t.Status, + CreatedAt: fmtTime(t.CreatedAt), FinishedAt: fmtTimePtr(t.FinishedAt), + }) + } + response.Success(c, gin.H{"list": list, "total": total}) +} + +// ---- D24:拦截号码下载(GET /record/down/:id/intercepted?format=csv) ---- + +// downIntercepted CSV 导出(mobile,error_code,reason;reason 取 send_block_log +// 拦截留痕,无记录退 error_code 本身;无拦截/任务不存在→404 业务码,契约同 mock)。 +func (h *recordHandler) downIntercepted(c *gin.Context) { + id, err := strconv.ParseInt(c.Param("id"), 10, 64) + if err != nil || id <= 0 { + response.ErrorWithMsg(c, errors.InvalidParam, "任务 id 非法") + return + } + if format := c.DefaultQuery("format", "csv"); format != "csv" { + response.ErrorWithMsg(c, errors.InvalidParam, "不支持的导出格式") + return + } + var task entity.MessageTask + if err := h.db.Select("id", "task_no").First(&task, id).Error; err != nil { + response.ErrorWithMsg(c, errors.NotFound, "任务不存在") + return + } + type row struct { + Mobile string + ErrorCode string + } + var rows []row + if err := h.db.Model(&entity.MessageDetail{}). + Select("mobile", "error_code"). + Where("task_id = ? AND status = 5", id).Order("id ASC").Scan(&rows).Error; err != nil { + bizResp(c, err) + return + } + if len(rows) == 0 { + response.ErrorWithMsg(c, errors.NotFound, "该批次无拦截号码") + return + } + // 拦截原因留痕(task_no 检索;受理期拦截未投通道,send_block_log 必有记录)。 + reasons := map[string]string{} + var logs []entity.SendBlockLog + if err := h.db.Select("mobile", "msg"). + Where("task_no = ?", task.TaskNo).Find(&logs).Error; err == nil { + for _, l := range logs { + reasons[l.Mobile] = l.Msg + } + } + var b strings.Builder + b.WriteString("mobile,error_code,reason\n") + for _, r := range rows { + reason := reasons[r.Mobile] + if reason == "" { + reason = r.ErrorCode + } + reason = strings.ReplaceAll(reason, ",", ",") // CSV 逗号转义(中文逗号替换) + b.WriteString(r.Mobile + "," + r.ErrorCode + "," + reason + "\n") + } + c.Header("Content-Disposition", fmt.Sprintf(`attachment; filename="intercepted-%d.csv"`, id)) + c.Data(http.StatusOK, "text/csv; charset=utf-8", []byte(b.String())) +} + +// ---- D25:号码级明细(GET /record/down/details) ---- + +// downDetailDTO 明细行(message_detail 口径;契约 record.ts DownDetail)。 +type downDetailDTO struct { + ID int64 `json:"id"` + TaskID int64 `json:"task_id"` + TaskNo string `json:"task_no"` + Mobile string `json:"mobile"` + Province string `json:"province"` + Carrier string `json:"carrier"` + Status int8 `json:"status"` + ErrorCode string `json:"error_code"` + ExtCode string `json:"ext_code"` + CallData string `json:"call_data"` + Fee float64 `json:"fee"` + CreatedAt fmtTime `json:"created_at"` +} + +// downDetails GET /record/down/details——明细分页(mobile 尾号模糊/task_no 精确/ +// status/error_code 精确/时间窗;缺省 5 天热数据窗口由后端强制,契约同 mock)。 +func (h *recordHandler) downDetails(c *gin.Context) { + page := intQuery(c, "page", 1) + size := intQuery(c, "page_size", 100) + if size > downlinkPageSizeMax { + size = downlinkPageSizeMax + } + // Day66 单表化:business 走 d 冗余列(原 JOIN t 逐 task 随机回表,340 万行 + // HDD 冷缓存 Count 29.5s);task_no 精确钻入时才动态挂 t JOIN。 + q := h.db.Table("message_detail AS d"). + Where("d.business IN ?", []string{"sms", ""}) // ''=回填窗口兼容(回填完空集) + if v := strings.TrimSpace(c.Query("task_no")); v != "" { + q = q.Joins("JOIN message_task t ON t.id = d.task_id"). + Where("t.task_no = ?", v) + } + if v := strings.TrimSpace(c.Query("mobile")); v != "" { + q = q.Where("d.mobile LIKE ?", "%"+v) // 尾号匹配(契约:模糊·尾号) + } + if v := intQuery(c, "status", -1); v >= 0 { + q = q.Where("d.status = ?", v) + } + if v := strings.TrimSpace(c.Query("error_code")); v != "" { + q = q.Where("d.error_code = ?", v) + } + lo, err := qTime(c, "start_time") + if err != nil { + response.ErrorWithMsg(c, errors.InvalidParam, "start_time "+err.Error()) + return + } + hi, err := qTime(c, "end_time") + if err != nil { + response.ErrorWithMsg(c, errors.InvalidParam, "end_time "+err.Error()) + return + } + if lo == nil { // 缺省窗口:5 天热数据(created_at > now-5d) + t := time.Now().AddDate(0, 0, -downWindowDays) + lo = &t + } + q = q.Where("d.created_at >= ?", *lo) + if hi != nil { + q = q.Where("d.created_at <= ?", *hi) + } + var total int64 + if err := q.Session(&gorm.Session{}).Count(&total).Error; err != nil { + bizResp(c, err) + return + } + // Day66 延迟关联:窄列 Pluck 当页 id(主键逆序零 filesort);回表仅当页行。 + var ids []int64 + if total > int64((page-1)*size) { + if err := q.Session(&gorm.Session{}).Order("d.id DESC"). + Limit(size).Offset((page-1)*size).Pluck("d.id", &ids).Error; err != nil { + bizResp(c, err) + return + } + } + type scanRow struct { + ID int64 + TaskID int64 + TaskNo string + Mobile string + Province string + Carrier string + Status int8 + ErrorCode string + ExtCode string + CallData string + Fee float64 + CreatedAt time.Time + } + var rows []scanRow + if len(ids) > 0 { // 回表 JOIN t 拿 task_no 展示列(当页≤100 行 PK eq_ref 无碍)。 + if err := h.db.Table("message_detail AS d"). + Joins("JOIN message_task t ON t.id = d.task_id"). + Where("d.id IN ?", ids). + Select("d.id, d.task_id, t.task_no, d.mobile, d.province, d.carrier, " + + "d.status, d.error_code, d.ext_code, d.call_data, d.fee, d.created_at"). + Order("d.id DESC").Scan(&rows).Error; err != nil { + bizResp(c, err) + return + } + } + list := make([]downDetailDTO, 0, len(rows)) + for _, r := range rows { + list = append(list, downDetailDTO{ + ID: r.ID, TaskID: r.TaskID, TaskNo: r.TaskNo, Mobile: r.Mobile, + Province: r.Province, Carrier: r.Carrier, Status: r.Status, + ErrorCode: r.ErrorCode, ExtCode: r.ExtCode, CallData: r.CallData, + Fee: r.Fee, CreatedAt: fmtTime(r.CreatedAt), + }) + } + response.Success(c, gin.H{"list": list, "total": total}) +} + +// ---- D25:通道日志钻入(GET /record/down/details/:id/channel-logs) ---- + +// channelLogEntryDTO 通道侧交互记录(契约 record.ts ChannelLogEntry)。 +type channelLogEntryDTO struct { + At fmtTime `json:"at"` + Kind string `json:"kind"` + Level int8 `json:"level"` + MsgID string `json:"msg_id"` + Detail string `json:"detail"` + LatencyMs int `json:"latency_ms"` +} + +// detailChannelLogs 明细→段级 msg_id(message_report_seg)→channel_log 交互留痕。 +// 拦截/待发未投通道无段记录→空列表(connect 类聚合行无 msg_id,不纳入钻入口径)。 +func (h *recordHandler) detailChannelLogs(c *gin.Context) { + id, err := strconv.ParseInt(c.Param("id"), 10, 64) + if err != nil || id <= 0 { + response.ErrorWithMsg(c, errors.InvalidParam, "明细 id 非法") + return + } + var d entity.MessageDetail + if err := h.db.Select("id").First(&d, id).Error; err != nil { + response.ErrorWithMsg(c, errors.NotFound, "明细不存在") + return + } + var msgIDs []string + if err := h.db.Model(&entity.MessageReportSeg{}).Select("msg_id"). + Where("detail_id = ?", id).Scan(&msgIDs).Error; err != nil { + bizResp(c, err) + return + } + list := []channelLogEntryDTO{} // 空列表非 nil(契约 {total:0,list:[]}) + if len(msgIDs) > 0 { + var logs []entity.ChannelLog + if err := h.db.Where("msg_id IN ?", msgIDs). + Order("created_at ASC, id ASC").Find(&logs).Error; err != nil { + bizResp(c, err) + return + } + for _, l := range logs { + list = append(list, channelLogEntryDTO{ + At: fmtTime(l.CreatedAt), Kind: l.Kind, Level: l.Level, + MsgID: l.MsgID, Detail: l.Detail, LatencyMs: l.LatencyMs, + }) + } + } + response.Success(c, gin.H{"total": len(list), "list": list}) +} + +// ---- D24-25 v2:下行明细富查询(GET /sms/downlink-details) ---- +// 契约=web/src/api/sms.ts DownlinkDetailRow/Query(三行筛选+展开高级,分页默认 +// 10/页);数据=message_detail JOIN task/account/channel + report_seg 聚合 +// (raw_code 通道原始码;MAX 使长短信任一段失败优先呈现)。耗时=回执-发送秒数。 + +// downlinkRowDTO v2 富表格行(字段与契约逐一对应;account_sub=账号备注)。 +type downlinkRowDTO struct { + BatchID int64 `json:"batch_id"` + TaskNo string `json:"task_no"` + AccountID int64 `json:"account_id"` + AccountName string `json:"account_name"` + AccountSub string `json:"account_sub"` + ParentAccountID int64 `json:"parent_account_id"` + ChannelID int64 `json:"channel_id"` + ChannelCode string `json:"channel_code"` + ChannelName string `json:"channel_name"` + ChannelNumber string `json:"channel_number"` // code+ext_code 拼接 + ExtCode string `json:"ext_code"` + Mobile string `json:"mobile"` + Carrier string `json:"carrier"` + Province string `json:"province"` + Content string `json:"content"` + CreatedAt fmtTime `json:"created_at"` + SendAt *fmtTime `json:"send_at"` + ReportAt *fmtTime `json:"report_at"` + Fee float64 `json:"fee"` + DurationS *int64 `json:"duration_s"` // 回执-发送(秒;未达 null) + Status int8 `json:"status"` + RawCode string `json:"raw_code"` // 通道原始码(DELIVRD/FD:047…) + ErrorCode string `json:"error_code"` // 转义码(ISC:xxx;成功空) + Source int8 `json:"source"` + CallData string `json:"call_data"` +} + +// downlinkConcat 通道号拼接 SQL 表达式(MySQL CONCAT / SQLite ||,方言分支保两库)。 +func downlinkConcat(db *gorm.DB, a, b string) string { + if db.Dialector != nil && db.Name() == "mysql" { + return "CONCAT(" + a + ", " + b + ")" + } + return "(" + a + " || " + b + ")" +} + +// downlinkDuration 秒差 SQL 表达式(send_at→report_at;NULL 传播返回 NULL; +// SQLite +0.5 修正 julianday 亚秒截断,MySQL TIMESTAMPDIFF 原生秒差)。 +func downlinkDuration(db *gorm.DB, from, to string) string { + if db.Dialector != nil && db.Name() == "mysql" { + return fmt.Sprintf("TIMESTAMPDIFF(SECOND, %s, %s)", from, to) + } + return fmt.Sprintf("CAST((julianday(%s) - julianday(%s)) * 86400 + 0.5 AS INTEGER)", to, from) +} + +// Day67 回表段 raw_code 改相关标量子查询(见 downlinkDetails 内注释);原 +// downlinkSegJoin 全表 GROUP BY 派生表随 seg 表 178 万行退化已移除。 + +// downlinkDetails GET /sms/downlink-details——号码级明细 v2(全筛选语义见契约 +// sms.ts DownlinkDetailQuery;city 市级为 UI 占位后端忽略,二期回填)。 +func (h *recordHandler) downlinkDetails(c *gin.Context) { + page := intQuery(c, "page", 1) + size := intQuery(c, "page_size", 10) + if size > downlinkPageSizeMax { + size = downlinkPageSizeMax + } + // Day64 延迟关联三段式:筛选闭包(Count/分页 id 两用)——原一次性全宽 JOIN+排序在 + // 3 万+行集上 filesort 宽行(content 长文本)落盘 HDD(实测 12s),窄列分页后回表仅 10 行。 + // ch 为 LEFT JOIN(一对一 PK)不改行数,窄版保留以支持 channel_number 前缀筛选。 + lo, err := qTime(c, "start_time") + if err != nil { + response.ErrorWithMsg(c, errors.InvalidParam, "start_time "+err.Error()) + return + } + hi, err := qTime(c, "end_time") + if err != nil { + response.ErrorWithMsg(c, errors.InvalidParam, "end_time "+err.Error()) + return + } + if lo == nil { // 缺省 5 天窗(同 downDetails/前端「5 天热数据」口径);宽窗显式传 start_time。 + t := time.Now().AddDate(0, 0, -downWindowDays) + lo = &t + } + filters := func() *gorm.DB { + // Day66 单表化:business/account_id/source 条件全走 d 冗余列——原常挂 + // t/a JOIN 在 340 万行+HDD 冷缓存下逐 task 随机回表,Count 实测 29.5s + // (buffer_pool 被百万级写入冲刷后);单表走 idx_business_created 覆盖扫描。 + // 回填窗口兼容:business IN ('sms','')/source OR 0=未回填存量行,回填 + // 完成后空值段空集,条件退化为纯索引 range。 + q := h.db.Table("message_detail AS d"). + Where("d.business IN ?", []string{"sms", ""}) + // batch_id 双兼容:数字 id 或 task_no(批次钻入链统一入口;低频钻入, + // t JOIN 动态挂载,结果集小驱动无碍)。 + if v := strings.TrimSpace(c.Query("batch_id")); v != "" { + q = q.Joins("JOIN message_task t ON t.id = d.task_id") + if n, perr := strconv.ParseInt(v, 10, 64); perr == nil { + q = q.Where("t.id = ? OR t.task_no = ?", n, v) + } else { + q = q.Where("t.task_no = ?", v) + } + } + if v := intQuery(c, "account_id", 0); v > 0 { + q = q.Where("d.account_id = ?", v) + } + // 上级账号=自身+子孙集(物化路径前缀;缺 path 旧数据退 parent_id 一级; + // Day66:a JOIN 动态挂载且改挂 d.account_id——受理账号语义等价)。 + if v := intQuery(c, "parent_account_id", 0); v > 0 { + var pa entity.AccountUser + if err := h.db.Select("id", "parent_id", "path").First(&pa, v).Error; err != nil { + return q.Where("1 = 0") // 父账号不存在→恒空集(与原空响应语义等价) + } + q = q.Joins("JOIN account_user a ON a.id = d.account_id") + if pa.Path != "" { + q = q.Where("a.path LIKE ?", pa.Path+"%") + } else { + q = q.Where("a.id = ? OR a.parent_id = ?", v, v) + } + } + if v := strings.TrimSpace(c.Query("mobile")); v != "" { + q = q.Where("d.mobile LIKE ?", "%"+v+"%") + } + if v := strings.TrimSpace(c.Query("content")); v != "" { + q = q.Where("d.content LIKE ?", "%"+v+"%") + } + // 计费条数比较(fee_op 缺省 >=;契约三值)。 + if fee := c.Query("fee"); fee != "" { + if n, perr := strconv.ParseFloat(fee, 64); perr == nil { + switch c.DefaultQuery("fee_op", ">=") { + case "=": + q = q.Where("d.fee = ?", n) + case "<=": + q = q.Where("d.fee <= ?", n) + default: + q = q.Where("d.fee >= ?", n) + } + } + } + if v := intQuery(c, "source", 0); v > 0 { + q = q.Where("d.source = ? OR d.source = 0", v) // OR 0=回填窗口兼容(回填完空集) + } + if v := strings.TrimSpace(c.Query("carrier")); v != "" { + q = q.Where("d.carrier = ?", v) + } + if v := strings.TrimSpace(c.Query("province")); v != "" { + q = q.Where("d.province = ?", v) + } + if v := intQuery(c, "channel_id", 0); v > 0 { + q = q.Where("d.channel_id = ?", v) + } + if v := intQuery(c, "status", -1); v >= 0 { + q = q.Where("d.status = ?", v) + } + // 通道号码前缀(10659* / 10659 均前缀匹配,剥尾部 *;mock 同口径; + // Day66:ch JOIN 动态挂载——Count 默认路径不再常挂)。 + if v := strings.TrimSpace(c.Query("channel_number")); v != "" { + q = q.Joins("LEFT JOIN channel_channel ch ON ch.id = d.channel_id") + pref := strings.TrimRight(v, "*") + q = q.Where(downlinkConcat(h.db, "ch.code", "d.ext_code")+" LIKE ?", pref+"%") + } + if v := strings.TrimSpace(c.Query("call_data")); v != "" { + q = q.Where("d.call_data LIKE ?", "%"+v+"%") + } + // 详细状态=段级原始码(EXISTS 下推,长短信多段任一命中)。 + if v := strings.TrimSpace(c.Query("raw_code")); v != "" { + q = q.Where("EXISTS (SELECT 1 FROM message_report_seg s WHERE s.detail_id = d.id AND s.raw_code = ?)", v) + } + if raws := c.QueryArray("raw_codes[]"); len(raws) > 0 { + q = q.Where("EXISTS (SELECT 1 FROM message_report_seg s WHERE s.detail_id = d.id AND s.raw_code IN ?)", raws) + } + // 通道耗时下界(仅 >=;表达式方言分支)。 + if dur := c.Query("duration_s"); dur != "" { + if n, perr := strconv.ParseInt(dur, 10, 64); perr == nil { + q = q.Where(downlinkDuration(h.db, "d.send_at", "d.report_at")+" >= ?", n) + } + } + q = q.Where("d.created_at >= ?", *lo) // 窗在闭包外已定(含缺省 5 天) + if hi != nil { + q = q.Where("d.created_at <= ?", *hi) + } + return q + } + var total int64 + if err := filters().Session(&gorm.Session{}).Count(&total).Error; err != nil { + bizResp(c, err) + return + } + // 窄列分页取当页 detail id(created_at+id 两列排序,filesort 代价最小);空页跳过回表。 + var ids []int64 + if total > int64((page-1)*size) { + if err := filters().Order("d.created_at DESC, d.id DESC"). + Limit(size).Offset((page-1)*size).Pluck("d.id", &ids).Error; err != nil { + bizResp(c, err) + return + } + } + type scanRow struct { + BatchID int64 + TaskNo string + AccountID int64 + AccountName string + AccountSub sql.NullString + ParentAccountID int64 + ChannelID int64 + ChannelCode sql.NullString + ChannelName sql.NullString + ExtCode string + Mobile string + Carrier string + Province string + Content string + CreatedAt time.Time + SendAt *time.Time + ReportAt *time.Time + Fee float64 + DurationS sql.NullInt64 + Status int8 + RawCode sql.NullString + ErrorCode string + Source int8 + CallData string + } + var rows []scanRow + if len(ids) > 0 { + // Day67:raw_code 取相关标量子查询——只对当页 id 各做一次 idx_seg_detail + // 探测(10 行毫秒级);原 LEFT JOIN 全表 GROUP BY 派生表在 message_report_seg + // 2.2万→178万行后每请求全量物化 16.6s(HDD,EXPLAIN derived2 全索引扫), + // 同数据同结果实测 0.003s。MAX 语义不变:长短信多段字典序失败码优先。 + if err := h.db.Table("message_detail AS d"). + Joins("JOIN message_task t ON t.id = d.task_id"). + Joins("JOIN account_user a ON a.id = t.account_id"). + Joins("LEFT JOIN channel_channel ch ON ch.id = d.channel_id"). + Where("d.id IN ?", ids). + Select("t.id AS batch_id, t.task_no, t.account_id, a.username AS account_name, " + + "a.remark AS account_sub, a.parent_id AS parent_account_id, " + + "d.channel_id, ch.code AS channel_code, ch.name AS channel_name, d.ext_code, " + + "d.mobile, d.carrier, d.province, d.content, d.created_at, d.send_at, d.report_at, d.fee, " + + downlinkDuration(h.db, "d.send_at", "d.report_at") + " AS duration_s, " + + "d.status, (SELECT MAX(s.raw_code) FROM message_report_seg s WHERE s.detail_id = d.id) AS raw_code, " + + "d.error_code, t.source, d.call_data"). + Order("d.created_at DESC, d.id DESC"). + Scan(&rows).Error; err != nil { + bizResp(c, err) + return + } + } + list := make([]downlinkRowDTO, 0, len(rows)) + for _, r := range rows { + var dur *int64 + if r.DurationS.Valid { + v := r.DurationS.Int64 + dur = &v + } + list = append(list, downlinkRowDTO{ + BatchID: r.BatchID, TaskNo: r.TaskNo, AccountID: r.AccountID, + AccountName: r.AccountName, AccountSub: r.AccountSub.String, + ParentAccountID: r.ParentAccountID, ChannelID: r.ChannelID, + ChannelCode: r.ChannelCode.String, ChannelName: r.ChannelName.String, + ChannelNumber: r.ChannelCode.String + r.ExtCode, ExtCode: r.ExtCode, + Mobile: r.Mobile, Carrier: r.Carrier, Province: r.Province, + Content: r.Content, CreatedAt: fmtTime(r.CreatedAt), + SendAt: fmtTimePtr(r.SendAt), ReportAt: fmtTimePtr(r.ReportAt), + Fee: r.Fee, DurationS: dur, Status: r.Status, + RawCode: r.RawCode.String, ErrorCode: r.ErrorCode, + Source: r.Source, CallData: r.CallData, + }) + } + response.Success(c, gin.H{"list": list, "total": total}) +} diff --git a/internal/api/http/v1/record_handler_test.go b/internal/api/http/v1/record_handler_test.go new file mode 100644 index 00000000..420d1d80 --- /dev/null +++ b/internal/api/http/v1/record_handler_test.go @@ -0,0 +1,481 @@ +// record_handler_test.go Day 60(D24-25):record 域五端点——批次聚合/拦截 CSV/ +// 号码级明细(5 天窗)/通道日志钻入/下行明细 v2 全筛选(SQLite 种子对齐 msw +// mock 口径:3 账号树+2 通道+六态明细+段级回执+通道日志+拦截留痕)。 +package v1 + +import ( + "encoding/json" + "fmt" + "net/http" + "strings" + "testing" + "time" + + "github.com/gin-gonic/gin" + "github.com/glebarez/sqlite" + "gorm.io/gorm" + + "go-sms/internal/middleware" + "go-sms/internal/model/entity" + "go-sms/internal/service/account" +) + +// d60Seed 种子句柄(断言取行用;T1 今日API/T2 今日CMPP/T3 4天前WEB/T4 video/T5 6天前)。 +type d60Seed struct { + task1, task2, task3, task4, task5 int64 + d1, d2, d3, d4, d5, d7, d9, d11 int64 // 六态代表行 + t1No, t2No, t3No string +} + +func newD60Router(t *testing.T) (*gin.Engine, *gorm.DB, *d60Seed) { + t.Helper() + gin.SetMode(gin.TestMode) + db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{}) + if err != nil { + t.Fatal(err) + } + if sqlDB, e := db.DB(); e == nil { + sqlDB.SetMaxOpenConns(1) + } + if err := db.AutoMigrate(&entity.AccountUser{}, &entity.ChannelChannel{}, + &entity.MessageTask{}, &entity.MessageDetail{}, &entity.MessageReportSeg{}, + &entity.ChannelLog{}, &entity.SendBlockLog{}); err != nil { + t.Fatal(err) + } + now := time.Now() + // Day62d 跨天防护:00:00~00:35 间跑测时 now.Add(-X分钟) 落昨天, + // 「start_time=今天」断言口径破裂(total=0);钉在今日 00:35 保证相对时间同日。 + if d := now.Add(-35 * time.Minute); d.Day() != now.Day() { + now = time.Date(now.Year(), now.Month(), now.Day(), 0, 35, 0, 0, now.Location()) + } + daysAgoT := func(n int, offset time.Duration) time.Time { return now.AddDate(0, 0, -n).Add(offset) } + tp := func(t time.Time) *time.Time { return &t } + // 账号树:100001→264305/264306;100002(旁支)→264307(上级筛选可证伪)。 + accts := []entity.AccountUser{ + {Model: entity.Model{ID: 100001}, Username: "100001", Status: 1, Path: "/1/100001/", Remark: "集团总账号"}, + {Model: entity.Model{ID: 264305}, Username: "264305", Status: 1, ParentID: 100001, Path: "/1/100001/264305/", Remark: "广东移动-行业-壹通道"}, + {Model: entity.Model{ID: 264306}, Username: "264306", Status: 1, ParentID: 100001, Path: "/1/100001/264306/", Remark: "江苏联通-营销-贰通道"}, + {Model: entity.Model{ID: 100002}, Username: "100002", Status: 1, Path: "/1/100002/", Remark: "旁支根"}, + {Model: entity.Model{ID: 264307}, Username: "264307", Status: 1, ParentID: 100002, Path: "/1/100002/264307/", Remark: "北京电信-验证码通道"}, + } + for i := range accts { + if err := db.Create(&accts[i]).Error; err != nil { + t.Fatal(err) + } + } + chs := []entity.ChannelChannel{ + {Model: entity.Model{ID: 1}, Name: "移动壹通道", Code: "10690331"}, + {Model: entity.Model{ID: 2}, Name: "联通贰通道", Code: "10659"}, + } + for i := range chs { + if err := db.Create(&chs[i]).Error; err != nil { + t.Fatal(err) + } + } + s := &d60Seed{ + task1: 829289401, task2: 829289402, task3: 829289403, task4: 829289404, task5: 829289405, + d1: 8292894010001, d2: 8292894010002, d3: 8292894010003, d4: 8292894010004, + d5: 8292894010005, d7: 8292894020002, d9: 8292894030001, d11: 8292894050001, + t1No: "T20260914001", t2No: "T20260914002", t3No: "T20260910003", + } + tasks := []entity.MessageTask{ + {ID: s.task1, TaskNo: s.t1No, AccountID: 264305, ChannelID: 1, SendType: 1, + Sign: "【盈讯网络】", Content: "【盈讯网络】您的验证码是 8837,5 分钟内有效。", + MobileCount: 6, SuccessCount: 2, FailCount: 1, FeeTotal: 5, + Status: 2, CreatedAt: now.Add(-30 * time.Minute)}, + {ID: s.task2, TaskNo: s.t2No, AccountID: 264306, ChannelID: 2, SendType: 1, + Sign: "【盈讯网络】", Content: "【盈讯网络】会员日活动开启。", + MobileCount: 2, SuccessCount: 1, FailCount: 1, FeeTotal: 2, + Status: 2, Source: 2, CreatedAt: now.Add(-25 * time.Minute)}, + {ID: s.task3, TaskNo: s.t3No, AccountID: 264307, ChannelID: 2, SendType: 3, + Sign: "【盈讯网络】", Content: "【盈讯网络】账单提醒。", MobileCount: 1, + SuccessCount: 1, FeeTotal: 1, Status: 1, Source: 4, CreatedAt: daysAgoT(4, time.Hour)}, + {ID: s.task4, TaskNo: "T20260914004", AccountID: 264305, SendType: 1, + Sign: "v", Content: "视频短信", Business: "video", + MobileCount: 1, SuccessCount: 1, Status: 2, CreatedAt: now.Add(-20 * time.Minute)}, + {ID: s.task5, TaskNo: "T20260908005", AccountID: 264305, ChannelID: 1, SendType: 1, + Sign: "【盈讯网络】", Content: "【盈讯网络】六天前批次。", MobileCount: 1, + SuccessCount: 1, FeeTotal: 1, Status: 2, CreatedAt: daysAgoT(6, time.Hour)}, + } + for i := range tasks { + if err := db.Create(&tasks[i]).Error; err != nil { + t.Fatal(err) + } + } + return seedD60Details(t, db, s, now, daysAgoT, tp) +} + +// seedD60Details 明细六态+段级回执+通道日志+拦截留痕,并装配路由。 +func seedD60Details(t *testing.T, db *gorm.DB, s *d60Seed, now time.Time, + daysAgoT func(int, time.Duration) time.Time, tp func(time.Time) *time.Time) (*gin.Engine, *gorm.DB, *d60Seed) { + t.Helper() + mk := func(id, taskID, acc, ch int64, mobile, carrier, prov string, status int8, + errCode, ext string, fee float64, created time.Time, send, report *time.Time) entity.MessageDetail { + return entity.MessageDetail{ + SnowflakeModel: entity.SnowflakeModel{ID: id, CreatedAt: created}, + TaskID: taskID, AccountID: acc, ChannelID: ch, Mobile: mobile, + Content: "【盈讯网络】您的验证码是 8837,5 分钟内有效。", Province: prov, + Carrier: carrier, Status: status, ErrorCode: errCode, ExtCode: ext, + Fee: fee, SendAt: send, ReportAt: report, + } + } + // T1 六态:成功×2(含长短信 fee2)/失败 FD:047/拦截/在途/待发;ext=6108; + // 秒级时刻(created→send 1s,send→report 4s/2s——duration_s 断言口径)。 + c1 := now.Add(-30 * time.Minute) + c2 := now.Add(-25 * time.Minute) + details := []entity.MessageDetail{ + mk(s.d1, s.task1, 264305, 1, "13800000001", "移动", "广东", 2, "", "6108", 1, + c1, tp(c1.Add(time.Second)), tp(c1.Add(5*time.Second))), + mk(s.d2, s.task1, 264305, 1, "13800000002", "移动", "广东", 2, "", "6108", 2, + c1, tp(c1.Add(time.Second)), tp(c1.Add(5*time.Second))), + mk(s.d3, s.task1, 264305, 1, "13800000003", "移动", "北京", 3, "ISC:012", "6108", 1, + c1, tp(c1.Add(time.Second)), tp(c1.Add(3*time.Second))), + mk(s.d4, s.task1, 264305, 1, "13800000004", "电信", "上海", 5, "ISC:031", "", 0, + c1, nil, nil), + mk(s.d5, s.task1, 264305, 1, "13800000005", "联通", "江苏", 1, "", "6108", 1, + c1, tp(c1.Add(time.Second)), nil), + {SnowflakeModel: entity.SnowflakeModel{ID: 8292894010006, CreatedAt: c1}, + TaskID: s.task1, AccountID: 264305, ChannelID: 1, Mobile: "13800000006", + Content: "【盈讯网络】您的验证码是 8837,5 分钟内有效。", Province: "浙江", + Carrier: "移动", Status: 0, Fee: 1}, + // T2(CMPP):成功+失败 GB:0001;ext=0117。 + mk(8292894020001, s.task2, 264306, 2, "13900000001", "联通", "江苏", 2, "", "0117", 1, + c2, tp(c2.Add(time.Second)), tp(c2.Add(5*time.Second))), + mk(s.d7, s.task2, 264306, 2, "13900000002", "联通", "江苏", 3, "ISC:027", "0117", 1, + c2, tp(c2.Add(time.Second)), tp(c2.Add(3*time.Second))), + // T3(旁支,4 天前)。 + mk(s.d9, s.task3, 264307, 2, "13700000001", "电信", "北京", 2, "", "0117", 1, + daysAgoT(4, time.Hour), tp(daysAgoT(4, time.Hour).Add(time.Second)), + tp(daysAgoT(4, time.Hour).Add(5*time.Second))), + // T4(video,业务隔离验证)。 + {SnowflakeModel: entity.SnowflakeModel{ID: 8292894040001, CreatedAt: now.Add(-20 * time.Minute)}, + TaskID: s.task4, AccountID: 264305, Mobile: "13800000009", + Content: "视频短信", Status: 2, Fee: 1, + Business: "video"}, // Day66:明细 business 单表化(T4 原靠 t.business JOIN 隔离) + // T5(6 天前,5 天窗口外)。 + mk(s.d11, s.task5, 264305, 1, "13800000010", "移动", "广东", 2, "", "6108", 1, + daysAgoT(6, time.Hour), tp(daysAgoT(6, time.Hour).Add(time.Second)), + tp(daysAgoT(6, time.Hour).Add(5*time.Second))), + } + // Day66:detail.source 冗余对齐种子的 task 来源(T2=CMPP 2/T3=WEB 4/其余 API 1)。 + srcByTask := map[int64]int8{s.task2: 2, s.task3: 4} + for i := range details { + if s, ok := srcByTask[details[i].TaskID]; ok { + details[i].Source = s + } + } + for i := range details { + if err := db.Create(&details[i]).Error; err != nil { + t.Fatal(err) + } + } + segs := []entity.MessageReportSeg{ + {DetailID: s.d1, ChannelID: 1, MsgID: "M1001", Mobile: "13800000001", RawCode: "DELIVRD"}, + {DetailID: s.d2, ChannelID: 1, MsgID: "M1002", Mobile: "13800000002", PkNumber: 1, RawCode: "DELIVRD"}, + {DetailID: s.d2, ChannelID: 1, MsgID: "M1003", Mobile: "13800000002", PkNumber: 2, RawCode: "DELIVRD"}, + {DetailID: s.d3, ChannelID: 1, MsgID: "M1004", Mobile: "13800000003", RawCode: "FD:047"}, + {DetailID: 8292894020001, ChannelID: 2, MsgID: "M1005", Mobile: "13900000001", RawCode: "DELIVRD"}, + {DetailID: s.d7, ChannelID: 2, MsgID: "M1006", Mobile: "13900000002", RawCode: "GB:0001"}, + {DetailID: s.d9, ChannelID: 2, MsgID: "M1007", Mobile: "13700000001", RawCode: "DELIVRD"}, + {DetailID: s.d11, ChannelID: 1, MsgID: "M1008", Mobile: "13800000010", RawCode: "DELIVRD"}, + } + for i := range segs { + if err := db.Create(&segs[i]).Error; err != nil { + t.Fatal(err) + } + } + logs := []entity.ChannelLog{ + {Model: entity.Model{CreatedAt: now.Add(-29 * time.Minute)}, ChannelID: 1, Kind: "submit", MsgID: "M1001", Detail: "CMPP2 submit 分包下发", LatencyMs: 30}, + {Model: entity.Model{CreatedAt: now.Add(-25 * time.Minute)}, ChannelID: 1, Kind: "deliver", MsgID: "M1001", Detail: "DELIV 回执:成功", LatencyMs: 45}, + {Model: entity.Model{CreatedAt: now.Add(-27 * time.Minute)}, ChannelID: 1, Kind: "deliver_fail", Level: 2, MsgID: "M1004", Detail: "回执错误:FD:047", LatencyMs: 120}, + } + for i := range logs { + if err := db.Create(&logs[i]).Error; err != nil { + t.Fatal(err) + } + } + if err := db.Create(&entity.SendBlockLog{TaskNo: s.t1No, AccountID: 264305, + Mobile: "13800000004", Interceptor: "keyword", Code: "ISC:031", + Msg: "内容不合规拦截"}).Error; err != nil { + t.Fatal(err) + } + acctSvc := account.NewService(db, account.BcryptMinCost) + r := gin.New() + Register(r.Group("/api/v1"), Deps{ + Account: acctSvc, + Auth: middleware.AuthJWTWithChecker(d25Secret, acctSvc.CheckEnabled), + DB: db, + }) + return r, db, s +} + +// d60Token 测试 JWT(customer 角色;record 端点仅 JWT 保护)。 +func d60Token(t *testing.T, id int64) string { + t.Helper() + tok, err := middleware.SignAccessToken(d25Secret, id, fmt.Sprintf("%d", id), "customer", time.Minute) + if err != nil { + t.Fatal(err) + } + return tok +} + +// d60Get 断言 200 + code=ISC:000,返回 data 原始 JSON。 +func d60Get(t *testing.T, r *gin.Engine, path string) map[string]json.RawMessage { + t.Helper() + w := doReq(r, http.MethodGet, path, d60Token(t, 264305)) + if w.Code != http.StatusOK { + t.Fatalf("GET %s → HTTP %d: %s", path, w.Code, w.Body.String()) + } + var body struct { + Code string `json:"code"` + Data map[string]json.RawMessage `json:"data"` + } + if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil { + t.Fatal(err) + } + if body.Code != "ISC:000" { + t.Fatalf("GET %s → code=%s: %s", path, body.Code, w.Body.String()) + } + return body.Data +} + +func d60Total(t *testing.T, data map[string]json.RawMessage) int64 { + t.Helper() + var n int64 + if err := json.Unmarshal(data["total"], &n); err != nil { + t.Fatal(err) + } + return n +} + +func d60Rows(t *testing.T, data map[string]json.RawMessage) []map[string]any { + t.Helper() + var rows []map[string]any + if err := json.Unmarshal(data["list"], &rows); err != nil { + t.Fatal(err) + } + return rows +} + +// d60GetExpectErr 断言非 2xx 业务码+HTTP 状态。 +func d60GetExpectErr(t *testing.T, r *gin.Engine, path string, wantHTTP int, wantCode string) { + t.Helper() + w := doReq(r, http.MethodGet, path, d60Token(t, 264305)) + if w.Code != wantHTTP { + t.Fatalf("GET %s → HTTP %d, 期望 %d: %s", path, w.Code, wantHTTP, w.Body.String()) + } + var body struct { + Code string `json:"code"` + } + if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil || body.Code != wantCode { + t.Fatalf("GET %s → code=%s, 期望 %s: %s", path, body.Code, wantCode, w.Body.String()) + } +} + +func TestRecordDownList_FiltersAndAgg(t *testing.T) { + r, _, s := newD60Router(t) + // 默认:4 个 sms 批次(video T4 隔离),最新在前。 + data := d60Get(t, r, "/api/v1/record/down?page=1&page_size=10") + if got := d60Total(t, data); got != 4 { + t.Fatalf("批次 total = %d, 期望 4(video 隔离)", got) + } + rows := d60Rows(t, data) + if rows[0]["task_no"] != "T20260908005" { // id DESC:T5(829289405)最大 + t.Fatalf("排序首行 = %v, 期望 T5(id DESC)", rows[0]["task_no"]) + } + // T1 行:拦截 1/发送中 2(D5 提交+D6 待发)。 + var t1 map[string]any + for _, row := range rows { + if row["task_no"] == s.t1No { + t1 = row + } + } + if t1 == nil || t1["intercepted_count"] != float64(1) || t1["sending_count"] != float64(2) { + t.Fatalf("T1 聚合 = %+v, 期望 intercepted=1 sending=2", t1) + } + // task_no 精确 / status / 时间窗。 + if got := d60Total(t, d60Get(t, r, "/api/v1/record/down?task_no="+s.t3No)); got != 1 { + t.Fatalf("task_no 筛选 total = %d, 期望 1", got) + } + if got := d60Total(t, d60Get(t, r, "/api/v1/record/down?status=1")); got != 1 { + t.Fatalf("status=1 total = %d, 期望 1", got) + } + today := time.Now().Format("2006-01-02") + if got := d60Total(t, d60Get(t, r, "/api/v1/record/down?start_time="+today)); got != 2 { + t.Fatalf("start_time=今天 total = %d, 期望 2", got) + } +} + +func TestRecordDownInterceptedCSV(t *testing.T) { + r, _, s := newD60Router(t) + // 有拦截:CSV header+1 行,reason 取 send_block_log 留痕。 + w := doReq(r, http.MethodGet, fmt.Sprintf("/api/v1/record/down/%d/intercepted?format=csv", s.task1), + d60Token(t, 264305)) + if w.Code != http.StatusOK { + t.Fatalf("CSV HTTP %d: %s", w.Code, w.Body.String()) + } + if ct := w.Header().Get("Content-Type"); ct != "text/csv; charset=utf-8" { + t.Fatalf("Content-Type = %s", ct) + } + lines := strings.Split(strings.TrimRight(w.Body.String(), "\n"), "\n") + if len(lines) != 2 || lines[0] != "mobile,error_code,reason" { + t.Fatalf("CSV 行 = %v", lines) + } + if lines[1] != "13800000004,ISC:031,内容不合规拦截" { + t.Fatalf("拦截行 = %q", lines[1]) + } + // 无拦截/任务不存在→404 业务码;格式不支持→400。 + d60GetExpectErr(t, r, fmt.Sprintf("/api/v1/record/down/%d/intercepted", s.task2), 404, "ISC:404") + d60GetExpectErr(t, r, "/api/v1/record/down/999/intercepted", 404, "ISC:404") + d60GetExpectErr(t, r, fmt.Sprintf("/api/v1/record/down/%d/intercepted?format=xlsx", s.task1), 400, "ISC:400") +} + +func TestRecordDownDetails(t *testing.T) { + r, _, s := newD60Router(t) + // 默认 5 天窗口:video(T4)与 6 天前(T5)被裁→9。 + if got := d60Total(t, d60Get(t, r, "/api/v1/record/down/details")); got != 9 { + t.Fatalf("明细 total = %d, 期望 9(5 天窗+业务隔离)", got) + } + if got := d60Total(t, d60Get(t, r, "/api/v1/record/down/details?mobile=000001")); got != 3 { + t.Fatalf("尾号 000001 total = %d, 期望 3(138/139/137 三段各一)", got) + } + if got := d60Total(t, d60Get(t, r, "/api/v1/record/down/details?task_no="+s.t3No)); got != 1 { + t.Fatalf("task_no 钻入 total = %d, 期望 1", got) + } + data := d60Get(t, r, "/api/v1/record/down/details?status=5") + rows := d60Rows(t, data) + if len(rows) != 1 || rows[0]["error_code"] != "ISC:031" { + t.Fatalf("status=5 rows = %+v", rows) + } + if got := d60Total(t, d60Get(t, r, "/api/v1/record/down/details?error_code=ISC:027")); got != 1 { + t.Fatalf("error_code=ISC:027 total = %d, 期望 1", got) + } + start := time.Now().AddDate(0, 0, -7).Format("2006-01-02") + if got := d60Total(t, d60Get(t, r, "/api/v1/record/down/details?start_time="+start)); got != 10 { + t.Fatalf("7 天窗 total = %d, 期望 10", got) + } +} + +func TestRecordDetailChannelLogs(t *testing.T) { + r, _, s := newD60Router(t) + // 成功明细:submit→deliver 两段按时间序。 + data := d60Get(t, r, fmt.Sprintf("/api/v1/record/down/details/%d/channel-logs", s.d1)) + if got := d60Total(t, data); got != 2 { + t.Fatalf("通道日志 total = %d, 期望 2", got) + } + rows := d60Rows(t, data) + if rows[0]["kind"] != "submit" || rows[1]["kind"] != "deliver" { + t.Fatalf("日志序 = %v→%v", rows[0]["kind"], rows[1]["kind"]) + } + if rows[1]["msg_id"] != "M1001" || rows[1]["latency_ms"] != float64(45) { + t.Fatalf("回执行 = %+v", rows[1]) + } + // 拦截明细:未投通道→空列表(非 null)。 + data = d60Get(t, r, fmt.Sprintf("/api/v1/record/down/details/%d/channel-logs", s.d4)) + if got := d60Total(t, data); got != 0 { + t.Fatalf("拦截明细日志 total = %d, 期望 0", got) + } + if string(data["list"]) != "[]" { + t.Fatalf("拦截明细 list = %s, 期望 []", data["list"]) + } + d60GetExpectErr(t, r, "/api/v1/record/down/details/999999/channel-logs", 404, "ISC:404") +} + +func TestSmsDownlinkDetails_RowShape(t *testing.T) { + r, _, s := newD60Router(t) + // batch_id 数字钻入+成功态:T1 两行(长短信),字段完整性逐项。 + data := d60Get(t, r, fmt.Sprintf("/api/v1/sms/downlink-details?batch_id=%d&status=2", s.task1)) + if got := d60Total(t, data); got != 2 { + t.Fatalf("v2 成功行 total = %d, 期望 2", got) + } + rows := d60Rows(t, data) + // 同 created 秒并列按 id DESC:rows[0]=D2(长短信 fee2),rows[1]=D1。 + row := rows[0] + want := map[string]any{ + "batch_id": float64(s.task1), "task_no": s.t1No, "account_id": 264305.0, + "account_name": "264305", "account_sub": "广东移动-行业-壹通道", + "parent_account_id": 100001.0, "channel_id": 1.0, + "channel_code": "10690331", "channel_name": "移动壹通道", + "channel_number": "106903316108", "ext_code": "6108", + "mobile": "13800000002", "carrier": "移动", "province": "广东", + "raw_code": "DELIVRD", "error_code": "", "source": 1.0, + } + for k, v := range want { + if row[k] != v { + t.Fatalf("行字段 %s = %v, 期望 %v", k, row[k], v) + } + } + if row["send_at"] == nil || row["report_at"] == nil || row["duration_s"] != 4.0 { + t.Fatalf("耗时三元组 = send:%v report:%v duration:%v", row["send_at"], row["report_at"], row["duration_s"]) + } + if !strings.Contains(row["created_at"].(string), " ") { // 非 RFC3339(无 T) + t.Fatalf("created_at = %v, 期望 YYYY-MM-DD HH:mm:ss", row["created_at"]) + } + // 长短信行(rows[0])fee=2;次行 D1 fee=1;batch_id 传 task_no 文本等价(双兼容)。 + if rows[0]["fee"] != 2.0 || rows[1]["fee"] != 1.0 { + t.Fatalf("fee = %v/%v, 期望 2/1", rows[0]["fee"], rows[1]["fee"]) + } + if got := d60Total(t, d60Get(t, r, "/api/v1/sms/downlink-details?batch_id="+s.t2No)); got != 2 { + t.Fatalf("task_no 钻入 total = %d, 期望 2", got) + } + // 旁支不串树:parent=100001 命中 264305/264306 树。Day64 起无 start_time 默认 5 天窗 + // (同 downDetails),T5 六天前行(D11)被排除→8 行;100002 仅 D9(4 天前,窗内)1 行。 + if got := d60Total(t, d60Get(t, r, "/api/v1/sms/downlink-details?parent_account_id=100001")); got != 8 { + t.Fatalf("parent=100001 total = %d, 期望 8", got) + } + if got := d60Total(t, d60Get(t, r, "/api/v1/sms/downlink-details?parent_account_id=100002")); got != 1 { + t.Fatalf("parent=100002 total = %d, 期望 1", got) + } +} + +func TestSmsDownlinkDetails_Filters(t *testing.T) { + r, _, s := newD60Router(t) + base := "/api/v1/sms/downlink-details" + cases := []struct { + name, q string + want int64 + }{ + {"通道号码前缀(剥*)", "?channel_number=10659*&start_time=2020-01-01", 3}, // D7/D8/D9 + {"通道号码前缀(无*)", "?channel_number=10659&start_time=2020-01-01", 3}, // 同上 + {"原始码精确", "?raw_code=FD:047&start_time=2020-01-01", 1}, // D3 + {"原始码多值", "?raw_codes[]=GB:0001&raw_codes[]=FD:047&start_time=2020-01-01", 2}, + {"耗时下界4s", "?duration_s=4&start_time=2020-01-01", 5}, // D1/D2/D8/D9/D11 + {"计费条数=2", "?fee=2&fee_op==&start_time=2020-01-01", 1}, // D2 + {"计费条数<=1", "?fee=1&fee_op=<=&start_time=2020-01-01", 9}, + {"来源CMPP", "?source=2&start_time=2020-01-01", 2}, // T2 两行 + {"拦截态空耗时", "?status=5&start_time=2020-01-01", 1}, // D4 + {"号码模糊", "?mobile=138000000&start_time=2020-01-01", 7}, // 138 段 + {"内容模糊", "?content=验证码是&start_time=2020-01-01", 10}, // 全部 sms 明细内容 + {"运营商", "?carrier=电信&start_time=2020-01-01", 2}, // D4/D9 + {"省份", "?province=北京&start_time=2020-01-01", 2}, // D3/D9 + {"通道id", "?channel_id=1&start_time=2020-01-01", 7}, + } + for _, c := range cases { + if got := d60Total(t, d60Get(t, r, base+c.q)); got != c.want { + t.Fatalf("%s total = %d, 期望 %d", c.name, got, c.want) + } + } + // 拦截行:send/report/duration 均 null(可空语义)。 + rows := d60Rows(t, d60Get(t, r, base+"?status=5")) + if rows[0]["send_at"] != nil || rows[0]["report_at"] != nil || rows[0]["duration_s"] != nil { + t.Fatalf("拦截行可空字段 = %v", rows[0]) + } + // 分页:全量 10 行(放宽窗口),page_size=3 第 2 页 3 行且序=created DESC。 + full := "?start_time=2020-01-01&page_size=3&page=2" + rows = d60Rows(t, d60Get(t, r, base+full)) + if len(rows) != 3 { + t.Fatalf("分页第 2 页 = %d 行, 期望 3", len(rows)) + } + if rows[0]["task_no"] != s.t1No || rows[2]["task_no"] != s.t1No { + t.Fatalf("分页序异常: %v→%v", rows[0]["task_no"], rows[2]["task_no"]) + } + // 时间窗:仅今天→T1/T2 的 8 行。 + today := time.Now().Format("2006-01-02") + if got := d60Total(t, d60Get(t, r, base+"?start_time="+today)); got != 8 { + t.Fatalf("当天 total = %d, 期望 8", got) + } + // Day64 默认窗:无 start_time 缺省 5 天(同 downDetails)——T3(4 天前)含、T5(6 天前)排除。 + if got := d60Total(t, d60Get(t, r, base)); got != 9 { + t.Fatalf("默认 5 天窗 total = %d, 期望 9", got) + } +} diff --git a/internal/api/http/v1/record_repush_handler.go b/internal/api/http/v1/record_repush_handler.go new file mode 100644 index 00000000..71dbda18 --- /dev/null +++ b/internal/api/http/v1/record_repush_handler.go @@ -0,0 +1,240 @@ +// record_repush_handler.go 阶段 5 收尾(D28/Day58 挂账清偿):回执重推域 +// 四端点——回执分页/重推受理(30 天窗口双闸后端侧)/挂起明细分页/ +// 手动配对四方式。契约=web/src/api/record.ts(RepushReport/RepushRequest/ +// PendingDetail/PairRequest)+ msw fe4RepushHandlers 响应形状({code,msg,data})。 +// 查询类 JWT 保护即可(与 record 域同口径);配对涉及资金动作但与回执消费 +// 语义等价(finalizeDetail 单一实现),操作留痕挂账审计补全。 +package v1 + +import ( + "strconv" + "strings" + "time" + + "github.com/gin-gonic/gin" + "gorm.io/gorm" + + "go-sms/internal/pkg/errors" + "go-sms/internal/pkg/response" + "go-sms/internal/service/report" +) + +// repushPageSizeMax 重推域分页上限。 +const repushPageSizeMax = 1000 + +// registerRepushRoutes 注册回执重推域端点(pair=nil 不注册——装配缺服务时 +// 前端 404 优于半可用)。 +func registerRepushRoutes(protected *gin.RouterGroup, pair *report.PairService) { + h := &repushHandler{pair: pair} + protected.GET("/record/repush", h.list) + protected.POST("/record/repush", h.create) + protected.GET("/record/repush/pending", h.pending) + protected.POST("/record/repush/pair", h.createPair) +} + +type repushHandler struct{ pair *report.PairService } + +// repushReportDTO 回执行(契约 record.ts RepushReport;report JOIN detail JOIN task)。 +type repushReportDTO struct { + ID int64 `json:"id"` + DetailID int64 `json:"detail_id"` + TaskNo string `json:"task_no"` + Mobile string `json:"mobile"` + AccountID int64 `json:"account_id"` + Status string `json:"status"` // SUCCESS/FAILURE/UNKNOWN(Day55 三态) + RawCode string `json:"raw_code"` + ErrorCode string `json:"error_code"` + ReportAt fmtTime `json:"report_at"` + PushStatus int8 `json:"push_status"` // 0未推 1已推 2失败(重推候选) + PushedAt *fmtTime `json:"pushed_at"` +} + +// list GET /record/repush——回执分页(account_id/mobile 尾号模糊/task_no 精确/ +// status/时间窗),按 report_at 降序。 +func (h *repushHandler) list(c *gin.Context) { + page, _ := strconv.ParseInt(c.DefaultQuery("page", "1"), 10, 64) + size, _ := strconv.ParseInt(c.DefaultQuery("page_size", "100"), 10, 64) + if page < 1 { + page = 1 + } + if size < 1 || size > repushPageSizeMax { + size = 100 + } + sess := h.pair.DB().WithContext(c.Request.Context()). + Table("message_report AS r"). + Joins("JOIN message_detail d ON d.id = r.detail_id"). + Joins("JOIN message_task t ON t.id = d.task_id") + if v := strings.TrimSpace(c.Query("task_no")); v != "" { + sess = sess.Where("t.task_no = ?", v) + } + if v := strings.TrimSpace(c.Query("mobile")); v != "" { + sess = sess.Where("d.mobile LIKE ?", "%"+v) + } + if v, err := strconv.ParseInt(c.Query("account_id"), 10, 64); err == nil && v > 0 { + sess = sess.Where("d.account_id = ?", v) + } + if v := strings.TrimSpace(c.Query("status")); v != "" { + sess = sess.Where("r.status = ?", v) + } + if t, err := qTime(c, "start_time"); err != nil { + response.ErrorWithMsg(c, errors.InvalidParam, "start_time "+err.Error()) + return + } else if t != nil { + sess = sess.Where("r.report_at >= ?", *t) + } + if t, err := qTime(c, "end_time"); err != nil { + response.ErrorWithMsg(c, errors.InvalidParam, "end_time "+err.Error()) + return + } else if t != nil { + sess = sess.Where("r.report_at <= ?", *t) + } + var total int64 + if err := sess.Session(&gorm.Session{}).Count(&total).Error; err != nil { + response.Error(c, errors.InternalError) + return + } + var rows []repushReportDTO + if err := sess.Session(&gorm.Session{}). + Select(`r.id, r.detail_id, t.task_no, d.mobile, d.account_id, + r.status, r.raw_code, r.error_code, r.report_at, r.push_status, r.pushed_at`). + Order("r.report_at DESC"). + Limit(int(size)).Offset(int((page - 1) * size)). + Scan(&rows).Error; err != nil { + response.Error(c, errors.InternalError) + return + } + response.Success(c, gin.H{"list": rows, "total": total}) +} + +// repushCreateReq 重推受理请求体。 +type repushCreateReq struct { + AccountID int64 `json:"account_id"` + Mobiles []string `json:"mobiles"` + StartTime string `json:"start_time"` + EndTime string `json:"end_time"` +} + +// create POST /record/repush——重推受理(同步执行版;30 天窗口第二道闸: +// 必填/格式/s<=e/不早于 30 天/不晚于当前)→ {task_id, count}。 +func (h *repushHandler) create(c *gin.Context) { + var req repushCreateReq + if err := c.ShouldBindJSON(&req); err != nil { + response.ErrorWithMsg(c, errors.InvalidParam, err.Error()) + return + } + if req.StartTime == "" || req.EndTime == "" { + response.ErrorWithMsg(c, errors.InvalidParam, "时间窗必填") + return + } + start, err := parseTimeParam(req.StartTime) + if err != nil { + response.ErrorWithMsg(c, errors.InvalidParam, "start_time "+err.Error()) + return + } + end, err := parseTimeParam(req.EndTime) + if err != nil { + response.ErrorWithMsg(c, errors.InvalidParam, "end_time "+err.Error()) + return + } + now := time.Now() + switch { + case start.After(*end): + response.ErrorWithMsg(c, errors.InvalidParam, "开始时间晚于结束时间") + return + case start.Before(now.AddDate(0, 0, -report.RepushWindowDays)): + response.ErrorWithMsg(c, errors.InvalidParam, "窗口超出 30 天") + return + case end.After(now.Add(5 * time.Minute)): + response.ErrorWithMsg(c, errors.InvalidParam, "结束时间不能晚于当前时间") + return + } + taskID, count, err := h.pair.Repush(c.Request.Context(), report.RepushRequest{ + AccountID: req.AccountID, Mobiles: req.Mobiles, Start: *start, End: *end, + }) + if err != nil { + response.Error(c, errors.InternalError) + return + } + response.Success(c, gin.H{"task_id": taskID, "count": count}) +} + +// pending GET /record/repush/pending——挂起明细分页(3h 外 status=1)。 +func (h *repushHandler) pending(c *gin.Context) { + page, _ := strconv.ParseInt(c.DefaultQuery("page", "1"), 10, 64) + size, _ := strconv.ParseInt(c.DefaultQuery("page_size", "100"), 10, 64) + rows, total, err := h.pair.Pending(c.Request.Context(), report.PairQuery{ + Page: page, PageSize: size, + Mobile: strings.TrimSpace(c.Query("mobile")), + TaskNo: strings.TrimSpace(c.Query("task_no")), + }) + if err != nil { + response.Error(c, errors.InternalError) + return + } + type row struct { + DetailID int64 `json:"detail_id"` + TaskNo string `json:"task_no"` + MsgID string `json:"msg_id"` + Mobile string `json:"mobile"` + Content string `json:"content"` + SentAt fmtTime `json:"sent_at"` + AgeHours int64 `json:"age_hours"` + } + list := make([]row, 0, len(rows)) + for _, r := range rows { + list = append(list, row{ + DetailID: r.DetailID, TaskNo: r.TaskNo, MsgID: r.MsgID, Mobile: r.Mobile, + Content: r.Content, SentAt: fmtTime(r.SentAt), AgeHours: r.AgeHours, + }) + } + response.Success(c, gin.H{"list": list, "total": total}) +} + +// pairCreateReq 手动配对请求体(契约 record.ts PairRequest)。 +type pairCreateReq struct { + Mode string `json:"mode"` + MsgID string `json:"msg_id"` + Mobile string `json:"mobile"` + DetailID int64 `json:"detail_id"` + TaskNo string `json:"task_no"` + StartTime *string `json:"start_time"` + EndTime *string `json:"end_time"` + TargetStatus int8 `json:"target_status"` +} + +// createPair POST /record/repush/pair——手动配对四方式→ {matched,updated,skipped}。 +func (h *repushHandler) createPair(c *gin.Context) { + var req pairCreateReq + if err := c.ShouldBindJSON(&req); err != nil { + response.ErrorWithMsg(c, errors.InvalidParam, err.Error()) + return + } + pr := report.PairRequest{ + Mode: req.Mode, MsgID: req.MsgID, Mobile: req.Mobile, + DetailID: req.DetailID, TaskNo: req.TaskNo, TargetStatus: req.TargetStatus, + } + if req.StartTime != nil && *req.StartTime != "" { + t, err := parseTimeParam(*req.StartTime) + if err != nil { + response.ErrorWithMsg(c, errors.InvalidParam, "start_time "+err.Error()) + return + } + pr.Start = t + } + if req.EndTime != nil && *req.EndTime != "" { + t, err := parseTimeParam(*req.EndTime) + if err != nil { + response.ErrorWithMsg(c, errors.InvalidParam, "end_time "+err.Error()) + return + } + pr.End = t + } + res, err := h.pair.Pair(c.Request.Context(), pr) + if err != nil { + response.ErrorWithMsg(c, errors.InvalidParam, err.Error()) + return + } + response.Success(c, gin.H{ + "matched": res.Matched, "updated": res.Updated, "skipped": res.Skipped, + }) +} diff --git a/internal/api/http/v1/record_repush_handler_test.go b/internal/api/http/v1/record_repush_handler_test.go new file mode 100644 index 00000000..8d23ba9e --- /dev/null +++ b/internal/api/http/v1/record_repush_handler_test.go @@ -0,0 +1,430 @@ +// record_repush_handler_test.go 阶段 5 收尾(D28):回执重推域四端点—— +// 回执分页筛选(三态/任务号/尾号/时间窗)/重推受理 30 天双闸(四类拒绝+ +// 受理过:事件重投+push_status 回写)/挂起明细 3h 口径(含/不含证伪)/ +// 手动配对四方式(detail/msg_mobile 经 seg 反查/task_time/time_mobile)+ +// 终态锁定幂等(重复配对 matched=0)。种子口径对齐 msw fe4RepushHandlers。 +package v1 + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/url" + "testing" + "time" + + "github.com/gin-gonic/gin" + "github.com/glebarez/sqlite" + "gorm.io/gorm" + + "go-sms/internal/middleware" + "go-sms/internal/model/entity" + "go-sms/internal/service/account" + "go-sms/internal/service/report" +) + +// d28Sink report.PushSink 测试实现(收集事件)。 +type d28Sink struct{ ev *[]*report.DeliverEvent } + +func (f *d28Sink) PushDeliver(_ context.Context, ev *report.DeliverEvent) error { + *f.ev = append(*f.ev, ev) + return nil +} + +type d28Seed struct { + taskA, taskB int64 + p1, p2, p3, pNew, dDone int64 // p*=3h 外挂起 / pNew=3h 内 / dDone=终态 + dFail, dOld int64 // 终态:失败(推送失败候选)/31 天前窗口外 + m1, m2, m3, mNew, mDone string +} + +func newD28Router(t *testing.T) (*gin.Engine, *gorm.DB, *d28Seed, *[]*report.DeliverEvent) { + t.Helper() + gin.SetMode(gin.TestMode) + db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{}) + if err != nil { + t.Fatal(err) + } + if sqlDB, e := db.DB(); e == nil { + sqlDB.SetMaxOpenConns(1) + } + if err := db.AutoMigrate(&entity.AccountUser{}, &entity.MessageTask{}, &entity.MessageDetail{}, + &entity.MessageReportSeg{}, &entity.MessageReport{}); err != nil { + t.Fatal(err) + } + if err := db.Create(&entity.AccountUser{ + Model: entity.Model{ID: 264305}, Username: "264305", Status: 1, + Path: "/1/100001/264305/", Remark: "广东移动-行业-壹通道", + }).Error; err != nil { + t.Fatal(err) + } + now := time.Now() + tp := func(t time.Time) *time.Time { return &t } + s := &d28Seed{ + taskA: 9500000001, taskB: 9500000002, + p1: 9600000001, p2: 9600000002, p3: 9600000003, pNew: 9600000004, dDone: 9600000011, + dFail: 9600000012, dOld: 9600000013, + m1: "13800002001", m2: "13800002002", m3: "13900002003", + mNew: "13700002004", mDone: "13800003001", + } + tasks := []entity.MessageTask{ + {ID: s.taskA, TaskNo: "T20260915001", AccountID: 264305, ChannelID: 1, + SendType: 1, MobileCount: 6, Status: 1, Source: 2, CreatedAt: now.Add(-7 * time.Hour)}, + {ID: s.taskB, TaskNo: "T20260915002", AccountID: 264306, ChannelID: 2, + SendType: 1, MobileCount: 1, Status: 1, Source: 1, CreatedAt: now.Add(-5 * time.Hour)}, + } + for i := range tasks { + if err := db.Create(&tasks[i]).Error; err != nil { + t.Fatal(err) + } + } + mk := func(id, task, acc, ch int64, mobile string, status int8, send time.Time) entity.MessageDetail { + return entity.MessageDetail{ + SnowflakeModel: entity.SnowflakeModel{ID: id, CreatedAt: send}, + TaskID: task, AccountID: acc, ChannelID: ch, Mobile: mobile, + Content: "【盈讯网络】您的验证码是 8832,5 分钟内有效。", + Status: status, SendAt: tp(send), + } + } + h5, h6, h4, h1 := now.Add(-5*time.Hour), now.Add(-6*time.Hour), now.Add(-4*time.Hour), now.Add(-time.Hour) + details := []entity.MessageDetail{ + mk(s.p1, s.taskA, 264305, 1, s.m1, 1, h5), // 3h 外挂起(pair 主用例) + mk(s.p2, s.taskA, 264305, 1, s.m2, 1, h6), // 3h 外挂起(msg_mobile) + mk(s.p3, s.taskB, 264306, 2, s.m3, 1, h4), // 3h 外挂起(task_time 圈 B) + mk(s.pNew, s.taskA, 264305, 1, s.mNew, 1, h1), // 3h 内(证伪) + mk(s.dDone, s.taskA, 264305, 1, s.mDone, 2, h5), // 终态成功 + mk(s.dFail, s.taskA, 264306, 1, "13800003002", 3, h6), // 终态失败 + mk(s.dOld, s.taskA, 264305, 1, "13800003003", 2, now.Add(-31*24*time.Hour)), // 31 天前 + } + for i := range details { + if err := db.Create(&details[i]).Error; err != nil { + t.Fatal(err) + } + } + segs := []entity.MessageReportSeg{ + {DetailID: s.p1, ChannelID: 1, MsgID: "8a01f2", Mobile: s.m1, RawCode: "DELIVRD"}, + {DetailID: s.p2, ChannelID: 1, MsgID: "7b02c1", Mobile: s.m2, RawCode: "DELIVRD"}, + } + for i := range segs { + if err := db.Create(&segs[i]).Error; err != nil { + t.Fatal(err) + } + } + reports := []entity.MessageReport{ + {DetailID: s.dDone, ChannelID: 1, Status: "SUCCESS", RawCode: "DELIVRD", + ErrorCode: "", ReportAt: h5, PushStatus: 1, PushedAt: tp(h5.Add(time.Minute))}, + {DetailID: s.dFail, ChannelID: 1, Status: "FAILURE", RawCode: "GB:0001", + ErrorCode: "GB:0001", ReportAt: h6, PushStatus: 2, PushedAt: tp(h6.Add(time.Minute))}, + {DetailID: s.dOld, ChannelID: 1, Status: "SUCCESS", RawCode: "DELIVRD", + ErrorCode: "", ReportAt: now.Add(-31 * 24 * time.Hour), PushStatus: 0}, + } + for i := range reports { + if err := db.Create(&reports[i]).Error; err != nil { + t.Fatal(err) + } + } + var events []*report.DeliverEvent + sink := &d28Sink{ev: &events} + pairSvc := report.NewPairService(db, nil, nil).WithPushSink(sink) + acctSvc := account.NewService(db, account.BcryptMinCost) + r := gin.New() + Register(r.Group("/api/v1"), Deps{ + Account: acctSvc, + Auth: middleware.AuthJWTWithChecker(d25Secret, acctSvc.CheckEnabled), + DB: db, + Pair: pairSvc, + }) + return r, db, s, &events +} + +// qesc query 时间参数转义(空格破坏 httptest 请求行)。 +func qesc(s string) string { return url.QueryEscape(s) } + +// d28Post POST 并返回 (HTTP 码, 业务 code)。 +func d28Post(t *testing.T, r *gin.Engine, path, body string) (int, string) { + t.Helper() + w := doReqBody(r, http.MethodPost, path, d60Token(t, 264305), "application/json", []byte(body)) + var shell struct { + Code string `json:"code"` + } + _ = json.Unmarshal(w.Body.Bytes(), &shell) + return w.Code, shell.Code +} + +// d28Data GET 断言 200+ISC:000,返回 data。 +func d28Data(t *testing.T, r *gin.Engine, path string) map[string]json.RawMessage { + return d60Get(t, r, path) +} + +// TestD28_RepushList 回执分页:三态/任务号/尾号/时间窗 JOIN 口径。 +func TestD28_RepushList(t *testing.T) { + r, _, s, _ := newD28Router(t) + data := d28Data(t, r, "/api/v1/record/repush?page=1&page_size=100") + var total float64 + if err := json.Unmarshal(data["total"], &total); err != nil { + t.Fatal(err) + } + if total != 3 { // dDone/dFail/dOld 三行 report + t.Fatalf("total=%v, want 3", total) + } + // 三态筛:SUCCESS=dDone+dOld + data = d28Data(t, r, "/api/v1/record/repush?status=SUCCESS") + json.Unmarshal(data["total"], &total) + if total != 2 { + t.Fatalf("status=SUCCESS total=%v, want 2", total) + } + // 时间窗:31 天前 dOld 排除 + data = d28Data(t, r, "/api/v1/record/repush?start_time="+url.QueryEscape(time.Now().Add(-48*time.Hour).Format("2006-01-02 15:04:05"))) + json.Unmarshal(data["total"], &total) + if total != 2 { // dDone+dFail + t.Fatalf("48h 窗 total=%v, want 2", total) + } + // 尾号模糊:…3002=dFail + data = d28Data(t, r, "/api/v1/record/repush?mobile=3002") + json.Unmarshal(data["total"], &total) + if total != 1 { + t.Fatalf("mobile=3002 total=%v, want 1", total) + } + _ = s +} + +// TestD28_RepushCreate_WindowRejects 30 天双闸四类拒绝(必填/倒序/超 30 天/未来)。 +func TestD28_RepushCreate_WindowRejects(t *testing.T) { + r, _, _, _ := newD28Router(t) + now := time.Now() + d31 := now.Add(-31 * 24 * time.Hour).Format("2006-01-02 15:04:05") + future := now.Add(time.Hour).Format("2006-01-02 15:04:05") + past := now.Add(-2 * time.Hour).Format("2006-01-02 15:04:05") + cases := []struct { + name, body string + }{ + {"缺时间", `{"account_id":264305}`}, + {"倒序", fmt.Sprintf(`{"start_time":%q,"end_time":%q}`, past, d31)}, + {"超30天", fmt.Sprintf(`{"start_time":%q,"end_time":%q}`, d31, d31)}, + {"未来end", fmt.Sprintf(`{"start_time":%q,"end_time":%q}`, past, future)}, + } + for _, tc := range cases { + httpCode, code := d28Post(t, r, "/api/v1/record/repush", tc.body) + if httpCode != http.StatusBadRequest || code != "ISC:400" { + t.Fatalf("%s: HTTP %d code=%s, want 400/ISC:400", tc.name, httpCode, code) + } + } +} + +// TestD28_RepushCreate_OK 受理过:count=窗内命中,事件重投,失败候选回写已推。 +func TestD28_RepushCreate_OK(t *testing.T) { + r, db, _, events := newD28Router(t) + now := time.Now() + body := fmt.Sprintf(`{"start_time":%q,"end_time":%q}`, + now.Add(-48*time.Hour).Format("2006-01-02 15:04:05"), + now.Format("2006-01-02 15:04:05")) + w := doReqBody(r, http.MethodPost, "/api/v1/record/repush", + d60Token(t, 264305), "application/json", []byte(body)) + var shell struct { + Code string `json:"code"` + Data struct { + TaskID int64 `json:"task_id"` + Count int64 `json:"count"` + } `json:"data"` + } + if err := json.Unmarshal(w.Body.Bytes(), &shell); err != nil { + t.Fatal(err) + } + if shell.Code != "ISC:000" { + t.Fatalf("code=%s body=%s", shell.Code, w.Body.String()) + } + if shell.Data.Count != 2 { // dDone+dFail(dOld 31 天外) + t.Fatalf("count=%d, want 2", shell.Data.Count) + } + if shell.Data.TaskID <= 0 { + t.Fatalf("task_id=%d, want >0", shell.Data.TaskID) + } + if len(*events) != 2 { + t.Fatalf("events=%d, want 2(重投与首推同口径)", len(*events)) + } + // 事件 payload:DELIVRD + GB:0001(statForDeliver 透传截断口径) + stats := map[string]bool{} + for _, ev := range *events { + stats[ev.Stat] = true + } + if !stats["DELIVRD"] || !stats["GB:0001"] { + t.Fatalf("stat 集合=%v, want DELIVRD+GB:0001", stats) + } + // 失败候选回写:dFail push_status 2→1 + var ps int8 + if err := db.Raw("SELECT push_status FROM message_report WHERE detail_id = ?", + int64(9600000012)).Scan(&ps).Error; err != nil { + t.Fatal(err) + } + if ps != 1 { + t.Fatalf("dFail push_status=%d, want 1", ps) + } +} + +// TestD28_Pending 挂起明细:3h 外 status=1 才入列;msg_id=首段;age_hours≥3。 +func TestD28_Pending(t *testing.T) { + r, _, s, _ := newD28Router(t) + data := d28Data(t, r, "/api/v1/record/repush/pending?page=1&page_size=100") + var total float64 + json.Unmarshal(data["total"], &total) + if total != 3 { // p1/p2/p3(pNew 3h 内、dDone 终态不入) + t.Fatalf("total=%v, want 3", total) + } + type row struct { + DetailID int64 `json:"detail_id"` + MsgID string `json:"msg_id"` + Mobile string `json:"mobile"` + AgeHours int64 `json:"age_hours"` + } + var list []row + if err := json.Unmarshal(data["list"], &list); err != nil { + t.Fatal(err) + } + byID := map[int64]row{} + for _, x := range list { + byID[x.DetailID] = x + } + if byID[s.p1].MsgID != "8a01f2" || byID[s.p1].Mobile != s.m1 { + t.Fatalf("p1 行=%+v, want msg 8a01f2/%s", byID[s.p1], s.m1) + } + if byID[s.p1].AgeHours < 3 { + t.Fatalf("p1 age_hours=%d, want ≥3", byID[s.p1].AgeHours) + } + // 尾号筛 + data = d28Data(t, r, "/api/v1/record/repush/pending?mobile=2002") + json.Unmarshal(data["total"], &total) + if total != 1 { + t.Fatalf("mobile=2002 total=%v, want 1", total) + } +} + +// d28PairResp 配对响应壳。 +type d28PairResp struct { + Code string `json:"code"` + Data struct { + Matched int64 `json:"matched"` + Updated int64 `json:"updated"` + Skipped int64 `json:"skipped"` + } `json:"data"` +} + +func d28PairCall(t *testing.T, r *gin.Engine, body string) d28PairResp { + t.Helper() + w := doReqBody(r, http.MethodPost, "/api/v1/record/repush/pair", + d60Token(t, 264305), "application/json", []byte(body)) + var resp d28PairResp + if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil { + t.Fatal(err) + } + return resp +} + +// TestD28_Pair_Detail detail 精确圈:终态回写+report 落库+行离场+重复幂等。 +func TestD28_Pair_Detail(t *testing.T) { + r, db, s, events := newD28Router(t) + resp := d28PairCall(t, r, fmt.Sprintf(`{"mode":"detail","detail_id":%d,"target_status":3}`, s.p1)) + if resp.Code != "ISC:000" || resp.Data.Matched != 1 || resp.Data.Updated != 1 || resp.Data.Skipped != 0 { + t.Fatalf("resp=%+v, want matched/updated=1", resp) + } + var d entity.MessageDetail + if err := db.First(&d, s.p1).Error; err != nil { + t.Fatal(err) + } + if d.Status != 3 || d.ErrorCode != "MANUAL" || d.ReportAt == nil { + t.Fatalf("p1 终态=%d err=%s report_at=%v, want 3/MANUAL/非空", d.Status, d.ErrorCode, d.ReportAt) + } + var cnt int64 + db.Model(&entity.MessageReport{}).Where("detail_id = ?", s.p1).Count(&cnt) + if cnt != 1 { + t.Fatalf("report 落库=%d, want 1(30 天重推窗口数据源)", cnt) + } + // pending 行离场 + data := d28Data(t, r, "/api/v1/record/repush/pending?page=1&page_size=100") + var total float64 + json.Unmarshal(data["total"], &total) + if total != 2 { // p2/p3 + t.Fatalf("pair 后 pending total=%v, want 2", total) + } + // 重复配对:pendingScope 已排除→matched=0(终态锁定幂等,资金至多一次) + resp = d28PairCall(t, r, fmt.Sprintf(`{"mode":"detail","detail_id":%d,"target_status":4}`, s.p1)) + if resp.Data.Matched != 0 || resp.Data.Updated != 0 { + t.Fatalf("重复配对 resp=%+v, want matched/updated=0", resp) + } + // 首次配对即推送 1 次(完整终态链:CMPP 源任务人工终态同步下发客户; + // stat=MANUAL=errCode 透传;重复配对不再推——幂等锚=首锁) + if len(*events) != 1 { + t.Fatalf("推送事件=%d, want 1(首配对下发,重复不再推)", len(*events)) + } + if (*events)[0].Stat != "MANUAL" || (*events)[0].DetailID != s.p1 { + t.Fatalf("事件=%+v, want stat=MANUAL detail=%d", (*events)[0], s.p1) + } +} + +// TestD28_Pair_MsgMobile 经 seg(msg_id+mobile 唯一键)反查圈中。 +func TestD28_Pair_MsgMobile(t *testing.T) { + r, db, s, _ := newD28Router(t) + resp := d28PairCall(t, r, fmt.Sprintf(`{"mode":"msg_mobile","msg_id":"7b02c1","mobile":%q,"target_status":4}`, s.m2)) + if resp.Data.Matched != 1 || resp.Data.Updated != 1 { + t.Fatalf("resp=%+v, want matched/updated=1", resp) + } + var d entity.MessageDetail + db.First(&d, s.p2) + if d.Status != 4 { + t.Fatalf("p2 status=%d, want 4", d.Status) + } +} + +// TestD28_Pair_TaskTime task_time 圈任务 B(3h 内挂起 pNew 不入=窗口+3h 双闸)。 +func TestD28_Pair_TaskTime(t *testing.T) { + r, db, s, _ := newD28Router(t) + now := time.Now() + resp := d28PairCall(t, r, fmt.Sprintf(`{"mode":"task_time","task_no":"T20260915002","start_time":%q,"end_time":%q,"target_status":2}`, + now.Add(-8*time.Hour).Format("2006-01-02 15:04:05"), now.Format("2006-01-02 15:04:05"))) + if resp.Data.Matched != 1 || resp.Data.Updated != 1 { + t.Fatalf("resp=%+v, want p3 圈中回写", resp) + } + var d entity.MessageDetail + db.First(&d, s.p3) + if d.Status != 2 { + t.Fatalf("p3 status=%d, want 2", d.Status) + } + // taskA 剩余挂起=p1/p2(5h/6h 前);pNew(1h 前)被 3h 口径排除=双闸证伪 + resp = d28PairCall(t, r, `{"mode":"task_time","task_no":"T20260915001","target_status":4}`) + if resp.Data.Matched != 2 || resp.Data.Updated != 2 { + t.Fatalf("taskA 圈中=%+v, want matched/updated=2(p1+p2)", resp.Data) + } + var dn entity.MessageDetail + db.First(&dn, s.pNew) + if dn.Status != 1 { + t.Fatalf("pNew(3h 内)被误圈,status=%d want 1", dn.Status) + } +} + +// TestD28_Pair_TimeMobile mobile+时间窗圈中;参数校验(mode/target/必填)。 +func TestD28_Pair_TimeMobile(t *testing.T) { + r, db, s, _ := newD28Router(t) + now := time.Now() + resp := d28PairCall(t, r, fmt.Sprintf(`{"mode":"time_mobile","mobile":%q,"start_time":%q,"end_time":%q,"target_status":3}`, + s.m1, now.Add(-6*time.Hour).Format("2006-01-02 15:04:05"), now.Format("2006-01-02 15:04:05"))) + if resp.Data.Matched != 1 || resp.Data.Updated != 1 { + t.Fatalf("resp=%+v, want p1 圈中", resp) + } + var d entity.MessageDetail + db.First(&d, s.p1) + if d.Status != 3 { + t.Fatalf("p1 status=%d, want 3", d.Status) + } + // 参数拒绝 + for name, body := range map[string]string{ + "mode非法": `{"mode":"nope","target_status":3}`, + "target": fmt.Sprintf(`{"mode":"detail","detail_id":%d,"target_status":5}`, s.p1), + "必填缺失": `{"mode":"msg_mobile","target_status":3}`, + "任务号不存在": `{"mode":"task_time","task_no":"NOPE","target_status":3}`, + } { + httpCode, code := d28Post(t, r, "/api/v1/record/repush/pair", body) + if httpCode != http.StatusBadRequest || code != "ISC:400" { + t.Fatalf("%s: HTTP %d code=%s, want 400/ISC:400", name, httpCode, code) + } + } +} diff --git a/internal/api/http/v1/review_handler.go b/internal/api/http/v1/review_handler.go new file mode 100644 index 00000000..949a0ff6 --- /dev/null +++ b/internal/api/http/v1/review_handler.go @@ -0,0 +1,217 @@ +// review_handler.go Day 43:消息审核端点(待审列表/通过/拒绝)+D19 定时任务管理 +// (列表/取消/改期)。审核动作 audit:write 门禁;列表 message:read。 +package v1 + +import ( + "strconv" + "time" + + "go-sms/internal/middleware" + "go-sms/internal/pkg/errors" + "go-sms/internal/pkg/jwt" + "go-sms/internal/pkg/response" + auditsvc "go-sms/internal/service/audit" + + "github.com/gin-gonic/gin" +) + +// registerReviewRoutes 审核中心+定时任务端点(rv 可 nil——未装配时跳过)。 +func registerReviewRoutes(protected *gin.RouterGroup, perm middleware.PermissionChecker, rv *auditsvc.ReviewService) { + h := &reviewHandler{rv: rv} + gate := func(obj, act string) gin.HandlerFunc { + return middleware.RequirePermission(perm, obj, act) + } + // Day 43:审核中心 + protected.GET("/audits/messages", gate("audit", "read"), h.list) + protected.GET("/audits/messages/counts", gate("audit", "read"), h.counts) + protected.POST("/audits/messages/batch-review", gate("audit", "write"), h.batchReview) + protected.POST("/audits/messages/:id/approve", gate("audit", "write"), h.approve) + protected.POST("/audits/messages/:id/reject", gate("audit", "write"), h.reject) + // D19:定时任务管理 + protected.GET("/send/tasks", gate("message", "read"), h.tasks) + protected.GET("/send/tasks/:id/details", gate("message", "read"), h.details) // Day 46/D22 + protected.POST("/send/tasks/:id/cancel", gate("message", "write"), h.cancel) + protected.PUT("/send/tasks/:id/reschedule", gate("message", "write"), h.reschedule) +} + +type reviewHandler struct { + rv *auditsvc.ReviewService +} + +// list GET /audits/messages:待审任务分页(audit_status 过滤,默认 0 待审;-1 全部)。 +func (h *reviewHandler) list(c *gin.Context) { + q := auditsvc.TaskQuery{ + Page: intQuery(c, "page", 1), PageSize: intQuery(c, "page_size", 20), + AuditStatus: int8QueryDefault(c, "audit_status", 0), // 默认待审 + Status: int8QueryDefault(c, "status", -1), + } + if v, err := strconv.ParseInt(c.Query("account_id"), 10, 64); err == nil && v > 0 { + q.AccountID = v + } + rows, total, err := h.rv.ListTasks(c.Request.Context(), q) + if err != nil { + response.Error(c, errors.InternalError) + return + } + response.Success(c, gin.H{"total": total, "list": rows}) +} + +// counts GET /audits/messages/counts:审核态计数(D21 Tab 徽标)。 +func (h *reviewHandler) counts(c *gin.Context) { + total, byStatus, err := h.rv.CountByStatus(c.Request.Context()) + if err != nil { + response.Error(c, errors.InternalError) + return + } + response.Success(c, gin.H{"total": total, "by_status": byStatus}) +} + +// batchReviewBody 批量审核请求体(D21)。 +type batchReviewBody struct { + IDs []int64 `json:"ids" binding:"required"` + Pass bool `json:"pass"` + Reason string `json:"reason"` +} + +// batchReview POST /audits/messages/batch-review:批量通过/拒绝(已审跳过幂等)。 +func (h *reviewHandler) batchReview(c *gin.Context) { + var body batchReviewBody + if err := c.ShouldBindJSON(&body); err != nil { + response.ErrorWithMsg(c, errors.InvalidParam, "参数错误: "+err.Error()) + return + } + ok, err := h.rv.BatchReview(c.Request.Context(), body.IDs, body.Pass, + currentAuditor(c), body.Reason) + if err != nil { + bizResp(c, err) + return + } + response.Success(c, gin.H{"ok": ok, "total": len(body.IDs)}) +} + +// auditActionBody 审核/拒绝请求体。 +type auditActionBody struct { + Reason string `json:"reason"` +} + +// approve POST /audits/messages/:id/approve(当前登录人为审核人)。 +func (h *reviewHandler) approve(c *gin.Context) { + var body auditActionBody + _ = c.ShouldBindJSON(&body) // reason 可空 + task, rec, err := h.rv.Approve(c.Request.Context(), pathID(c), currentAuditor(c), body.Reason) + if err != nil { + bizResp(c, err) + return + } + response.Success(c, gin.H{"task": task, "record": rec}) +} + +// reject POST /audits/messages/:id/reject(reason 必填)。 +func (h *reviewHandler) reject(c *gin.Context) { + var body auditActionBody + if err := c.ShouldBindJSON(&body); err != nil { + response.ErrorWithMsg(c, errors.InvalidParam, "参数错误: "+err.Error()) + return + } + task, rec, err := h.rv.Reject(c.Request.Context(), pathID(c), currentAuditor(c), body.Reason) + if err != nil { + bizResp(c, err) + return + } + response.Success(c, gin.H{"task": task, "record": rec}) +} + +// tasks GET /send/tasks:任务分页(状态/审核态/类型/账号过滤;D19 定时列表)。 +func (h *reviewHandler) tasks(c *gin.Context) { + q := auditsvc.TaskQuery{ + Page: intQuery(c, "page", 1), PageSize: intQuery(c, "page_size", 20), + AuditStatus: int8QueryDefault(c, "audit_status", -1), + Status: int8QueryDefault(c, "status", -1), + SendType: int8QueryDefault(c, "send_type", 0), + } + if v, err := strconv.ParseInt(c.Query("account_id"), 10, 64); err == nil && v > 0 { + q.AccountID = v + } + rows, total, err := h.rv.ListTasks(c.Request.Context(), q) + if err != nil { + response.Error(c, errors.InternalError) + return + } + response.Success(c, gin.H{"total": total, "list": rows}) +} + +// details GET /send/tasks/:id/details:任务明细分页(Day 46/D22 结果反馈页; +// status/error_code 过滤;含 ext_code/call_data 逐号核对)。 +func (h *reviewHandler) details(c *gin.Context) { + q := auditsvc.DetailQuery{ + Page: intQuery(c, "page", 1), + PageSize: intQuery(c, "page_size", 50), + Status: int8QueryDefault(c, "status", -1), + ErrorCode: c.Query("error_code"), + } + rows, total, err := h.rv.TaskDetails(c.Request.Context(), pathID(c), q) + if err != nil { + response.Error(c, errors.InternalError) + return + } + response.Success(c, gin.H{"total": total, "list": rows}) +} + +// cancel POST /send/tasks/:id/cancel:取消待发任务(幂等拒绝:非待发 ISC:038)。 +func (h *reviewHandler) cancel(c *gin.Context) { + task, err := h.rv.Cancel(c.Request.Context(), pathID(c)) + if err != nil { + bizResp(c, err) + return + } + response.Success(c, task) +} + +// rescheduleBody 改期请求体。 +type rescheduleBody struct { + SendAt string `json:"send_at" binding:"required"` // YYYY-MM-DD HH:mm(与提交口径一致) +} + +// reschedule PUT /send/tasks/:id/reschedule:定时任务改期(仅定时+待发)。 +func (h *reviewHandler) reschedule(c *gin.Context) { + var body rescheduleBody + if err := c.ShouldBindJSON(&body); err != nil { + response.ErrorWithMsg(c, errors.InvalidParam, "参数错误: "+err.Error()) + return + } + at, err := time.ParseInLocation("2006-01-02 15:04", body.SendAt, time.Local) + if err != nil { + response.ErrorWithMsg(c, errors.InvalidParam, "send_at 须为 YYYY-MM-DD HH:mm 格式") + return + } + task, err := h.rv.Reschedule(c.Request.Context(), pathID(c), at) + if err != nil { + bizResp(c, err) + return + } + response.Success(c, task) +} + +// pathID 取 :id 路径参数(非法→0;服务层 NotFound)。 +func pathID(c *gin.Context) int64 { + v, _ := strconv.ParseInt(c.Param("id"), 10, 64) + return v +} + +// currentAuditor 当前操作人(JWT claims.Username;缺省 system)。 +func currentAuditor(c *gin.Context) string { + if v, ok := c.Get(middleware.ContextKeyClaims); ok { + if claims, ok := v.(*jwt.Claims); ok && claims.Username != "" { + return claims.Username + } + } + return "system" +} + +// int8QueryDefault int8 查询参数(缺省/非法→def)。 +func int8QueryDefault(c *gin.Context, key string, def int8) int8 { + if v, err := strconv.Atoi(c.Query(key)); err == nil { + return int8(v) + } + return def +} diff --git a/internal/api/http/v1/route_handler.go b/internal/api/http/v1/route_handler.go new file mode 100644 index 00000000..4f7c28fc --- /dev/null +++ b/internal/api/http/v1/route_handler.go @@ -0,0 +1,127 @@ +// route_handler.go Day 38:导流规则管理端点(channel:write 门禁)。 +package v1 + +import ( + "strconv" + + "github.com/gin-gonic/gin" + + "go-sms/internal/middleware" + "go-sms/internal/pkg/errors" + "go-sms/internal/pkg/response" + "go-sms/internal/service/router" +) + +// steerHandler 导流规则接口。 +type steerHandler struct{ svc *router.Router } + +// registerSteerRoutes 注册导流规则端点(channel:write 门禁)。 +func registerSteerRoutes(protected *gin.RouterGroup, perm middleware.PermissionChecker, svc *router.Router) { + h := &steerHandler{svc: svc} + gate := func(obj, act string) gin.HandlerFunc { + return middleware.RequirePermission(perm, obj, act) + } + protected.POST("/route-rules", gate("channel", "write"), h.create) + protected.GET("/route-rules", h.list) + protected.PUT("/route-rules/:id", gate("channel", "write"), h.update) + protected.DELETE("/route-rules/:id", gate("channel", "write"), h.remove) + // Day 63:账号级通道绑定(账号详情页「发送通道」;绑定/原子切换/解绑, + // GET 快照含通道名/状态,前端免二次查询)。 + protected.GET("/accounts/:id/channel-steer", h.accountSteer) + protected.PUT("/accounts/:id/channel-steer", + gate("channel", "write"), h.setAccountSteer) +} + +// accountSteer GET /accounts/:id/channel-steer 查账号当前绑定(rule_id=0=未绑定)。 +func (h *steerHandler) accountSteer(c *gin.Context) { + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + resp, err := h.svc.GetAccountSteer(c.Request.Context(), id) + if err != nil { + bizResp(c, err) + return + } + response.Success(c, resp) +} + +// setAccountSteer PUT /accounts/:id/channel-steer body {channel_id}: +// >0=绑定/切换(事务原子);0=解绑回退四步智能路由。保存即生效(引擎实时查库)。 +func (h *steerHandler) setAccountSteer(c *gin.Context) { + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + var req struct { + ChannelID int64 `json:"channel_id"` + } + if err := c.ShouldBindJSON(&req); err != nil { + response.ErrorWithMsg(c, errors.InvalidParam, "参数错误: "+err.Error()) + return + } + if req.ChannelID < 0 { + response.ErrorWithMsg(c, errors.InvalidParam, "channel_id 须为非负整数") + return + } + rule, err := h.svc.SetAccountSteer(c.Request.Context(), id, req.ChannelID) + if err != nil { + bizResp(c, err) + return + } + if rule == nil { // 解绑成功(无新规则) + response.Success(c, gin.H{"account_id": id, "rule_id": 0}) + return + } + response.Success(c, gin.H{ + "account_id": id, "rule_id": rule.ID, "channel_id": rule.ChannelID, + }) +} + +// create POST /route-rules。 +func (h *steerHandler) create(c *gin.Context) { + var req router.CreateRuleReq + if err := c.ShouldBindJSON(&req); err != nil { + response.ErrorWithMsg(c, errors.InvalidParam, "参数错误: "+err.Error()) + return + } + rule, err := h.svc.CreateRule(c.Request.Context(), &req) + if err != nil { + bizResp(c, err) + return + } + response.Success(c, gin.H{ + "id": rule.ID, "account_id": rule.AccountID, "channel_id": rule.ChannelID, + "rule_type": rule.RuleType, "rule_config": rule.RuleConfig, + "priority": rule.Priority, "status": rule.Status, + }) +} + +// list GET /route-rules。 +func (h *steerHandler) list(c *gin.Context) { + list, err := h.svc.ListRules(c.Request.Context()) + if err != nil { + bizResp(c, err) + return + } + response.Success(c, gin.H{"total": len(list), "list": list}) +} + +// update PUT /route-rules/:id。 +func (h *steerHandler) update(c *gin.Context) { + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + var fields map[string]any + if err := c.ShouldBindJSON(&fields); err != nil { + response.ErrorWithMsg(c, errors.InvalidParam, "参数错误: "+err.Error()) + return + } + if err := h.svc.UpdateRule(c.Request.Context(), id, fields); err != nil { + bizResp(c, err) + return + } + response.Success(c, gin.H{"id": id}) +} + +// remove DELETE /route-rules/:id。 +func (h *steerHandler) remove(c *gin.Context) { + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + if err := h.svc.DeleteRule(c.Request.Context(), id); err != nil { + bizResp(c, err) + return + } + response.Success(c, gin.H{"id": id}) +} diff --git a/internal/api/http/v1/route_steer_bind_test.go b/internal/api/http/v1/route_steer_bind_test.go new file mode 100644 index 00000000..04c64b9e --- /dev/null +++ b/internal/api/http/v1/route_steer_bind_test.go @@ -0,0 +1,162 @@ +package v1 + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + + "github.com/gin-gonic/gin" + "github.com/glebarez/sqlite" + "gorm.io/gorm" + + "go-sms/internal/middleware" + "go-sms/internal/model/entity" + "go-sms/internal/service/router" +) + +// getJSON/putJSON 通用 HTTP 辅助(与 postJSON 同构)。 +func getJSON(r *gin.Engine, path string) *httptest.ResponseRecorder { + w := httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, path, nil)) + return w +} + +func putJSON(r *gin.Engine, path string, body any) *httptest.ResponseRecorder { + raw, _ := json.Marshal(body) + w := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPut, path, bytes.NewReader(raw)) + req.Header.Set("Content-Type", "application/json") + r.ServeHTTP(w, req) + return w +} + +// newSteerTestRouter 内存库+导流路由(/accounts/:id/channel-steer)。 +// 前置注入 claims 模拟已认证(PUT 门禁 RequirePermission 依赖 ContextKeyClaims)。 +func newSteerTestRouter(t *testing.T) (*gin.Engine, *gorm.DB) { + t.Helper() + gin.SetMode(gin.TestMode) + db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{}) + if err != nil { + t.Fatal(err) + } + if err := db.AutoMigrate(&entity.RouteRule{}, &entity.ChannelChannel{}); err != nil { + t.Fatal(err) + } + r := gin.New() + r.Use(func(c *gin.Context) { + c.Set(middleware.ContextKeyClaims, &middleware.Claims{AccountID: 1, Username: "tester"}) + c.Next() + }) + Register(r.Group("/api/v1"), Deps{Router: router.NewRouter(db)}) + return r, db +} + +// seedSteerChannel 建一条通道(status 可控;零值会被列 default 吞,UPDATE 强制写)。 +func seedSteerChannel(t *testing.T, db *gorm.DB, id int64, name string, status int8) { + t.Helper() + ch := &entity.ChannelChannel{ + Model: entity.Model{ID: id}, Name: name, Code: "1069" + name, + Protocol: "cmpp", Host: "127.0.0.1", Port: 7890, Status: 1, + } + if err := db.Create(ch).Error; err != nil { + t.Fatal(err) + } + if status != 1 { + if err := db.Model(ch).Update("status", status).Error; err != nil { + t.Fatal(err) + } + } +} + +// steerData 解析成功响应 data 段(非 ISC:000 即 Fatal,可传 wantFail 反转)。 +func steerData(t *testing.T, w *httptest.ResponseRecorder) map[string]any { + t.Helper() + var resp struct { + Code string `json:"code"` + Data map[string]any `json:"data"` + } + if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil { + t.Fatalf("响应解析失败: %v body=%s", err, w.Body.String()) + } + if resp.Code != "ISC:000" { + t.Fatalf("业务码=%s body=%s", resp.Code, w.Body.String()) + } + return resp.Data +} + +// steerCode 仅取业务码。 +func steerCode(t *testing.T, w *httptest.ResponseRecorder) string { + t.Helper() + var resp struct { + Code string `json:"code"` + } + if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil { + t.Fatalf("响应解析失败: %v body=%s", err, w.Body.String()) + } + return resp.Code +} + +// TestAPI_AccountChannelSteer 绑定→查询→原子切换(旧规则软删)→解绑全链。 +func TestAPI_AccountChannelSteer(t *testing.T) { + r, db := newSteerTestRouter(t) + seedSteerChannel(t, db, 1, "ch-a", 1) + seedSteerChannel(t, db, 2, "ch-b", 1) + + // 未绑定初态:rule_id=0(走四步智能路由)。 + if d := steerData(t, getJSON(r, "/api/v1/accounts/3/channel-steer")); d["rule_id"].(float64) != 0 { + t.Fatalf("初态应未绑定,实际 %v", d["rule_id"]) + } + + // 绑定 ch-a:快照含通道名/状态。 + steerData(t, putJSON(r, "/api/v1/accounts/3/channel-steer", map[string]any{"channel_id": 1})) + d := steerData(t, getJSON(r, "/api/v1/accounts/3/channel-steer")) + if d["channel_name"] != "ch-a" || d["channel_status"].(float64) != 1 { + t.Fatalf("绑定快照错误: %v", d) + } + + // 切换 ch-b:新规则 ID 变化+库内启用规则恰 1 条(旧规则软删,原子)。 + d = steerData(t, putJSON(r, "/api/v1/accounts/3/channel-steer", map[string]any{"channel_id": 2})) + rule2 := d["rule_id"].(float64) + var active int64 + db.Model(&entity.RouteRule{}).Where("account_id=3 AND rule_type='account'").Count(&active) + if active != 1 || rule2 == 0 { + t.Fatalf("切换后启用规则应恰 1 条且新 ID 有效,实际 active=%d rule_id=%v", active, rule2) + } + if d = steerData(t, getJSON(r, "/api/v1/accounts/3/channel-steer")); d["channel_name"] != "ch-b" { + t.Fatalf("切换后快照应指向 ch-b: %v", d) + } + + // 解绑:rule_id=0,启用规则清零。 + steerData(t, putJSON(r, "/api/v1/accounts/3/channel-steer", map[string]any{"channel_id": 0})) + if d := steerData(t, getJSON(r, "/api/v1/accounts/3/channel-steer")); d["rule_id"].(float64) != 0 { + t.Fatal("解绑后应 rule_id=0") + } + db.Model(&entity.RouteRule{}).Where("account_id=3 AND rule_type='account'").Count(&active) + if active != 0 { + t.Fatalf("解绑后启用规则应为 0,实际 %d", active) + } +} + +// TestAPI_AccountChannelSteer_Invalid 通道不存在/停用拒绝且不残留规则。 +func TestAPI_AccountChannelSteer_Invalid(t *testing.T) { + r, db := newSteerTestRouter(t) + seedSteerChannel(t, db, 1, "ch-a", 0) // 停用 + seedSteerChannel(t, db, 2, "ch-b", 1) + + if c := steerCode(t, putJSON(r, "/api/v1/accounts/3/channel-steer", map[string]any{"channel_id": 999})); c == "ISC:000" { + t.Fatal("不存在通道应拒绝") + } + if c := steerCode(t, putJSON(r, "/api/v1/accounts/3/channel-steer", map[string]any{"channel_id": 1})); c == "ISC:000" { + t.Fatal("停用通道应拒绝") + } + if c := steerCode(t, putJSON(r, "/api/v1/accounts/3/channel-steer", map[string]any{"channel_id": -1})); c == "ISC:000" { + t.Fatal("负 channel_id 应拒绝") + } + var active int64 + db.Model(&entity.RouteRule{}).Where("account_id=3 AND rule_type='account'").Count(&active) + if active != 0 { + t.Fatalf("失败请求不应建规则,实际 %d 条", active) + } +} diff --git a/internal/api/http/v1/send_day42_test.go b/internal/api/http/v1/send_day42_test.go new file mode 100644 index 00000000..228882d9 --- /dev/null +++ b/internal/api/http/v1/send_day42_test.go @@ -0,0 +1,143 @@ +// send_day42_test.go Day 42:/send/precheck 预检端点——拦截器链真入口(D18 提交前预检)。 +package v1 + +import ( + "net/http" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/glebarez/sqlite" + "gorm.io/gorm" + + "go-sms/internal/middleware" + "go-sms/internal/model/entity" + "go-sms/internal/pkg/casbin" + "go-sms/internal/service/account" + "go-sms/internal/service/audit" + "go-sms/internal/service/channel" + "go-sms/internal/service/interceptor" + "go-sms/internal/service/template" +) + +// newD42Router Day 42 路由:模板+拦截链(sqlite,黑名单/频次策略/拦截日志表)。 +func newD42Router(t *testing.T) (*gin.Engine, *gorm.DB) { + t.Helper() + gin.SetMode(gin.TestMode) + db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{}) + if err != nil { + t.Fatal(err) + } + if sqlDB, e := db.DB(); e == nil { + sqlDB.SetMaxOpenConns(1) + } + if err := db.AutoMigrate(&entity.AccountUser{}, &entity.TemplateSMS{}, + &entity.SendBlockLog{}); err != nil { + t.Fatal(err) + } + // 策略表与账号/消息系实体共用索引名(idx_account_status/uk_mobile_account), + // glebarez sqlite 索引名为库级作用域,建索引报错但表已建好,忽略(见 interceptor 测试同注)。 + _ = db.AutoMigrate(&entity.PolicyFrequency{}) + _ = db.AutoMigrate(&entity.PolicyBlacklist{}) + _ = db.AutoMigrate(&entity.PolicyWhitelist{}) + e, err := casbin.New(db) + if err != nil { + t.Fatal(err) + } + for _, p := range [][]string{{"admin", "*", "*"}, {"customer", "message", "write"}} { + if _, err := e.AddPolicy(p[0], p[1], p[2]); err != nil { + t.Fatal(err) + } + } + users := []entity.AccountUser{ + {Username: "d42-admin", Role: "admin", Status: 1}, + {Username: "d42-cust", Role: "customer", Status: 1}, + } + for i := range users { + if err := db.Create(&users[i]).Error; err != nil { + t.Fatal(err) + } + if _, err := e.BindRole(users[i].ID, users[i].Role); err != nil { + t.Fatal(err) + } + } + acctSvc := account.NewService(db, account.BcryptMinCost).WithEnforcer(e) + chain := interceptor.NewDefaultChain(db, nil, interceptor.NewDBRecorder(db), + interceptor.Options{FreqStore: interceptor.NewMemoryFreqStore()}) + r := gin.New() + Register(r.Group("/api/v1"), Deps{ + Account: acctSvc, + Audit: audit.NewService(db), + Channel: channel.NewService(db), + Template: template.NewService(db), + Interceptor: chain, + Auth: middleware.AuthJWTWithChecker(d25Secret, acctSvc.CheckEnabled), + Perm: middleware.CasbinChecker(e), + }) + return r, db +} + +// TestAPI_SendPrecheck 验收:黑名单/频次/签名逐号预检(DryRun);全过 passed=total。 +func TestAPI_SendPrecheck(t *testing.T) { + r, db := newD42Router(t) + tok := d25Token(t, 2, "customer") // customer:message:write(ID=2 d42-cust) + + // 造数:黑名单 1 号 + 频次策略(同号码自然日 max=1)。 + if err := db.Create(&entity.PolicyBlacklist{Mobile: "13800138000", AccountID: 0}).Error; err != nil { + t.Fatal(err) + } + if err := db.Create(&entity.PolicyFrequency{ + AccountID: 2, Dim: 1, WindowUnit: 1, MaxCount: 1, Status: 1}).Error; err != nil { + t.Fatal(err) + } + + // ① 黑名单拦截:1 黑 + 1 干净号 → blocked 1 / passed 1。 + body := `{"account_id":2,"mobiles":["13800138000","13800138001"],"content":"【云】双 11 大促"}` + w := doReqBody(r, http.MethodPost, "/api/v1/send/precheck", tok, "application/json", []byte(body)) + if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), `"passed":1`) || + !strings.Contains(w.Body.String(), `"interceptor":"blacklist"`) { + t.Fatalf("黑名单预检 = %d: %s", w.Code, w.Body.String()) + } + // 拦截原因落库(DryRun 不落库——预检无副作用;仅提交主链落库,这里应 0 行)。 + var n int64 + db.Model(&entity.SendBlockLog{}).Count(&n) + if n != 0 { + t.Fatalf("DryRun 预检不应落库: %d", n) + } + + // ② 签名拦截:无【】签名。 + body = `{"account_id":2,"mobiles":["13800138002"],"content":"无签名内容"}` + w = doReqBody(r, http.MethodPost, "/api/v1/send/precheck", tok, "application/json", []byte(body)) + if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), `"interceptor":"sign"`) { + t.Fatalf("签名预检 = %d: %s", w.Code, w.Body.String()) + } + + // ③ 模板短信预检:未过审 400 → 审核过后渲染逐号预检通过。 + w = doReqBody(r, http.MethodPost, "/api/v1/templates", tok, "application/json", + []byte(`{"account_id":2,"name":"会员日","content":"【云】{name}您好,会员日 5 折"}`)) + if w.Code != http.StatusOK { + t.Fatalf("建模板 = %d: %s", w.Code, w.Body.String()) + } + adminTok := d25Token(t, 1, "admin") + body = `{"account_id":2,"template_id":1,"mobiles":["13800138003"],"variables":{"name":"张三"}}` + if w := doReqBody(r, http.MethodPost, "/api/v1/send/precheck", tok, "application/json", []byte(body)); w.Code != http.StatusBadRequest { + t.Fatalf("模板未过审预检应 400: %d %s", w.Code, w.Body.String()) + } + doReqBody(r, http.MethodPut, "/api/v1/templates/1/review", adminTok, "application/json", []byte(`{"pass":true}`)) + if w := doReqBody(r, http.MethodPost, "/api/v1/send/precheck", tok, "application/json", []byte(body)); w.Code != http.StatusOK || + !strings.Contains(w.Body.String(), `"passed":1`) { + t.Fatalf("过审模板预检应通过: %d %s", w.Code, w.Body.String()) + } + // 缺参拒绝。 + body = `{"account_id":2,"template_id":1,"mobiles":["13800138003"]}` + if w := doReqBody(r, http.MethodPost, "/api/v1/send/precheck", tok, "application/json", []byte(body)); w.Code != http.StatusBadRequest { + t.Fatalf("模板缺参预检应 400: %d %s", w.Code, w.Body.String()) + } + + // ④ 非法号码(基础校验拒绝路径)。 + body = `{"account_id":2,"mobiles":["123"],"content":"【云】x"}` + w = doReqBody(r, http.MethodPost, "/api/v1/send/precheck", tok, "application/json", []byte(body)) + if w.Code != http.StatusBadRequest { + t.Fatalf("非法号码应 400: %d %s", w.Code, w.Body.String()) + } +} diff --git a/internal/api/http/v1/send_handler.go b/internal/api/http/v1/send_handler.go new file mode 100644 index 00000000..02511f98 --- /dev/null +++ b/internal/api/http/v1/send_handler.go @@ -0,0 +1,245 @@ +// send_handler.go Day 42:/send/precheck——发送预检(拦截器链真入口)。 +// D18 个性短信工作台提交前逐号预检(DryRun:频次只读不占配额,拦截不落库); +// Day 46 提交主链复用同一 Chain(非 DryRun,命中落 send_block_log)。 +package v1 + +import ( + "strconv" + "time" + + "github.com/gin-gonic/gin" + + "go-sms/internal/middleware" + "go-sms/internal/model/entity" + "go-sms/internal/pkg/errors" + jwtpkg "go-sms/internal/pkg/jwt" + "go-sms/internal/pkg/response" + "go-sms/internal/service/interceptor" + "go-sms/internal/service/send" + "go-sms/internal/service/template" +) + +// registerSendRoutes 注册发送域端点(chain/submit/fileImport 可 nil——未装配时对应端点不注册)。 +func registerSendRoutes(protected *gin.RouterGroup, perm middleware.PermissionChecker, + tplSvc *template.Service, chain *interceptor.Chain, submit *send.SubmitService, + fileImport *send.FileImportService) { + h := &sendHandler{tplSvc: tplSvc, chain: chain, submitSvc: submit, importSvc: fileImport} + gate := func(obj, act string) gin.HandlerFunc { + return middleware.RequirePermission(perm, obj, act) + } + protected.POST("/send/precheck", gate("message", "write"), h.precheck) + // Day 43 修复循环:最小提交链(受理落库+审核分流;限流/扣费/下发 Day45/46)。 + if submit != nil { + protected.POST("/send/submit", gate("message", "write"), h.submit) + } + // Day 44:号码文件导入(TXT/CSV/XLSX→解析校验去重→MinIO 落对象)。 + if fileImport != nil { + protected.POST("/files/numbers/import", gate("message", "write"), h.importFile) + } +} + +type sendHandler struct { + tplSvc *template.Service // 模板渲染(模板短信预检) + chain *interceptor.Chain // 拦截器链(预检 DryRun) + submitSvc *send.SubmitService // 提交受理(Day 43 修复循环) + importSvc *send.FileImportService // 号码文件导入(Day 44) +} + +// importFile POST /files/numbers/import(multipart 字段 file;可选 account_id 缺省取 JWT)。 +func (h *sendHandler) importFile(c *gin.Context) { + fh, err := c.FormFile("file") + if err != nil { + response.ErrorWithMsg(c, errors.InvalidParam, "缺少文件(file 字段)") + return + } + v, _ := c.Get(middleware.ContextKeyClaims) + claims, _ := v.(*middleware.Claims) + accountID := int64(0) + if claims != nil { + accountID = claims.AccountID + } + if formID := c.PostForm("account_id"); formID != "" { + if id, perr := strconv.ParseInt(formID, 10, 64); perr == nil { + accountID = id + } + } + if accountID <= 0 { + response.ErrorWithMsg(c, errors.InvalidParam, "account_id 缺失") + return + } + f, err := fh.Open() + if err != nil { + response.ErrorWithMsg(c, errors.InvalidParam, "文件读取失败: "+err.Error()) + return + } + defer f.Close() + res, err := h.importSvc.Import(c.Request.Context(), f, fh.Filename, fh.Size, accountID) + if err != nil { + bizResp(c, err) + return + } + response.Success(c, res) +} + +// BlockItem 单号码拦截结果。 +type BlockItem struct { + Mobile string `json:"mobile"` + Interceptor string `json:"interceptor"` + Code string `json:"code"` + Msg string `json:"msg"` +} + +// PrecheckResp 预检结果。 +type PrecheckResp struct { + Total int `json:"total"` + Passed int `json:"passed"` + Blocked []BlockItem `json:"blocked"` // 空=全过 +} + +// precheck POST /send/precheck(SubmitReq;模板短信自动渲染)→ 逐号过拦截链(DryRun)。 +func (h *sendHandler) precheck(c *gin.Context) { + var req send.SubmitReq + if err := c.ShouldBindJSON(&req); err != nil { + response.ErrorWithMsg(c, errors.InvalidParam, "参数错误: "+err.Error()) + return + } + var tpl *entity.TemplateSMS + if req.TemplateID > 0 { + if h.tplSvc == nil { + response.ErrorWithMsg(c, errors.InvalidParam, "模板服务未装配") + return + } + t, err := h.tplSvc.GetByID(c.Request.Context(), req.TemplateID) + if err != nil { + bizResp(c, err) + return + } + tpl = t + } + // 基础校验(号码合法/类型/内容/变量)+渲染,复用 Day41 校验器同源逻辑。 + if _, err := req.Validate(tpl); err != nil { + bizResp(c, err) + return + } + content := req.Content + if tpl != nil { + rendered, err := h.tplSvc.Render(tpl, req.Variables) + if err != nil { + bizResp(c, err) + return + } + content = rendered + } + resp := PrecheckResp{Total: len(req.Mobiles), Blocked: []BlockItem{}} + if h.chain == nil { // 未装配拦截链:基础校验即通过 + resp.Passed = resp.Total + response.Success(c, resp) + return + } + // Day51 R3:批量预检同样经请求级快照(白名单/黑名单 IN 批查,策略跨号复用)。 + sc := h.chain.NewScope(c.Request.Context(), req.AccountID, req.Mobiles) + for _, m := range req.Mobiles { + b := h.chain.Check(c.Request.Context(), &interceptor.Req{ + TaskNo: req.TaskNo, AccountID: req.AccountID, Mobile: m, + Content: content, SendType: req.SendType, DryRun: true, Scope: sc, + }) + if b == nil { + resp.Passed++ + continue + } + resp.Blocked = append(resp.Blocked, BlockItem{ + Mobile: m, Interceptor: b.Interceptor, Code: b.Code, Msg: b.Msg}) + } + response.Success(c, resp) +} + +// SubmitResp 提交受理响应。 +type SubmitResp struct { + TaskNo string `json:"task_no"` + TaskID int64 `json:"task_id"` + AuditStatus int8 `json:"audit_status"` + AuditHint string `json:"audit_hint"` + ValidCount int `json:"valid_count"` + Segments int `json:"segments"` + TotalFee int `json:"total_fee"` + ScheduleAt string `json:"schedule_at,omitempty"` // RFC3339(定时任务) +} + +// auditHint 审核态文案(响应提示;0 待人工/1 过/2 拒/3 免审)。 +func auditHint(s int8) string { + switch s { + case 1: + return "审核通过,等待调度" + case 2: + return "审核拒绝(命中敏感词)" + case 3: + return "免审受理,等待调度" + default: + return "已受理,待人工审核(48h 未审自动退回)" + } +} + +// submit POST /send/submit——受理发送任务(Day 43 修复循环:最小提交链; +// 校验→计费→余额只读校验→落任务+明细→审核分流;限流/扣费/下发 Day45/46)。 +func (h *sendHandler) submit(c *gin.Context) { + var req send.SubmitReq + if err := c.ShouldBindJSON(&req); err != nil { + response.ErrorWithMsg(c, errors.InvalidParam, "参数错误: "+err.Error()) + return + } + // 账号:请求未带则取 JWT(管理端代提交可显式指定;客户自提交缺省本人)。 + req.Source = send.TaskSourceWeb // Day 60:Web 控制台提交打标(内部字段,请求体不可覆写) + if req.AccountID == 0 { + if v, ok := c.Get(middleware.ContextKeyClaims); ok { + if claims, ok := v.(*jwtpkg.Claims); ok { + req.AccountID = claims.AccountID + } + } + } + if req.AccountID == 0 { + response.ErrorWithMsg(c, errors.InvalidParam, "缺少账号(account_id)") + return + } + var tpl *entity.TemplateSMS + if req.TemplateID > 0 { + if h.tplSvc == nil { + response.ErrorWithMsg(c, errors.InvalidParam, "模板服务未装配") + return + } + t, err := h.tplSvc.GetByID(c.Request.Context(), req.TemplateID) + if err != nil { + bizResp(c, err) + return + } + tpl = t + } + // 渲染内容(直发=原样;模板=Render),与 estimate/precheck 同源。 + if _, err := req.Validate(tpl); err != nil { + bizResp(c, err) + return + } + content := req.Content + if tpl != nil { + rendered, err := h.tplSvc.Render(tpl, req.Variables) + if err != nil { + bizResp(c, err) + return + } + content = rendered + } + res, err := h.submitSvc.Submit(c.Request.Context(), &req, tpl, content, c.ClientIP()) + if err != nil { + bizResp(c, err) + return + } + resp := SubmitResp{ + TaskNo: res.Task.TaskNo, TaskID: res.Task.ID, + AuditStatus: res.Task.AuditStatus, AuditHint: auditHint(res.Task.AuditStatus), + ValidCount: res.Estimate.ValidCount, Segments: res.Estimate.Segments, + TotalFee: res.Estimate.TotalFee, + } + if res.Task.ScheduleAt != nil { + resp.ScheduleAt = res.Task.ScheduleAt.Format(time.RFC3339) + } + response.Success(c, resp) +} diff --git a/internal/api/http/v1/stats_handler.go b/internal/api/http/v1/stats_handler.go new file mode 100644 index 00000000..a5d3799a --- /dev/null +++ b/internal/api/http/v1/stats_handler.go @@ -0,0 +1,305 @@ +// stats_handler.go Day68:运营总览(/home)真实数据——四指标卡 summary + 近 N 日 +// trend 两端点。契约=web/src/api/stats.ts(FE-Design-Audit B1,此前仅 msw mock +// 承载);响应形状与 mock ok() 逐字段一致({code,msg,data})。 +// +// 性能(Day64/67 教训前置):趋势/历史不直查明细(340 万行×7 天=700 万条目扫描, +// HDD 5s+/次×60s 自动刷新不可持续)——日汇总表 stats_daily 由后台 60s ticker 增量 +// UPSERT(当天行滚动更新+跨天补昨日终值,幂等),API 只读汇总表毫秒级;聚合 SQL +// 三条纯覆盖索引 COUNT(总量 idx_detail_created/成败 idx_status_time(status, +// created_at))零随机回表。 +// +// 口径:success_rate=终态成功率 success/(success+failed)(在途0/提交1/未知4/拦截5 +// 不计分母,运营语义);today_sent=全部提交含在途。balance_alert_count 同 +// service/account/warning.go ScanOnce 口径(启用规则×启用账号×可用额度 +// balance+credit_balance<阈值)。pending_audit_count=message_task.audit_status=0。 +// +// 角色范围:admin/ops/service=全平台(stats_daily);group/customer=仅自己账号 +// (明细直查——自有量级小;大客户场景预留账号维度汇总,见 entity.StatsDaily 注)。 +package v1 + +import ( + "time" + + "github.com/gin-gonic/gin" + "go.uber.org/zap" + "gorm.io/gorm" + "gorm.io/gorm/clause" + + "go-sms/internal/middleware" + "go-sms/internal/model/entity" + "go-sms/internal/pkg/response" +) + +const ( + // statsRefreshEvery 汇总刷新周期(与前端 Dashboard 60s 自动刷新同频)。 + statsRefreshEvery = time.Minute + // statsTrendMaxDays 趋势最大天数(防 days 超大;mock 契约默认 7)。 + statsTrendMaxDays = 30 + // statsRefresherBackfillDays 启动回补天数(趋势窗余量)。 + statsRefresherBackfillDays = 30 +) + +type statsHandler struct{ db *gorm.DB } + +// registerStatsRoutes 注册 stats 域端点(查询类,JWT 保护即可,不挂 Casbin)。 +func registerStatsRoutes(protected *gin.RouterGroup, db *gorm.DB) { + h := &statsHandler{db: db} + protected.GET("/stats/summary", h.summary) + protected.GET("/stats/trend", h.trend) +} + +// statsSummaryDTO 四指标卡(mock 契约逐字段)。 +type statsSummaryDTO struct { + TodaySent int64 `json:"today_sent"` + YesterdaySent int64 `json:"yesterday_sent"` + SuccessRate float64 `json:"success_rate"` // 0~1(终态口径) + SuccessRateDelta float64 `json:"success_rate_delta"` // 今-昨(pp 差值) + BalanceAlertCount int64 `json:"balance_alert_count"` // 余额低于预警线账号数 + PendingAuditCount int64 `json:"pending_audit_count"` // 待人工审核条数 +} + +// trendDTO 趋势点(mock 契约:date='MM-DD')。 +type trendDTO struct { + Date string `json:"date"` + Sent int64 `json:"sent"` + Success int64 `json:"success"` +} + +// statsClaims 从 gin 上下文取登录 Claims(protected 组内恒在;nil 仅测试场景)。 +func statsClaims(c *gin.Context) *middleware.Claims { + v, _ := c.Get(middleware.ContextKeyClaims) + claims, _ := v.(*middleware.Claims) + return claims +} + +// statsIsPlatform 平台口径角色判定(admin/ops/service);其余(group/customer) +// 走自己账号范围。 +func statsIsPlatform(c *gin.Context) bool { + claims := statsClaims(c) + if claims == nil { + return true + } + for _, r := range claims.Roles { + if r == "admin" || r == "ops" || r == "service" { + return true + } + } + return false +} + +// statsRate 终态成功率(分母 0 返回 0)。 +func statsRate(succ, fail int64) float64 { + if d := succ + fail; d > 0 { + return float64(succ) / float64(d) + } + return 0 +} + +// platformDay 读汇总表单日三元组(无行=0,如启动回补前的首分钟)。 +func (h *statsHandler) platformDay(day time.Time) (sub, succ, fail int64) { + var row entity.StatsDaily + if err := h.db.Where("day = ?", day.Format("2006-01-02")).Take(&row).Error; err != nil { + return 0, 0, 0 + } + return row.Submitted, row.Success, row.Failed +} + +// accountDay 客户口径单日直查(自有量级小,一条聚合可接受;SUM 布尔两库通用)。 +func (h *statsHandler) accountDay(accountID int64, day time.Time) (sub, succ, fail int64) { + type r struct { + Total int64 + Succ int64 + Fail int64 + } + var row r + if err := h.db.Table("message_detail"). + Select("COUNT(*) AS total, COALESCE(SUM(status = 2), 0) AS succ, COALESCE(SUM(status = 3), 0) AS fail"). + Where("account_id = ? AND created_at >= ? AND created_at < ?", + accountID, day, day.AddDate(0, 0, 1)). + Take(&row).Error; err != nil { + return 0, 0, 0 + } + return row.Total, row.Succ, row.Fail +} + +// balanceAlertCount 余额预警计数(平台=全量规则;客户=自己 0/1)。Raw 绕 gorm +// 软删过滤需手工 deleted_at IS NULL(与 warning.go Take 自动过滤口径一致)。 +func (h *statsHandler) balanceAlertCount(c *gin.Context, platform bool) int64 { + if platform { + var n int64 + h.db.Raw(`SELECT COUNT(*) FROM system_alert_rule r + JOIN account_user a ON a.id = r.target_id AND a.status = 1 AND a.deleted_at IS NULL + WHERE r.status = 1 AND r.target_type = 'account' AND r.metric = 'balance' + AND (a.balance + a.credit_balance) < r.threshold`).Scan(&n) + return n + } + claims := statsClaims(c) + if claims == nil { + return 0 + } + var rule entity.SystemAlertRule + if err := h.db.Where( + "status = 1 AND target_type = ? AND metric = ? AND target_id = ?", + "account", "balance", claims.AccountID, + ).Take(&rule).Error; err != nil { + return 0 // 未配置阈值不计 + } + var acct entity.AccountUser + if err := h.db.Select("balance", "credit_balance").Take(&acct, claims.AccountID).Error; err != nil { + return 0 + } + if float64(acct.Balance+acct.CreditBalance) < rule.Threshold { + return 1 + } + return 0 +} + +// pendingAuditCount 待人工审核计数(audit_status=0;idx_audit 覆盖快扫)。 +func (h *statsHandler) pendingAuditCount(c *gin.Context, platform bool) int64 { + q := h.db.Table("message_task").Where("audit_status = 0") + if !platform { + if claims := statsClaims(c); claims != nil { + q = q.Where("account_id = ?", claims.AccountID) + } + } + var n int64 + q.Count(&n) + return n +} + +// summary GET /stats/summary——四指标卡。 +func (h *statsHandler) summary(c *gin.Context) { + now := time.Now() + // 自然日窗口(00:00~24:00):与 statsAggregateDay 聚合口径一致,且避免 + // 「行 created_at 与请求时刻同毫秒」的窗口边界竞争。 + today := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location()) + yesterday := today.AddDate(0, 0, -1) + platform := statsIsPlatform(c) + var tSub, tSucc, tFail, ySub, ySucc, yFail int64 + if platform { + tSub, tSucc, tFail = h.platformDay(today) + ySub, ySucc, yFail = h.platformDay(yesterday) + } else { + claims := statsClaims(c) + tSub, tSucc, tFail = h.accountDay(claims.AccountID, today) + ySub, ySucc, yFail = h.accountDay(claims.AccountID, yesterday) + } + response.Success(c, statsSummaryDTO{ + TodaySent: tSub, + YesterdaySent: ySub, + SuccessRate: statsRate(tSucc, tFail), + SuccessRateDelta: statsRate(tSucc, tFail) - statsRate(ySucc, yFail), + BalanceAlertCount: h.balanceAlertCount(c, platform), + PendingAuditCount: h.pendingAuditCount(c, platform), + }) +} + +// trend GET /stats/trend?days=7——近 N 日趋势(缺日补零;date=MM-DD 同 mock)。 +func (h *statsHandler) trend(c *gin.Context) { + days := intQuery(c, "days", 7) + if days < 1 { + days = 7 + } + if days > statsTrendMaxDays { + days = statsTrendMaxDays + } + now := time.Now() + // 自然日起点(与 summary/聚合同口径,避免毫秒级窗口边界竞争)。 + start := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location()). + AddDate(0, 0, -(days - 1)) + byDay := map[string][2]int64{} + if statsIsPlatform(c) { + var rows []entity.StatsDaily + if err := h.db.Where("day >= ?", start.Format("2006-01-02")). + Order("day").Find(&rows).Error; err != nil { + bizResp(c, err) + return + } + for _, r := range rows { + byDay[r.Day] = [2]int64{r.Submitted, r.Success} + } + } else { + claims := statsClaims(c) + type row struct { + Day string + Submitted int64 + Success int64 + } + var rows []row + if err := h.db.Table("message_detail"). + Select("date(created_at) AS day, COUNT(*) AS submitted, COALESCE(SUM(status = 2), 0) AS success"). + Where("account_id = ? AND created_at >= ?", claims.AccountID, start). + Group("day").Order("day").Scan(&rows).Error; err != nil { + bizResp(c, err) + return + } + for _, r := range rows { + byDay[r.Day] = [2]int64{r.Submitted, r.Success} + } + } + list := make([]trendDTO, 0, days) + for i := 0; i < days; i++ { + day := start.AddDate(0, 0, i) + v := byDay[day.Format("2006-01-02")] + list = append(list, trendDTO{Date: day.Format("01-02"), Sent: v[0], Success: v[1]}) + } + response.Success(c, list) +} + +// statsAggregateDay 单日聚合(幂等 UPSERT):三条纯覆盖索引 COUNT——总量走 +// idx_detail_created,成功/失败各走 idx_status_time(status,created_at)—— +// 零随机回表(Day67 教训:合一条 SUM(status=2) 会让覆盖索引失效退化百万级回表)。 +func statsAggregateDay(db *gorm.DB, day time.Time) error { + lo := time.Date(day.Year(), day.Month(), day.Day(), 0, 0, 0, 0, day.Location()) + hi := lo.AddDate(0, 0, 1) + var submitted, success, failed int64 + if err := db.Table("message_detail"). + Where("created_at >= ? AND created_at < ?", lo, hi). + Count(&submitted).Error; err != nil { + return err + } + if err := db.Table("message_detail"). + Where("status = ? AND created_at >= ? AND created_at < ?", 2, lo, hi). + Count(&success).Error; err != nil { + return err + } + if err := db.Table("message_detail"). + Where("status = ? AND created_at >= ? AND created_at < ?", 3, lo, hi). + Count(&failed).Error; err != nil { + return err + } + row := entity.StatsDaily{ + Day: lo.Format("2006-01-02"), Submitted: submitted, Success: success, Failed: failed, + } + return db.Clauses(clause.OnConflict{ + Columns: []clause.Column{{Name: "day"}}, + DoUpdates: clause.AssignmentColumns([]string{"submitted", "success", "failed", "updated_at"}), + }).Create(&row).Error +} + +// StartStatsRefresher 后台汇总刷新(仅 gateway 装配调用;测试/迁移工具不启): +// 启动即后台回补 30 天(不阻塞启动,HDD 首轮 1~2 分钟),此后 60s ticker 聚合 +// 今天+昨天(跨天窗口补昨日终值)。幂等 UPSERT——多实例重复刷新无害。 +func StartStatsRefresher(db *gorm.DB, log *zap.Logger) { + go func() { + for i := statsRefresherBackfillDays - 1; i >= 0; i-- { + day := time.Now().AddDate(0, 0, -i) + if err := statsAggregateDay(db, day); err != nil && log != nil { + log.Warn("stats_backfill_day_failed", zap.String("day", day.Format("2006-01-02")), zap.Error(err)) + } + } + if log != nil { + log.Info("stats_backfill_done") + } + ticker := time.NewTicker(statsRefreshEvery) + defer ticker.Stop() + for range ticker.C { + now := time.Now() + for _, d := range []time.Time{now, now.AddDate(0, 0, -1)} { + if err := statsAggregateDay(db, d); err != nil && log != nil { + log.Warn("stats_refresh_failed", zap.Error(err)) + } + } + } + }() +} diff --git a/internal/api/http/v1/stats_handler_test.go b/internal/api/http/v1/stats_handler_test.go new file mode 100644 index 00000000..e28fcb69 --- /dev/null +++ b/internal/api/http/v1/stats_handler_test.go @@ -0,0 +1,208 @@ +package v1 + +// stats_handler_test.go Day68:运营总览两端点——聚合内核(UPSERT 幂等)+平台/ +// 客户双口径 summary+trend 补零与 MM-DD 格式。sqlite 单测覆盖逻辑;覆盖索引 +// 代价在 dev MySQL 实机验收(此前 bench 已证覆盖 COUNT 亚秒)。 + +import ( + "encoding/json" + "math" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/gin-gonic/gin" + "github.com/glebarez/sqlite" + "gorm.io/gorm" + + "go-sms/internal/middleware" + "go-sms/internal/model/entity" +) + +// newStatsRouter 种子:平台今日 3 行(成功×2+失败×1)/昨日 2 行(成功+失败); +// 客户 100 今日 1 成功/昨日 1 失败;平台待审 2+客户免审;客户阈值 10000 余额 +// 5000 → 预警 1。claims 由返回的 setClaims 注入(模拟 JWT 中间件)。 +func newStatsRouter(t *testing.T) (*gin.Engine, *gorm.DB, func(*middleware.Claims)) { + t.Helper() + gin.SetMode(gin.TestMode) + db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{}) + if err != nil { + t.Fatal(err) + } + if s, e := db.DB(); e == nil { + s.SetMaxOpenConns(1) + } + if err := db.AutoMigrate(&entity.MessageTask{}, &entity.MessageDetail{}, + &entity.AccountUser{}, &entity.SystemAlertRule{}, &entity.StatsDaily{}); err != nil { + t.Fatal(err) + } + now := time.Now() + mk := func(id, accountID int64, status int8, created time.Time) entity.MessageDetail { + return entity.MessageDetail{ + SnowflakeModel: entity.SnowflakeModel{ID: id, CreatedAt: created}, + TaskID: 900000 + id, AccountID: accountID, ChannelID: 1, + Mobile: "13000001111", Content: "t", Status: status, + } + } + details := []entity.MessageDetail{ + // 平台(account 1)今日:2 成功+1 失败;昨日:1 成功+1 失败。 + mk(1, 1, 2, now), mk(2, 1, 2, now), mk(3, 1, 3, now), + mk(4, 1, 2, now.AddDate(0, 0, -1)), mk(5, 1, 3, now.AddDate(0, 0, -1)), + // 客户 100:今日 1 成功;昨日 1 失败。 + mk(6, 100, 2, now), mk(7, 100, 3, now.AddDate(0, 0, -1)), + } + if err := db.Create(&details).Error; err != nil { + t.Fatal(err) + } + tasks := []entity.MessageTask{ + {ID: 900001, TaskNo: "T900001", AccountID: 1, AuditStatus: 0}, + {ID: 900002, TaskNo: "T900002", AccountID: 1, AuditStatus: 0}, + {ID: 900007, TaskNo: "T900007", AccountID: 100, AuditStatus: 3}, + } + if err := db.Create(&tasks).Error; err != nil { + t.Fatal(err) + } + accts := []entity.AccountUser{ + {Model: entity.Model{ID: 1}, Username: "admin", Status: 1, Balance: 9999999}, + {Model: entity.Model{ID: 100}, Username: "cust100", Status: 1, Balance: 5000}, + } + if err := db.Create(&accts).Error; err != nil { + t.Fatal(err) + } + rules := []entity.SystemAlertRule{ + {Model: entity.Model{ID: 1}, TargetType: "account", TargetID: 100, Metric: "balance", + Op: "lt", Threshold: 10000, NotifyType: "wechat", CooldownMin: 30, Status: 1}, + } + if err := db.Create(&rules).Error; err != nil { + t.Fatal(err) + } + // 预聚合今/昨两天(内核路径直测;customer 直查不依赖汇总表)。 + for _, d := range []time.Time{now, now.AddDate(0, 0, -1)} { + if err := statsAggregateDay(db, d); err != nil { + t.Fatal(err) + } + } + rg := gin.New() + api := rg.Group("/api/v1") + var claims *middleware.Claims + api.Use(func(c *gin.Context) { + if claims != nil { + c.Set(middleware.ContextKeyClaims, claims) + } + }) + registerStatsRoutes(api, db) + setClaims := func(cl *middleware.Claims) { claims = cl } + return rg, db, setClaims +} + +func TestStatsSummary_Platform(t *testing.T) { + rg, _, setClaims := newStatsRouter(t) + setClaims(&middleware.Claims{AccountID: 1, Username: "admin", Roles: []string{"admin"}}) + w := httptest.NewRecorder() + rg.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/api/v1/stats/summary", nil)) + if w.Code != 200 { + t.Fatalf("status=%d body=%s", w.Code, w.Body.String()) + } + var res struct { + Data statsSummaryDTO `json:"data"` + } + if err := json.Unmarshal(w.Body.Bytes(), &res); err != nil { + t.Fatal(err) + } + d := res.Data + if d.TodaySent != 4 { // 平台=全量:3+客户 1 + t.Errorf("today_sent=%d want 4", d.TodaySent) + } + if d.YesterdaySent != 3 { + t.Errorf("yesterday_sent=%d want 3", d.YesterdaySent) + } + // 今日终态:成功 3(平台2+客户1)/失败 1 → 0.75;昨日成功1/失败2(含客户 + // 昨日失败行——平台口径=全量) → 1/3;delta=0.75-1/3。 + if math.Abs(d.SuccessRate-0.75) > 1e-9 { + t.Errorf("success_rate=%v want 0.75", d.SuccessRate) + } + if math.Abs(d.SuccessRateDelta-(0.75-1.0/3.0)) > 1e-9 { + t.Errorf("success_rate_delta=%v want %.6f", d.SuccessRateDelta, 0.75-1.0/3.0) + } + if d.BalanceAlertCount != 1 { + t.Errorf("balance_alert_count=%d want 1", d.BalanceAlertCount) + } + if d.PendingAuditCount != 2 { + t.Errorf("pending_audit_count=%d want 2", d.PendingAuditCount) + } +} + +func TestStatsSummary_Customer(t *testing.T) { + rg, _, setClaims := newStatsRouter(t) + setClaims(&middleware.Claims{AccountID: 100, Username: "cust100", Roles: []string{"customer"}}) + w := httptest.NewRecorder() + rg.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/api/v1/stats/summary", nil)) + if w.Code != 200 { + t.Fatalf("status=%d body=%s", w.Code, w.Body.String()) + } + var res struct { + Data statsSummaryDTO `json:"data"` + } + if err := json.Unmarshal(w.Body.Bytes(), &res); err != nil { + t.Fatal(err) + } + d := res.Data + if d.TodaySent != 1 || d.YesterdaySent != 1 { + t.Errorf("sent today=%d yesterday=%d want 1/1", d.TodaySent, d.YesterdaySent) + } + // 今日 1成功0失败=1.0;昨日 0成功1失败=0 → delta 1.0。 + if math.Abs(d.SuccessRate-1.0) > 1e-9 || math.Abs(d.SuccessRateDelta-1.0) > 1e-9 { + t.Errorf("rate=%v delta=%v want 1/1", d.SuccessRate, d.SuccessRateDelta) + } + if d.BalanceAlertCount != 1 { // 自己 5000<10000 + t.Errorf("balance_alert_count=%d want 1", d.BalanceAlertCount) + } + if d.PendingAuditCount != 0 { + t.Errorf("pending_audit_count=%d want 0", d.PendingAuditCount) + } +} + +func TestStatsTrend(t *testing.T) { + rg, db, setClaims := newStatsRouter(t) + setClaims(&middleware.Claims{AccountID: 1, Username: "admin", Roles: []string{"admin"}}) + w := httptest.NewRecorder() + rg.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/api/v1/stats/trend?days=3", nil)) + if w.Code != 200 { + t.Fatalf("status=%d body=%s", w.Code, w.Body.String()) + } + var res struct { + Data []trendDTO `json:"data"` + } + if err := json.Unmarshal(w.Body.Bytes(), &res); err != nil { + t.Fatal(err) + } + if len(res.Data) != 3 { + t.Fatalf("trend len=%d want 3", len(res.Data)) + } + today, yesterday, ereyday := res.Data[2], res.Data[1], res.Data[0] + if today.Sent != 4 || today.Success != 3 { + t.Errorf("today sent/success=%d/%d want 4/3", today.Sent, today.Success) + } + if yesterday.Sent != 3 || yesterday.Success != 1 { + t.Errorf("yesterday sent/success=%d/%d want 3/1", yesterday.Sent, yesterday.Success) + } + if ereyday.Sent != 0 || ereyday.Success != 0 { + t.Errorf("前天应补零 got %d/%d", ereyday.Sent, ereyday.Success) + } + if len(today.Date) != 5 || today.Date[2] != '-' { // MM-DD + t.Errorf("date=%q want MM-DD", today.Date) + } + // 内核幂等:重跑聚合数值不变。 + if err := statsAggregateDay(db, time.Now()); err != nil { + t.Fatal(err) + } + var row entity.StatsDaily + if err := db.Where("day = ?", time.Now().Format("2006-01-02")).Take(&row).Error; err != nil { + t.Fatal(err) + } + if row.Submitted != 4 || row.Success != 3 || row.Failed != 1 { + t.Errorf("重跑后 submitted/success/failed=%d/%d/%d want 4/3/1", + row.Submitted, row.Success, row.Failed) + } +} diff --git a/internal/api/http/v1/template_day41_test.go b/internal/api/http/v1/template_day41_test.go new file mode 100644 index 00000000..1ec6f29f --- /dev/null +++ b/internal/api/http/v1/template_day41_test.go @@ -0,0 +1,80 @@ +// template_day41_test.go Day 41:模板 CRUD/审核状态机/发送预估端点(阶段 4 开篇)。 +package v1 + +import ( + "net/http" + "strings" + "testing" +) + +// TestAPI_TemplateLifecycle 验收:创建待审→customer 可建(message:write)→审核通过→编辑回待审→拒审→删除。 +func TestAPI_TemplateLifecycle(t *testing.T) { + r := newD35Router(t) + tok := d25Token(t, 2, "customer") // customer:message:write + adminTok := d25Token(t, 1, "admin") + + // 创建(待审) + w := doReqBody(r, http.MethodPost, "/api/v1/templates", tok, "application/json", + []byte(`{"account_id":2,"name":"验证码","content":"您的验证码{code},5分钟内有效"}`)) + if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), `"status":0`) { + t.Fatalf("创建 = %d: %s", w.Code, w.Body.String()) + } + // 审核(过) + if w := doReqBody(r, http.MethodPut, "/api/v1/templates/1/review", adminTok, "application/json", + []byte(`{"pass":true}`)); w.Code != http.StatusOK { + t.Fatalf("审核 = %d: %s", w.Code, w.Body.String()) + } + // 通过态删除 → 拒绝 + if w := doReq(r, http.MethodDelete, "/api/v1/templates/1", tok); w.Code != http.StatusBadRequest { + t.Fatalf("通过态删除应 400: %d", w.Code) + } + // 编辑内容 → 回待审 + if w := doReqBody(r, http.MethodPut, "/api/v1/templates/1", tok, "application/json", + []byte(`{"content":"新内容{code}"}`)); w.Code != http.StatusOK { + t.Fatalf("编辑 = %d: %s", w.Code, w.Body.String()) + } + if w := doReq(r, http.MethodGet, "/api/v1/templates/1", tok); !strings.Contains(w.Body.String(), `"status":0`) { + t.Fatalf("编辑后应待审: %s", w.Body.String()) + } + // 列表状态过滤(指针语义:status=0 待审) + if w := doReq(r, http.MethodGet, "/api/v1/templates?status=0", tok); !strings.Contains(w.Body.String(), `"total":1`) { + t.Fatalf("待审过滤应 1: %s", w.Body.String()) + } + // 拒审带理由 → 可删除 + doReqBody(r, http.MethodPut, "/api/v1/templates/1/review", adminTok, "application/json", []byte(`{"pass":false,"reason":"不合规"}`)) + if w := doReq(r, http.MethodDelete, "/api/v1/templates/1", tok); w.Code != http.StatusOK { + t.Fatalf("拒审后删除 = %d: %s", w.Code, w.Body.String()) + } +} + +// TestAPI_SendEstimate 验收:预估条数与后端 SmsLength 同源;模板未过审/缺参/非法号码拒绝路径。 +func TestAPI_SendEstimate(t *testing.T) { + r := newD35Router(t) + tok := d25Token(t, 2, "customer") + + // 直发中文 71 字 ×2 号码(1 重复) → 2×2=4 条 + long := strings.Repeat("汉", 71) + body := `{"mobiles":["13800138000","13800138001","13800138000"],"content":"` + long + `","sign":"【测】"}` + w := doReqBody(r, http.MethodPost, "/api/v1/send/estimate", tok, "application/json", []byte(body)) + if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), `"total_fee":4`) { + t.Fatalf("预估 = %d: %s", w.Code, w.Body.String()) + } + // Day41 验收二变:签名可选(内容自带),缺 sign 不再拒——正向:内容自带签名直发 + w = doReqBody(r, http.MethodPost, "/api/v1/send/estimate", tok, "application/json", + []byte(`{"mobiles":["13800138000"],"content":"【测】hi","send_type":1}`)) + if w.Code != http.StatusOK { + t.Fatalf("无 sign 自带签名应 200: %d: %s", w.Code, w.Body.String()) + } + // 拒绝路径:内容为空 + w = doReqBody(r, http.MethodPost, "/api/v1/send/estimate", tok, "application/json", + []byte(`{"mobiles":["13800138000"],"content":"","send_type":1}`)) + if w.Code != http.StatusBadRequest { + t.Fatalf("空内容应 400: %d", w.Code) + } + // 拒绝路径:模板不存在 + w = doReqBody(r, http.MethodPost, "/api/v1/send/estimate", tok, "application/json", + []byte(`{"mobiles":["13800138000"],"template_id":99,"variables":{"a":"b"},"sign":"【测】"}`)) + if w.Code != http.StatusNotFound { + t.Fatalf("模板 99 应 404: %d", w.Code) + } +} diff --git a/internal/api/http/v1/template_handler.go b/internal/api/http/v1/template_handler.go new file mode 100644 index 00000000..ff00f3ab --- /dev/null +++ b/internal/api/http/v1/template_handler.go @@ -0,0 +1,165 @@ +// template_handler.go Day 41:模板 CRUD+审核端点+发送预估(D17 群发工作台实时计费条数)。 +package v1 + +import ( + "strconv" + + "github.com/gin-gonic/gin" + + "go-sms/internal/middleware" + "go-sms/internal/model/entity" + "go-sms/internal/pkg/errors" + "go-sms/internal/pkg/response" + "go-sms/internal/service/send" + "go-sms/internal/service/template" +) + +// templateHandler 模板接口。 +type templateHandler struct{ svc *template.Service } + +func registerTemplateRoutes(protected *gin.RouterGroup, perm middleware.PermissionChecker, svc *template.Service) { + h := &templateHandler{svc: svc} + gate := func(obj, act string) gin.HandlerFunc { + return middleware.RequirePermission(perm, obj, act) + } + protected.GET("/templates", h.list) + protected.POST("/templates", gate("message", "write"), h.create) + protected.GET("/templates/:id", h.get) + protected.PUT("/templates/:id", gate("message", "write"), h.update) + protected.DELETE("/templates/:id", gate("message", "write"), h.remove) + protected.PUT("/templates/:id/review", gate("message", "write"), h.review) + // Day 44(D20):批量审核(事务内原子翻转 WHERE status=0;已审跳过)。 + protected.PUT("/templates/batch-review", gate("message", "write"), h.batchReview) + // 发送预估:模板短信自动带出模板内容渲染(D17 实时条数与后端同源) + protected.POST("/send/estimate", gate("message", "write"), h.estimate) +} + +func (h *templateHandler) list(c *gin.Context) { + q := &template.Query{ + Page: intQuery(c, "page", 1), PageSize: intQuery(c, "page_size", 20), + Name: c.Query("name"), + } + if v := c.Query("account_id"); v != "" { + id, _ := strconv.ParseInt(v, 10, 64) + q.AccountID = id + } + if v := c.Query("status"); v != "" { + st, _ := strconv.Atoi(v) + s := int8(st) + q.Status = &s + } + list, total, err := h.svc.List(c.Request.Context(), q) + if err != nil { + bizResp(c, err) + return + } + response.Success(c, gin.H{"total": total, "list": list}) +} + +func (h *templateHandler) create(c *gin.Context) { + var req template.CreateReq + if err := c.ShouldBindJSON(&req); err != nil { + response.ErrorWithMsg(c, errors.InvalidParam, "参数错误: "+err.Error()) + return + } + t, err := h.svc.Create(c.Request.Context(), &req) + if err != nil { + bizResp(c, err) + return + } + response.Success(c, t) +} + +func (h *templateHandler) get(c *gin.Context) { + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + t, err := h.svc.GetByID(c.Request.Context(), id) + if err != nil { + bizResp(c, err) + return + } + response.Success(c, t) +} + +func (h *templateHandler) update(c *gin.Context) { + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + var body map[string]any + if err := c.ShouldBindJSON(&body); err != nil || len(body) == 0 { + response.ErrorWithMsg(c, errors.InvalidParam, "请求体需为字段对象") + return + } + if err := h.svc.Update(c.Request.Context(), id, body); err != nil { + bizResp(c, err) + return + } + response.Success(c, gin.H{"id": id}) +} + +func (h *templateHandler) remove(c *gin.Context) { + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + if err := h.svc.Delete(c.Request.Context(), id); err != nil { + bizResp(c, err) + return + } + response.Success(c, gin.H{"id": id}) +} + +// review PUT /templates/:id/review {pass: bool, reason}。 +func (h *templateHandler) review(c *gin.Context) { + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + var req struct { + Pass bool `json:"pass"` + Reason string `json:"reason"` + } + if err := c.ShouldBindJSON(&req); err != nil { + response.ErrorWithMsg(c, errors.InvalidParam, "参数错误: "+err.Error()) + return + } + if err := h.svc.Review(c.Request.Context(), id, req.Pass, req.Reason); err != nil { + bizResp(c, err) + return + } + response.Success(c, gin.H{"id": id}) +} + +// batchReview PUT /templates/batch-review {ids:[], pass, reason} → {ok, total}。 +func (h *templateHandler) batchReview(c *gin.Context) { + var req struct { + IDs []int64 `json:"ids"` + Pass bool `json:"pass"` + Reason string `json:"reason"` + } + if err := c.ShouldBindJSON(&req); err != nil || len(req.IDs) == 0 { + response.ErrorWithMsg(c, errors.InvalidParam, "参数错误: ids 非空数组") + return + } + ok, err := h.svc.BatchReview(c.Request.Context(), req.IDs, req.Pass, req.Reason) + if err != nil { + bizResp(c, err) + return + } + response.Success(c, gin.H{"ok": ok, "total": len(req.IDs)}) +} + +// estimate POST /send/estimate(SubmitReq;template_id>0 时服务端取模板渲染)。 +func (h *templateHandler) estimate(c *gin.Context) { + var req send.SubmitReq + if err := c.ShouldBindJSON(&req); err != nil { + response.ErrorWithMsg(c, errors.InvalidParam, "参数错误: "+err.Error()) + return + } + var tpl *entity.TemplateSMS + if req.TemplateID > 0 { + t, err := h.svc.GetByID(c.Request.Context(), req.TemplateID) + if err != nil { + bizResp(c, err) + return + } + tpl = t + } + est, err := req.Validate(tpl) + if err != nil { + bizResp(c, err) + return + } + response.Success(c, est) +} diff --git a/internal/api/http/v1/upstream_handler.go b/internal/api/http/v1/upstream_handler.go new file mode 100644 index 00000000..f74d85c4 --- /dev/null +++ b/internal/api/http/v1/upstream_handler.go @@ -0,0 +1,76 @@ +// upstream_handler.go Day 41(清债③):上家(通道方)管理端点——补齐 FE-1 UpstreamList.vue 的既有调用。 +package v1 + +import ( + "strconv" + + "github.com/gin-gonic/gin" + + "go-sms/internal/model/entity" + "go-sms/internal/pkg/errors" + "go-sms/internal/pkg/response" + "go-sms/internal/service/channel" +) + +// upstreamHandler 上家接口。 +type upstreamHandler struct{ svc *channel.UpstreamService } + +// list GET /channels/upstreams?page&page_size&name&status。 +func (h *upstreamHandler) list(c *gin.Context) { + q := &channel.UpstreamQuery{ + Page: intQuery(c, "page", 1), PageSize: intQuery(c, "page_size", 20), + Name: c.Query("name"), + } + if v := c.Query("status"); v != "" { + st, _ := strconv.Atoi(v) + q.Status = int8(st) + } else { + q.Status = -1 + } + list, total, err := h.svc.List(c.Request.Context(), q) + if err != nil { + bizResp(c, err) + return + } + response.Success(c, gin.H{"total": total, "list": list}) +} + +// create POST /channels/upstreams {name,contact,phone,category,status,remark}。 +func (h *upstreamHandler) create(c *gin.Context) { + var req entity.ChannelUpstream + if err := c.ShouldBindJSON(&req); err != nil || req.Name == "" { + response.ErrorWithMsg(c, errors.InvalidParam, "name 必填") + return + } + u, err := h.svc.Create(c.Request.Context(), &req) + if err != nil { + bizResp(c, err) + return + } + response.Success(c, u) +} + +// update PUT /channels/upstreams/:id(白名单字段)。 +func (h *upstreamHandler) update(c *gin.Context) { + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + var body map[string]any + if err := c.ShouldBindJSON(&body); err != nil || len(body) == 0 { + response.ErrorWithMsg(c, errors.InvalidParam, "请求体需为字段对象") + return + } + if err := h.svc.Update(c.Request.Context(), id, body); err != nil { + bizResp(c, err) + return + } + response.Success(c, gin.H{"id": id}) +} + +// remove DELETE /channels/upstreams/:id(被通道引用则拒绝)。 +func (h *upstreamHandler) remove(c *gin.Context) { + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + if err := h.svc.Delete(c.Request.Context(), id); err != nil { + bizResp(c, err) + return + } + response.Success(c, gin.H{"id": id}) +} diff --git a/internal/api/http/v1/warning_handler.go b/internal/api/http/v1/warning_handler.go new file mode 100644 index 00000000..54263c2d --- /dev/null +++ b/internal/api/http/v1/warning_handler.go @@ -0,0 +1,86 @@ +// warning_handler.go Day 27:余额预警配置端点(本人或 admin 可读写)。 +package v1 + +import ( + "net/http" + "slices" + "strconv" + + "github.com/gin-gonic/gin" + + "go-sms/internal/pkg/errors" + "go-sms/internal/pkg/response" + "go-sms/internal/service/account" +) + +// warningHandler 预警配置接口。 +type warningHandler struct { + svc *account.WarningService +} + +// requireSelfOrAdmin 非 admin 仅允许操作本人资源;越权 abort 403 并返回 false。 +func requireSelfOrAdmin(c *gin.Context, id int64) bool { + claims := operatorClaims(c) + if claims == nil { + response.Error(c, errors.Unauthorized) + return false + } + if !slices.Contains(claims.Roles, "admin") && claims.AccountID != id { + c.AbortWithStatusJSON(http.StatusForbidden, gin.H{ + "code": errors.Forbidden.Code, + "msg": "仅可操作本人预警配置", + }) + return false + } + return true +} + +// get GET /accounts/:id/warning:预警配置(未配置返回 null)。 +func (h *warningHandler) get(c *gin.Context) { + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + if !requireSelfOrAdmin(c, id) { + return + } + rule, err := h.svc.GetWarningConfig(c.Request.Context(), id) + if err != nil { + response.Error(c, errors.InternalError) + return + } + response.Success(c, gin.H{"id": id, "config": rule}) +} + +// set PUT /accounts/:id/warning:设置阈值/冷却/通知方式/接收 webhook。 +func (h *warningHandler) set(c *gin.Context) { + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + if !requireSelfOrAdmin(c, id) { + return + } + var cfg account.WarningConfig + if err := c.ShouldBindJSON(&cfg); err != nil { + response.ErrorWithMsg(c, errors.InvalidParam, "参数错误: "+err.Error()) + return + } + if err := h.svc.SetWarningConfig(c.Request.Context(), id, &cfg); err != nil { + if bizErr, ok := err.(*errors.Error); ok { + response.Error(c, bizErr) + return + } + c.Set("biz_error", err.Error()) + response.Error(c, errors.InternalError) + return + } + response.Success(c, gin.H{"id": id, "config": cfg}) +} + +// disable DELETE /accounts/:id/warning:停用预警(保留参数)。 +func (h *warningHandler) disable(c *gin.Context) { + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + if !requireSelfOrAdmin(c, id) { + return + } + if err := h.svc.DisableWarningConfig(c.Request.Context(), id); err != nil { + response.Error(c, errors.InternalError) + return + } + response.Success(c, gin.H{"id": id, "disabled": true}) +}