Files
go-sms-V2/internal/api/http/v1/account.go
T

780 lines
28 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 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/archive"
"go-sms/internal/service/audit"
"go-sms/internal/service/auth"
"go-sms/internal/service/callback"
"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/settle"
"go-sms/internal/service/sysconfig"
"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
// Settle S2:结算域(消耗日汇总查询/手动回补;充值订单/月结/阶梯/利润
// 随 D3~D5 追加;nil=不注册,前端 404 优于半可用)。
Settle *settle.Service
// Callback S4·C1:回调任务管理(死信查询/重派;PushWorker 在 consumer
// 进程,gateway 侧仅管理面;nil=不注册)。
Callback *callback.Service
// Archive S4·D3:明细冷热归档(/record/history 冷查走 ClickHouse;
// nil=不注册 history 端点,前端 404 优于半可用)。
Archive *archive.Service
// SysConfig Issue#3 方案B:系统参数配置(/system/config GET/PUT;
// access 系统默认接入码回退的数据源;nil=不注册)。
SysConfig *sysconfig.Service
// Health Issue#6·P2:系统健康总览(/ops/system/overview;nil=不注册)。
Health *HealthDeps
}
// 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)
// Issue#5·P0-A:账号分时单价时间线(结算/出账售价事实源的配置面;account:write)
registerAccountPriceRoutes(protected, deps.Perm, deps.Account)
}
// 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)
}
// Issue#3 方案B:系统参数配置(system_config KV 管理页数据源)。
if deps.SysConfig != nil {
registerSysConfigRoutes(protected, deps.Perm, deps.SysConfig)
}
// 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, deps.Archive)
}
// Day68:运营总览(/home)真实数据——summary 四指标卡+trend 近 N 日趋势
// (查询类,JWT 保护即可;口径/角色范围见 stats_handler.go 头注)。
if deps.DB != nil {
registerStatsRoutes(protected, deps.DB)
}
// S2:结算域(D2 消耗日汇总两端点;D3~D5 端点随任务追加,见 settle_handler.go)。
if deps.Settle != nil {
registerSettleRoutes(protected, deps)
}
if deps.Callback != nil {
registerCallbackRoutes(protected, deps)
}
// Issue#6·P2:系统健康总览(Dashboard 系统健康卡)。
if deps.Health != nil {
registerOpsRoutes(protected, deps)
}
// 阶段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)})
}