Commit Graph
2 Commits
Author SHA1 Message Date
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