fund_handler_test.go 37 KB

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