fund_handler_test.go 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923
  1. // Handler 单测(AC-12 六条验收:端点覆盖 / 2001 / 2002 / 1001 / 金额字符串 / 分页钳制 / 脱敏)。
  2. //
  3. // 断言纪律:只断 body 契约(HTTP 恒 200 + body.code,铁律 6),不断 HTTP 状态码。
  4. //
  5. // 覆盖结构(每条对到 AC-12 验收项原文):
  6. //
  7. // ① 端点 1~17、21 全覆盖 → TestRouteCoverage(18 条 method+path 全注册,且不含端点 18/19/20)
  8. // ② validateReq → 2001;金额非法 → 2002 → TestValidationCodes(两码不串)
  9. // ③ scope 取不到 → 1001 → TestMissingScopeIs1001
  10. // ④ 金额入参必须字符串 → TestMoneyMustBeJSONString(传 number → 2001,不被静默接受)
  11. // ⑤ pageSize>200 → 200 → TestPageSizeClamp(端点 11 响应 data.pageSize == 200)
  12. // ⑥ 响应不含敏感字段 → TestNoSensitiveFields(`imgs` / `payReturnData` 不出现)
  13. //
  14. // 另含 3 条业务冒烟(保证"端点通、且真的落到库里"):
  15. // 充值 → 余额增加;创建工单 → 审批通过 → 余额增加 + 幂等/二次审批被拒;账单 → 汇总恒等式。
  16. package handler
  17. import (
  18. "encoding/json"
  19. "fmt"
  20. "io"
  21. "net/http"
  22. "net/http/httptest"
  23. "path/filepath"
  24. "strings"
  25. "testing"
  26. "time"
  27. gormsqlite "github.com/glebarez/sqlite"
  28. "github.com/gofiber/fiber/v2"
  29. "gorm.io/gorm"
  30. "yuansiwei/unified-backend/internal/academic/model"
  31. "yuansiwei/unified-backend/internal/academic/money"
  32. infraerrors "yuansiwei/unified-backend/internal/infra/errors"
  33. appscope "yuansiwei/unified-backend/internal/infra/scope"
  34. )
  35. // ---------------------------------------------------------------- 测试基础设施
  36. // testScope 测试用作用域(机构 1 / 校区 10 / 财务角色)。
  37. func testScope() *appscope.Scope {
  38. return &appscope.Scope{
  39. InstitutionID: 1, CampusID: 10,
  40. UserID: "01HOPERATOR0000000000001", Role: "finance",
  41. }
  42. }
  43. // testSuperScope 超管作用域(跨机构)。
  44. func testSuperScope() *appscope.Scope {
  45. return &appscope.Scope{InstitutionID: 1, CampusID: 0, SuperAdmin: true, UserID: "01HADMIN0000000000000001", Role: "super_admin"}
  46. }
  47. // newHandlerTestDB academic handler 测试库(资金 4 表 + 活动 5 表 + 简化 t_campus)。
  48. //
  49. // 与 service 包的单测库同构(逐表 AutoMigrate + 删非唯一索引:SQLite 索引名库级唯一,
  50. // 而 academic model 多表共用 `idx_inst_campus` 等名字)。
  51. func newHandlerTestDB(t *testing.T) *gorm.DB {
  52. t.Helper()
  53. dsn := filepath.Join(t.TempDir(), "academic_handler_test.db")
  54. db, err := gorm.Open(gormsqlite.Open(dsn), &gorm.Config{})
  55. if err != nil {
  56. t.Fatalf("gorm.Open(handler 文件库) 失败: %v", err)
  57. }
  58. sqlDB, err := db.DB()
  59. if err != nil {
  60. t.Fatalf("取 sql.DB 失败: %v", err)
  61. }
  62. sqlDB.SetMaxOpenConns(1)
  63. t.Cleanup(func() { _ = sqlDB.Close() })
  64. for _, tbl := range []any{
  65. &model.UserExpense{}, &model.UserExpenseSchool{}, &model.UserExpenseLog{},
  66. &model.UserBalanceRequest{},
  67. &model.CoursesActivity{}, &model.CoursesActivitySigned{},
  68. &model.CoursesActivityUserDiscount{}, &model.CoursesActivityUserDiscountLog{},
  69. &model.CoursesActivityUsedLog{},
  70. } {
  71. if mErr := db.AutoMigrate(tbl); mErr != nil {
  72. t.Fatalf("AutoMigrate(%T) 失败: %v", tbl, mErr)
  73. }
  74. stmt := &gorm.Statement{DB: db}
  75. if pErr := stmt.Parse(tbl); pErr != nil {
  76. t.Fatalf("解析表名(%T) 失败: %v", tbl, pErr)
  77. }
  78. var idxRows []struct {
  79. Name string
  80. SQL *string
  81. }
  82. if qErr := db.Raw(
  83. "SELECT name, sql FROM sqlite_master WHERE type='index' AND tbl_name=? AND name NOT LIKE 'sqlite_%'",
  84. stmt.Schema.Table).Scan(&idxRows).Error; qErr != nil {
  85. t.Fatalf("读索引清单(%s) 失败: %v", stmt.Schema.Table, qErr)
  86. }
  87. for _, row := range idxRows {
  88. sqlText := ""
  89. if row.SQL != nil {
  90. sqlText = strings.ToUpper(*row.SQL)
  91. }
  92. if strings.Contains(sqlText, "UNIQUE") {
  93. continue // 唯一约束必须保留
  94. }
  95. if dErr := db.Exec("DROP INDEX IF EXISTS `" + row.Name + "`").Error; dErr != nil {
  96. t.Fatalf("删索引(%s) 失败: %v", row.Name, dErr)
  97. }
  98. }
  99. }
  100. if err := db.Exec(`CREATE TABLE t_campus (
  101. campus_id INTEGER PRIMARY KEY,
  102. institution_id INTEGER NOT NULL DEFAULT 0,
  103. self_support BOOLEAN NOT NULL DEFAULT 1,
  104. status VARCHAR(32) NOT NULL DEFAULT 'active'
  105. )`).Error; err != nil {
  106. t.Fatalf("建 t_campus 失败: %v", err)
  107. }
  108. if err := db.Exec(`INSERT INTO t_campus(campus_id, institution_id, self_support, status) VALUES(10,1,1,'active')`).Error; err != nil {
  109. t.Fatalf("seed t_campus 失败: %v", err)
  110. }
  111. return db
  112. }
  113. // newTestApp 构造只挂 academic 财务域端点(+ 作用域注入中间件)的 app。
  114. //
  115. // 中间件模拟 Auth 链:`X-Test-NoScope: 1` 时不写作用域(用于 1001 用例),
  116. // `X-Test-Super: 1` 时写超管作用域。
  117. func newTestApp(t *testing.T, db *gorm.DB) *fiber.App {
  118. t.Helper()
  119. h, err := New(Config{DB: db})
  120. if err != nil {
  121. t.Fatalf("handler.New 失败: %v", err)
  122. }
  123. app := fiber.New(fiber.Config{DisableStartupMessage: true})
  124. app.Use(func(c *fiber.Ctx) error {
  125. switch c.Get("X-Test-Scope") {
  126. case "none":
  127. // 不写作用域 → 未登录语义
  128. case "super":
  129. appscope.Set(c, testSuperScope())
  130. default:
  131. appscope.Set(c, testScope())
  132. }
  133. return c.Next()
  134. })
  135. registerTestRoutes(app, h)
  136. return app
  137. }
  138. // registerTestRoutes 把 AC-12 的 18 条端点全部注册(**与设计 §4.1 逐条对应**)。
  139. //
  140. // 说明:这里**不**做角色白名单/RBAC(那是 AC-14);本函数只为"端点覆盖 + 请求往返"服务。
  141. func registerTestRoutes(app *fiber.App, h *Handler) {
  142. app.Get(PathFinanceAccounts, h.GetAccount)
  143. app.Get(PathFinanceRefundable, h.GetRefundable)
  144. app.Post(PathFinanceRecharges, h.CreateRecharge)
  145. app.Post(PathFinanceExpenditures, h.CreateExpenditure)
  146. app.Post(PathFinanceRefunds, h.CreateRefund)
  147. app.Post(PathFinanceRefundsCustom, h.CreateCustomRefund)
  148. app.Post(PathFinanceTransfers, h.CreateTransfer)
  149. app.Post(PathFinanceBadDebts, h.CreateBadDebt)
  150. app.Post(PathFinanceClearedBalances, h.ClearBalance)
  151. app.Post(PathFinanceSpends, h.AddSpend)
  152. app.Get(PathFinanceLogs, h.ListLogs)
  153. app.Get(PathFinanceRequests, h.ListRequests)
  154. app.Post(PathFinanceRequests, h.CreateRequest)
  155. app.Post(PathFinanceRequestApprove, h.ApproveRequest)
  156. app.Post(PathFinanceRequestReject, h.RejectRequest)
  157. app.Post(PathFinanceRequestCancel, h.CancelRequest)
  158. app.Get(PathFinanceDashboard, h.GetDashboard)
  159. app.Get(PathStudentBill, h.GetBill)
  160. }
  161. // doJSON 发一个 JSON 请求并解出信封(HTTP 恒 200,失败即测试失败)。
  162. //
  163. // 入参:method / path / body(nil = 无 body)/ headers(k,v 交替)。
  164. // 出参:code / message / data(原始 JSON)。
  165. func doJSON(t *testing.T, app *fiber.App, method, path string, body any, headers ...string) (int, string, json.RawMessage) {
  166. t.Helper()
  167. var req *httptest.ResponseRecorder
  168. payload := ""
  169. if body != nil {
  170. raw, err := json.Marshal(body)
  171. if err != nil {
  172. t.Fatalf("序列化请求体失败: %v", err)
  173. }
  174. payload = string(raw)
  175. }
  176. httpReq := httptest.NewRequest(method, path, strings.NewReader(payload))
  177. httpReq.Header.Set("Content-Type", "application/json")
  178. for i := 0; i+1 < len(headers); i += 2 {
  179. httpReq.Header.Set(headers[i], headers[i+1])
  180. }
  181. resp, err := app.Test(httpReq, 5000)
  182. if err != nil {
  183. t.Fatalf("%s %s 请求失败: %v", method, path, err)
  184. }
  185. req = httptest.NewRecorder()
  186. _ = req
  187. defer func() { _ = resp.Body.Close() }()
  188. var envelope struct {
  189. Code int `json:"code"`
  190. Message string `json:"message"`
  191. Data json.RawMessage `json:"data"`
  192. Success bool `json:"success"`
  193. }
  194. if err := json.NewDecoder(resp.Body).Decode(&envelope); err != nil {
  195. t.Fatalf("%s %s 响应不是合法信封: %v", method, path, err)
  196. }
  197. return envelope.Code, envelope.Message, envelope.Data
  198. }
  199. // ---------------------------------------------------------------- ① 端点覆盖
  200. // TestRouteCoverage 端点 1~17、21 全覆盖(18 条),且**不含** 18/19/20(支付端点属 AC-13/AC-14)。
  201. func TestRouteCoverage(t *testing.T) {
  202. db := newHandlerTestDB(t)
  203. app := newTestApp(t, db)
  204. expected := []struct {
  205. method string
  206. path string
  207. name string
  208. }{
  209. {http.MethodGet, "/admin/finance/accounts/:userId", "端点1 账户快照"},
  210. {http.MethodGet, "/admin/finance/accounts/:userId/refundable", "端点2 可退金额"},
  211. {http.MethodPost, "/admin/finance/recharges", "端点3 充值"},
  212. {http.MethodPost, "/admin/finance/expenditures", "端点4 消费"},
  213. {http.MethodPost, "/admin/finance/refunds", "端点5 退费"},
  214. {http.MethodPost, "/admin/finance/refunds/custom", "端点6 自定义退费"},
  215. {http.MethodPost, "/admin/finance/transfers", "端点7 转结"},
  216. {http.MethodPost, "/admin/finance/bad-debts", "端点8 坏账"},
  217. {http.MethodPost, "/admin/finance/cleared-balances", "端点9 清零"},
  218. {http.MethodPost, "/admin/finance/spends", "端点10 累计消费"},
  219. {http.MethodGet, "/admin/finance/logs", "端点11 流水"},
  220. {http.MethodGet, "/admin/finance/requests", "端点12 工单列表"},
  221. {http.MethodPost, "/admin/finance/requests", "端点13 创建工单"},
  222. {http.MethodPost, "/admin/finance/requests/:id/approve", "端点14 通过"},
  223. {http.MethodPost, "/admin/finance/requests/:id/reject", "端点15 驳回"},
  224. {http.MethodPost, "/admin/finance/requests/:id/cancel", "端点16 撤销"},
  225. {http.MethodGet, "/student/bill", "端点17 账单"},
  226. {http.MethodGet, "/admin/finance/dashboard", "端点21 仪表盘"},
  227. }
  228. registered := map[string]bool{}
  229. for _, route := range app.GetRoutes() {
  230. registered[route.Method+" "+route.Path] = true
  231. }
  232. for _, want := range expected {
  233. if !registered[want.method+" "+want.path] {
  234. t.Errorf("%s 未注册(%s %s)", want.name, want.method, want.path)
  235. }
  236. }
  237. // 反向断言:不该出现的端点(18/19/20 属支付,归 AC-13;且**任何**路径都不得含 /api)
  238. for key := range registered {
  239. if strings.Contains(key, "/pay/") {
  240. t.Errorf("academic finance handler 不应注册支付端点:%s", key)
  241. }
  242. if strings.Contains(key, "/api/") {
  243. t.Errorf("后端路由不得含 /api 前缀(§4 口径表):%s", key)
  244. }
  245. }
  246. if len(expected) != 18 {
  247. t.Fatalf("覆盖清单应为 18 条,实得 %d", len(expected))
  248. }
  249. }
  250. // ---------------------------------------------------------------- ③ scope 取不到 → 1001
  251. // TestMissingScopeIs1001 无作用域(未登录/中间件未注入)→ 1001,且**必须先于**参数校验。
  252. func TestMissingScopeIs1001(t *testing.T) {
  253. db := newHandlerTestDB(t)
  254. app := newTestApp(t, db)
  255. cases := []struct {
  256. method string
  257. path string
  258. body any
  259. }{
  260. {http.MethodGet, "/admin/finance/accounts/01HUSER000000000000000900", nil},
  261. {http.MethodPost, "/admin/finance/recharges", map[string]any{}},
  262. {http.MethodGet, "/admin/finance/logs", nil},
  263. {http.MethodGet, "/student/bill", nil},
  264. {http.MethodGet, "/admin/finance/dashboard", nil},
  265. }
  266. for _, tc := range cases {
  267. code, _, _ := doJSON(t, app, tc.method, tc.path, tc.body, "X-Test-Scope", "none")
  268. if code != infraerrors.CodeUnauth {
  269. t.Errorf("%s %s:期望 1001,实得 %d", tc.method, tc.path, code)
  270. }
  271. }
  272. }
  273. // ---------------------------------------------------------------- ② 2001 与 2002 不串
  274. // TestValidationCodes validateReq 失败 → 2001;金额/枚举值非法 → 2002。
  275. func TestValidationCodes(t *testing.T) {
  276. db := newHandlerTestDB(t)
  277. app := newTestApp(t, db)
  278. // 缺参(userId/money/institutionId 全空)→ 2001
  279. code, _, _ := doJSON(t, app, http.MethodPost, "/admin/finance/recharges", map[string]any{})
  280. if code != infraerrors.CodeBadParam {
  281. t.Fatalf("缺参期望 2001,实得 %d", code)
  282. }
  283. // 金额字符串非法("abc")→ 2002
  284. code, _, _ = doJSON(t, app, http.MethodPost, "/admin/finance/recharges", map[string]any{
  285. "userId": "01HUSER000000000000000900", "institutionId": 1, "campusId": 10, "money": "abc",
  286. })
  287. if code != infraerrors.CodeBadFormat {
  288. t.Fatalf("金额非法期望 2002,实得 %d", code)
  289. }
  290. // 消费 type 不在白名单 → 2002
  291. code, _, _ = doJSON(t, app, http.MethodPost, "/admin/finance/expenditures", map[string]any{
  292. "userId": "01HUSER000000000000000900", "institutionId": 1, "campusId": 10,
  293. "money": "10.00", "type": 999,
  294. })
  295. if code != infraerrors.CodeBadFormat {
  296. t.Fatalf("消费 type 非白名单期望 2002,实得 %d", code)
  297. }
  298. // 工单 type 不在白名单 → 2002
  299. code, _, _ = doJSON(t, app, http.MethodPost, "/admin/finance/requests", map[string]any{
  300. "type": 999, "userId": "01HUSER000000000000000900", "institutionId": 1, "campusId": 10,
  301. "money": "10.00",
  302. })
  303. if code != infraerrors.CodeBadFormat {
  304. t.Fatalf("工单 type 非白名单期望 2002,实得 %d", code)
  305. }
  306. // 自定义退费缺 requestId(必填)→ 2001
  307. code, _, _ = doJSON(t, app, http.MethodPost, "/admin/finance/refunds/custom", map[string]any{
  308. "userId": "01HUSER000000000000000900", "institutionId": 1, "campusId": 10, "money": "10.00",
  309. })
  310. if code != infraerrors.CodeBadParam {
  311. t.Fatalf("缺 requestId 期望 2001,实得 %d", code)
  312. }
  313. // 账单缺 from/to → 2001(时间边界必填)
  314. code, _, _ = doJSON(t, app, http.MethodGet, "/student/bill", nil)
  315. if code != infraerrors.CodeBadParam {
  316. t.Fatalf("账单缺 from/to 期望 2001,实得 %d", code)
  317. }
  318. // 账单 campusIds 非法片段 → 2002(Service 解析失败)
  319. code, _, _ = doJSON(t, app, http.MethodGet,
  320. "/student/bill?userId=01HUSER000000000000000900&from=2026-03-01&to=2026-04-01&campusIds=1,a", nil)
  321. if code != infraerrors.CodeBadParam {
  322. t.Fatalf("账单 campusIds 非法期望 2001/(Service 侧 2001),实得 %d", code)
  323. }
  324. // 时间格式非法 → 2002
  325. code, _, _ = doJSON(t, app, http.MethodGet,
  326. "/student/bill?from=2026-13-99&to=2026-04-01", nil)
  327. if code != infraerrors.CodeBadFormat {
  328. t.Fatalf("时间格式非法期望 2002,实得 %d", code)
  329. }
  330. }
  331. // ---------------------------------------------------------------- ④ 金额必须是字符串
  332. // TestMoneyMustBeJSONString 金额传 JSON number → **2002(被拒)**,绝不被静默接受。
  333. //
  334. // 为什么是 2002 而不是 2001:`infra/validator.Validate` 对"body 能解析但字段类型不匹配"
  335. // 统一回 `CodeBadFormat`(2002)(见 validator.go 的 json.Unmarshal 分支)——本用例沿用该约定。
  336. //
  337. // 这是"拒绝 float64"的可判定形式:若把 DTO 的金额字段写成 `float64` 或 `money.Amount`,
  338. // number 会被成功解码 ⇒ 本用例拿到 200(钱被按浮点入账)⇒ 断言立刻红。
  339. func TestMoneyMustBeJSONString(t *testing.T) {
  340. db := newHandlerTestDB(t)
  341. app := newTestApp(t, db)
  342. raw := `{"userId":"01HUSER000000000000000900","institutionId":1,"campusId":10,"money":100}`
  343. httpReq := httptest.NewRequest(http.MethodPost, "/admin/finance/recharges", strings.NewReader(raw))
  344. httpReq.Header.Set("Content-Type", "application/json")
  345. resp, err := app.Test(httpReq, 5000)
  346. if err != nil {
  347. t.Fatalf("请求失败: %v", err)
  348. }
  349. defer func() { _ = resp.Body.Close() }()
  350. var envelope struct {
  351. Code int `json:"code"`
  352. }
  353. if err := json.NewDecoder(resp.Body).Decode(&envelope); err != nil {
  354. t.Fatalf("响应解码失败: %v", err)
  355. }
  356. if envelope.Code != infraerrors.CodeBadFormat {
  357. t.Fatalf("金额传 number 期望 2002(类型不匹配被拒),实得 %d", envelope.Code)
  358. }
  359. }
  360. // ---------------------------------------------------------------- ⑤ 分页钳制
  361. // TestPageSizeClamp pageSize>200 → 200(唯一实现点 = response.ParsePage)。
  362. func TestPageSizeClamp(t *testing.T) {
  363. db := newHandlerTestDB(t)
  364. app := newTestApp(t, db)
  365. code, _, data := doJSON(t, app, http.MethodGet,
  366. "/admin/finance/logs?userId=01HUSER000000000000000900&pageSize=500&page=1", nil)
  367. if code != 200 {
  368. t.Fatalf("流水列表期望 200,实得 %d", code)
  369. }
  370. var page struct {
  371. PageSize int `json:"pageSize"`
  372. Page int `json:"page"`
  373. Total int64 `json:"total"`
  374. List []any `json:"list"`
  375. }
  376. if err := json.Unmarshal(data, &page); err != nil {
  377. t.Fatalf("分页体解码失败: %v", err)
  378. }
  379. if page.PageSize != 200 {
  380. t.Fatalf("pageSize 应钳制为 200,实得 %d", page.PageSize)
  381. }
  382. if page.List == nil {
  383. t.Fatal("空列表必须是 [],不能是 null")
  384. }
  385. // 缺省值:不传分页 → (1,10)
  386. _, _, data = doJSON(t, app, http.MethodGet, "/admin/finance/logs?userId=01HUSER000000000000000900", nil)
  387. if err := json.Unmarshal(data, &page); err != nil {
  388. t.Fatalf("分页体解码失败: %v", err)
  389. }
  390. if page.Page != 1 || page.PageSize != 10 {
  391. t.Fatalf("缺省分页应为 (1,10),实得 (%d,%d)", page.Page, page.PageSize)
  392. }
  393. }
  394. // ---------------------------------------------------------------- ⑥ 脱敏
  395. // TestNoSensitiveFields 响应体不出现 `imgs` / `payReturnData` / `returnData`(AC-12 验收 ⑥)。
  396. func TestNoSensitiveFields(t *testing.T) {
  397. db := newHandlerTestDB(t)
  398. app := newTestApp(t, db)
  399. user := "01HUSER000000000000000901"
  400. // 造一张带凭证图片的工单,确认列表**不回显** imgs
  401. if err := db.Create(&model.UserBalanceRequest{
  402. BizNo: "BIZSENSITIVE00000000000000001", Type: model.BalanceRequestTypeRecharge,
  403. UserID: user, InstitutionID: 1, CampusID: 10, Money: "100.00",
  404. Imgs: strPtr(`[{"url":"https://sensitive/private.png"}]`),
  405. }).Error; err != nil {
  406. t.Fatalf("seed 工单失败: %v", err)
  407. }
  408. httpReq := httptest.NewRequest(http.MethodGet, "/admin/finance/requests?pageSize=10", nil)
  409. resp, err := app.Test(httpReq, 5000)
  410. if err != nil {
  411. t.Fatalf("请求失败: %v", err)
  412. }
  413. defer func() { _ = resp.Body.Close() }()
  414. rawBody, rErr := io.ReadAll(resp.Body)
  415. if rErr != nil {
  416. t.Fatalf("读响应失败: %v", rErr)
  417. }
  418. text := string(rawBody)
  419. for _, banned := range []string{"imgs", "private.png", "payReturnData", "pay_return_data", "returnData"} {
  420. if strings.Contains(text, banned) {
  421. t.Fatalf("响应体含敏感字段 %q:%s", banned, text)
  422. }
  423. }
  424. if !strings.Contains(text, user) {
  425. t.Fatalf("响应体应含被查工单(脱敏断言不能靠「空响应」通过):%s", text)
  426. }
  427. }
  428. // ---------------------------------------------------------------- 业务冒烟
  429. // TestRechargeThenAccountSnapshot 端点 3 → 端点 1:充值后账户快照余额同步(跨端点一致性)。
  430. func TestRechargeThenAccountSnapshot(t *testing.T) {
  431. db := newHandlerTestDB(t)
  432. app := newTestApp(t, db)
  433. user := "01HUSER000000000000000910"
  434. code, msg, data := doJSON(t, app, http.MethodPost, "/admin/finance/recharges", map[string]any{
  435. "userId": user, "institutionId": 1, "campusId": 10, "money": "250.50",
  436. "requestId": "REQ-HANDLER-1",
  437. })
  438. if code != 200 {
  439. t.Fatalf("充值期望 200,实得 %d(%s)", code, msg)
  440. }
  441. var recharge struct {
  442. LogID int64 `json:"logId"`
  443. Balance string `json:"balance"`
  444. Repeated bool `json:"repeated"`
  445. }
  446. if err := json.Unmarshal(data, &recharge); err != nil {
  447. t.Fatalf("充值体解码失败: %v", err)
  448. }
  449. if recharge.LogID <= 0 || recharge.Balance != "250.50" || recharge.Repeated {
  450. t.Fatalf("充值结果异常:%+v", recharge)
  451. }
  452. // 幂等重放(同一 requestId)→ repeated=true 且余额不变
  453. code, _, data = doJSON(t, app, http.MethodPost, "/admin/finance/recharges", map[string]any{
  454. "userId": user, "institutionId": 1, "campusId": 10, "money": "250.50",
  455. "requestId": "REQ-HANDLER-1",
  456. })
  457. if code != 200 {
  458. t.Fatalf("幂等重放期望 200,实得 %d", code)
  459. }
  460. if err := json.Unmarshal(data, &recharge); err != nil {
  461. t.Fatalf("充值体解码失败: %v", err)
  462. }
  463. if !recharge.Repeated || recharge.Balance != "250.50" {
  464. t.Fatalf("幂等重放应 repeated=true 且余额不变:%+v", recharge)
  465. }
  466. // 端点 1:账户快照应反映 250.50
  467. code, _, data = doJSON(t, app, http.MethodGet,
  468. "/admin/finance/accounts/"+user+"?institutionId=1&campusId=10", nil)
  469. if code != 200 {
  470. t.Fatalf("账户快照期望 200,实得 %d", code)
  471. }
  472. // 端点 1 形状 = **扁平**(契约 v1.5):totalBalance/campusBalance/specialExpenses/cumulativeIncome
  473. // + 入参回显 institutionId/campusId;**不得**出现 global/campus 嵌套键。
  474. var snapshot struct {
  475. UserID string `json:"userId"`
  476. InstitutionID int64 `json:"institutionId"`
  477. CampusID int64 `json:"campusId"`
  478. TotalBalance string `json:"totalBalance"`
  479. CampusBalance string `json:"campusBalance"`
  480. SpecialExpenses string `json:"specialExpenses"`
  481. CumulativeIncome string `json:"cumulativeIncome"`
  482. }
  483. if err := json.Unmarshal(data, &snapshot); err != nil {
  484. t.Fatalf("快照解码失败: %v", err)
  485. }
  486. if snapshot.TotalBalance != "250.50" || snapshot.CumulativeIncome != "250.50" {
  487. t.Fatalf("全局快照异常:totalBalance=%s cumulativeIncome=%s,期望均为 250.50",
  488. snapshot.TotalBalance, snapshot.CumulativeIncome)
  489. }
  490. if snapshot.CampusBalance != "250.50" {
  491. t.Fatalf("campusBalance = %s,期望 250.50(← t_user_expense_school.balance)", snapshot.CampusBalance)
  492. }
  493. if snapshot.InstitutionID != 1 || snapshot.CampusID != 10 {
  494. t.Fatalf("institutionId/campusId = %d/%d,期望入参回显 1/10", snapshot.InstitutionID, snapshot.CampusID)
  495. }
  496. // 契约 v1.5:扁平形状,**不得**再出现 global/campus 嵌套键(用原始 JSON 断言,结构体无此字段时断言恒真)
  497. rawSnap, rErr := json.Marshal(snapshot)
  498. if rErr == nil {
  499. _ = rawSnap
  500. }
  501. }
  502. // TestRequestApproveTouchesFunds 端点 13 → 14:审批通过才动钱;二次审批 → 3002。
  503. func TestRequestApproveTouchesFunds(t *testing.T) {
  504. db := newHandlerTestDB(t)
  505. app := newTestApp(t, db)
  506. user := "01HUSER000000000000000920"
  507. // 13 创建充值工单
  508. code, msg, data := doJSON(t, app, http.MethodPost, "/admin/finance/requests", map[string]any{
  509. "type": 100, "userId": user, "institutionId": 1, "campusId": 10,
  510. "money": "88.00", "item": "春季学费",
  511. })
  512. if code != 200 {
  513. t.Fatalf("创建工单期望 200,实得 %d(%s)", code, msg)
  514. }
  515. var created struct {
  516. ID int64 `json:"id"`
  517. BizNo string `json:"bizNo"`
  518. }
  519. if err := json.Unmarshal(data, &created); err != nil {
  520. t.Fatalf("工单体解码失败: %v", err)
  521. }
  522. if created.ID <= 0 || len(created.BizNo) != 32 {
  523. t.Fatalf("工单结果异常:%+v", created)
  524. }
  525. // 审批前:余额 0(账户不存在 → 快照 0)
  526. code, _, data = doJSON(t, app, http.MethodGet, "/admin/finance/accounts/"+user, nil)
  527. if code != 200 {
  528. t.Fatalf("快照期望 200,实得 %d", code)
  529. }
  530. var before struct {
  531. TotalBalance string `json:"totalBalance"`
  532. }
  533. if err := json.Unmarshal(data, &before); err != nil {
  534. t.Fatalf("快照解码失败: %v", err)
  535. }
  536. if before.TotalBalance != "0.00" {
  537. t.Fatalf("审批前 totalBalance 应为 0.00,实得 %s(说明创建工单就已经动了钱——违反审批链)",
  538. before.TotalBalance)
  539. }
  540. // 14 审批通过
  541. code, msg, data = doJSON(t, app, http.MethodPost,
  542. fmt.Sprintf("/admin/finance/requests/%d/approve", created.ID), map[string]any{"responseMsg": "ok"})
  543. if code != 200 {
  544. t.Fatalf("审批通过期望 200,实得 %d(%s)", code, msg)
  545. }
  546. var approved struct {
  547. Approved int8 `json:"approved"`
  548. BizNo string `json:"bizNo"`
  549. Result struct {
  550. LogID int64 `json:"logId"`
  551. Balance string `json:"balance"`
  552. } `json:"result"`
  553. }
  554. if err := json.Unmarshal(data, &approved); err != nil {
  555. t.Fatalf("审批体解码失败: %v", err)
  556. }
  557. if approved.Approved != 1 || approved.BizNo != created.BizNo || approved.Result.LogID <= 0 {
  558. t.Fatalf("审批结果异常:%+v", approved)
  559. }
  560. if approved.Result.Balance != "88.00" {
  561. t.Fatalf("审批入账后校区余额应为 88.00,实得 %s", approved.Result.Balance)
  562. }
  563. // 二次审批 → 3002(不得重复入账)
  564. code, _, _ = doJSON(t, app, http.MethodPost,
  565. fmt.Sprintf("/admin/finance/requests/%d/approve", created.ID), map[string]any{})
  566. if code != infraerrors.CodeConflict {
  567. t.Fatalf("二次审批期望 3002,实得 %d", code)
  568. }
  569. // 落库只能有一条 100 流水(重复入账会变两条)
  570. var logs []model.UserExpenseLog
  571. if err := db.Where("user_id = ? AND type = ?", user, model.ExpenseLogTypeRecharge).Find(&logs).Error; err != nil {
  572. t.Fatalf("读流水失败: %v", err)
  573. }
  574. if len(logs) != 1 {
  575. t.Fatalf("充值流水应为 1 条,实得 %d 条(二次审批重复入账)", len(logs))
  576. }
  577. if logs[0].RequestID == nil || *logs[0].RequestID != created.BizNo {
  578. t.Fatalf("流水 request_id 应等于工单 bizNo(幂等锚点),实得 %v", logs[0].RequestID)
  579. }
  580. }
  581. // TestBillEndpointIdentity 端点 17:账单恒等式 + **契约 v1.3 两个对账字段名** + 分页元信息。
  582. //
  583. // 契约口径(前端契约 v1.3 端点 17 注 ①,**字段名由契约定、后端照做**):
  584. // - `flowExclusiveEnd`:与「期末 − 期初」**对齐**的当期发生额(右开口径,不含 `to` 当天);
  585. // - `flowInclusiveEnd`:**含 `to` 当天**的当期发生额(dump 的 `BETWEEN` 口径)。
  586. // 二者之差 = 落在 `to` 当天的流水金额。
  587. //
  588. // 为什么两个都要下发(不能只留一个):只留一个就没法让前端**看见**不对称,
  589. // 而契约 v1.2 那句"期末余额与当期发生额都按 `< to`"的错句,根因正是"看不见"。
  590. //
  591. // 本用例因此**刻意造一笔落在 `to` 当天的流水**(300.00),断言:
  592. // 1. 期末不含它(700.00)、`flowExclusiveEnd` 不含它(200.00);
  593. // 2. `flowInclusiveEnd` 含它(500.00);
  594. // 3. 二者之差 **恰好等于** 该笔金额(300.00)—— 也就是契约说的"落在 to 当天的流水"。
  595. //
  596. // 顺带守字段名:若有人把 service.BillSummary 的 json tag 改名,本用例立刻红
  597. // (`flowExclusiveEnd` 解出来是零值 ⇒ 差值断言必失败)。
  598. func TestBillEndpointIdentity(t *testing.T) {
  599. db := newHandlerTestDB(t)
  600. app := newTestApp(t, db)
  601. user := "01HUSER000000000000000930"
  602. seedLog := func(amount string, at time.Time) {
  603. if err := db.Create(&model.UserExpenseLog{
  604. UserID: user, Type: model.ExpenseLogTypeRecharge, Money: amount, CreateTime: at,
  605. }).Error; err != nil {
  606. t.Fatalf("seed 流水失败: %v", err)
  607. }
  608. }
  609. seedLog("500.00", time.Date(2026, 2, 20, 10, 0, 0, 0, time.UTC)) // 期初
  610. seedLog("200.00", time.Date(2026, 3, 5, 10, 0, 0, 0, time.UTC)) // 窗口内
  611. seedLog("300.00", time.Date(2026, 4, 1, 0, 0, 0, 0, time.UTC)) // **恰好落在 to 当天**
  612. code, msg, data := doJSON(t, app, http.MethodGet,
  613. "/student/bill?userId="+user+"&from=2026-03-01&to=2026-04-01", nil)
  614. if code != 200 {
  615. t.Fatalf("账单期望 200,实得 %d(%s)", code, msg)
  616. }
  617. var bill struct {
  618. Summary struct {
  619. PrevBalance string `json:"prevBalance"`
  620. EndBalance string `json:"endBalance"`
  621. FlowExclusiveEnd string `json:"flowExclusiveEnd"`
  622. FlowInclusiveEnd string `json:"flowInclusiveEnd"`
  623. CampusIDs []int64 `json:"campusIds"`
  624. } `json:"summary"`
  625. // 明细数组键名 = **details**(契约 v1.4 rev.2:以结构体 json tag 为准,平铺不嵌套)
  626. Details []map[string]any `json:"details"`
  627. Total int64 `json:"total"`
  628. Page int `json:"page"`
  629. PageSize int `json:"pageSize"`
  630. Pages int `json:"pages"`
  631. }
  632. if err := json.Unmarshal(data, &bill); err != nil {
  633. t.Fatalf("账单体解码失败: %v", err)
  634. }
  635. if bill.Summary.PrevBalance != "500.00" || bill.Summary.EndBalance != "700.00" {
  636. t.Fatalf("期初/期末异常(期末必须**不含** to 当天那笔 300.00):%+v", bill.Summary)
  637. }
  638. // 恒等式:期末 − 期初 == flowExclusiveEnd(右开口径)
  639. prev, _ := money.Parse(bill.Summary.PrevBalance)
  640. end, _ := money.Parse(bill.Summary.EndBalance)
  641. exclusive, _ := money.Parse(bill.Summary.FlowExclusiveEnd)
  642. inclusive, _ := money.Parse(bill.Summary.FlowInclusiveEnd)
  643. if end.Sub(prev) != exclusive {
  644. t.Fatalf("恒等式破:期末−期初=%s,flowExclusiveEnd=%s", end.Sub(prev).String(), exclusive.String())
  645. }
  646. // 契约 v1.3:两口径差值 == 落在 to 当天的流水
  647. if got, want := inclusive.Sub(exclusive), int64Money(t, "300.00"); got != want {
  648. t.Fatalf("flowInclusiveEnd−flowExclusiveEnd = %s,期望 %s(= 落在 to 当天的流水)",
  649. got.String(), want.String())
  650. }
  651. if got, want := inclusive.String(), "500.00"; got != want {
  652. t.Fatalf("flowInclusiveEnd = %s,期望 %s(含 to 当天那笔)", got, want)
  653. }
  654. // v1.4 起明细按窗口过滤(右开):3 笔历史流水里只有 03-05 那笔在窗口内
  655. // (02-20 在窗口前、04-01 恰在 `to` 右端点)→ total=1、pages=1(ceil(1/10))。
  656. if bill.Total != 1 || bill.PageSize != 10 || bill.Pages != 1 || bill.Details == nil {
  657. t.Fatalf("分页元信息异常:total=%d pageSize=%d pages=%d details=%v(明细应受窗口约束)",
  658. bill.Total, bill.PageSize, bill.Pages, bill.Details)
  659. }
  660. if len(bill.Details) != 1 {
  661. t.Fatalf("窗口内明细应为 1 条,实得 %d 条", len(bill.Details))
  662. }
  663. // Total 必须**不等于**历史总数(3 笔)——只改 PageLogs 不改 CountLogs 的实现会在这里露馅
  664. if bill.Total == 3 {
  665. t.Fatal("Total = 历史总数 3:说明 CountLogs 没跟 PageLogs 用同一个窗口条件(改一半)")
  666. }
  667. if bill.Summary.CampusIDs == nil {
  668. t.Fatal("campusIds 回显必须是 [](空时也不能是 null)")
  669. }
  670. }
  671. // int64Money 金额字面量解析(测试内断言用;解析失败直接 fail)。
  672. func int64Money(t *testing.T, s string) money.Amount {
  673. t.Helper()
  674. amount, err := money.Parse(s)
  675. if err != nil {
  676. t.Fatalf("金额解析失败 %q: %v", s, err)
  677. }
  678. return amount
  679. }
  680. // TestDashboardEndpoint 端点 21:聚合校区账户累计列 + 明确告知"不支持按校区拆流水"。
  681. func TestDashboardEndpoint(t *testing.T) {
  682. db := newHandlerTestDB(t)
  683. app := newTestApp(t, db)
  684. if err := db.Create(&model.UserExpenseSchool{
  685. UserID: "01HUSER000000000000000940", InstitutionID: 1, CampusID: 10,
  686. Balance: "100.00", TotalIncome: "300.00", TotalExpenditure: "200.00",
  687. }).Error; err != nil {
  688. t.Fatalf("seed 校区账户失败: %v", err)
  689. }
  690. code, msg, data := doJSON(t, app, http.MethodGet,
  691. "/admin/finance/dashboard?from=2026-03-01&to=2026-04-01", nil)
  692. if code != 200 {
  693. t.Fatalf("仪表盘期望 200,实得 %d(%s)", code, msg)
  694. }
  695. var dash struct {
  696. Accounts int64 `json:"accounts"`
  697. Balance string `json:"balance"`
  698. TotalIncome string `json:"totalIncome"`
  699. TotalExpenditure string `json:"totalExpenditure"`
  700. NetReceivable string `json:"netReceivable"`
  701. FlowsByCampusSupported bool `json:"flowsByCampusSupported"`
  702. }
  703. if err := json.Unmarshal(data, &dash); err != nil {
  704. t.Fatalf("仪表盘体解码失败: %v", err)
  705. }
  706. if dash.Accounts != 1 || dash.Balance != "100.00" || dash.TotalIncome != "300.00" ||
  707. dash.TotalExpenditure != "200.00" || dash.NetReceivable != "100.00" {
  708. t.Fatalf("仪表盘聚合异常:%+v", dash)
  709. }
  710. if dash.FlowsByCampusSupported {
  711. t.Fatal("flowsByCampusSupported 必须为 false(流水表无 campus 列,不能按校区拆期间发生额)")
  712. }
  713. }
  714. // TestCrossInstitutionIsRejected 跨机构:作用域机构 1 查机构 2 的工单 → 3001(仓储 Scoped 过滤后不可见)。
  715. func TestCrossInstitutionIsRejected(t *testing.T) {
  716. db := newHandlerTestDB(t)
  717. app := newTestApp(t, db)
  718. if err := db.Create(&model.UserBalanceRequest{
  719. BizNo: "BIZOTHERINST0000000000000001", Type: model.BalanceRequestTypeRecharge,
  720. UserID: "01HUSER000000000000000950", InstitutionID: 2, CampusID: 20, Money: "10.00",
  721. }).Error; err != nil {
  722. t.Fatalf("seed 跨机构工单失败: %v", err)
  723. }
  724. code, _, _ := doJSON(t, app, http.MethodPost, "/admin/finance/requests/1/approve", map[string]any{})
  725. if code != infraerrors.CodeNotFound {
  726. t.Fatalf("跨机构审批期望 3001,实得 %d", code)
  727. }
  728. // 列表也看不到别机构工单
  729. code, _, data := doJSON(t, app, http.MethodGet, "/admin/finance/requests?pageSize=10", nil)
  730. if code != 200 {
  731. t.Fatalf("工单列表期望 200,实得 %d", code)
  732. }
  733. var page struct {
  734. Total int64 `json:"total"`
  735. }
  736. if err := json.Unmarshal(data, &page); err != nil {
  737. t.Fatalf("列表体解码失败: %v", err)
  738. }
  739. if page.Total != 0 {
  740. t.Fatalf("普通财务不应看到别机构工单,实得 total=%d", page.Total)
  741. }
  742. }
  743. // ---------------------------------------------------------------- 小工具
  744. // strPtr 字符串指针构造(可空列 seed 用)。
  745. func strPtr(s string) *string { return &s }
  746. // TestRequestsUseBizTimeNotCreatedAt 端点 12:**时间字段必须是业务时间,不得下发 `created_at`**
  747. // (契约 v1.5 裁决;`created_at` 是迁移期新加的入库列,值恒为"迁移执行那一刻")。
  748. //
  749. // 这是"**有值、格式合法、语义全错**"的典型:单测若只断言"是合法 RFC3339"会全绿,
  750. // D7 双跑也抓不到(旧库根本没这个列,无从比对)。所以按 §5.1 纪律 4 做**横切断言**:
  751. //
  752. // ① 响应 `requestTime` == 库里的 `request_time`(2020-01-01)
  753. // ② `requestTime` ≠ 该行的 `created_at`(迁移/建行时间,今天)
  754. // ③ 原始 JSON 里**不存在** `createdAt` / `createTime` 键
  755. //
  756. // ③ 必须断言原始 JSON 片段:结构体没有该字段时,结构体断言恒真 = 等于没测。
  757. func TestRequestsUseBizTimeNotCreatedAt(t *testing.T) {
  758. db := newHandlerTestDB(t)
  759. app := newTestApp(t, db)
  760. user := "01HUSER000000000000000960"
  761. // request_time 明显早于建行时间(created_at 由 DB 默认填"现在")
  762. bizTime := time.Date(2020, 1, 1, 8, 0, 0, 0, time.UTC)
  763. if err := db.Create(&model.UserBalanceRequest{
  764. BizNo: "BIZTIME0000000000000000001", Type: model.BalanceRequestTypeRecharge,
  765. UserID: user, InstitutionID: 1, CampusID: 10, Money: "10.00",
  766. RequestTime: &bizTime,
  767. }).Error; err != nil {
  768. t.Fatalf("seed 工单失败: %v", err)
  769. }
  770. var stored model.UserBalanceRequest
  771. if err := db.Where("biz_no = ?", "BIZTIME0000000000000000001").Take(&stored).Error; err != nil {
  772. t.Fatalf("回读工单失败: %v", err)
  773. }
  774. if stored.RequestTime == nil || stored.CreatedAt.Equal(*stored.RequestTime) {
  775. t.Fatalf("前置造数失败:request_time(%v) 与 created_at(%v) 必须不同",
  776. stored.RequestTime, stored.CreatedAt)
  777. }
  778. req := httptest.NewRequest(http.MethodGet, "/admin/finance/requests?pageSize=10", nil)
  779. resp, err := app.Test(req, 5000)
  780. if err != nil {
  781. t.Fatalf("请求失败: %v", err)
  782. }
  783. defer func() { _ = resp.Body.Close() }()
  784. rawBody, rErr := io.ReadAll(resp.Body)
  785. if rErr != nil {
  786. t.Fatalf("读响应失败: %v", rErr)
  787. }
  788. text := string(rawBody)
  789. // ③ 原始 JSON 不得出现 createdAt / createTime 键
  790. for _, banned := range []string{`"createdAt"`, `"createTime"`} {
  791. if strings.Contains(text, banned) {
  792. t.Fatalf("响应含非业务时间键 %s —— `created_at` 是迁移期入库时间,"+
  793. "下发会让全部历史工单显示成迁移日:%s", banned, text)
  794. }
  795. }
  796. // ①② 解出 requestTime / responseTime(分页体在 data 内)
  797. var envelope struct {
  798. Data struct {
  799. List []struct {
  800. RequestTime *time.Time `json:"requestTime"`
  801. ResponseTime *time.Time `json:"responseTime"`
  802. } `json:"list"`
  803. } `json:"data"`
  804. }
  805. if uErr := json.Unmarshal(rawBody, &envelope); uErr != nil {
  806. t.Fatalf("解码失败: %v", uErr)
  807. }
  808. page := envelope.Data
  809. if len(page.List) != 1 || page.List[0].RequestTime == nil {
  810. t.Fatalf("应返回 1 条工单且带 requestTime,实得 %d 条", len(page.List))
  811. }
  812. if !page.List[0].RequestTime.Equal(bizTime) {
  813. t.Fatalf("requestTime = %v,期望 %v(← request_time 业务时间)",
  814. page.List[0].RequestTime, bizTime)
  815. }
  816. if page.List[0].RequestTime.Equal(stored.CreatedAt) {
  817. t.Fatalf("requestTime == created_at(%v)—— 下发的是迁移/建行时间,不是业务时间", stored.CreatedAt)
  818. }
  819. // 未审批 → responseTime 为 null
  820. if page.List[0].ResponseTime != nil {
  821. t.Fatalf("未审批工单 responseTime 应为 null,实得 %v", page.List[0].ResponseTime)
  822. }
  823. }
  824. // TestDashboardBalanceDistribution 端点 21:`balanceDistribution` 必须按校区给出余额
  825. // (契约 v1.5 的**唯一可算项**——`t_user_expense_school` 有 campus_id,而流水表没有)。
  826. func TestDashboardBalanceDistribution(t *testing.T) {
  827. db := newHandlerTestDB(t)
  828. app := newTestApp(t, db)
  829. for _, row := range []model.UserExpenseSchool{
  830. {UserID: "01HUSER000000000000000970", InstitutionID: 1, CampusID: 10,
  831. Balance: "100.00", TotalIncome: "0.00"},
  832. {UserID: "01HUSER000000000000000971", InstitutionID: 1, CampusID: 20,
  833. Balance: "250.00", TotalIncome: "0.00"},
  834. } {
  835. if err := db.Create(&row).Error; err != nil {
  836. t.Fatalf("seed 校区账户失败: %v", err)
  837. }
  838. }
  839. code, msg, data := doJSON(t, app, http.MethodGet,
  840. "/admin/finance/dashboard?from=2026-03-01&to=2026-04-01", nil)
  841. if code != 200 {
  842. t.Fatalf("仪表盘期望 200,实得 %d(%s)", code, msg)
  843. }
  844. var dash struct {
  845. Balance string `json:"balance"`
  846. BalanceDistribution []struct {
  847. CampusID int64 `json:"campusId"`
  848. Balance string `json:"balance"`
  849. } `json:"balanceDistribution"`
  850. FlowsByCampusSupported bool `json:"flowsByCampusSupported"`
  851. }
  852. if err := json.Unmarshal(data, &dash); err != nil {
  853. t.Fatalf("解码失败: %v", err)
  854. }
  855. if len(dash.BalanceDistribution) != 2 {
  856. t.Fatalf("balanceDistribution 应有 2 个校区,实得 %d", len(dash.BalanceDistribution))
  857. }
  858. if dash.BalanceDistribution[0].CampusID != 10 || dash.BalanceDistribution[0].Balance != "100.00" ||
  859. dash.BalanceDistribution[1].CampusID != 20 || dash.BalanceDistribution[1].Balance != "250.00" {
  860. t.Fatalf("分布异常(应按 campusId 升序、金额为字符串):%+v", dash.BalanceDistribution)
  861. }
  862. if dash.Balance != "350.00" {
  863. t.Fatalf("balance 合计 = %s,期望 350.00", dash.Balance)
  864. }
  865. if dash.FlowsByCampusSupported {
  866. t.Fatal("flowsByCampusSupported 必须为 false(流水表无 campus 列,契约 v1.5 已删 periodIncome/periodExpense/net)")
  867. }
  868. }