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
4 changes: 3 additions & 1 deletion cmd/server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down
31 changes: 31 additions & 0 deletions docs/TODO.md
Original file line number Diff line number Diff line change
Expand Up @@ -865,6 +865,37 @@
驗收:`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 同批),失敗靜默不擋叫車。
- **✅ 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(軌跡, 路線)`,故「實際依行駛路線可能不同」的免責成立。

## 下次任務

**新需求(2026-07-16 加入,尚未實作,皆需後端地基先行)**:
Expand Down
77 changes: 77 additions & 0 deletions internal/handler/estimate_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
74 changes: 74 additions & 0 deletions internal/handler/ride.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ type RideHandler struct {
rides *service.RideQueryService
rideService *service.RideService
stops *service.RideStopService
estimate *service.EstimateService
}

func NewRideHandler(
Expand All @@ -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 {
Expand Down Expand Up @@ -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) {
Expand Down
123 changes: 123 additions & 0 deletions internal/service/estimate.go
Original file line number Diff line number Diff line change
@@ -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
}
Loading
Loading