From 208336299a406331e1755b0c1d96b8f04433eb8a Mon Sep 17 00:00:00 2001 From: awei Date: Thu, 23 Jul 2026 07:55:17 +0800 Subject: [PATCH 1/2] =?UTF-8?q?feat(R):=20=E5=BB=BA=E5=96=AE=E5=89=8D?= =?UTF-8?q?=E8=BB=8A=E8=B3=87=E9=A0=90=E4=BC=B0=E5=A0=B1=E5=83=B9=20API?= =?UTF-8?q?=EF=BC=88=E6=87=B8=E8=80=8C=E6=9C=AA=E6=B1=BA=20#1=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit POST /api/customer/rides/estimate(customer JWT,純唯讀、不建單、不寫 DB): 以全程規劃路線(起點→各停靠點→終點,含繞路)試算車資,讓乘客建單前就看到 預估,不必到行程結束才知道多少錢。多停靠點行程放大了「先搭後知價」的痛點, 這是本題主因。是預估不是定價——計費仍在完成時依實際行駛路線定格。 - service.EstimateService{osrm, fees}:與完成計費共用同一份 FeeSettings.Quote, 預估與實收落在同一套費率規則,差異只來自「規劃路線 vs 實際行駛路線」。 - 距離走既有 osrm.RouteVia(與 N5 計費同一支多點 API);OSRM 掛掉時內部退回 逐段 haversine,故預估永遠算得出近似值,不因路網引擎不可用就卡住乘客。 - 沿用 validateStops/座標驗證,不另造一套。目的地座標必填(沒終點無法路由); 車種選填(寵物車含清潔費)。多停靠點時全部站入路線(預估階段沒人被跳過)。 - 白名單輸出:fare/cleaning_fee/total/distance/duration——不回 commission/ driver_net 等內部費率(比照 FeeSettings.CustomerJSON)。 - 錯誤:座標/車種/停靠點填錯→400(沿用 createStatusForErr);未就緒→503。 驗收:service 8 案+handler 2 案綁定/授權邊界皆綠;全 repo go test ./... 無 FAIL。 尚未做:docker live E2E 對帳「預估 vs 完成實收」差異合理。 Co-Authored-By: Claude Opus 4.8 --- cmd/server/main.go | 4 +- docs/TODO.md | 26 ++++ internal/handler/estimate_test.go | 77 ++++++++++++ internal/handler/ride.go | 74 ++++++++++++ internal/service/estimate.go | 123 +++++++++++++++++++ internal/service/estimate_test.go | 192 ++++++++++++++++++++++++++++++ 6 files changed, 495 insertions(+), 1 deletion(-) create mode 100644 internal/handler/estimate_test.go create mode 100644 internal/service/estimate.go create mode 100644 internal/service/estimate_test.go diff --git a/cmd/server/main.go b/cmd/server/main.go index 9bfff13..6739c91 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -180,7 +180,8 @@ func main() { driverHandler := handler.NewDriverHandler(trackingService, driverRegistry, rideQueryService, cfg.JWTSecret, cfg.JWTExpiryHours) driverHandler.SetEarnings(reportRepo, feeSettings) rideHandler := handler.NewRideHandler(dispatchService, trackingService, rideQueryService, rideService) - rideHandler.SetStops(rideStopService) // N7:司機標記到達/跳過停靠點 + rideHandler.SetStops(rideStopService) // N7:司機標記到達/跳過停靠點 + rideHandler.SetEstimate(service.NewEstimateService(osrm, feeSettings)) // 懸而未決 #1:建單前車資預估 deviceTokenHandler := handler.NewDeviceTokenHandler(deviceTokenService) wsHandler := handler.NewWSHandler(hub, cfg.JWTSecret, cfg.WSWriteWaitSec, cfg.WSPongWaitSec, cfg.WSMaxMessageBytes) chatHandler := handler.NewChatHandler(chatService) @@ -230,6 +231,7 @@ func main() { customerAuthed.Use(middleware.CustomerAuth(cfg.JWTSecret)) { customerAuthed.POST("/rides", rideHandler.Create) + customerAuthed.POST("/customer/rides/estimate", rideHandler.EstimateFare) customerAuthed.GET("/customer/fees", customerHandler.Fees) customerAuthed.GET("/customer/rides", rideHandler.HistoryByCustomer) customerAuthed.GET("/customer/rides/active", rideHandler.ActiveByCustomer) diff --git a/docs/TODO.md b/docs/TODO.md index 3b12ef7..ba4e79e 100644 --- a/docs/TODO.md +++ b/docs/TODO.md @@ -865,6 +865,32 @@ 驗收:`TestDriverProfile_*`(授權邊界/參數驗證/`改電話不重置車輛審核` 走真 DB)。 App 端對應:司機車輛設定頁加聯絡電話欄(fleet-app 同批)。 +## 💰 R. 建單前車資預估報價 API(2026-07-23) + +> App 端「懸而未決 #1」拍板:投資一支報價 API,讓乘客在**建單前**看到預估車資, +> 不必到行程結束才知道多少錢——多停靠點行程(N5「車資=全程實際路線含繞路」)放大了 +> 「先搭後知價」的痛點,這是本題主因。**是預估不是定價**:計費仍在完成時依實際行駛路線定格。 + +- [x] **`POST /api/customer/rides/estimate`(customer JWT,純唯讀)** ✅ 2026-07-23 + 新 `service.EstimateService{osrm, fees}`:以全程規劃路線(起點 → 各停靠點 → 終點,**含繞路**) + 算里程,**與完成計費共用同一份 `FeeSettings.Quote`**——預估與實收落在同一套費率規則, + 差異只來自「規劃路線 vs 實際行駛路線」(繞路、跳過站、GPS 軌跡)。 + - 距離走既有 `osrm.RouteVia`(與 N5 計費同一支多點路線 API);OSRM 掛掉時內部退回逐段 + haversine,故**預估永遠算得出一個近似值**,不因路網引擎暫時不可用就讓乘客卡住。 + - 輸入形狀與建單相同,**沿用** `validateStops`/`sortStopsBySeq`/座標驗證——不另造一套 + 驗證邏輯。**目的地座標必填**(沒終點無法路由);車種選填(寵物車含清潔費)。 + - **多停靠點:全部停靠點都入路線**(預估階段還沒有人被跳過),與計費的 `billableStopPoints` + (排除已跳過者)刻意不同:那是實際計費,這是全程預估。 + - 回傳**白名單欄位**:`fare_cents`/`cleaning_fee_cents`/`total_cents`/`distance_m`/ + `duration_sec`——**不回** `commission`/`driver_net` 等內部費率(比照 `FeeSettings.CustomerJSON`)。 + - 錯誤對應:座標/車種/停靠點填錯 → 400(沿用建單 `createStatusForErr`); + 服務未就緒(未注入 osrm/fees)→ 503。 + - 驗收:`internal/service/estimate_test.go` 8 案(單點/多停靠點全程入路線/寵物清潔費/ + 缺目的地 400/非法車種/min_fare 下限/未成對停靠點/未就緒)+ + `internal/handler/estimate_test.go` 2 案(授權 401/403、綁定 400、未就緒 503)。 + - App 端對應:叫車表單顯示預估卡(fleet-app 同批),失敗靜默不擋叫車。 + - **尚未做**:docker compose live E2E 對帳「預估 vs 完成實收」的差異合理,留待下次。 + ## 下次任務 **新需求(2026-07-16 加入,尚未實作,皆需後端地基先行)**: diff --git a/internal/handler/estimate_test.go b/internal/handler/estimate_test.go new file mode 100644 index 0000000..17f2406 --- /dev/null +++ b/internal/handler/estimate_test.go @@ -0,0 +1,77 @@ +package handler + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/gin-gonic/gin" + + "line-fleet-dispatch/internal/auth" + "line-fleet-dispatch/internal/middleware" + osrmclient "line-fleet-dispatch/internal/osrm" + "line-fleet-dispatch/internal/service" +) + +// 驗 RideHandler.EstimateFare 的授權/綁定/未就緒邊界(401/403/400/503)。 +// 車資實算與 200 成功值由 service 層單元測試(estimate_test.go)與 docker e2e 覆蓋—— +// 這裡只確認 HTTP 邊界,用 fees=nil 的 EstimateService(estimate 非 nil 但呼叫時回未就緒)。 +func setupEstimateRouter(withEstimate bool) *gin.Engine { + gin.SetMode(gin.TestMode) + h := NewRideHandler(nil, nil, nil, service.NewRideService(nil, nil, nil, nil)) + if withEstimate { + // fees=nil → Estimate() 回 ErrEstimateUnavailable(503);足以測綁定/授權路徑。 + h.SetEstimate(service.NewEstimateService(osrmclient.NewClient("http://127.0.0.1:0"), nil)) + } + r := gin.New() + r.POST("/api/customer/rides/estimate", middleware.CustomerAuth("s"), h.EstimateFare) + return r +} + +func postEstimate(t *testing.T, r *gin.Engine, token, body string) int { + t.Helper() + w := httptest.NewRecorder() + req, _ := http.NewRequest("POST", "/api/customer/rides/estimate", strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + if token != "" { + req.Header.Set("Authorization", "Bearer "+token) + } + r.ServeHTTP(w, req) + return w.Code +} + +func TestEstimateFare_授權與綁定邊界(t *testing.T) { + r := setupEstimateRouter(true) + ctok, _ := auth.GenerateToken("customer", 9, "s", time.Hour) + dtok, _ := auth.GenerateToken("driver", 7, "s", time.Hour) + + // 無 token → 401(中介層攔截) + if code := postEstimate(t, r, "", `{"pickup_lat":25,"pickup_lng":121}`); code != http.StatusUnauthorized { + t.Fatalf("無 token 預期 401,得到 %d", code) + } + // driver token → 403(角色不符) + if code := postEstimate(t, r, dtok, `{"pickup_lat":25,"pickup_lng":121}`); code != http.StatusForbidden { + t.Fatalf("driver token 預期 403,得到 %d", code) + } + // customer token + 壞 JSON → 400(綁定失敗即返回,未觸及 Estimate) + if code := postEstimate(t, r, ctok, `{bad`); code != http.StatusBadRequest { + t.Fatalf("壞 JSON 預期 400,得到 %d", code) + } + // customer token + 合法 JSON、但服務未就緒(fees=nil)→ 503 + if code := postEstimate(t, r, ctok, + `{"pickup_lat":25.03,"pickup_lng":121.56,"dropoff_lat":25.05,"dropoff_lng":121.52}`); code != http.StatusServiceUnavailable { + t.Fatalf("服務未就緒預期 503,得到 %d", code) + } +} + +// 未呼叫 SetEstimate(estimate==nil)→ handler 早退 503,不 panic。 +func TestEstimateFare_未啟用回503(t *testing.T) { + r := setupEstimateRouter(false) + ctok, _ := auth.GenerateToken("customer", 9, "s", time.Hour) + if code := postEstimate(t, r, ctok, + `{"pickup_lat":25.03,"pickup_lng":121.56,"dropoff_lat":25.05,"dropoff_lng":121.52}`); code != http.StatusServiceUnavailable { + t.Fatalf("未啟用預期 503,得到 %d", code) + } +} diff --git a/internal/handler/ride.go b/internal/handler/ride.go index 2cd6ec0..8bed144 100644 --- a/internal/handler/ride.go +++ b/internal/handler/ride.go @@ -18,6 +18,7 @@ type RideHandler struct { rides *service.RideQueryService rideService *service.RideService stops *service.RideStopService + estimate *service.EstimateService } func NewRideHandler( @@ -34,6 +35,11 @@ func (h *RideHandler) SetStops(stops *service.RideStopService) { h.stops = stops } +// SetEstimate 注入車資預估服務(建單前預估,懸而未決 #1);可選。 +func (h *RideHandler) SetEstimate(estimate *service.EstimateService) { + h.estimate = estimate +} + // stopStatusForErr 停靠點標記的錯誤對應。 func stopStatusForErr(err error) int { switch { @@ -280,6 +286,74 @@ func createStatusForErr(err error) int { } } +// EstimateFare POST /api/customer/rides/estimate — 乘客建單**前**預估車資(懸而未決 #1)。 +// 純唯讀、不建單。目的地座標必填(沒終點無法算路線);車種選填(寵物車含清潔費); +// 多停靠點時起訖由 stops 推導。輸入形狀與 Create 相同(少了 pickup_address/dropoff_address)。 +func (h *RideHandler) EstimateFare(c *gin.Context) { + if h.estimate == nil { + c.JSON(http.StatusServiceUnavailable, gin.H{"error": "車資預估未啟用"}) + return + } + var req struct { + PickupLat float64 `json:"pickup_lat"` + PickupLng float64 `json:"pickup_lng"` + DropoffLat *float64 `json:"dropoff_lat"` + DropoffLng *float64 `json:"dropoff_lng"` + RequiredVehicleType string `json:"required_vehicle_type"` + Stops []struct { + Seq int `json:"seq"` + Kind string `json:"kind"` + Lat float64 `json:"lat"` + Lng float64 `json:"lng"` + Address string `json:"address"` + PassengerLabel string `json:"passenger_label"` + } `json:"stops"` + } + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "參數錯誤"}) + return + } + stops := make([]service.StopInput, 0, len(req.Stops)) + for _, s := range req.Stops { + stops = append(stops, service.StopInput{ + Seq: s.Seq, + Kind: s.Kind, + Lat: s.Lat, + Lng: s.Lng, + Address: s.Address, + PassengerLabel: s.PassengerLabel, + }) + } + res, err := h.estimate.Estimate(c.Request.Context(), service.EstimateRequest{ + PickupLat: req.PickupLat, + PickupLng: req.PickupLng, + DropoffLat: req.DropoffLat, + DropoffLng: req.DropoffLng, + RequiredVehicleType: req.RequiredVehicleType, + Stops: stops, + }) + if err != nil { + c.JSON(estimateStatusForErr(err), gin.H{"error": err.Error()}) + return + } + c.JSON(http.StatusOK, gin.H{ + "distance_m": res.DistanceM, + "duration_sec": res.DurationSec, + "fare_cents": res.FareCents, + "cleaning_fee_cents": res.CleaningFeeCents, + "total_cents": res.TotalCents, + }) +} + +// estimateStatusForErr 預估錯誤對應 HTTP 狀態碼:服務未就緒回 503, +// 其餘(座標/車種/停靠點填錯)沿用建單的 400 對應。 +func estimateStatusForErr(err error) int { + if errors.Is(err, service.ErrEstimateUnavailable) { + return http.StatusServiceUnavailable + } + return createStatusForErr(err) +} + // ActiveByCustomer GET /api/customer/rides/active — 乘客當前進行中訂單(App 啟動/重連取 ride_id 用) // 無進行中訂單時回 {"ride": null},非錯誤。 func (h *RideHandler) ActiveByCustomer(c *gin.Context) { diff --git a/internal/service/estimate.go b/internal/service/estimate.go new file mode 100644 index 0000000..6baed62 --- /dev/null +++ b/internal/service/estimate.go @@ -0,0 +1,123 @@ +package service + +import ( + "context" + "errors" + + "line-fleet-dispatch/internal/constants" + osrmclient "line-fleet-dispatch/internal/osrm" +) + +// ErrEstimateUnavailable 未注入 OSRM/費率設定時無法計算預估(設定問題,非乘客輸入錯)。 +var ErrEstimateUnavailable = errors.New("車資預估暫時無法使用") + +// EstimateService 乘客建單**前**的車資預估(懸而未決 #1)。 +// +// 純唯讀:不建單、不寫 DB、不派單——單純「以全程規劃路線試算車資」,讓乘客在多停靠點行程 +// 排了一堆繞路之前就先看到大概金額,而不是到行程結束才知道(N5「先搭後知價」的解法)。 +// +// 與完成時計費(TrackingService.Complete)共用同一份 FeeSettings.Quote,確保預估與實收落在 +// **同一套計費規則**上;兩者的差異只來自「規劃路線 vs 實際行駛路線」(繞路、跳過站、GPS 軌跡), +// 這也是為什麼要對乘客標明「預估、實際依行駛路線可能不同」。 +type EstimateService struct { + osrm *osrmclient.Client + fees *FeeSettings +} + +// NewEstimateService 建立預估服務。osrm/fees 皆必要,缺任一則 Estimate 回 ErrEstimateUnavailable。 +func NewEstimateService(osrm *osrmclient.Client, fees *FeeSettings) *EstimateService { + return &EstimateService{osrm: osrm, fees: fees} +} + +// EstimateRequest 預估輸入。座標/車種/停靠點與 CustomerCreateRequest 同形狀, +// 但**目的地座標為必填**——沒有終點座標就算不出路線,也就無法預估 +// (建單時 dropoff 可只給地址字串,那條路徑無座標可路由,本就不該顯示預估)。 +type EstimateRequest struct { + PickupLat, PickupLng float64 + DropoffLat, DropoffLng *float64 + // RequiredVehicleType 選填:''=不指定。指定寵物車(pet)時預估會含清潔費。 + RequiredVehicleType string + // Stops 選填(N3):多乘客/多停靠點。有給時起訖由 stops 推導,忽略上面的 pickup/dropoff。 + Stops []StopInput +} + +// EstimateResult 預估結果(金額皆為「分」,一律整數元)。 +// **只回乘客該知道的欄位**:車資、清潔費、合計、距離、時間—— +// 不回手續費/實得等內部費率(比照 FeeSettings.CustomerJSON 的白名單方針)。 +type EstimateResult struct { + DistanceM int + DurationSec int + FareCents int64 + CleaningFeeCents int64 + TotalCents int64 +} + +// Estimate 以全程規劃路線(起點 → 各停靠點 → 最終目的地,**含繞路**)試算車資。 +// +// 距離來自 OSRM RouteVia(與 N5 計費同一支多點路線 API);OSRM 不可用時 RouteVia 內部 +// 退回逐段 haversine,因此預估**永遠算得出一個數**(近似值),不會因路網引擎暫時掛掉就報錯—— +// 這正是預估該有的行為,寧可給近似也不要讓乘客卡住。 +func (s *EstimateService) Estimate(ctx context.Context, req EstimateRequest) (EstimateResult, error) { + if s == nil || s.osrm == nil || s.fees == nil { + return EstimateResult{}, ErrEstimateUnavailable + } + // 車種選填;有給就必須是白名單 code(與建單同一條件,錯誤在此變 400 而非讓後續流程收到髒值)。 + if req.RequiredVehicleType != "" && !constants.IsValidVehicleType(req.RequiredVehicleType) { + return EstimateResult{}, ErrInvalidVehicleType + } + points, err := s.routePoints(&req) + if err != nil { + return EstimateResult{}, err + } + durationSec, distanceM, err := s.osrm.RouteVia(ctx, points) + if err != nil { + // points 保證 ≥2,RouteVia 只有點數不足才回錯;理論上到不了這裡,防禦性處理。 + return EstimateResult{}, err + } + q := s.fees.Quote(distanceM, req.RequiredVehicleType) + return EstimateResult{ + DistanceM: distanceM, + DurationSec: durationSec, + FareCents: q.FareCents, + CleaningFeeCents: q.CleaningFeeCents, + TotalCents: q.FareCents + q.CleaningFeeCents, + }, nil +} + +// routePoints 依輸入推導「起點 → 各停靠點 → 終點」的有序座標,套用與建單相同的驗證。 +// +// 多停靠點時**所有停靠點都入路線**——預估階段還沒有人被跳過(跳過是司機途中的動作), +// 這與 billableStopPoints(排除已跳過者)刻意不同:那是實際計費,這是全程預估。 +func (s *EstimateService) routePoints(req *EstimateRequest) ([]osrmclient.Point, error) { + if len(req.Stops) > 0 { + if err := validateStops(req.Stops); err != nil { + return nil, err + } + sorted := sortStopsBySeq(req.Stops) + if _, ok := firstPickup(sorted); !ok { + return nil, ErrUnpairedStop + } + if _, ok := finalDropoff(sorted); !ok { + return nil, ErrUnpairedStop + } + pts := make([]osrmclient.Point, 0, len(sorted)) + for _, st := range sorted { + pts = append(pts, osrmclient.Point{Lat: st.Lat, Lng: st.Lng}) + } + return pts, nil + } + // 單點訂單:起點合法 + 終點座標**必填**(沒座標無法路由)。 + if err := validatePickupCoords(req.PickupLat, req.PickupLng); err != nil { + return nil, err + } + if req.DropoffLat == nil || req.DropoffLng == nil { + return nil, ErrInvalidCoords + } + if err := validatePickupCoords(*req.DropoffLat, *req.DropoffLng); err != nil { + return nil, err + } + return []osrmclient.Point{ + {Lat: req.PickupLat, Lng: req.PickupLng}, + {Lat: *req.DropoffLat, Lng: *req.DropoffLng}, + }, nil +} diff --git a/internal/service/estimate_test.go b/internal/service/estimate_test.go new file mode 100644 index 0000000..eaad84d --- /dev/null +++ b/internal/service/estimate_test.go @@ -0,0 +1,192 @@ +package service + +import ( + "context" + "errors" + "strings" + "testing" + + "line-fleet-dispatch/internal/constants" +) + +// 座標點數=path 中 `/driving/` 之後以 `;` 分隔的段數。 +func coordCount(t *testing.T, path string) int { + t.Helper() + i := strings.Index(path, "/driving/") + if i < 0 { + t.Fatalf("OSRM path 不含 /driving/:%s", path) + } + return strings.Count(path[i:], ";") + 1 +} + +func ptr(f float64) *float64 { return &f } + +// 單點行程:終點座標齊全 → 依 OSRM 距離算車資,total = fare(未指定寵物車無清潔費)。 +func TestEstimateSinglePoint(t *testing.T) { + osrm, fake := newFakeOSRM(t, 5000) // 5km + fees := newFeeSettingsForTest(8500, 2000, 8500, 1500, 300000) + svc := NewEstimateService(osrm, fees) + + res, err := svc.Estimate(context.Background(), EstimateRequest{ + PickupLat: 25.033, + PickupLng: 121.5654, + DropoffLat: ptr(25.0517), + DropoffLng: ptr(121.5170), + }) + if err != nil { + t.Fatalf("預估失敗:%v", err) + } + // fare = roundNtd(8500 + round(2000*5000/1000)) = 8500 + 10000 = 18500 + if res.FareCents != 18500 { + t.Errorf("fare = %d,預期 18500", res.FareCents) + } + if res.CleaningFeeCents != 0 { + t.Errorf("未指定寵物車不應有清潔費,得 %d", res.CleaningFeeCents) + } + if res.TotalCents != 18500 { + t.Errorf("total = %d,預期 18500(=fare)", res.TotalCents) + } + if res.DistanceM != 5000 { + t.Errorf("distance = %d,預期 5000", res.DistanceM) + } + if n := coordCount(t, fake.lastPath(t)); n != 2 { + t.Errorf("單點行程應送 2 個座標,得 %d", n) + } +} + +// 指定寵物車 → total = fare + 清潔費。 +func TestEstimatePetCleaningFee(t *testing.T) { + osrm, _ := newFakeOSRM(t, 5000) + fees := newFeeSettingsWithCleaning(8500, 2000, 8500, 1500, 2000) // 清潔費 20% + svc := NewEstimateService(osrm, fees) + + res, err := svc.Estimate(context.Background(), EstimateRequest{ + PickupLat: 25.033, + PickupLng: 121.5654, + DropoffLat: ptr(25.0517), + DropoffLng: ptr(121.5170), + RequiredVehicleType: constants.VehicleTypePet, + }) + if err != nil { + t.Fatalf("預估失敗:%v", err) + } + // fare 18500;清潔費 = floorNtd(18500*2000/10000) = 3700;total = 22200 + if res.CleaningFeeCents != 3700 { + t.Errorf("清潔費 = %d,預期 3700", res.CleaningFeeCents) + } + if res.TotalCents != 22200 { + t.Errorf("total = %d,預期 22200(fare 18500 + 清潔費 3700)", res.TotalCents) + } +} + +// 多停靠點:全程所有停靠點都入路線(預估階段還沒有人被跳過)。 +func TestEstimateMultiStop(t *testing.T) { + osrm, fake := newFakeOSRM(t, 8000) + fees := newFeeSettingsForTest(8500, 2000, 8500, 1500, 300000) + svc := NewEstimateService(osrm, fees) + + stops := []StopInput{ + {Seq: 3, Kind: constants.StopKindDropoff, Lat: 25.05, Lng: 121.52, PassengerLabel: "A"}, + {Seq: 1, Kind: constants.StopKindPickup, Lat: 25.03, Lng: 121.56, PassengerLabel: "A"}, + {Seq: 4, Kind: constants.StopKindDropoff, Lat: 25.06, Lng: 121.51, PassengerLabel: "B"}, + {Seq: 2, Kind: constants.StopKindPickup, Lat: 25.04, Lng: 121.55, PassengerLabel: "B"}, + } + res, err := svc.Estimate(context.Background(), EstimateRequest{Stops: stops}) + if err != nil { + t.Fatalf("預估失敗:%v", err) + } + // fare = roundNtd(8500 + round(2000*8000/1000)) = 8500 + 16000 = 24500 + if res.FareCents != 24500 { + t.Errorf("fare = %d,預期 24500", res.FareCents) + } + if n := coordCount(t, fake.lastPath(t)); n != 4 { + t.Errorf("四停行程應送 4 個座標,得 %d", n) + } +} + +// 缺目的地座標 → 400(ErrInvalidCoords):沒終點無法算路線。 +func TestEstimateMissingDropoffCoords(t *testing.T) { + osrm, _ := newFakeOSRM(t, 5000) + fees := newFeeSettingsForTest(8500, 2000, 8500, 1500, 300000) + svc := NewEstimateService(osrm, fees) + + _, err := svc.Estimate(context.Background(), EstimateRequest{ + PickupLat: 25.033, + PickupLng: 121.5654, + // 無 dropoff 座標 + }) + if !errors.Is(err, ErrInvalidCoords) { + t.Errorf("缺目的地座標應回 ErrInvalidCoords,得 %v", err) + } +} + +// 車種非白名單 → ErrInvalidVehicleType。 +func TestEstimateInvalidVehicleType(t *testing.T) { + osrm, _ := newFakeOSRM(t, 5000) + fees := newFeeSettingsForTest(8500, 2000, 8500, 1500, 300000) + svc := NewEstimateService(osrm, fees) + + _, err := svc.Estimate(context.Background(), EstimateRequest{ + PickupLat: 25.033, + PickupLng: 121.5654, + DropoffLat: ptr(25.0517), + DropoffLng: ptr(121.5170), + RequiredVehicleType: "spaceship", + }) + if !errors.Is(err, ErrInvalidVehicleType) { + t.Errorf("非法車種應回 ErrInvalidVehicleType,得 %v", err) + } +} + +// 距離極短 → fare 落到 min_fare 下限(不會算成 0 或低於下限)。 +func TestEstimateMinFareFloor(t *testing.T) { + osrm, _ := newFakeOSRM(t, 1000) // 1km + fees := newFeeSettingsForTest(5000, 2000, 12000, 1000, 0) + svc := NewEstimateService(osrm, fees) + + res, err := svc.Estimate(context.Background(), EstimateRequest{ + PickupLat: 25.033, + PickupLng: 121.5654, + DropoffLat: ptr(25.0517), + DropoffLng: ptr(121.5170), + }) + if err != nil { + t.Fatalf("預估失敗:%v", err) + } + // fare 原算 = 5000 + round(2000*1000/1000) = 7000 < 12000 → 夾到 min_fare 12000 + if res.FareCents != 12000 { + t.Errorf("fare = %d,預期夾到 min_fare 12000", res.FareCents) + } +} + +// 停靠點填錯(少一半的乘客)→ 驗證錯誤,不放行。 +func TestEstimateUnpairedStops(t *testing.T) { + osrm, _ := newFakeOSRM(t, 5000) + fees := newFeeSettingsForTest(8500, 2000, 8500, 1500, 300000) + svc := NewEstimateService(osrm, fees) + + // A 只有上車、沒有下車 → 無法執行的行程。 + stops := []StopInput{ + {Seq: 1, Kind: constants.StopKindPickup, Lat: 25.03, Lng: 121.56, PassengerLabel: "A"}, + } + _, err := svc.Estimate(context.Background(), EstimateRequest{Stops: stops}) + if err == nil { + t.Fatal("未成對的停靠點應回錯誤,卻成功") + } + if !errors.Is(err, ErrUnpairedStop) { + t.Errorf("預期 ErrUnpairedStop,得 %v", err) + } +} + +// 服務未就緒(osrm/fees 缺)→ ErrEstimateUnavailable,不是 panic。 +func TestEstimateUnavailableWhenNotConfigured(t *testing.T) { + fees := newFeeSettingsForTest(8500, 2000, 8500, 1500, 300000) + svc := NewEstimateService(nil, fees) // 無 OSRM + _, err := svc.Estimate(context.Background(), EstimateRequest{ + PickupLat: 25.033, PickupLng: 121.5654, + DropoffLat: ptr(25.0517), DropoffLng: ptr(121.5170), + }) + if !errors.Is(err, ErrEstimateUnavailable) { + t.Errorf("無 OSRM 應回 ErrEstimateUnavailable,得 %v", err) + } +} From 4d6b3d439bb8a94be0d036e496ad878ef0bea78e Mon Sep 17 00:00:00 2001 From: awei Date: Thu, 23 Jul 2026 08:24:23 +0800 Subject: [PATCH 2/2] =?UTF-8?q?docs(R):=20=E5=A0=B1=E5=83=B9=20API=20?= =?UTF-8?q?=E6=A8=A1=E6=93=AC=E5=99=A8=20live=20E2E=20=E5=B0=8D=E5=B8=B3?= =?UTF-8?q?=E7=B5=90=E6=9E=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 不繞路時實收=預估(共用 FeeSettings.Quote+同一 OSRM 路線):單點 6811m 預估 22100=完成 22100;寵物車(清潔費 20%)預估 22100+4400=完成 22100+4400; App 建單 ride #24 完成卡 NT$94=同座標預估 NT$94。繞路時走 N5 max(軌跡,路線)。 Co-Authored-By: Claude Opus 4.8 --- docs/TODO.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/docs/TODO.md b/docs/TODO.md index ba4e79e..1a2f64e 100644 --- a/docs/TODO.md +++ b/docs/TODO.md @@ -889,7 +889,12 @@ 缺目的地 400/非法車種/min_fare 下限/未成對停靠點/未就緒)+ `internal/handler/estimate_test.go` 2 案(授權 401/403、綁定 400、未就緒 503)。 - App 端對應:叫車表單顯示預估卡(fleet-app 同批),失敗靜默不擋叫車。 - - **尚未做**:docker compose live E2E 對帳「預估 vs 完成實收」的差異合理,留待下次。 + - **✅ live E2E 對帳(2026-07-23,本機起服務 + m6_pixel)**:預估與完成共用 + `FeeSettings.Quote`+同一 OSRM 路線 → 不繞路時**實收=預估**。實測: + 單點 6811m 預估 fare 22100 = 完成 22100;**寵物車**(清潔費率 20%)預估 + fare 22100+清潔費 4400 = 完成 22100+4400(車資與清潔費皆一致); + App 建單 ride #24(429m)完成卡「車資 NT$94」= 同座標預估 NT$94。 + 繞路時走 N5 既有 `max(軌跡, 路線)`,故「實際依行駛路線可能不同」的免責成立。 ## 下次任務