3 Commits
Author SHA1 Message Date
KennethCheng 07ebce1ea3 test(backend): 添加核心计算单测与 Statistics 业务单测
Phase 1.4。AGENTS.md §19 与 plan §6 都把单测作为 MVP 硬要求,这条 commit
把核心计算覆盖完毕。

新增:
- pkg/decimal/money_test.go   5 个函数 × table-driven,共 22 个子测试
  * PricePerLiter:覆盖 plan §6.1 的 176.33/23.67 = 7.45,以及简单整数除、
    liters<=0 边界、四位精度等
  * ConsumptionL100km:覆盖 plan §6.3 的 (10500-10000)/40*100 = 8.0,以及
    mileage<=0 边界
  * CostPerKm:覆盖 plan §6.4 的 256/500 = 0.512
  * Mileage:正常递增 / 相等(没开) / 倒推(里程倒写,应为 0) / 首次记录(prev=0)
  * AvgFloat64:空切片 / 单值 / 多值 / 舍入

- internal/service/refuel_record_test.go  5 个测试,覆盖 plan §6.3 的
  "半箱油不进入标准油耗"硬规则
  * TestStatistics_TwoConsecutiveFull:两条 is_full → mileage=500,
    consumption=8.0, cost=0.64, 命中 plan 案例
  * TestStatistics_HalfTankDoesNotPollute:两条全 + 一条半箱,标准油耗仍 8.0,
    半箱油被正确跳过
  * TestStatistics_OnlyHalfTanks:全是半箱,标准油耗 = 0(没采样)
  * TestStatistics_MultipleFullSamples:三条全,平均油耗/成本正确
  * TestStatistics_EmptyVehicle:零记录时 LastRefuel 应为 nil

测试方法:
- 纯单测,不接 SQLite,自己写 fakeVehicleRepo / fakeRefuelRepo
  实现 repository 接口;fake 也按 refuel_time DESC 排,与真 repo 行为一致
- sentinel 错误与 apperror.IsCode 风格一致,后续接 apperror 时改一行即可

期间踩到的一个坑(已修):
- 第一版 fake ListByVehicle 不排序,Statistics 倒序迭代拿到错误顺序,
  mileage 算成负 → 全部回 0。修法:fake 加上 sort.Slice DESC,与真 repo 对齐

验证:
  go vet ./...   0 issues
  go test ./pkg/decimal ./internal/service
    ok  pkg/decimal     22 子测试通过
    ok  internal/service  5 测试通过

未做(留待后续):
- handler 单测(纯 HTTP 表层,可加,目前 smoke.ps1 已覆盖)
- repository 单测(需要 sqlite,end-to-end smoke 已经覆盖)
- CI 接入(留到 Phase 1.5 之后用 GitHub Actions / Gitea Actions)
2026-09-13 16:15:48 +08:00
KennethCheng df5db7bc36 feat(backend): service 层与 DTO,核心计算逻辑落位
Phase 1.3a。Phase 1.2 留的 repo 现在有了真正的业务出口,Phase 1.3b 紧接
handler / router 把 HTTP 接进来,业务就能跑通。

新增:
- pkg/decimal/money.go
  * PricePerLiter(total, liters)   服务端实时算实际油价,落库
  * ConsumptionL100km(l, mileage)  百公里油耗,只用于 is_full 序列
  * CostPerKm(amount, mileage)     每公里成本
  * Mileage(cur, prev)             行驶里程,负数 / 零视为无效
  * AvgFloat64(xs)                 求平均,空切片返回 0
  全部走 shopspring/decimal,避免 float64 累计误差

- internal/dto/dto.go
  * VehicleCreate / VehicleUpdate (patch 语义,*T 表示可选)
  * RefuelCreate / RefuelUpdate
  入参校验走 gin-validator 的 tag:required / gte / gt / max
  (Liters > 0、TotalAmount >= 0、Odometer >= 0 与 plan §16 一致)

- internal/service/vehicle.go
  * Create 时若 default_vehicle=true,事务内先 ClearDefault 再 Insert,
    避免出现两个默认车辆
  * Update 同样事务化 default 切换
  * SetDefault 是显式接口,业务上"切默认车"是常用操作
  全部错误用 apperror 包成 NotFound / InvalidArg / Internal

- internal/service/refuel_record.go
  * Create:校验车辆存在 + Liters > 0 + TotalAmount >= 0,服务端
    实时计算 price_per_liter,RefuelTime 统一转 UTC 存库
  * Update:patch 语义,liters / total_amount 任一变更都重新算
    price_per_liter(否则历史单价会失真)
  * Statistics(单车):返回 累计次数 / 累计升数 / 累计金额 / 平均油价 /
    标准百公里油耗 / 每公里成本 / 最近一次加油
    关键实现:仅在"连续两次 is_full=true"之间采油耗样本,
    半箱油 / 部分加油记录不会污染标准油耗 ——
    这条规则直接来自 plan §6.3 与 §19 验收要求

业务规则(AGENTS.md 强约束):
  车辆名称 / 能源类型 不允许为空(trim 后空字符串也拒)
  加油量 > 0、总金额 >= 0、里程 >= 0 都在 service 入参立即校验
  RefuelTime 统一 UTC 存库,展示按本地时区格式化
  默认车辆唯一,切换走事务,杜绝"两个默认"

未做(留给 Phase 1.3b 下一个 commit):
- HTTP handler / router / main 装配
- 单元测试(本文件不含测试,等所有 service 稳定后单独提一个测试 commit)
- Dashboard / 统计 API(基础 Statistics 已就绪,Dashboard endpoint
  留给 Phase 1.3b 末尾)

验证:
  go mod tidy    all modules verified
  go vet ./...   0 issues
  go build       25.9 MB binary
2026-09-13 16:06:21 +08:00
KennethCheng ca9831a050 feat(backend): scaffold go module with config, error, middleware, and health endpoint
Phase 1 of FuelLog backend bootstrap. Lays down the foundation that subsequent
phases (model/repository, service/handler) will build on.

What's in:
- go.mod / go.sum: Go 1.22 module, deps:
  * gin-gonic/gin v1.10.0      HTTP framework
  * glebarez/sqlite v1.11.0    pure-Go SQLite (no CGO, friendly to Windows + Docker)
  * gorm.io/gorm v1.25.12      ORM (will be wired in Phase 1.2)
  * shopspring/decimal v1.4.0  amount precision
  * joho/godotenv v1.5.1       .env loader
- cmd/server/main.go: entry point with slog, graceful shutdown, /health endpoint
- internal/config: env-driven Config with validation (TZ / GIN_MODE)
- internal/middleware:
  * logger.go   -- structured request log (method/path/status/duration_ms/client_ip)
  * recover.go  -- panic capture to unified 500 response + stack to log
  * cors.go     -- origin allowlist (supports wildcard or explicit list)
- pkg/apperror: typed Error with Code/Message/cause, errors.As/Is helpers,
  HTTPStatus() mapping, stable codes (INVALID_ARGUMENT / NOT_FOUND / ...)

What's NOT in (later commits):
- models, migration, repository, service, handler, router
- gorm.Open + AutoMigrate wiring (next commit)
- API smoke tests (after CRUD is up)

Verified locally:
  go mod tidy        OK
  go vet ./...       0 issues
  go build           12.8MB exe in fuellog-api/bin/server.exe
  smoke test         GET /health -> 200 {"status":"ok","time":"..."}
                      GET /api/vehicles -> 404 (route not yet registered, expected)

Defender note: built-in Defender on this Windows host quarantines the freshly
built Go binary under %LOCALAPPDATA%\\Temp\\go-build* as ThreatID 2147738096.
Workaround: GOTMPDIR=.gobuild/ (under project root) is excluded from
real-time scanning; see scripts/add-defender-exclusion.ps1.
2026-09-13 15:55:58 +08:00