e2e_edge_cases_test.go 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087
  1. package testutil
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "testing"
  7. "time"
  8. "wails-app/internal/dao"
  9. "wails-app/internal/global"
  10. "wails-app/internal/model/common/response"
  11. dt_svc "wails-app/internal/modules/digital-ticket/service"
  12. )
  13. // TestVehicleReEntry 同一车辆重复入场应被拦截
  14. func TestVehicleReEntry(t *testing.T) {
  15. env := InitTestEnv(t)
  16. createVehicle(t, env, "JingR00001", "RFID_REENTRY", 1)
  17. entryResp, entryBody := env.DoPost("/vehicle/entry", map[string]interface{}{
  18. "plate_number": "JingR00001", "rfid_tag": "RFID_REENTRY",
  19. "parking_lot_id": 1, "parking_space_id": 1, "entry_image": "test.jpg",
  20. })
  21. AssertResponse(t, entryResp, entryBody, http.StatusOK, response.SUCCESS)
  22. _, entryBody2 := env.DoPost("/vehicle/entry", map[string]interface{}{
  23. "plate_number": "JingR00001", "rfid_tag": "RFID_REENTRY",
  24. "parking_lot_id": 1, "parking_space_id": 2, "entry_image": "test2.jpg",
  25. })
  26. var result struct { Code int `json:"code"`; Msg string `json:"msg"` }
  27. json.Unmarshal(entryBody2, &result)
  28. if result.Code == response.SUCCESS {
  29. t.Fatalf("BUG: Vehicle re-entry was NOT blocked! code=%d msg=%s", result.Code, result.Msg)
  30. }
  31. fmt.Println("PASS: Re-entry attempt correctly rejected")
  32. }
  33. // TestExitWithoutEntry 未入场车辆尝试出场应返回错误
  34. func TestExitWithoutEntry(t *testing.T) {
  35. env := InitTestEnv(t)
  36. _, exitPreviewBody := env.DoPost("/vehicle/exit/preview", map[string]interface{}{
  37. "plate_number": "JingZ99999", "rfid_tag": "RFID_NOENTRY",
  38. })
  39. var result struct { Code int `json:"code"`; Msg string `json:"msg"` }
  40. json.Unmarshal(exitPreviewBody, &result)
  41. if result.Code == response.SUCCESS {
  42. t.Fatalf("BUG: Exit preview succeeded for non-entered vehicle!")
  43. }
  44. fmt.Println("PASS: Exit without entry correctly rejected")
  45. }
  46. // TestPaymentInsufficientAmount 支付金额不足时的行为
  47. func TestPaymentInsufficientAmount(t *testing.T) {
  48. env := InitTestEnv(t)
  49. createVehicle(t, env, "JingP00001", "RFID_PAY", 1)
  50. _, _ = env.DoPost("/vehicle/entry", map[string]interface{}{
  51. "plate_number": "JingP00001", "rfid_tag": "RFID_PAY",
  52. "parking_lot_id": 1, "parking_space_id": 1, "entry_image": "test.jpg",
  53. })
  54. entryTime := time.Now().Add(-3 * time.Hour)
  55. global.GVA_DB.Model(&dao.VehicleRecord{}).Where("plate_number = ?", "JingP00001").Update("entry_time", entryTime)
  56. _, exitConfirmBody := env.DoPost("/vehicle/exit/confirm", map[string]interface{}{
  57. "plate_number": "JingP00001", "rfid_tag": "RFID_PAY",
  58. "payment_method": "cash", "paid_amount": 0.0,
  59. })
  60. var result struct { Code int `json:"code"`; Msg string `json:"msg"` }
  61. json.Unmarshal(exitConfirmBody, &result)
  62. fmt.Printf("INFO: Insufficient payment response: code=%d msg=%s\n", result.Code, result.Msg)
  63. }
  64. // TestVIPExpired 过期 VIP 应恢复普通计费
  65. func TestVIPExpired(t *testing.T) {
  66. env := InitTestEnv(t)
  67. ownerResp, ownerBody := env.DoPost("/owner/create", map[string]interface{}{
  68. "owner_name": "VIP Expired Test", "owner_surname": "VIP",
  69. "owner_phone": "13900000001", "is_vip": true,
  70. "vip_expire_time": time.Now().Add(-24*time.Hour).Format(time.RFC3339),
  71. })
  72. AssertResponse(t, ownerResp, ownerBody, http.StatusOK, response.SUCCESS)
  73. var owner dao.Owner
  74. env.DB.Where("owner_phone = ?", "13900000001").First(&owner)
  75. createVehicleWithOwner(t, env, "JingV00001", "RFID_VIP_EXP", owner.ID)
  76. _, _ = env.DoPost("/vehicle/entry", map[string]interface{}{
  77. "plate_number": "JingV00001", "rfid_tag": "RFID_VIP_EXP",
  78. "parking_lot_id": 1, "parking_space_id": 1, "entry_image": "test.jpg",
  79. })
  80. entryTime := time.Now().Add(-3 * time.Hour)
  81. global.GVA_DB.Model(&dao.VehicleRecord{}).Where("plate_number = ?", "JingV00001").Update("entry_time", entryTime)
  82. exitResp, exitBody := env.DoPost("/vehicle/exit/preview", map[string]interface{}{
  83. "plate_number": "JingV00001", "rfid_tag": "RFID_VIP_EXP",
  84. })
  85. AssertResponse(t, exitResp, exitBody, http.StatusOK, response.SUCCESS)
  86. var result struct {
  87. Data struct {
  88. Fee float64 `json:"fee"`
  89. } `json:"data"`
  90. }
  91. json.Unmarshal(exitBody, &result)
  92. if result.Data.Fee == 0 {
  93. t.Fatalf("BUG: Expired VIP still getting free parking! Fee should be > 0")
  94. }
  95. fmt.Printf("PASS: Expired VIP charged correctly, fee=%.2f\n", result.Data.Fee)
  96. }
  97. // TestFreeDuration 免费时长内不应收费
  98. func TestFreeDuration(t *testing.T) {
  99. env := InitTestEnv(t)
  100. createVehicle(t, env, "JingF00001", "RFID_FREE", 1)
  101. _, _ = env.DoPost("/vehicle/entry", map[string]interface{}{
  102. "plate_number": "JingF00001", "rfid_tag": "RFID_FREE",
  103. "parking_lot_id": 1, "parking_space_id": 1, "entry_image": "test.jpg",
  104. })
  105. entryTime := time.Now().Add(-10 * time.Minute)
  106. global.GVA_DB.Model(&dao.VehicleRecord{}).Where("plate_number = ?", "JingF00001").Update("entry_time", entryTime)
  107. exitResp, exitBody := env.DoPost("/vehicle/exit/preview", map[string]interface{}{
  108. "plate_number": "JingF00001", "rfid_tag": "RFID_FREE",
  109. })
  110. AssertResponse(t, exitResp, exitBody, http.StatusOK, response.SUCCESS)
  111. var preview struct { Fee float64 `json:"fee"` }
  112. json.Unmarshal(exitBody, &preview)
  113. if preview.Fee != 0 {
  114. t.Fatalf("BUG: Vehicle within free duration should have zero fee, got %.2f", preview.Fee)
  115. }
  116. fmt.Println("PASS: Free duration correctly applied")
  117. }
  118. // TestDailyCap 超过每日封顶费用应封顶
  119. func TestDailyCap(t *testing.T) {
  120. env := InitTestEnv(t)
  121. createVehicle(t, env, "JingD00001", "RFID_CAP", 1)
  122. _, _ = env.DoPost("/vehicle/entry", map[string]interface{}{
  123. "plate_number": "JingD00001", "rfid_tag": "RFID_CAP",
  124. "parking_lot_id": 1, "parking_space_id": 1, "entry_image": "test.jpg",
  125. })
  126. entryTime := time.Now().Add(-24 * time.Hour)
  127. global.GVA_DB.Model(&dao.VehicleRecord{}).Where("plate_number = ?", "JingD00001").Update("entry_time", entryTime)
  128. exitResp, exitBody := env.DoPost("/vehicle/exit/preview", map[string]interface{}{
  129. "plate_number": "JingD00001", "rfid_tag": "RFID_CAP",
  130. })
  131. AssertResponse(t, exitResp, exitBody, http.StatusOK, response.SUCCESS)
  132. var preview struct { Fee float64 `json:"fee"` }
  133. json.Unmarshal(exitBody, &preview)
  134. if preview.Fee > 50.0 {
  135. t.Fatalf("BUG: Fee exceeds daily cap! Expected <= 50, got %.2f", preview.Fee)
  136. }
  137. fmt.Printf("PASS: Daily cap applied correctly, fee=%.2f\n", preview.Fee)
  138. }
  139. // TestNoFeeConfig 无收费配置时默认计费
  140. func TestNoFeeConfig(t *testing.T) {
  141. env := InitTestEnv(t)
  142. var normalType dao.VehicleType
  143. env.DB.Where("is_system = ? AND name != ?", true, "临时车").First(&normalType)
  144. if normalType.ID == 0 {
  145. normalType = dao.VehicleType{Name: "特殊车", Remarks: "无收费配置"}
  146. env.DB.Create(&normalType)
  147. }
  148. env.DB.Where("vehicle_type_id = ?", normalType.ID).Delete(&dao.FeeConfig{})
  149. createVehicleWithOwner(t, env, "JingN00001", "RFID_NOFEE", normalType.ID)
  150. _, _ = env.DoPost("/vehicle/entry", map[string]interface{}{
  151. "plate_number": "JingN00001", "rfid_tag": "RFID_NOFEE",
  152. "parking_lot_id": 1, "parking_space_id": 1, "entry_image": "test.jpg",
  153. })
  154. entryTime := time.Now().Add(-1 * time.Hour)
  155. global.GVA_DB.Model(&dao.VehicleRecord{}).Where("plate_number = ?", "JingN00001").Update("entry_time", entryTime)
  156. exitResp, exitBody := env.DoPost("/vehicle/exit/preview", map[string]interface{}{
  157. "plate_number": "JingN00001", "rfid_tag": "RFID_NOFEE",
  158. })
  159. AssertResponse(t, exitResp, exitBody, http.StatusOK, response.SUCCESS)
  160. var result struct {
  161. Data struct {
  162. Fee float64 `json:"fee"`
  163. } `json:"data"`
  164. }
  165. json.Unmarshal(exitBody, &result)
  166. if result.Data.Fee <= 0 {
  167. t.Fatalf("BUG: No fee config should use default rate, got fee=%.2f", result.Data.Fee)
  168. }
  169. fmt.Printf("PASS: Default fee applied correctly, fee=%.2f\n", result.Data.Fee)
  170. }
  171. // TestShortlistByPlateOrRFID 黑白名单按车牌/RFID查询
  172. func TestShortlistByPlateOrRFID(t *testing.T) {
  173. env := InitTestEnv(t)
  174. createVehicle(t, env, "JingS00001", "RFID_FILTER", 1)
  175. var vehicle dao.Vehicle
  176. env.DB.Where("plate_number = ?", "JingS00001").First(&vehicle)
  177. _, _ = env.DoPost("/shortlist/createShortlist", dao.Shortlist{
  178. ListType: "黑名单", VehicleId: int(vehicle.ID), ExpirationTime: nil,
  179. })
  180. resp1, body1 := env.DoPost("/shortlist/queryShortlistList", map[string]interface{}{
  181. "page": 1, "pageSize": 10, "list_type": "", "plate_number": "JingS00001",
  182. })
  183. AssertResponse(t, resp1, body1, http.StatusOK, response.SUCCESS)
  184. list1 := ParsePageList(body1)
  185. if len(list1) < 1 { t.Fatalf("Expected at least 1 shortlist record by plate number") }
  186. fmt.Printf("PASS: Shortlist query by plate number returned %d records\n", len(list1))
  187. resp2, body2 := env.DoPost("/shortlist/queryShortlistList", map[string]interface{}{
  188. "page": 1, "pageSize": 10, "list_type": "", "rfid_tag": "RFID_FILTER",
  189. })
  190. AssertResponse(t, resp2, body2, http.StatusOK, response.SUCCESS)
  191. list2 := ParsePageList(body2)
  192. if len(list2) < 1 { t.Fatalf("Expected at least 1 shortlist record by RFID") }
  193. fmt.Printf("PASS: Shortlist query by RFID returned %d records\n", len(list2))
  194. }
  195. // TestShortlistUpdate 黑白名单更新
  196. func TestShortlistUpdate(t *testing.T) {
  197. env := InitTestEnv(t)
  198. createVehicle(t, env, "JingU00001", "RFID_UPDATE", 1)
  199. var vehicle dao.Vehicle
  200. env.DB.Where("plate_number = ?", "JingU00001").First(&vehicle)
  201. _, _ = env.DoPost("/shortlist/createShortlist", dao.Shortlist{
  202. ListType: "白名单", VehicleId: int(vehicle.ID), ExpirationTime: nil,
  203. })
  204. queryResp, queryBody := env.DoGet("/shortlist/queryAllShortlists", nil)
  205. AssertResponse(t, queryResp, queryBody, http.StatusOK, response.SUCCESS)
  206. var result struct { Data []map[string]interface{} `json:"data"` }
  207. json.Unmarshal(queryBody, &result)
  208. if len(result.Data) == 0 { t.Fatalf("No shortlist found") }
  209. idVal, ok := result.Data[0]["ID"]; if !ok { idVal = result.Data[0]["id"] }
  210. id := int(idVal.(float64))
  211. updateResp, updateBody := env.DoPut("/shortlist/updateShortlist", map[string]interface{}{
  212. "ID": id, "list_type": "黑名单", "vehicle_id": vehicle.ID,
  213. "expiration_time": time.Now().Add(30*24*time.Hour).Format(time.RFC3339),
  214. })
  215. AssertResponse(t, updateResp, updateBody, http.StatusOK, response.SUCCESS)
  216. updatedResp, updatedBody := env.DoGet("/shortlist/queryAllShortlists", nil)
  217. AssertResponse(t, updatedResp, updatedBody, http.StatusOK, response.SUCCESS)
  218. fmt.Println("PASS: Shortlist update successful")
  219. }
  220. // TestShortlistDelete 黑白名单删除
  221. func TestShortlistDelete(t *testing.T) {
  222. env := InitTestEnv(t)
  223. createVehicle(t, env, "JingDel001", "RFID_DELETE", 1)
  224. var vehicle dao.Vehicle
  225. env.DB.Where("plate_number = ?", "JingDel001").First(&vehicle)
  226. _, _ = env.DoPost("/shortlist/createShortlist", dao.Shortlist{
  227. ListType: "黑名单", VehicleId: int(vehicle.ID), ExpirationTime: nil,
  228. })
  229. queryResp, queryBody := env.DoGet("/shortlist/queryAllShortlists", nil)
  230. AssertResponse(t, queryResp, queryBody, http.StatusOK, response.SUCCESS)
  231. var result struct { Data []map[string]interface{} `json:"data"` }
  232. json.Unmarshal(queryBody, &result)
  233. if len(result.Data) == 0 { t.Fatalf("No shortlist found") }
  234. idVal, ok := result.Data[0]["ID"]; if !ok { idVal = result.Data[0]["id"] }
  235. id := int(idVal.(float64))
  236. deleteResp, deleteBody := env.DoDelete(fmt.Sprintf("/shortlist/deleteShortlist?id=%d", id))
  237. AssertResponse(t, deleteResp, deleteBody, http.StatusOK, response.SUCCESS)
  238. fmt.Println("PASS: Shortlist delete successful")
  239. }
  240. // TestOwnerVehicleRelationship 车主关联车辆查询
  241. func TestOwnerVehicleRelationship(t *testing.T) {
  242. env := InitTestEnv(t)
  243. ownerResp, ownerBody := env.DoPost("/owner/create", map[string]interface{}{
  244. "owner_name": "Rel Test Owner", "owner_surname": "REL",
  245. "owner_phone": "13911111111", "is_vip": false, "vip_expire_time": nil,
  246. })
  247. AssertResponse(t, ownerResp, ownerBody, http.StatusOK, response.SUCCESS)
  248. var owner dao.Owner
  249. env.DB.Where("owner_phone = ?", "13911111111").First(&owner)
  250. createVehicleWithOwner(t, env, "JingO00001", "RFID_OWNER", owner.ID)
  251. ownerListResp, ownerListBody := env.DoGet("/owner/list", map[string]string{"page": "1", "page_size": "10"})
  252. AssertResponse(t, ownerListResp, ownerListBody, http.StatusOK, response.SUCCESS)
  253. list := ParsePageList(ownerListBody)
  254. found := false
  255. for _, item := range list {
  256. m, ok := item.(map[string]interface{})
  257. if !ok { continue }
  258. if m["owner_phone"] == "13911111111" { found = true; break }
  259. }
  260. if !found { t.Fatalf("Owner not found in list") }
  261. fmt.Println("PASS: Owner-vehicle relationship verified")
  262. }
  263. // TestParkingLotCapacity 停车场容量检查
  264. func TestParkingLotCapacity(t *testing.T) {
  265. env := InitTestEnv(t)
  266. lotResp, lotBody := env.DoPost("/parking/lot/create", map[string]interface{}{
  267. "lot_code": "TEST_EMPTY", "lot_name": "Empty Lot",
  268. "capacity": 0, "description": "Zero capacity test",
  269. })
  270. AssertResponse(t, lotResp, lotBody, http.StatusOK, response.SUCCESS)
  271. createVehicle(t, env, "JingC00001", "RFID_FULL", 1)
  272. _, entryBody := env.DoPost("/vehicle/entry", map[string]interface{}{
  273. "plate_number": "JingC00001", "rfid_tag": "RFID_FULL",
  274. "parking_lot_id": 1, "parking_space_id": 1, "entry_image": "test.jpg",
  275. })
  276. var result struct { Code int `json:"code"`; Msg string `json:"msg"` }
  277. json.Unmarshal(entryBody, &result)
  278. fmt.Printf("INFO: Entry into zero-capacity lot: code=%d msg=%s\n", result.Code, result.Msg)
  279. }
  280. // TestBoothCRUD 岗亭CRUD
  281. func TestBoothCRUD(t *testing.T) {
  282. env := InitTestEnv(t)
  283. boothResp, boothBody := env.DoPost("/parking/booth/create", map[string]interface{}{
  284. "booth_code": "BT001", "booth_name": "Test Booth",
  285. "parking_lot_id": 1, "description": "Automated test booth",
  286. })
  287. AssertResponse(t, boothResp, boothBody, http.StatusOK, response.SUCCESS)
  288. listResp, listBody := env.DoGet("/parking/booth/list", map[string]string{"page": "1", "page_size": "10"})
  289. AssertResponse(t, listResp, listBody, http.StatusOK, response.SUCCESS)
  290. list := ParsePageList(listBody)
  291. if len(list) < 1 { t.Fatalf("Booth list is empty") }
  292. fmt.Printf("PASS: Booth CRUD successful, total %d booths\n", len(list))
  293. }
  294. // TestChannelCRUD 通道CRUD
  295. func TestChannelCRUD(t *testing.T) {
  296. env := InitTestEnv(t)
  297. channelResp, channelBody := env.DoPost("/parking/channel/create", map[string]interface{}{
  298. "channel_code": "CH-IN-TEST", "channel_name": "Test Entrance",
  299. "direction": "in", "parking_lot_id": 1, "booth_id": 1,
  300. "allow_temporary": true, "description": "Automated test channel",
  301. })
  302. AssertResponse(t, channelResp, channelBody, http.StatusOK, response.SUCCESS)
  303. listResp, listBody := env.DoGet("/parking/channel/list", map[string]string{"page": "1", "page_size": "10"})
  304. AssertResponse(t, listResp, listBody, http.StatusOK, response.SUCCESS)
  305. list := ParsePageList(listBody)
  306. if len(list) < 1 { t.Fatalf("Channel list is empty") }
  307. fmt.Printf("PASS: Channel CRUD successful, total %d channels\n", len(list))
  308. }
  309. // TestDeviceCRUD 设备CRUD
  310. func TestDeviceCRUD(t *testing.T) {
  311. env := InitTestEnv(t)
  312. deviceResp, deviceBody := env.DoPost("/parking/device/create", map[string]interface{}{
  313. "device_code": "DEV001", "device_name": "Test Device",
  314. "device_type": "TCP", "connect_type": "tcp", "ip_address": "127.0.0.1",
  315. "port": 9000, "is_active": true, "parking_lot_id": 1, "channel_id": 1,
  316. "description": "Automated test device",
  317. })
  318. AssertResponse(t, deviceResp, deviceBody, http.StatusOK, response.SUCCESS)
  319. listResp, listBody := env.DoGet("/parking/device/list", map[string]string{"page": "1", "page_size": "10"})
  320. AssertResponse(t, listResp, listBody, http.StatusOK, response.SUCCESS)
  321. list := ParsePageList(listBody)
  322. if len(list) < 1 { t.Fatalf("Device list is empty") }
  323. fmt.Printf("PASS: Device CRUD successful, total %d devices\n", len(list))
  324. }
  325. // TestVehicleTypeCRUD 自定义车辆类型CRUD
  326. func TestVehicleTypeCRUD(t *testing.T) {
  327. env := InitTestEnv(t)
  328. typeResp, typeBody := env.DoPost("/vehicle/type/create", map[string]interface{}{
  329. "name": "新能源车", "remarks": "测试新能源车辆类型", "is_system": false,
  330. })
  331. AssertResponse(t, typeResp, typeBody, http.StatusOK, response.SUCCESS)
  332. listResp, listBody := env.DoGet("/vehicle/type/all", nil)
  333. AssertResponse(t, listResp, listBody, http.StatusOK, response.SUCCESS)
  334. list := ParseDataList(listBody)
  335. if len(list) < 1 { t.Fatalf("Vehicle type list is empty") }
  336. fmt.Printf("PASS: Vehicle type CRUD successful, total %d types\n", len(list))
  337. }
  338. // ===================== Helper functions =====================
  339. // TestVehicleUpdate 车辆信息更新
  340. func TestVehicleUpdate(t *testing.T) {
  341. env := InitTestEnv(t)
  342. createVehicle(t, env, "JingUPD001", "RFID_UPDATE_TEST", 1)
  343. var v dao.Vehicle
  344. env.DB.Where("plate_number = ?", "JingUPD001").First(&v)
  345. resp, body := env.DoPut("/vehicle/update", map[string]interface{}{
  346. "ID": v.ID, "plate_number": "JingUPD001", "vehicle_type_id": 1,
  347. "vehicle_brand": "UpdatedBrand",
  348. "vehicle_color": "Blue", "rfid_tag": "RFID_UPDATE_TEST",
  349. })
  350. AssertResponse(t, resp, body, http.StatusOK, response.SUCCESS)
  351. fmt.Println("PASS: Vehicle update successful")
  352. }
  353. // TestVehicleDelete 车辆删除
  354. func TestVehicleDelete(t *testing.T) {
  355. env := InitTestEnv(t)
  356. createVehicle(t, env, "JingDEL001", "RFID_DELETE_TEST", 1)
  357. var v dao.Vehicle
  358. env.DB.Where("plate_number = ?", "JingDEL001").First(&v)
  359. resp, body := env.DoDelete(fmt.Sprintf("/vehicle/delete?id=%d", v.ID))
  360. AssertResponse(t, resp, body, http.StatusOK, response.SUCCESS)
  361. fmt.Println("PASS: Vehicle delete successful")
  362. }
  363. // TestVehicleList 车辆分页列表
  364. func TestVehicleList(t *testing.T) {
  365. env := InitTestEnv(t)
  366. createVehicle(t, env, "JingLST001", "RFID_LIST_TEST", 1)
  367. resp, body := env.DoGet("/vehicle/list", map[string]string{"page": "1", "page_size": "10"})
  368. AssertResponse(t, resp, body, http.StatusOK, response.SUCCESS)
  369. list := ParsePageList(body)
  370. if len(list) < 1 { t.Fatalf("Vehicle list is empty") }
  371. fmt.Printf("PASS: Vehicle list returned %d records\n", len(list))
  372. }
  373. // TestOwnerUpdate 业主信息更新
  374. func TestOwnerUpdate(t *testing.T) {
  375. env := InitTestEnv(t)
  376. ownerResp, ownerBody := env.DoPost("/owner/create", map[string]interface{}{
  377. "owner_name": "Update Test", "owner_surname": "Upd",
  378. "owner_phone": "13900000999", "is_vip": false,
  379. })
  380. AssertResponse(t, ownerResp, ownerBody, http.StatusOK, response.SUCCESS)
  381. var o dao.Owner
  382. env.DB.Where("owner_phone = ?", "13900000999").First(&o)
  383. updResp, updBody := env.DoPut("/owner/update", map[string]interface{}{
  384. "ID": o.ID, "owner_name": "Updated Name", "owner_surname": "Upd2",
  385. "owner_phone": "13900000999", "is_vip": true,
  386. })
  387. AssertResponse(t, updResp, updBody, http.StatusOK, response.SUCCESS)
  388. fmt.Println("PASS: Owner update successful")
  389. }
  390. // TestOwnerGetByPhone 按手机号查询业主
  391. func TestOwnerGetByPhone(t *testing.T) {
  392. env := InitTestEnv(t)
  393. _, _ = env.DoPost("/owner/create", map[string]interface{}{
  394. "owner_name": "Phone Query", "owner_surname": "Ph",
  395. "owner_phone": "13900000888", "is_vip": false,
  396. })
  397. resp, body := env.DoGet("/owner/get-by-phone", map[string]string{"phone": "13900000888"})
  398. AssertResponse(t, resp, body, http.StatusOK, response.SUCCESS)
  399. fmt.Println("PASS: Owner query by phone successful")
  400. }
  401. // TestFeeConfigCreate 收费配置创建
  402. func TestFeeConfigCreate(t *testing.T) {
  403. env := InitTestEnv(t)
  404. // 创建一个新的车辆类型并为其创建收费配置
  405. typeResp, typeBody := env.DoPost("/vehicle/type/create", map[string]interface{}{
  406. "name": "FeeConfigTest", "remarks": "Fee config test type", "is_system": false,
  407. })
  408. AssertResponse(t, typeResp, typeBody, http.StatusOK, response.SUCCESS)
  409. var vt2 dao.VehicleType
  410. env.DB.Where("name = ?", "FeeConfigTest").First(&vt2)
  411. resp, body := env.DoPost("/vehicle/fee-config/create", map[string]interface{}{
  412. "vehicle_type_id": vt2.ID, "start_time": 0, "start_fee": 0,
  413. "unit_time": 60, "unit_fee": 10, "daily_max_fee": 80,
  414. })
  415. AssertResponse(t, resp, body, http.StatusOK, response.SUCCESS)
  416. fmt.Println("PASS: Fee config create successful")
  417. }
  418. // TestParkingLotUpdate 停车场信息更新
  419. func TestParkingLotUpdate(t *testing.T) {
  420. env := InitTestEnv(t)
  421. var lot dao.ParkingLot
  422. env.DB.Where("lot_code = ?", "TEST001").First(&lot)
  423. resp, body := env.DoPut("/parking/lot/update", map[string]interface{}{
  424. "ID": lot.ID, "lot_code": "TEST001", "lot_name": "Updated Lot",
  425. "capacity": 200, "description": "Updated desc",
  426. })
  427. AssertResponse(t, resp, body, http.StatusOK, response.SUCCESS)
  428. fmt.Println("PASS: Parking lot update successful")
  429. }
  430. // ===================== 月租车管理模块测试 =====================
  431. // TestMonthlyCardCreate 办理月卡
  432. func TestMonthlyCardCreate(t *testing.T) {
  433. env := InitTestEnv(t)
  434. createVehicle(t, env, "JingMC001", "RFID_MC001", 1)
  435. var v dao.Vehicle
  436. env.DB.Where("plate_number = ?", "JingMC001").First(&v)
  437. resp, body := env.DoPost("/monthly-card/create", map[string]interface{}{
  438. "vehicle_id": v.ID, "card_type": "month", "fee": 300.0, "remark": "test month card",
  439. })
  440. AssertResponse(t, resp, body, http.StatusOK, response.SUCCESS)
  441. var card dao.MonthlyCard
  442. env.DB.Where("vehicle_id = ?", v.ID).First(&card)
  443. if card.ID == 0 { t.Fatalf("Monthly card not created in DB") }
  444. if card.PaymentStatus != "paid" { t.Fatalf("Expected paid, got %s", card.PaymentStatus) }
  445. // Verify shortlist (whitelist) was created
  446. var sl dao.Shortlist
  447. env.DB.Where("vehicle_id = ? AND list_type = ?", v.ID, "白名单").First(&sl)
  448. if sl.ID == 0 { t.Fatalf("Shortlist not created") }
  449. fmt.Println("PASS: Monthly card created successfully")
  450. }
  451. // TestMonthlyCardRenew 月卡续费
  452. func TestMonthlyCardRenew(t *testing.T) {
  453. env := InitTestEnv(t)
  454. createVehicle(t, env, "JingMC002", "RFID_MC002", 1)
  455. var v dao.Vehicle
  456. env.DB.Where("plate_number = ?", "JingMC002").First(&v)
  457. _, _ = env.DoPost("/monthly-card/create", map[string]interface{}{
  458. "vehicle_id": v.ID, "card_type": "month", "fee": 300.0,
  459. })
  460. var card dao.MonthlyCard
  461. env.DB.Where("vehicle_id = ?", v.ID).First(&card)
  462. origEnd := card.EndDate
  463. resp, body := env.DoPost("/monthly-card/renew", map[string]interface{}{
  464. "card_id": card.ID, "card_type": "month", "fee": 300.0,
  465. })
  466. AssertResponse(t, resp, body, http.StatusOK, response.SUCCESS)
  467. env.DB.Where("vehicle_id = ?", v.ID).First(&card)
  468. expectedEnd := origEnd.AddDate(0, 0, 30)
  469. if !card.EndDate.Equal(expectedEnd) && !card.EndDate.After(expectedEnd.Add(-time.Hour*23)) {
  470. t.Fatalf("EndDate not extended correctly: orig=%v, new=%v", origEnd, card.EndDate)
  471. }
  472. fmt.Println("PASS: Monthly card renewed successfully")
  473. }
  474. // TestMonthlyCardRefund 月卡退卡
  475. func TestMonthlyCardRefund(t *testing.T) {
  476. env := InitTestEnv(t)
  477. createVehicle(t, env, "JingMC003", "RFID_MC003", 1)
  478. var v dao.Vehicle
  479. env.DB.Where("plate_number = ?", "JingMC003").First(&v)
  480. _, _ = env.DoPost("/monthly-card/create", map[string]interface{}{
  481. "vehicle_id": v.ID, "card_type": "month", "fee": 300.0,
  482. })
  483. var card dao.MonthlyCard
  484. env.DB.Where("vehicle_id = ?", v.ID).First(&card)
  485. resp, body := env.DoDelete(fmt.Sprintf("/monthly-card/refund?id=%d", card.ID))
  486. AssertResponse(t, resp, body, http.StatusOK, response.SUCCESS)
  487. env.DB.First(&card, card.ID)
  488. if card.PaymentStatus != "refunded" { t.Fatalf("Expected refunded, got %s", card.PaymentStatus) }
  489. var count int64
  490. env.DB.Model(&dao.Shortlist{}).Where("vehicle_id = ? AND list_type = ?", v.ID, "白名单").Count(&count)
  491. if count != 0 { t.Fatalf("Shortlist should be removed after refund, found %d", count) }
  492. fmt.Println("PASS: Monthly card refunded successfully")
  493. }
  494. // TestMonthlyCardList 月卡列表查询
  495. func TestMonthlyCardList(t *testing.T) {
  496. env := InitTestEnv(t)
  497. createVehicle(t, env, "JingMC004", "RFID_MC004", 1)
  498. var v dao.Vehicle
  499. env.DB.Where("plate_number = ?", "JingMC004").First(&v)
  500. _, _ = env.DoPost("/monthly-card/create", map[string]interface{}{
  501. "vehicle_id": v.ID, "card_type": "quarter", "fee": 800.0,
  502. })
  503. resp, body := env.DoGet("/monthly-card/list", map[string]string{"page": "1", "page_size": "10"})
  504. AssertResponse(t, resp, body, http.StatusOK, response.SUCCESS)
  505. list := ParsePageList(body)
  506. if len(list) < 1 { t.Fatalf("Monthly card list is empty") }
  507. resp, body2 := env.DoGet("/monthly-card/list", map[string]string{
  508. "page": "1", "page_size": "10", "card_type": "quarter",
  509. })
  510. AssertResponse(t, resp, body2, http.StatusOK, response.SUCCESS)
  511. list2 := ParsePageList(body2)
  512. if len(list2) < 1 { t.Fatalf("Filtered list by card_type is empty") }
  513. fmt.Printf("PASS: Monthly card list returned %d records\\n", len(list))
  514. }
  515. // TestMonthlyCardDuplicate 重复办卡拦截
  516. func TestMonthlyCardDuplicate(t *testing.T) {
  517. env := InitTestEnv(t)
  518. createVehicle(t, env, "JingMC005", "RFID_MC005", 1)
  519. var v dao.Vehicle
  520. env.DB.Where("plate_number = ?", "JingMC005").First(&v)
  521. _, _ = env.DoPost("/monthly-card/create", map[string]interface{}{
  522. "vehicle_id": v.ID, "card_type": "month", "fee": 300.0,
  523. })
  524. _, body2 := env.DoPost("/monthly-card/create", map[string]interface{}{
  525. "vehicle_id": v.ID, "card_type": "year", "fee": 3000.0,
  526. })
  527. var result struct { Code int `json:"code"`; Msg string `json:"msg"` }
  528. json.Unmarshal(body2, &result)
  529. if result.Code == response.SUCCESS {
  530. t.Fatalf("BUG: Duplicate monthly card creation was NOT blocked!")
  531. }
  532. fmt.Printf("PASS: Duplicate card creation correctly rejected: %s\\n", result.Msg)
  533. }
  534. // TestMonthlyCardNonexistentRefund 不存在的月卡退卡
  535. func TestMonthlyCardNonexistentRefund(t *testing.T) {
  536. env := InitTestEnv(t)
  537. _, body := env.DoDelete("/monthly-card/refund?id=99999")
  538. // Should fail with error code
  539. var result struct { Code int `json:"code"`; Msg string `json:"msg"` }
  540. json.Unmarshal(body, &result)
  541. if result.Code == response.SUCCESS {
  542. t.Fatalf("BUG: Refunding non-existent card was NOT blocked!")
  543. }
  544. // HTTP status may vary, just check code != 0
  545. fmt.Printf("PASS: Non-existent card refund correctly rejected: code=%d msg=%s\\n", result.Code, result.Msg)
  546. }
  547. // TestMonthlyCardDifferentTypes 不同套餐类型
  548. func TestMonthlyCardDifferentTypes(t *testing.T) {
  549. env := InitTestEnv(t)
  550. createVehicle(t, env, "JingMC006", "RFID_MC006", 1)
  551. var v dao.Vehicle
  552. env.DB.Where("plate_number = ?", "JingMC006").First(&v)
  553. resp, body := env.DoPost("/monthly-card/create", map[string]interface{}{
  554. "vehicle_id": v.ID, "card_type": "year", "fee": 3000.0,
  555. })
  556. AssertResponse(t, resp, body, http.StatusOK, response.SUCCESS)
  557. var card dao.MonthlyCard
  558. env.DB.Where("vehicle_id = ?", v.ID).First(&card)
  559. duration := card.EndDate.Sub(card.StartDate).Hours() / 24
  560. if duration < 360 || duration > 370 {
  561. t.Fatalf("Year card should be ~365 days, got %.0f days", duration)
  562. }
  563. fmt.Printf("PASS: Year card duration = %.0f days\\n", duration)
  564. }
  565. // ===================== 数字票模块测试 =====================
  566. func createTicket(t *testing.T, env *TestEnv, plate, trigger string) (string, uint) {
  567. t.Helper()
  568. createVehicle(t, env, plate, "RFID_"+plate, 1)
  569. var v dao.Vehicle
  570. env.DB.Where("plate_number = ?", plate).First(&v)
  571. rec := dao.VehicleRecord{PlateNumber: plate, RFIDTag: "RFID_" + plate, EntryTime: time.Now(), ParkingLotID: 1}
  572. env.DB.Create(&rec)
  573. var svc = new(dt_svc.TicketService)
  574. ticket, err := svc.Create(plate, trigger, rec.ID)
  575. if err != nil {
  576. t.Fatalf("Failed to create ticket: %v", err)
  577. }
  578. return ticket.TicketNo, ticket.ID
  579. }
  580. // TestDigitalTicketDetail DT01: 查询数字票详情
  581. func TestDigitalTicketDetail(t *testing.T) {
  582. env := InitTestEnv(t)
  583. ticketNo, _ := createTicket(t, env, "DT001", "manual")
  584. resp, body := env.DoGet("/digital-ticket/"+ticketNo, nil)
  585. AssertResponse(t, resp, body, http.StatusOK, response.SUCCESS)
  586. data := ParseDataMap(body)
  587. if data["state"] != "pending_payment" {
  588. t.Fatalf("Expected state=pending_payment, got %v", data["state"])
  589. }
  590. if data["ticket_no"] != ticketNo {
  591. t.Fatalf("TicketNo mismatch")
  592. }
  593. if data["trigger_mode"] != "manual" {
  594. t.Fatalf("TriggerMode mismatch")
  595. }
  596. fmt.Println("PASS: Digital ticket detail query successful")
  597. }
  598. // TestDigitalTicketPay DT02: 支付数字票
  599. // BUG: paid_amount 字段在 digital_ticket 表中不存在,PayTicket API 会报 SQL 错误
  600. // 预期: 该测试应失败,暴露后端缺陷
  601. func TestDigitalTicketPay(t *testing.T) {
  602. env := InitTestEnv(t)
  603. ticketNo, _ := createTicket(t, env, "DT002", "plate_recognition")
  604. resp, body := env.DoPost("/digital-ticket/"+ticketNo+"/pay", map[string]interface{}{
  605. "payment_method": "cash", "payment_order_no": "PO002", "paid_amount": 20.0,
  606. })
  607. AssertResponse(t, resp, body, http.StatusOK, response.SUCCESS)
  608. fmt.Println("PASS: Pay API works correctly")
  609. }
  610. // TestDigitalTicketExit DT03: 离场验证
  611. func TestDigitalTicketExit(t *testing.T) {
  612. env := InitTestEnv(t)
  613. ticketNo, _ := createTicket(t, env, "DT003", "rfid")
  614. // 支付
  615. _, _ = env.DoPost("/digital-ticket/"+ticketNo+"/pay", map[string]interface{}{
  616. "payment_method": "cash", "payment_order_no": "PO003", "paid_amount": 15.0,
  617. })
  618. // 支付成功后离场
  619. resp, body := env.DoPost("/digital-ticket/"+ticketNo+"/exit", nil)
  620. AssertResponse(t, resp, body, http.StatusOK, response.SUCCESS)
  621. fmt.Println("PASS: Pay → Exit flow works correctly")
  622. }
  623. // TestDigitalTicketList DT04: 数字票列表
  624. func TestDigitalTicketList(t *testing.T) {
  625. env := InitTestEnv(t)
  626. createTicket(t, env, "DT004", "manual")
  627. resp, body := env.DoGet("/digital-ticket/list", map[string]string{"page": "1", "page_size": "10"})
  628. AssertResponse(t, resp, body, http.StatusOK, response.SUCCESS)
  629. list := ParsePageList(body)
  630. if len(list) < 1 {
  631. t.Fatalf("Ticket list is empty")
  632. }
  633. fmt.Printf("PASS: Digital ticket list returned %d records\n", len(list))
  634. }
  635. // TestDigitalTicketFullFlow DT05: 完整流程
  636. // BUG: Pay API 因 paid_amount 缺失而失败,完整流程无法通过 pay API 完成
  637. // 测试验证: exit API 本身在状态正确时可正常工作
  638. func TestDigitalTicketFullFlow(t *testing.T) {
  639. env := InitTestEnv(t)
  640. ticketNo, _ := createTicket(t, env, "DT005", "manual")
  641. // Pay
  642. resp1, body1 := env.DoPost("/digital-ticket/"+ticketNo+"/pay", map[string]interface{}{
  643. "payment_method": "cash", "payment_order_no": "PO005", "paid_amount": 25.0,
  644. })
  645. AssertResponse(t, resp1, body1, http.StatusOK, response.SUCCESS)
  646. // Exit
  647. resp2, body2 := env.DoPost("/digital-ticket/"+ticketNo+"/exit", nil)
  648. AssertResponse(t, resp2, body2, http.StatusOK, response.SUCCESS)
  649. // Verify state
  650. _, getBody := env.DoGet("/digital-ticket/"+ticketNo, nil)
  651. data := ParseDataMap(getBody)
  652. if data["state"] != "exited" {
  653. t.Fatalf("Expected exited, got state=%v", data["state"])
  654. }
  655. fmt.Println("PASS: Full flow (pay → exit) works correctly")
  656. }
  657. // TestDigitalTicketInvalidExit DT06: 未支付直接离场被拒
  658. func TestDigitalTicketInvalidExit(t *testing.T) {
  659. env := InitTestEnv(t)
  660. ticketNo, _ := createTicket(t, env, "DT006", "manual")
  661. _, body := env.DoPost("/digital-ticket/"+ticketNo+"/exit", nil)
  662. var result struct{ Code int `json:"code"`; Msg string `json:"msg"` }
  663. json.Unmarshal(body, &result)
  664. if result.Code == response.SUCCESS {
  665. t.Fatalf("BUG: Exit without payment was NOT blocked!")
  666. }
  667. fmt.Printf("PASS: Exit without payment correctly rejected: %s\n", result.Msg)
  668. }
  669. // TestDigitalTicketNonexistent DT08: 不存在的票号
  670. func TestDigitalTicketNonexistent(t *testing.T) {
  671. env := InitTestEnv(t)
  672. _, body := env.DoGet("/digital-ticket/FAKE", nil)
  673. var result struct{ Code int `json:"code"`; Msg string `json:"msg"` }
  674. json.Unmarshal(body, &result)
  675. if result.Code == response.SUCCESS {
  676. t.Fatalf("BUG: Non-existent ticket returned success!")
  677. }
  678. fmt.Printf("PASS: Non-existent ticket correctly rejected: %s\n", result.Msg)
  679. }
  680. // TestDigitalTicketListFilter DT09+10: 列表过滤
  681. func TestDigitalTicketListFilter(t *testing.T) {
  682. env := InitTestEnv(t)
  683. createTicket(t, env, "DTFILTER", "manual")
  684. resp, body := env.DoGet("/digital-ticket/list", map[string]string{
  685. "page": "1", "page_size": "10", "plate_number": "DTFILTER",
  686. })
  687. AssertResponse(t, resp, body, http.StatusOK, response.SUCCESS)
  688. list := ParsePageList(body)
  689. if len(list) < 1 {
  690. t.Fatalf("Filter by plate returned empty")
  691. }
  692. fmt.Printf("PASS: Ticket list filter returned %d records\n", len(list))
  693. }
  694. // TestDigitalTicketEmptyList DT13: 空列表
  695. func TestDigitalTicketListPagination(t *testing.T) {
  696. env := InitTestEnv(t)
  697. createTicket(t, env, "DTPAGE", "manual")
  698. resp, body := env.DoGet("/digital-ticket/list", map[string]string{"page": "1", "page_size": "5"})
  699. AssertResponse(t, resp, body, http.StatusOK, response.SUCCESS)
  700. list := ParsePageList(body)
  701. if len(list) < 1 {
  702. t.Fatalf("Paginated list is empty")
  703. }
  704. fmt.Printf("PASS: Ticket list pagination returned %d records\n", len(list))
  705. }
  706. func createVehicleWithOwner(t *testing.T, env *TestEnv, plateNumber, rfidTag string, ownerID uint) {
  707. t.Helper()
  708. _, body := env.DoPost("/vehicle/create", map[string]interface{}{
  709. "plate_number": plateNumber, "vehicle_type_id": 1,
  710. "vehicle_brand": "TestBrand", "vehicle_color": "TestColor",
  711. "rfid_tag": rfidTag, "owner_id": ownerID,
  712. })
  713. var result struct { Code int `json:"code"`; Msg string `json:"msg"` }
  714. json.Unmarshal(body, &result)
  715. if result.Code != response.SUCCESS {
  716. t.Fatalf("Failed to create vehicle with owner: %s", result.Msg)
  717. }
  718. }
  719. // ===================== 交接班对账 (Shift) 测试 =====================
  720. //
  721. // 注意:由于 TestEnv 是全局缓存的,所有测试共享同一个数据库和操作员,
  722. // 每个 shift 测试必须清除前序测试遗留的当班记录。
  723. // closeActiveShift 清除操作员活动中当班(DB直接操作,不经过 API)
  724. func closeActiveShift(env *TestEnv) {
  725. env.DB.Model(&dao.ShiftRecord{}).
  726. Where("operator_id = ? AND status = ?", env.UserID, "active").
  727. Update("status", "closed")
  728. }
  729. // TestShiftStart SH01: 正常接班
  730. func TestShiftStart(t *testing.T) {
  731. env := InitTestEnv(t)
  732. closeActiveShift(env) // 清理前序状态
  733. resp, body := env.DoPost("/shift/start", map[string]interface{}{
  734. "starting_cash": 100.0,
  735. })
  736. AssertResponse(t, resp, body, http.StatusOK, response.SUCCESS)
  737. // 验证 DB 中创建了当班记录
  738. var rec dao.ShiftRecord
  739. env.DB.Where("operator_id = ? AND status = ?", env.UserID, "active").First(&rec)
  740. if rec.ID == 0 {
  741. t.Fatalf("Shift record not created in DB")
  742. }
  743. if rec.StartingCash != 100.0 {
  744. t.Fatalf("Expected starting_cash=100, got %.2f", rec.StartingCash)
  745. }
  746. fmt.Printf("PASS: Shift start successful, recordID=%d\n", rec.ID)
  747. }
  748. // TestShiftEnd SH02: 正常交班(含当班现金收款统计与差异计算)
  749. func TestShiftEnd(t *testing.T) {
  750. env := InitTestEnv(t)
  751. closeActiveShift(env)
  752. // 1. 接班
  753. startResp, startBody := env.DoPost("/shift/start", map[string]interface{}{
  754. "starting_cash": 100.0,
  755. })
  756. AssertResponse(t, startResp, startBody, http.StatusOK, response.SUCCESS)
  757. // 2. 伪造一笔现金收款记录(模拟当班期间收款50元)
  758. now := time.Now()
  759. env.DB.Exec(`INSERT INTO payment_record
  760. (record_id, payment_method, amount, paid_amount, change_amount, operator_id, paid_at, created_at, updated_at)
  761. VALUES (9999, 'cash', 50.0, 50.0, 0, ?, ?, ?, ?)`,
  762. env.UserID, now, now, now)
  763. // 3. 交班 — 接班100 + 当班收款50 = 应交150,实交150 → 差异0
  764. resp, body := env.DoPost("/shift/end", map[string]interface{}{
  765. "actual_cash": 150.0,
  766. "remark": "test shift end",
  767. })
  768. AssertResponse(t, resp, body, http.StatusOK, response.SUCCESS)
  769. // 4. 验证 DB 记录
  770. var rec dao.ShiftRecord
  771. env.DB.Where("operator_id = ? AND status = ?", env.UserID, "closed").Order("id DESC").First(&rec)
  772. if rec.ID == 0 {
  773. t.Fatalf("Shift record not updated in DB")
  774. }
  775. if rec.CollectedCash != 50.0 {
  776. t.Fatalf("Expected collected_cash=50, got %.2f", rec.CollectedCash)
  777. }
  778. if rec.ExpectedTotal != 150.0 {
  779. t.Fatalf("Expected expected_total=150, got %.2f", rec.ExpectedTotal)
  780. }
  781. if rec.Difference != 0.0 {
  782. t.Fatalf("Expected difference=0, got %.2f", rec.Difference)
  783. }
  784. if rec.Remark != "test shift end" {
  785. t.Fatalf("Remark mismatch: expected 'test shift end', got '%s'", rec.Remark)
  786. }
  787. fmt.Printf("PASS: Shift end successful, collected=%.2f expected=%.2f diff=%.2f\n",
  788. rec.CollectedCash, rec.ExpectedTotal, rec.Difference)
  789. }
  790. // TestShiftDoubleStart SH03: 重复接班被拦截
  791. func TestShiftDoubleStart(t *testing.T) {
  792. env := InitTestEnv(t)
  793. closeActiveShift(env)
  794. // 第一次接班 — 成功
  795. startResp, startBody := env.DoPost("/shift/start", map[string]interface{}{
  796. "starting_cash": 100.0,
  797. })
  798. AssertResponse(t, startResp, startBody, http.StatusOK, response.SUCCESS)
  799. // 第二次接班 — 应被拦截
  800. _, body := env.DoPost("/shift/start", map[string]interface{}{
  801. "starting_cash": 200.0,
  802. })
  803. var result struct {
  804. Code int `json:"code"`
  805. Msg string `json:"msg"`
  806. }
  807. json.Unmarshal(body, &result)
  808. if result.Code == response.SUCCESS {
  809. t.Fatalf("BUG: Double shift start was NOT blocked! code=%d msg=%s", result.Code, result.Msg)
  810. }
  811. fmt.Printf("PASS: Double start correctly rejected: msg=%s\n", result.Msg)
  812. }
  813. // TestShiftEndWithoutStart SH04: 未接班直接交班失败
  814. func TestShiftEndWithoutStart(t *testing.T) {
  815. env := InitTestEnv(t)
  816. closeActiveShift(env) // 确保没有当班记录
  817. resp, body := env.DoPost("/shift/end", map[string]interface{}{
  818. "actual_cash": 100.0,
  819. "remark": "no start",
  820. })
  821. // 期望返回错误(无当班记录)
  822. AssertResponse(t, resp, body, http.StatusOK, response.ERROR)
  823. var result struct {
  824. Code int `json:"code"`
  825. Msg string `json:"msg"`
  826. }
  827. json.Unmarshal(body, &result)
  828. fmt.Printf("PASS: End without start correctly rejected: code=%d msg=%s\n", result.Code, result.Msg)
  829. }
  830. // TestShiftCurrent SH05: 查询当前当班信息
  831. func TestShiftCurrent(t *testing.T) {
  832. env := InitTestEnv(t)
  833. closeActiveShift(env)
  834. // 先接班
  835. _, _ = env.DoPost("/shift/start", map[string]interface{}{
  836. "starting_cash": 200.0,
  837. })
  838. // 查询当班
  839. resp, body := env.DoGet("/shift/current", nil)
  840. AssertResponse(t, resp, body, http.StatusOK, response.SUCCESS)
  841. var result struct {
  842. Code int `json:"code"`
  843. Data map[string]interface{} `json:"data"`
  844. Msg string `json:"msg"`
  845. }
  846. json.Unmarshal(body, &result)
  847. if result.Data == nil {
  848. t.Fatalf("Shift current data is nil")
  849. }
  850. startCash, ok := result.Data["starting_cash"].(float64)
  851. if !ok || startCash != 200.0 {
  852. t.Fatalf("Expected starting_cash=200, got %v", result.Data["starting_cash"])
  853. }
  854. fmt.Printf("PASS: Shift current query successful, starting_cash=%.2f\n", startCash)
  855. }
  856. // TestShiftList SH06: 交接班记录列表
  857. func TestShiftList(t *testing.T) {
  858. env := InitTestEnv(t)
  859. closeActiveShift(env)
  860. // 接班 → 交班 → 产生一条历史记录
  861. _, _ = env.DoPost("/shift/start", map[string]interface{}{"starting_cash": 50.0})
  862. _, _ = env.DoPost("/shift/end", map[string]interface{}{"actual_cash": 50.0, "remark": "list test"})
  863. // 查询列表
  864. resp, body := env.DoGet("/shift/list", map[string]string{
  865. "page": "1",
  866. "page_size": "10",
  867. })
  868. AssertResponse(t, resp, body, http.StatusOK, response.SUCCESS)
  869. list := ParsePageList(body)
  870. if len(list) == 0 {
  871. t.Fatalf("Shift list is empty after creating a record")
  872. }
  873. fmt.Printf("PASS: Shift list returned %d records\n", len(list))
  874. }
  875. // ===================== 收入报表 (Revenue Report) 测试 =====================
  876. // createParkingPayment 辅助函数:创建一笔车辆进出+支付记录(用于报表测试)
  877. func createParkingPayment(t *testing.T, env *TestEnv, plateNumber, rfidTag string, amount float64, method string) {
  878. t.Helper()
  879. createVehicle(t, env, plateNumber, rfidTag, 1)
  880. entryResp, entryBody := env.DoPost("/vehicle/entry", map[string]interface{}{
  881. "plate_number": plateNumber,
  882. "rfid_tag": rfidTag,
  883. "parking_lot_id": 1,
  884. "parking_space_id": 1,
  885. "entry_image": "test_revenue_entry.jpg",
  886. })
  887. AssertResponse(t, entryResp, entryBody, http.StatusOK, response.SUCCESS)
  888. // 修改入场时间为数小时前,以确保产生费用
  889. entryTime := time.Now().Add(-3 * time.Hour)
  890. env.DB.Model(&dao.VehicleRecord{}).Where("plate_number = ?", plateNumber).Update("entry_time", entryTime)
  891. exitResp, exitBody := env.DoPost("/vehicle/exit/confirm", map[string]interface{}{
  892. "plate_number": plateNumber,
  893. "rfid_tag": rfidTag,
  894. "payment_method": method,
  895. "paid_amount": amount,
  896. })
  897. AssertResponse(t, exitResp, exitBody, http.StatusOK, response.SUCCESS)
  898. }
  899. // TestRevenueReportBasic RR01: 基础收入报表查询(无参数)
  900. // BUG: 后端 RevenueReport 当 start_date/end_date 为空时,SQL 条件为
  901. // paid_at >= '' AND paid_at <= ' 23:59:59'
  902. // 导致所有记录被过滤,data 返回 null。
  903. func TestRevenueReportBasic(t *testing.T) {
  904. env := InitTestEnv(t)
  905. createParkingPayment(t, env, "JingREV001", "RFID_REV001", 15.0, "cash")
  906. resp, body := env.DoGet("/report/revenue", nil)
  907. // HTTP 层面是 200
  908. if resp.StatusCode != http.StatusOK {
  909. t.Fatalf("Expected 200, got %d", resp.StatusCode)
  910. }
  911. var result struct {
  912. Code int `json:"code"`
  913. Data json.RawMessage `json:"data"`
  914. Msg string `json:"msg"`
  915. }
  916. json.Unmarshal(body, &result)
  917. // BUG: 无日期参数时 data 应为有数据,但后端返回 null
  918. if result.Code != response.SUCCESS {
  919. t.Fatalf("Revenue report failed: code=%d msg=%s", result.Code, result.Msg)
  920. }
  921. if result.Data == nil || string(result.Data) == "null" {
  922. t.Fatalf("BUG: Revenue report with no date params returns null data! "+
  923. "Cause: SQL condition 'paid_at >= \"\" AND paid_at <= \" 23:59:59\"' filters out all records. "+
  924. "Fix: when start/end_date are empty, omit the WHERE clause or default to today.")
  925. }
  926. fmt.Printf("PASS: Revenue report basic query successful, data=%s\n", string(result.Data))
  927. }
  928. // TestRevenueReportDateRange RR02: 指定日期范围的收入报表
  929. func TestRevenueReportDateRange(t *testing.T) {
  930. env := InitTestEnv(t)
  931. createParkingPayment(t, env, "JingREV002", "RFID_REV002", 20.0, "cash")
  932. today := time.Now().Format("2006-01-02")
  933. resp, body := env.DoGet("/report/revenue", map[string]string{
  934. "start_date": today,
  935. "end_date": today,
  936. })
  937. AssertResponse(t, resp, body, http.StatusOK, response.SUCCESS)
  938. var result struct {
  939. Code int `json:"code"`
  940. Data json.RawMessage `json:"data"`
  941. Msg string `json:"msg"`
  942. }
  943. json.Unmarshal(body, &result)
  944. if len(result.Data) == 0 || string(result.Data) == "null" {
  945. t.Fatalf("Revenue report with date range returned empty")
  946. }
  947. fmt.Printf("PASS: Revenue report with date range successful, data=%s\n", string(result.Data))
  948. }
  949. // TestRevenueReportWithLotFilter RR03: 指定停车场的收入报表
  950. func TestRevenueReportWithLotFilter(t *testing.T) {
  951. env := InitTestEnv(t)
  952. createParkingPayment(t, env, "JingREV003", "RFID_REV003", 25.0, "cash")
  953. today := time.Now().Format("2006-01-02")
  954. resp, body := env.DoGet("/report/revenue", map[string]string{
  955. "parking_lot_id": "1",
  956. "start_date": today,
  957. "end_date": today,
  958. })
  959. AssertResponse(t, resp, body, http.StatusOK, response.SUCCESS)
  960. var result struct {
  961. Code int `json:"code"`
  962. Data json.RawMessage `json:"data"`
  963. Msg string `json:"msg"`
  964. }
  965. json.Unmarshal(body, &result)
  966. if len(result.Data) == 0 || string(result.Data) == "null" {
  967. t.Fatalf("Revenue report with lot filter returned empty")
  968. }
  969. fmt.Printf("PASS: Revenue report with lot filter successful, data=%s\n", string(result.Data))
  970. }