Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions cmd/server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,7 @@ func main() {
// 乘客認證:註冊/登入(line_user_id + 密碼 JWT)
customerRegistry := service.NewCustomerRegistry(customerRepo)
customerHandler := handler.NewCustomerHandler(customerRegistry, cfg.JWTSecret, cfg.JWTExpiryHours)
customerHandler.SetFeeSettings(feeSettings) // P5:乘客可讀的唯讀費率(白名單輸出)

// Routes
r.GET("/healthz", healthHandler.Healthz)
Expand All @@ -204,6 +205,7 @@ func main() {
customerAuthed.Use(middleware.CustomerAuth(cfg.JWTSecret))
{
customerAuthed.POST("/rides", rideHandler.Create)
customerAuthed.GET("/customer/fees", customerHandler.Fees)
customerAuthed.GET("/customer/rides/active", rideHandler.ActiveByCustomer)
customerAuthed.GET("/customer/rides/:id", rideHandler.GetByCustomer)
customerAuthed.POST("/rides/:id/cancel-by-customer", rideHandler.CancelByCustomer)
Expand Down
5 changes: 5 additions & 0 deletions db/migrations/000019_add_pet_cleaning_fee.down.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
-- DROP COLUMN 會自動連帶刪除依賴該欄位的 CHECK;DROP CONSTRAINT 是明示意圖(IF EXISTS,無害)。
ALTER TABLE daily_driver_earnings DROP COLUMN IF EXISTS cleaning_fee_cents;
ALTER TABLE rides DROP COLUMN IF EXISTS cleaning_fee_cents;
ALTER TABLE fleet_settings DROP CONSTRAINT IF EXISTS chk_fleet_settings_pet_cleaning_fee_bps;
ALTER TABLE fleet_settings DROP COLUMN IF EXISTS pet_cleaning_fee_bps;
20 changes: 20 additions & 0 deletions db/migrations/000019_add_pet_cleaning_fee.up.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
-- 寵物用車清潔費(O6):乘客指定 pet 車種的行程,在車資之上加收清潔費。
-- 判斷依據是 rides.required_vehicle_type(乘客要什麼車),**不是** drivers.vehicle_type
-- (司機開什麼車)——乘客沒指定寵物車卻剛好被派到寵物車司機時不得加收。

-- 費率:比照 lost_item_fee_bps 的 bps 慣例。上限 30% 寫進 CHECK,不只靠 API 驗證:
-- 這是乘客實際被收的錢,設定寫錯的後果是超收。
ALTER TABLE fleet_settings ADD COLUMN IF NOT EXISTS pet_cleaning_fee_bps INT NOT NULL DEFAULT 0;
ALTER TABLE fleet_settings DROP CONSTRAINT IF EXISTS chk_fleet_settings_pet_cleaning_fee_bps;
ALTER TABLE fleet_settings ADD CONSTRAINT chk_fleet_settings_pet_cleaning_fee_bps
CHECK (pet_cleaning_fee_bps >= 0 AND pet_cleaning_fee_bps <= 3000);

-- 快照:完成時定格寫入(比照 fare/commission/net 的費率快照制,000012)。
-- nullable——未完成/取消/舊資料為 NULL,與既有計費欄位語意一致。
ALTER TABLE rides ADD COLUMN IF NOT EXISTS cleaning_fee_cents BIGINT;

-- 報表分項(F5/F6/F7 的一致性延伸):
-- 「營業額」(revenue_cents) 維持只含車資,清潔費另立分項——它是清潔成本補償、不是營收,
-- 且不計入抽成(拍板 2026-07-16)。NOT NULL DEFAULT 0:彙總欄位一律有值,
-- 報表 SUM 不必處理 NULL。
ALTER TABLE daily_driver_earnings ADD COLUMN IF NOT EXISTS cleaning_fee_cents BIGINT NOT NULL DEFAULT 0;
70 changes: 64 additions & 6 deletions docs/TODO.md
Original file line number Diff line number Diff line change
Expand Up @@ -439,7 +439,52 @@
司機列表顯示車種車牌;是否需要「車輛審核」狀態(pending/approved)待拍板——
若需要,O3 的 gate 條件要改成「已審核」而非「有填」。

- [ ] **O6. 寵物用車清潔費** ✅ **已定案(2026-07-16):比例加收,上限 30%**
- [x] **O6. 寵物用車清潔費** ✅ **已實作(2026-07-17,migration `000019`)**(定案 2026-07-16:比例加收,上限 30%)

**計費**(`FeeSettings.Quote`):簽名改為 `Quote(distanceM int, requiredVehicleType string) RideQuote`。
**刻意改簽名而不留舊 wrapper**——留了就是留一個「忘了帶車種=靜靜不收清潔費」的陷阱;
改簽名讓漏改的呼叫點直接編譯不過(實測產品碼只有 `tracking.go` 一處,測試三處)。
```
cleaning_fee = floorNtd(fare × pet_cleaning_fee_bps / 10000) // 僅乘客指定 pet;捨去(利乘客)
commission = floorNtd(fare × commission_bps / 10000) // 基準只有 fare,清潔費不計入抽成
driver_net = fare − commission + cleaning_fee // 清潔費全額歸司機
```
**判斷依據是 `rides.required_vehicle_type`,不是 `drivers.vehicle_type`**——
`Quote` 只吃乘客指定的車種,司機車種根本傳不進去(型別層面就擋掉誤用)。

**報表分項(與計費同批,不可分開上線)**:`daily_driver_earnings` 加 `cleaning_fee_cents`;
`RollupRideDay`/`MonthlyDriverStats`/`DriverMonthlyEarnings` 三段 SQL 同步。
營業額(`revenue_cents`)**維持只含車資**;應付總公司=手續費+月會費,**不受清潔費影響**。
**為什麼不能分兩批**:`net_cents` 來自 `driver_net_amount_cents`,該欄已含清潔費 →
不同步加分項欄,司機收入頁的「營業額 − 手續費」就對不上實得(差額正是清潔費),
破壞先前打通的三端對帳。等式因此改為 **營業額 − 手續費 + 清潔費 = 實得**(測試直接釘住這條式子)。

**資料**:`fleet_settings.pet_cleaning_fee_bps`(CHECK `0..3000`,上限進 DB 不只靠 API——
這是乘客實際被收的錢,寫錯就是超收)、`rides.cleaning_fee_cents`(nullable,完成時定格)、
`daily_driver_earnings.cleaning_fee_cents`(NOT NULL DEFAULT 0,彙總欄一律有值)。
非寵物車行程寫 **0 而非 NULL**:「這趟沒加收」與「舊資料沒這個概念」是兩件事。

**乘客端可見**:`ride.completed` payload 加 `cleaning_fee_cents`,**只在 >0 時帶**——
帶 0 會讓 App 顯示一列「清潔費 NT$0」。

**驗收**:`go build`/`vet`/`gofmt` 綠。
單元:清潔費算式(釘住「不計入抽成」的具體數字——正確 2700、誤把清潔費計入基準則為 3300)、
只看乘客指定車種(`''`/sedan/suv/van7/accessible 皆不加收)、費率 0 不加收、捨去到整數元、
上限 `MaxPetCleaningFeeBps`、**P5 白名單**(`CustomerJSON` 只有一個欄位,內部費率一個都不能出現)。
整合(真 PostGIS + Redis):`TestComplete_指定寵物車落帳清潔費`(定格寫入+payload 分項)、
**`TestComplete_寵物車司機載到未指定的乘客不加收`**(最容易寫錯的一條)、
`TestCleaningFeeReports`(報表分項與等式)、`TestFleetSettingsPetCleaningFeeCap`(DB CHECK 擋 3001/負值)、
`TestPetCleaningFeeMigrationReversible`。
**反向驗證**:清潔費計入抽成基準 → 手續費變 3300,FAIL;`CustomerJSON` 改回 `JSON()` →
手續費/月會費整組外洩,FAIL;`Quote` 改吃司機車種 → 未指定的乘客被加收,FAIL。
**未驗**:docker compose 全服務 live E2E。

**下游待同步(本 repo 之外,兩端都會「少一個分項」而非算錯)**:
- admin:費率設定頁加 `pet_cleaning_fee_bps`;月報表加清潔費分項欄(`total_cleaning_fee_cents`)。
- App:完成卡分項顯示(`CompletedRideSummary` 加 `cleaningFeeCents`);
司機收入頁改用「營業額 − 手續費 + 清潔費 = 實得」(`GET /api/driver/earnings` 已回 `total_cleaning_fee_cents`)。

原始定案內容如下(保留供對照):
**規則** ✅ 觸發條件已拍板(2026-07-16):**依「乘客指定的車種」加收,不是依司機的車種**——
乘客叫車時指定 `pet`(寵物用車)的行程,才在車資之上加收清潔費(見 **P. 乘客指定車種**)。
比例由後台設定,**硬上限 30%**(超過一律拒絕)。
Expand Down Expand Up @@ -607,7 +652,17 @@
3. 實作時機:與 P3 同一批(P3 讓「找不到」變得可能發生,兩者不可分開上線——
只上 P3 不上 P4,乘客會收到誤導性的泛用取消訊息)。

- [ ] **P5. 乘客可讀的唯讀費率端點** ✅ **已定案(2026-07-16,採建議方案):新增專用端點**
- [x] **P5. 乘客可讀的唯讀費率端點** ✅ **已實作(2026-07-17)**(定案 2026-07-16:新增專用端點)
**`GET /api/customer/fees`**(customer JWT,唯讀)→ 目前只回 `pet_cleaning_fee_bps`。
回的是 `FeeSettings.CustomerJSON()`——**另建的白名單 map,不是把 admin 的 `JSON()` 過濾**。
理由如定案所述:過濾式寫法日後新增內部費率欄位時容易忘了濾,白名單預設什麼都不給。
讀記憶體快取(與 F4 同源),無額外 DB 負擔。
掛既有 `customerAuthed` 群組(`middleware.CustomerAuth`)。
**驗收**:`TestCustomerJSON白名單` 逐一斷言 `commission_bps`/`monthly_membership_fee_cents`/
起步價/每公里/最低車資/遺失物費率**皆不得出現**,且欄位總數為 1。
**反向驗證**:改成 `return s.JSON()` → 測試抓到 `commission_bps` 外洩,FAIL。

原始定案內容如下(保留供對照):
**`GET /api/customer/fees`**(customer JWT,唯讀):只回乘客該知道的欄位——
`pet_cleaning_fee_bps`(寵物車清潔費%);日後乘客需要知道的費率(如起步價,若要做預估)再逐一加入。
**白名單輸出,絕不可外洩** `commission_bps`(手續費)/`monthly_membership_fee_cents`(月會費)
Expand Down Expand Up @@ -645,10 +700,13 @@
清潔費依乘客指定車種、上限 30%、**不計入抽成**/不降級+取消原因明確化/customer fees 端點/
**電話明碼、僅該趟乘客可見**)——**N、O、P 規格完備,可開始實作**,
建議順序:O1→O2→O3(車輛地基)→ P1→P2→P3+P4(車種)→ O6+P5(清潔費)→ O4/O7(乘客可見)→ N(多停靠點,最大塊)。
**進度:O1 ✅(2026-07-16)、O2 ✅、O3 ✅、P1 ✅、P2 ✅、P3 ✅、P4 ✅(皆 2026-07-17)
→ **乘客指定車種整條鏈路已通**:建單帶車種 → 只派同車種 → 找不到就明確取消並帶機器可讀原因。
下一項建議 **O6+P5(清潔費)**——P 章節只剩 P5(`GET /api/customer/fees`),
而 O6 的觸發條件(依 `rides.required_vehicle_type` 是否為 `pet`)現在已經存在了。**
**進度:O1 ✅(2026-07-16)、O2 ✅、O3 ✅、P1 ✅、P2 ✅、P3 ✅、P4 ✅、O6 ✅、P5 ✅(皆 2026-07-17)
→ **P 章節全數完成**;O 章節只剩 **O4(乘客端可見車輛資訊)/O5(admin 呈現,可選)/
O7(車輛快照+司機電話+留言板)**。
寵物車清潔費整條鏈路已通:乘客指定 pet → 只派寵物車 → 完成時依**乘客指定的車種**加收 →
報表分項(營業額不含、抽成不含、全額歸司機)→ `ride.completed` 帶分項 → 乘客可查費率。
下一項建議 **O4+O7**(都是「乘客端可見的司機/車輛資訊」,共用 `ride.accepted` payload 與
rides 快照欄,分開做會改到同一批地方兩次)。**

計費地基 **F1–F8+F3 里程退路+F9-1~F9-6+M 整數台幣 已全數合併進 main**,三端對帳與 F3/F9-3/F9-4 皆 docker E2E 驗過。
其餘皆屬「量體上升後才需」的大資料量最佳化,勿過早做:
Expand Down
5 changes: 4 additions & 1 deletion internal/handler/admin.go
Original file line number Diff line number Diff line change
Expand Up @@ -390,14 +390,17 @@ func (h *AdminHandler) PutFeeSettings(c *gin.Context) {
CommissionBps *int64 `json:"commission_bps"`
MonthlyMembershipFeeCents *int64 `json:"monthly_membership_fee_cents"`
LostItemFeeBps *int64 `json:"lost_item_fee_bps"`
// PetCleaningFeeBps 寵物車清潔費%(O6):硬上限 3000(30%),超過回 400。
PetCleaningFeeBps *int64 `json:"pet_cleaning_fee_bps"`
}
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "參數錯誤"})
return
}
actorID := middleware.AdminIDFromCtx(c)
if err := h.feeSettings.Update(req.BaseFareCents, req.PerKmFareCents, req.MinFareCents,
req.CommissionBps, req.MonthlyMembershipFeeCents, req.LostItemFeeBps, &actorID); err != nil {
req.CommissionBps, req.MonthlyMembershipFeeCents, req.LostItemFeeBps,
req.PetCleaningFeeBps, &actorID); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
Expand Down
21 changes: 21 additions & 0 deletions internal/handler/customer.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
// CustomerHandler 乘客註冊與登入
type CustomerHandler struct {
customers *service.CustomerRegistry
feeSettings *service.FeeSettings
jwtSecret string
jwtExpiryHours int
}
Expand All @@ -21,6 +22,26 @@ func NewCustomerHandler(customers *service.CustomerRegistry, jwtSecret string, j
return &CustomerHandler{customers: customers, jwtSecret: jwtSecret, jwtExpiryHours: jwtExpiryHours}
}

// SetFeeSettings 注入費率設定(供 GET /api/customer/fees);可選,比照 AdminHandler.SetFeeSettings。
func (h *CustomerHandler) SetFeeSettings(fees *service.FeeSettings) {
h.feeSettings = fees
}

// Fees GET /api/customer/fees(customer JWT,唯讀)——乘客該知道的費率(P5)。
// 乘客在「選擇車種」UI 呼叫它,選寵物用車的當下就顯示「將加收清潔費 X%」,
// 而不是等行程完成才知道。
//
// **白名單輸出**:回 FeeSettings.CustomerJSON(),不是把 admin 的 JSON() 過濾——
// commission_bps(手續費)與 monthly_membership_fee_cents(月會費)是內部費率,絕不可外洩給乘客。
// 讀記憶體快取(與 F4 同源),無額外 DB 負擔。
func (h *CustomerHandler) Fees(c *gin.Context) {
if h.feeSettings == nil {
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "費率查詢未啟用"})
return
}
c.JSON(http.StatusOK, h.feeSettings.CustomerJSON())
}

func (h *CustomerHandler) issueToken(id int64) (string, error) {
return auth.GenerateToken("customer", id, h.jwtSecret, time.Duration(h.jwtExpiryHours)*time.Hour)
}
Expand Down
33 changes: 19 additions & 14 deletions internal/model/models.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,11 +157,14 @@ type Ride struct {
// 這是清潔費(O6)加收與否的判斷依據——依**乘客要的車種**,不是司機開的車種。
RequiredVehicleType string `gorm:"column:required_vehicle_type;not null;default:''" json:"required_vehicle_type"`
// 計費欄位:完成時定格寫入(費率快照制),一律以「分」儲存;未完成/取消為 nil。
FareAmountCents *int64 `gorm:"column:fare_amount_cents" json:"fare_amount_cents"`
CommissionAmountCents *int64 `gorm:"column:commission_amount_cents" json:"commission_amount_cents"`
DriverNetAmountCents *int64 `gorm:"column:driver_net_amount_cents" json:"driver_net_amount_cents"`
CreatedAt time.Time `gorm:"not null" json:"created_at"`
UpdatedAt time.Time `gorm:"not null" json:"updated_at"`
FareAmountCents *int64 `gorm:"column:fare_amount_cents" json:"fare_amount_cents"`
CommissionAmountCents *int64 `gorm:"column:commission_amount_cents" json:"commission_amount_cents"`
DriverNetAmountCents *int64 `gorm:"column:driver_net_amount_cents" json:"driver_net_amount_cents"`
// CleaningFeeCents 寵物車清潔費(O6):僅 RequiredVehicleType == 'pet' 的行程才有值。
// 不計入抽成、全額歸司機(DriverNetAmountCents 已含它);報表的「營業額」不含它。
CleaningFeeCents *int64 `gorm:"column:cleaning_fee_cents" json:"cleaning_fee_cents"`
CreatedAt time.Time `gorm:"not null" json:"created_at"`
UpdatedAt time.Time `gorm:"not null" json:"updated_at"`
}

func (Ride) TableName() string {
Expand All @@ -170,15 +173,17 @@ func (Ride) TableName() string {

// FleetSettings 費率設定(單列,id 固定為 1)。金額以「分」儲存,手續費以 bps 儲存。
type FleetSettings struct {
ID int16 `gorm:"primaryKey" json:"-"`
BaseFareCents int64 `gorm:"column:base_fare_cents;not null" json:"base_fare_cents"`
PerKmFareCents int64 `gorm:"column:per_km_fare_cents;not null" json:"per_km_fare_cents"`
MinFareCents int64 `gorm:"column:min_fare_cents;not null" json:"min_fare_cents"`
CommissionBps int `gorm:"column:commission_bps;not null" json:"commission_bps"`
MonthlyMembershipFeeCents int64 `gorm:"column:monthly_membership_fee_cents;not null" json:"monthly_membership_fee_cents"`
LostItemFeeBps int `gorm:"column:lost_item_fee_bps;not null" json:"lost_item_fee_bps"`
UpdatedBy *int64 `gorm:"column:updated_by" json:"updated_by"`
UpdatedAt time.Time `gorm:"column:updated_at;not null" json:"updated_at"`
ID int16 `gorm:"primaryKey" json:"-"`
BaseFareCents int64 `gorm:"column:base_fare_cents;not null" json:"base_fare_cents"`
PerKmFareCents int64 `gorm:"column:per_km_fare_cents;not null" json:"per_km_fare_cents"`
MinFareCents int64 `gorm:"column:min_fare_cents;not null" json:"min_fare_cents"`
CommissionBps int `gorm:"column:commission_bps;not null" json:"commission_bps"`
MonthlyMembershipFeeCents int64 `gorm:"column:monthly_membership_fee_cents;not null" json:"monthly_membership_fee_cents"`
LostItemFeeBps int `gorm:"column:lost_item_fee_bps;not null" json:"lost_item_fee_bps"`
// PetCleaningFeeBps 寵物車清潔費%(O6):上限 3000(30%),由 DB CHECK 與 validateFeeSettings 雙重把關。
PetCleaningFeeBps int `gorm:"column:pet_cleaning_fee_bps;not null" json:"pet_cleaning_fee_bps"`
UpdatedBy *int64 `gorm:"column:updated_by" json:"updated_by"`
UpdatedAt time.Time `gorm:"column:updated_at;not null" json:"updated_at"`
}

func (FleetSettings) TableName() string {
Expand Down
54 changes: 54 additions & 0 deletions internal/repository/migrate_handle_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package repository

import (
"context"
"testing"

"github.com/golang-migrate/migrate/v4"
_ "github.com/golang-migrate/migrate/v4/database/postgres"
_ "github.com/golang-migrate/migrate/v4/source/file"
tcpostgres "github.com/testcontainers/testcontainers-go/modules/postgres"
gormpostgres "gorm.io/driver/postgres"
"gorm.io/gorm"
)

// newMigrateHandle 起真 PostGIS 容器、跑完整 migration,回傳 DB 連線與 migrate handle。
// 給「可逆性測試」用——它們需要 migrate handle 才能 down 到指定版本,
// 而 newMigratedTestDB 只給 DB。Docker 不可用時跳過。
//
// 可逆性測試請以**版本**表達意圖(m.Migrate(N)),不要用 m.Steps(-1):
// 後者卸的是最新的那個 migration,一旦有人在你之後新增 migration,
// 測試會安靜地改去驗別人的 down,你的 migration 反而失去覆蓋(O1 踩過,見 000018)。
func newMigrateHandle(t *testing.T) (*gorm.DB, *migrate.Migrate) {
t.Helper()
ctx := context.Background()
container, err := tcpostgres.Run(ctx, "postgis/postgis:16-3.4",
tcpostgres.WithDatabase("test"),
tcpostgres.WithUsername("test"),
tcpostgres.WithPassword("test"),
tcpostgres.BasicWaitStrategies(),
)
if err != nil {
t.Skipf("略過整合測試(Docker/testcontainers 不可用): %v", err)
}
t.Cleanup(func() { _ = container.Terminate(ctx) })

connStr, err := container.ConnectionString(ctx, "sslmode=disable")
if err != nil {
t.Fatalf("取得連線字串失敗: %v", err)
}

m, err := migrate.New("file://../../db/migrations", connStr)
if err != nil {
t.Fatalf("建立 migrate 失敗: %v", err)
}
if err := m.Up(); err != nil && err != migrate.ErrNoChange {
t.Fatalf("up 失敗: %v", err)
}

db, err := gorm.Open(gormpostgres.Open(connStr), &gorm.Config{})
if err != nil {
t.Fatalf("連線失敗: %v", err)
}
return db, m
}
2 changes: 1 addition & 1 deletion internal/repository/report_billing_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ func TestCompleteRideSnapshotsFare(t *testing.T) {
}

fare, commission, net := int64(18500), int64(2700), int64(15800)
if err := rides.CompleteRide(ride.ID, 5000, &fare, &commission, &net); err != nil {
if err := rides.CompleteRide(ride.ID, 5000, &fare, &commission, &net, nil); err != nil {
t.Fatalf("CompleteRide 失敗:%v", err)
}

Expand Down
Loading
Loading