diff --git a/cmd/server/main.go b/cmd/server/main.go index 92bef30..09021ea 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -73,6 +73,7 @@ func main() { feeSettingsRepo := repository.NewFeeSettingsRepository(db) membershipInvoiceRepo := repository.NewMembershipInvoiceRepository(db) rideMessageRepo := repository.NewRideMessageRepository(db) + rideStopRepo := repository.NewRideStopRepository(db) lostItemRepo := repository.NewLostItemRepository(db) // 軌跡分區維護:啟動時預建未來月分區 + 每日排程(避免跨月寫入失敗) @@ -128,6 +129,7 @@ func main() { dispatchService.SetRideEvents(rideEventRepo) deviceTokenService := service.NewDeviceTokenService(deviceTokenRepo) rideService := service.NewRideService(customerRepo, rideRepo, redisStore, dispatchService) + rideService.SetStops(rideStopRepo) // N3:多乘客/多停靠點行程 rideService.SetRideEvents(rideEventRepo) trackingService := service.NewTrackingService( driverRepo, rideRepo, trackRepo, redisStore, lineClient, dispatchService, diff --git a/db/migrations/000021_create_ride_stops.down.sql b/db/migrations/000021_create_ride_stops.down.sql new file mode 100644 index 0000000..345abe3 --- /dev/null +++ b/db/migrations/000021_create_ride_stops.down.sql @@ -0,0 +1,2 @@ +-- DROP TABLE 會連帶刪除其上的 CHECK、UNIQUE 與 FK。 +DROP TABLE IF EXISTS ride_stops; diff --git a/db/migrations/000021_create_ride_stops.up.sql b/db/migrations/000021_create_ride_stops.up.sql new file mode 100644 index 0000000..ac98266 --- /dev/null +++ b/db/migrations/000021_create_ride_stops.up.sql @@ -0,0 +1,34 @@ +-- 多乘客/多停靠點行程(N1):一張訂單裡多位同行乘客各自的上/下車點,依序停靠。 +-- **不是陌生人拼車**——同一張訂單、不需配對演算法、不需跨訂單分帳。 +-- +-- 相容性(N1/N3 明確要求):既有單點訂單**不會有任何 ride_stops 列**。 +-- rides.pickup_point / dropoff_point 仍是派單、地圖、報表的讀取來源, +-- 多停靠點訂單也照樣寫(第一個 pickup/最終 dropoff),既有路徑一行都不用改。 +-- ride_stops 為空 = 舊行為(含 LINE 建的無目的地訂單)。 +CREATE TABLE IF NOT EXISTS ride_stops ( + id BIGSERIAL PRIMARY KEY, + ride_id BIGINT NOT NULL REFERENCES rides(id) ON DELETE CASCADE, + seq INT NOT NULL, + kind TEXT NOT NULL, + point geography(Point, 4326) NOT NULL, + address TEXT NOT NULL DEFAULT '', + -- passenger_label 給司機辨識用(A/B/C…)。刻意不做值域 CHECK: + -- 它不參與任何邏輯判斷,值髒掉不會算錯錢(不像車種是計費依據)。 + passenger_label TEXT NOT NULL DEFAULT '', + -- 停靠點處理狀態(N7):兩個時間欄天然互斥,同時回答「是否發生」與「何時」, + -- 不必再維護一個狀態機。兩者皆 NULL = 尚未處理。 + -- skipped_at:乘客沒出現、司機標記跳過(2026-07-17 拍板)。 + -- **已跳過的停靠點不計入 N5 的計費路線**——沒去就沒開那段路。 + arrived_at TIMESTAMPTZ, + skipped_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + + CONSTRAINT chk_ride_stops_seq CHECK (seq >= 1), + CONSTRAINT chk_ride_stops_kind CHECK (kind IN ('pickup', 'dropoff')), + -- 同一趟不得有重複順序——seq 是「第幾站」,重複的話「下一站是誰」就沒有答案。 + CONSTRAINT uq_ride_stops_ride_seq UNIQUE (ride_id, seq) +); + +-- 依序讀取整趟停靠點(司機端行程卡、N5 計費路線)都是 (ride_id, seq) 範圍掃描。 +-- UNIQUE 已隱含建立此索引,故不另建。 diff --git a/docs/TODO.md b/docs/TODO.md index 3fea542..17abf7b 100644 --- a/docs/TODO.md +++ b/docs/TODO.md @@ -261,24 +261,48 @@ ### 施作項目(嚴格相依,由上而下) -- [ ] **N1. `ride_stops` 資料表**(新 migration) - 欄位建議:`ride_id`、`seq`(停靠順序,1..N)、`kind`(pickup/dropoff)、 - `point`(geography Point)、`address`、`passenger_label`(A/B/C/D,或 `passenger_name`)、 - `arrived_at`(司機到達時間,供軌跡稽核)。 - 索引 `(ride_id, seq)`;CHECK `seq >= 1`。 - **相容性**:既有單點訂單維持只用 `rides.pickup_point`/`dropoff_point`, - `ride_stops` 為空=舊行為(LINE 建的無目的地訂單也走這條)。 - -- [ ] **N2. 乘客數上限與驗證** ✅ **已定案(2026-07-16):5 位乘客,各自上下車** - → **最多 5 位乘客、最多 10 個停靠點**(每位一上一下)。上限值放常數或 `fleet_settings`(實作時定)。 - 驗證:每位乘客必須成對出現 pickup+dropoff;dropoff 的 `seq` 必須大於同一位乘客的 pickup; - 最終目的地=`seq` 最大的 dropoff。超過上限回 400。 - -- [ ] **N3. 建單 API 擴充**(`POST /api/rides`) +- [x] **N1. `ride_stops` 資料表** ✅ **已實作(2026-07-17,migration `000021`)** + `ride_id`(FK ON DELETE CASCADE)、`seq`、`kind`、`point`、`address`、`passenger_label`、 + `arrived_at`、`skipped_at`。CHECK:`seq >= 1`、`kind IN ('pickup','dropoff')`; + **UNIQUE `(ride_id, seq)`**——seq =「第幾站」,重複的話「下一站是誰」沒有答案。 + (UNIQUE 已隱含建立 `(ride_id, seq)` 索引,不另建。) + + **實作時定的三件事**: + 1. **狀態用兩個時間欄(`arrived_at`/`skipped_at`)而非 status 字串**:兩者天然互斥、 + 且都需要「何時發生」——時間欄同時回答「是否發生」與「何時」,不必另外維護狀態機。 + 皆 NULL = 尚未處理。`skipped_at` 對應 2026-07-17 拍板的「司機可跳過缺席乘客」。 + 2. **`passenger_label` 不做值域 CHECK**(不同於車種):純粹給司機辨識,不參與邏輯判斷, + 值髒掉不會算錯錢。 + 3. **相容性已用測試釘住**:既有單點訂單**不產生任何 ride_stops 列**。 + +- [x] **N2. 乘客數上限與驗證** ✅ **已實作(2026-07-17)**(定案 2026-07-16:5 位乘客,各自上下車) + 上限放 `internal/constants/ride_stop.go`(`MaxRidePassengers=5`/`MaxRideStops=10`), + **不放 `fleet_settings`**:它是產品規則不是營運費率,沒有「後台隨時要調」的需求, + 放常數才能被編譯期引用(測試也直接讀它)。 + 驗證在 `validateStops`(純函式,`internal/service/ride_stops_validate.go`),全部回 400: + 停靠點數 ≤10、乘客數 ≤5、kind 白名單、座標合法、**seq 不得重複**、 + 每位乘客**成對** pickup+dropoff、**dropoff.seq > pickup.seq**(不能先送再接)。 + 錯誤刻意分成多個(而非一個籠統的 ErrInvalidStops)——乘客填錯時要知道錯在哪。 + **驗收**:14 個單元案(合法:空 stops/兩人四停交錯/5 人 10 停上限/客戶端未依序送; + 非法:超上限/未成對/先下後上/重複上車點/seq 重複/seq=0/kind 非白名單/無標籤/座標非法)。 + +- [x] **N3. 建單 API 擴充**(`POST /api/rides`)✅ **已實作(2026-07-17)** body 加選填 `stops: [{seq, kind, lat, lng, address, passenger_label}]`。 - 無 `stops` 時完全維持現行行為(不可破壞既有 App/LINE 建單)。 - `rides.pickup_point` 仍寫第一個 pickup、`dropoff_point` 寫最終 dropoff, - 讓派單/地圖/報表等既有讀取路徑不必全面改寫。 + 無 `stops` =完全維持現行行為(**測試釘住:單點建單不產生 ride_stops 列**)。 + 有 `stops` 時 **pickup/dropoff 由 stops 推導**(第一個 pickup/seq 最大的 dropoff)並覆蓋 + body 的 `pickup_lat/lng` 等欄位 → `rides.pickup_point`/`dropoff_point` 照樣有值, + 派單、導航、地圖、F3 退路、報表**一行都不用改**。 + **落庫順序**:停靠點寫在 `rides.Create` 之後、**派單之前**(派單一發出司機就該看得到全程), + 寫失敗則整筆建單失敗——「只有第一個上車點、少載其餘乘客」的行程比沒建成更糟。 + **未注入 stops repo 卻收到 stops → `ErrStopsUnavailable` → 503**(不是 400: + 這是伺服器沒接好,不該讓乘客以為自己填錯)。 + + **驗收**:`go build`/`vet`/`gofmt` 綠;整合測試(真 PostGIS + Redis)—— + 多停靠點落庫(**含座標經緯度正確**、rides 推導正確、新停靠點為未處理狀態)、 + 客戶端未依序送仍依 seq 落庫、**單點訂單不建 stops**、驗證失敗不留孤兒訂單、未注入時明確失敗。 + **反向驗證**:`ST_MakePoint` 經緯度對調 → 座標跑到 lat=58.48(愛沙尼亞),FAIL; + 拿掉「由 stops 推導 pickup/dropoff」→ 建單以 `無效的上車座標` FAIL。 + **未驗**:docker compose 全服務 live E2E。 - [ ] **N4. 派單與 ETA**(`dispatch.go`) 派單仍以「第一個上車點」找最近司機(現行邏輯不變)。 diff --git a/internal/constants/ride_stop.go b/internal/constants/ride_stop.go new file mode 100644 index 0000000..2178182 --- /dev/null +++ b/internal/constants/ride_stop.go @@ -0,0 +1,19 @@ +package constants + +// 停靠點種類(N1)。值域由 DB CHECK `chk_ride_stops_kind` 一併把關。 +const ( + StopKindPickup = "pickup" // 該位乘客的上車點 + StopKindDropoff = "dropoff" // 該位乘客的下車點 +) + +// 多乘客/多停靠點上限(N2 拍板 2026-07-16): +// **5 位乘客、各自一上一下 → 最多 10 個停靠點**。 +const ( + MaxRidePassengers = 5 + MaxRideStops = MaxRidePassengers * 2 +) + +// IsValidStopKind 是否為合法的停靠點種類。 +func IsValidStopKind(s string) bool { + return s == StopKindPickup || s == StopKindDropoff +} diff --git a/internal/handler/ride.go b/internal/handler/ride.go index 0ecc25c..b3f53de 100644 --- a/internal/handler/ride.go +++ b/internal/handler/ride.go @@ -153,11 +153,33 @@ func (h *RideHandler) Create(c *gin.Context) { DropoffLng *float64 `json:"dropoff_lng"` // 選填(P2):未帶=不指定車種,維持現行行為,既有 App/LINE 建單不受影響。 RequiredVehicleType string `json:"required_vehicle_type"` + // 選填(N3):多乘客/多停靠點行程。未帶=傳統單點訂單。 + // 有帶時 pickup/dropoff 由 stops 推導(第一個 pickup/最終 dropoff), + // 此時上面的 pickup_lat/lng 等欄位會被忽略。 + Stops []struct { + Seq int `json:"seq"` + Kind string `json:"kind"` // pickup / dropoff + 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, + }) + } ride, err := h.rideService.CreateByCustomer( c.Request.Context(), customerID, service.CustomerCreateRequest{ PickupLat: req.PickupLat, @@ -167,6 +189,7 @@ func (h *RideHandler) Create(c *gin.Context) { DropoffLat: req.DropoffLat, DropoffLng: req.DropoffLng, RequiredVehicleType: req.RequiredVehicleType, + Stops: stops, }, ) if err != nil { @@ -179,8 +202,16 @@ func (h *RideHandler) Create(c *gin.Context) { // createStatusForErr 將下單錯誤對應到 HTTP 狀態碼。 func createStatusForErr(err error) int { switch { - case errors.Is(err, service.ErrInvalidCoords), errors.Is(err, service.ErrInvalidVehicleType): + case errors.Is(err, service.ErrInvalidCoords), errors.Is(err, service.ErrInvalidVehicleType), + // 停靠點填錯是乘客的輸入問題(N2)→ 400,錯誤訊息本身已說明錯在哪。 + errors.Is(err, service.ErrTooManyStops), errors.Is(err, service.ErrTooManyPassengers), + errors.Is(err, service.ErrInvalidStopKind), errors.Is(err, service.ErrDuplicateStopSeq), + errors.Is(err, service.ErrUnpairedStop), errors.Is(err, service.ErrDropoffBeforePickup), + errors.Is(err, service.ErrMissingPassenger): return http.StatusBadRequest + case errors.Is(err, service.ErrStopsUnavailable): + // 這是伺服器沒接好,不是乘客填錯——不可回 400 讓乘客以為是自己的問題。 + return http.StatusServiceUnavailable case errors.Is(err, service.ErrActiveRideExists): return http.StatusConflict case errors.Is(err, service.ErrRateLimited): diff --git a/internal/model/models.go b/internal/model/models.go index 52f0417..5418f49 100644 --- a/internal/model/models.go +++ b/internal/model/models.go @@ -210,6 +210,43 @@ func (MembershipInvoice) TableName() string { return "membership_invoices" } +// RideStop 多乘客/多停靠點行程的單一停靠點(N1)。 +// 一趟的停靠點依 Seq 由小到大依序造訪;**ride_stops 為空 = 傳統單點訂單**(既有行為)。 +type RideStop struct { + ID int64 `gorm:"primaryKey" json:"id"` + RideID int64 `gorm:"column:ride_id;not null" json:"ride_id"` + // Seq 停靠順序,1 起算;同一趟內唯一(uq_ride_stops_ride_seq)—— + // 重複的話「下一站是誰」就沒有答案。 + Seq int `gorm:"column:seq;not null" json:"seq"` + Kind string `gorm:"column:kind;not null" json:"kind"` // constants.StopKind* + // Point 停靠點座標。地址僅供顯示,導航與計費一律吃座標。 + Point GeoPoint `gorm:"column:point;type:geography(Point,4326);not null" json:"point"` + Address string `gorm:"not null;default:''" json:"address"` + // PassengerLabel 給司機辨識用(A/B/C…);不參與邏輯判斷,故無值域限制。 + PassengerLabel string `gorm:"column:passenger_label;not null;default:''" json:"passenger_label"` + // ArrivedAt/SkippedAt 停靠點處理狀態(N7):互斥,皆 nil = 尚未處理。 + // SkippedAt 非 nil = 乘客沒出現、司機標記跳過 → **不計入 N5 的計費路線** + // (沒去就沒開那段路,計入等於收乘客沒走的路的錢)。 + ArrivedAt *time.Time `gorm:"column:arrived_at" json:"arrived_at"` + SkippedAt *time.Time `gorm:"column:skipped_at" json:"skipped_at"` + CreatedAt time.Time `gorm:"not null" json:"created_at"` + UpdatedAt time.Time `gorm:"not null" json:"updated_at"` +} + +func (RideStop) TableName() string { + return "ride_stops" +} + +// Pending 尚未處理(未到達也未跳過)。 +func (s RideStop) Pending() bool { + return s.ArrivedAt == nil && s.SkippedAt == nil +} + +// Skipped 乘客沒出現、已被司機跳過;N5 計費路線不算這一段。 +func (s RideStop) Skipped() bool { + return s.SkippedAt != nil +} + // RideMessage 行程內對話訊息(乘客↔司機)。即時遞送走 WebSocket(chat.message),本表為歷史真源。 type RideMessage struct { ID int64 `gorm:"primaryKey" json:"id"` diff --git a/internal/repository/ride_stop.go b/internal/repository/ride_stop.go new file mode 100644 index 0000000..39d06f3 --- /dev/null +++ b/internal/repository/ride_stop.go @@ -0,0 +1,56 @@ +package repository + +import ( + "time" + + "gorm.io/gorm" + + "line-fleet-dispatch/internal/model" +) + +// RideStopRepository 多停靠點(N1)讀寫。 +type RideStopRepository struct { + db *gorm.DB +} + +func NewRideStopRepository(db *gorm.DB) *RideStopRepository { + return &RideStopRepository{db: db} +} + +// StopRow 落庫用的單一停靠點(座標分開傳,因為要走 ST_MakePoint)。 +type StopRow struct { + Seq int + Kind string + Lat, Lng float64 + Address string + PassengerLabel string +} + +// CreateForRide 批次寫入某趟的停靠點。 +// 呼叫端(RideService.CreateByCustomer)負責先驗證配對與上限。 +func (r *RideStopRepository) CreateForRide(rideID int64, rows []StopRow) error { + if len(rows) == 0 { + return nil + } + now := time.Now() + return r.db.Transaction(func(tx *gorm.DB) error { + for _, s := range rows { + // 座標走 ST_MakePoint(lng, lat)——與 rides 的寫法一致(經度在前)。 + err := tx.Exec(` + INSERT INTO ride_stops (ride_id, seq, kind, point, address, passenger_label, created_at, updated_at) + VALUES (?, ?, ?, ST_SetSRID(ST_MakePoint(?, ?), 4326)::geography, ?, ?, ?, ?) + `, rideID, s.Seq, s.Kind, s.Lng, s.Lat, s.Address, s.PassengerLabel, now, now).Error + if err != nil { + return err + } + } + return nil + }) +} + +// ListByRide 依 seq 由小到大回傳整趟停靠點;單點訂單回空 slice(非錯誤)。 +func (r *RideStopRepository) ListByRide(rideID int64) ([]model.RideStop, error) { + var stops []model.RideStop + err := r.db.Where("ride_id = ?", rideID).Order("seq ASC").Find(&stops).Error + return stops, err +} diff --git a/internal/service/ride.go b/internal/service/ride.go index fd22a34..e501d1d 100644 --- a/internal/service/ride.go +++ b/internal/service/ride.go @@ -25,11 +25,18 @@ type RideRequest struct { type RideService struct { customers *repository.CustomerRepository rides *repository.RideRepository + stops *repository.RideStopRepository redis *redisstore.Store dispatch *DispatchService audit rideAuditor } +// SetStops 注入停靠點 repo(供多乘客/多停靠點行程,N3);可選—— +// 未注入時帶 stops 的建單會被拒(見 CreateByCustomer),單點建單不受影響。 +func (s *RideService) SetStops(stops *repository.RideStopRepository) { + s.stops = stops +} + func NewRideService( customers *repository.CustomerRepository, rides *repository.RideRepository, @@ -105,6 +112,42 @@ type CustomerCreateRequest struct { DropoffLat, DropoffLng *float64 // RequiredVehicleType 選填(P2):'' =不指定,維持現行行為(任何車種都可派)。 RequiredVehicleType string + // Stops 選填(N3):多乘客/多停靠點行程。空 = 傳統單點訂單,完全維持現行行為。 + // 有給時,pickup/dropoff 座標改由 stops 推導(第一個 pickup/最終 dropoff), + // 呼叫端傳的 PickupLat/Lng 等欄位會被覆蓋。 + Stops []StopInput +} + +// prepareStops 驗證停靠點並由它們推導 rides 的 pickup/dropoff(N3)。 +// 回傳排序後的停靠點;單點訂單回 nil,req 不動。 +// +// **相容性的關鍵**:多停靠點行程仍照樣寫 rides.pickup_point(第一個上車點)與 +// dropoff_point(最終目的地)。派單找最近司機、司機導航、地圖、F3 路線里程退路、報表 +// ——全部照原樣讀 rides,一行都不用改。ride_stops 是額外資訊,不是替代品。 +func (s *RideService) prepareStops(req *CustomerCreateRequest) ([]StopInput, error) { + if len(req.Stops) == 0 { + return nil, nil // 單點訂單,維持現行行為 + } + if s.stops == nil { + // 沒注入 repo 卻收到 stops:與其默默當成單點訂單建出「少載四個人」的行程, + // 不如明確失敗。 + return nil, ErrStopsUnavailable + } + if err := validateStops(req.Stops); err != nil { + return nil, err + } + sorted := sortStopsBySeq(req.Stops) + first, ok := firstPickup(sorted) + if !ok { + return nil, ErrUnpairedStop + } + final, ok := finalDropoff(sorted) + if !ok { + return nil, ErrUnpairedStop + } + req.PickupLat, req.PickupLng, req.PickupAddress = first.Lat, first.Lng, first.Address + req.DropoffLat, req.DropoffLng, req.DropoffAddress = &final.Lat, &final.Lng, final.Address + return sorted, nil } // CreateByCustomer 供已登入乘客(App)直接叫車:身分取自 JWT 的 customer_id。 @@ -114,6 +157,11 @@ func (s *RideService) CreateByCustomer( customerID int64, req CustomerCreateRequest, ) (*model.Ride, error) { + // 多停靠點(N3):先驗證再由 stops 推導 pickup/dropoff,讓後續流程與單點訂單完全一致。 + sortedStops, err := s.prepareStops(&req) + if err != nil { + return nil, err + } if err := validatePickupCoords(req.PickupLat, req.PickupLng); err != nil { return nil, err } @@ -165,6 +213,13 @@ func (s *RideService) CreateByCustomer( if err := s.rides.Create(ride); err != nil { return nil, err } + // 停靠點必須在派單**之前**落庫:派單一發出,司機端就該看得到全程(N4)。 + // 寫失敗則整筆建單失敗——只有第一個上車點、少載其餘乘客的行程,比沒建成更糟。 + if len(sortedStops) > 0 { + if err := s.stops.CreateForRide(ride.ID, toStopRows(sortedStops)); err != nil { + return nil, err + } + } s.audit.record(ride.ID, nil, constants.RideStatusRequested, events.TypeRideRequested, events.ActorCustomer, idPtr(customer.ID), "app") @@ -176,6 +231,22 @@ func (s *RideService) CreateByCustomer( return ride, nil } +// toStopRows 轉成 repository 的落庫形狀。 +func toStopRows(stops []StopInput) []repository.StopRow { + rows := make([]repository.StopRow, 0, len(stops)) + for _, s := range stops { + rows = append(rows, repository.StopRow{ + Seq: s.Seq, + Kind: s.Kind, + Lat: s.Lat, + Lng: s.Lng, + Address: s.Address, + PassengerLabel: s.PassengerLabel, + }) + } + return rows +} + // RideQueryService 訂單查詢 type RideQueryService struct { tracks *repository.TrackRepository diff --git a/internal/service/ride_create_stops_test.go b/internal/service/ride_create_stops_test.go new file mode 100644 index 0000000..6bf9b7e --- /dev/null +++ b/internal/service/ride_create_stops_test.go @@ -0,0 +1,206 @@ +package service + +import ( + "context" + "errors" + "math" + "testing" + + "line-fleet-dispatch/internal/constants" + lineclient "line-fleet-dispatch/internal/line" + "line-fleet-dispatch/internal/repository" +) + +func newStopsRideService(t *testing.T) (*RideService, *repository.RideRepository, *repository.RideStopRepository, *repository.CustomerRepository) { + t.Helper() + db := newServiceTestDB(t) + customers := repository.NewCustomerRepository(db) + rides := repository.NewRideRepository(db) + stops := repository.NewRideStopRepository(db) + redis := newServiceTestRedis(t) + dispatch := NewDispatchService( + repository.NewDriverRepository(db), rides, customers, redis, + lineclient.NewClient(""), nil, NewDispatchSettings(3000, 5, 20, 1, 5), nil, + ) + svc := NewRideService(customers, rides, redis, dispatch) + svc.SetStops(stops) + return svc, rides, stops, customers +} + +// 兩人四停:A 在台北車站上、B 在市政府上、A 在松山機場下、B 在台北 101 下。 +func fourStopInputs() []StopInput { + return []StopInput{ + {Seq: 1, Kind: constants.StopKindPickup, Lat: 25.0478, Lng: 121.5170, Address: "台北車站", PassengerLabel: "A"}, + {Seq: 2, Kind: constants.StopKindPickup, Lat: 25.0339, Lng: 121.5645, Address: "市政府", PassengerLabel: "B"}, + {Seq: 3, Kind: constants.StopKindDropoff, Lat: 25.0697, Lng: 121.5522, Address: "松山機場", PassengerLabel: "A"}, + {Seq: 4, Kind: constants.StopKindDropoff, Lat: 25.0339, Lng: 121.5645, Address: "台北101", PassengerLabel: "B"}, + } +} + +// TestCreateByCustomer_多停靠點落庫 N1+N3:stops 寫入,且 rides 的 pickup/dropoff +// 由 stops 推導——這是相容性的核心,派單/導航/報表都還讀 rides。 +func TestCreateByCustomer_多停靠點落庫(t *testing.T) { + svc, rides, stopsRepo, customers := newStopsRideService(t) + + cust, err := customers.FindOrCreateByLineUserID("U_stops_ok", "包車乘客") + if err != nil { + t.Fatalf("建立乘客失敗:%v", err) + } + + created, err := svc.CreateByCustomer(context.Background(), cust.ID, CustomerCreateRequest{ + Stops: fourStopInputs(), + }) + if err != nil { + t.Fatalf("多停靠點建單失敗:%v", err) + } + + t.Run("rides 仍寫第一個上車點與最終目的地", func(t *testing.T) { + got, err := rides.GetByID(created.ID) + if err != nil { + t.Fatalf("重讀訂單失敗:%v", err) + } + // 第一個 pickup(seq=1,台北車站)→ 派單據此找最近司機。 + if math.Abs(got.PickupPoint.Lat-25.0478) > 1e-6 || got.PickupAddress != "台北車站" { + t.Fatalf("pickup 應為第一個上車點:%+v / %q", got.PickupPoint, got.PickupAddress) + } + // 最終 dropoff(seq 最大=4,台北 101)→ 導航、地圖、F3 路線退路讀這裡。 + if got.DropoffPoint == nil { + t.Fatal("dropoff_point 不該為 nil") + } + if math.Abs(got.DropoffPoint.Lat-25.0339) > 1e-6 || got.DropoffAddress != "台北101" { + t.Fatalf("dropoff 應為最終目的地:%+v / %q", got.DropoffPoint, got.DropoffAddress) + } + }) + + t.Run("stops 依序落庫且座標正確", func(t *testing.T) { + list, err := stopsRepo.ListByRide(created.ID) + if err != nil { + t.Fatalf("讀停靠點失敗:%v", err) + } + if len(list) != 4 { + t.Fatalf("預期 4 個停靠點,得到 %d", len(list)) + } + for i, want := range fourStopInputs() { + got := list[i] + if got.Seq != want.Seq || got.Kind != want.Kind || got.PassengerLabel != want.PassengerLabel { + t.Fatalf("第 %d 站不符:%+v", i, got) + } + // 座標經 ST_MakePoint(lng, lat) 落庫再讀回,經緯度不可對調。 + if math.Abs(got.Point.Lat-want.Lat) > 1e-6 || math.Abs(got.Point.Lng-want.Lng) > 1e-6 { + t.Fatalf("第 %d 站座標錯誤(經緯度可能對調):%+v,預期 lat=%f lng=%f", + i, got.Point, want.Lat, want.Lng) + } + if got.Address != want.Address { + t.Fatalf("第 %d 站地址錯誤:%q", i, got.Address) + } + // 剛建單,尚未到達也未跳過。 + if !got.Pending() { + t.Fatalf("新建的停靠點應為未處理:arrived=%v skipped=%v", got.ArrivedAt, got.SkippedAt) + } + } + }) +} + +// TestCreateByCustomer_客戶端未依序送 落庫一律以 seq 為準。 +func TestCreateByCustomer_停靠點未依序送(t *testing.T) { + svc, _, stopsRepo, customers := newStopsRideService(t) + + cust, err := customers.FindOrCreateByLineUserID("U_stops_unsorted", "乘客") + if err != nil { + t.Fatalf("建立乘客失敗:%v", err) + } + s := fourStopInputs() + s[0], s[3] = s[3], s[0] // 打亂 + + created, err := svc.CreateByCustomer(context.Background(), cust.ID, CustomerCreateRequest{Stops: s}) + if err != nil { + t.Fatalf("建單失敗:%v", err) + } + list, err := stopsRepo.ListByRide(created.ID) + if err != nil { + t.Fatalf("讀停靠點失敗:%v", err) + } + for i, want := range []int{1, 2, 3, 4} { + if list[i].Seq != want { + t.Fatalf("落庫後應依 seq 排序,得到 %+v", list) + } + } +} + +// TestCreateByCustomer_單點訂單不建stops N1/N3 的相容性保證: +// 既有 App/LINE 建單一律不產生任何 ride_stops 列。 +func TestCreateByCustomer_單點訂單不建stops(t *testing.T) { + svc, _, stopsRepo, customers := newStopsRideService(t) + + cust, err := customers.FindOrCreateByLineUserID("U_stops_single", "一般乘客") + if err != nil { + t.Fatalf("建立乘客失敗:%v", err) + } + dropLat, dropLng := 25.08, 121.57 + created, err := svc.CreateByCustomer(context.Background(), cust.ID, CustomerCreateRequest{ + PickupLat: 25.03, PickupLng: 121.56, PickupAddress: "台北車站", + DropoffAddress: "松山機場", DropoffLat: &dropLat, DropoffLng: &dropLng, + }) + if err != nil { + t.Fatalf("單點建單不該受 N3 影響:%v", err) + } + list, err := stopsRepo.ListByRide(created.ID) + if err != nil { + t.Fatalf("讀停靠點失敗:%v", err) + } + if len(list) != 0 { + t.Fatalf("單點訂單不該有 ride_stops 列,得到 %d 筆", len(list)) + } +} + +// TestCreateByCustomer_停靠點驗證失敗不建單 驗證失敗必須在建 ride 之前擋下, +// 否則會留下一筆「只有第一個上車點、少載其餘乘客」的孤兒訂單。 +func TestCreateByCustomer_停靠點驗證失敗不建單(t *testing.T) { + svc, rides, _, customers := newStopsRideService(t) + + cust, err := customers.FindOrCreateByLineUserID("U_stops_bad", "亂填乘客") + if err != nil { + t.Fatalf("建立乘客失敗:%v", err) + } + _, err = svc.CreateByCustomer(context.Background(), cust.ID, CustomerCreateRequest{ + Stops: []StopInput{ + {Seq: 1, Kind: constants.StopKindDropoff, Lat: 25.03, Lng: 121.56, PassengerLabel: "A"}, + {Seq: 2, Kind: constants.StopKindPickup, Lat: 25.04, Lng: 121.57, PassengerLabel: "A"}, + }, + }) + if !errors.Is(err, ErrDropoffBeforePickup) { + t.Fatalf("預期 ErrDropoffBeforePickup,得到 %v", err) + } + // 不該留下任何訂單。 + active, err := rides.FindActiveByCustomer(cust.ID) + if err != nil { + t.Fatalf("查詢失敗:%v", err) + } + if active != nil { + t.Fatalf("驗證失敗不該建出訂單,卻有 ride #%d", active.ID) + } +} + +// TestCreateByCustomer_未注入stops時明確失敗 設定沒接好時不可默默當單點訂單建出去 +// (那會變成「少載四個人」的行程)。 +func TestCreateByCustomer_未注入stops時明確失敗(t *testing.T) { + db := newServiceTestDB(t) + customers := repository.NewCustomerRepository(db) + rides := repository.NewRideRepository(db) + redis := newServiceTestRedis(t) + dispatch := NewDispatchService( + repository.NewDriverRepository(db), rides, customers, redis, + lineclient.NewClient(""), nil, NewDispatchSettings(3000, 5, 20, 1, 5), nil, + ) + svc := NewRideService(customers, rides, redis, dispatch) // 刻意不 SetStops + + cust, err := customers.FindOrCreateByLineUserID("U_stops_noinject", "乘客") + if err != nil { + t.Fatalf("建立乘客失敗:%v", err) + } + if _, err := svc.CreateByCustomer(context.Background(), cust.ID, CustomerCreateRequest{ + Stops: fourStopInputs(), + }); !errors.Is(err, ErrStopsUnavailable) { + t.Fatalf("預期 ErrStopsUnavailable,得到 %v", err) + } +} diff --git a/internal/service/ride_stops_validate.go b/internal/service/ride_stops_validate.go new file mode 100644 index 0000000..e711afc --- /dev/null +++ b/internal/service/ride_stops_validate.go @@ -0,0 +1,136 @@ +package service + +import ( + "errors" + "sort" + + "line-fleet-dispatch/internal/constants" +) + +// 停靠點驗證錯誤(N2)。分開成多個錯誤而非一個籠統的 ErrInvalidStops—— +// 乘客填錯時要知道錯在哪,handler 一律對應 400。 +var ( + ErrTooManyStops = errors.New("停靠點數量超過上限") + ErrTooManyPassengers = errors.New("乘客人數超過上限") + ErrInvalidStopKind = errors.New("停靠點種類無效") + ErrDuplicateStopSeq = errors.New("停靠點順序重複") + ErrUnpairedStop = errors.New("每位乘客都必須有上車點與下車點") + ErrDropoffBeforePickup = errors.New("乘客的下車點必須排在其上車點之後") + ErrMissingPassenger = errors.New("多停靠點行程必須指定乘客標籤") + // ErrStopsUnavailable 收到 stops 但未注入停靠點 repo(設定錯誤,非乘客的錯)。 + ErrStopsUnavailable = errors.New("多停靠點行程未啟用") +) + +// StopInput 建單時傳入的單一停靠點(N3)。 +type StopInput struct { + Seq int + Kind string + Lat, Lng float64 + Address string + PassengerLabel string +} + +// validateStops 檢查多停靠點行程的完整性(N2)。空 slice = 傳統單點訂單,直接放行。 +// +// 規則(2026-07-16 拍板:5 位乘客、各自上下車 → 最多 10 個停靠點): +// 1. 停靠點數 ≤ 10、乘客數 ≤ 5 +// 2. kind 必須是 pickup/dropoff;座標合法 +// 3. seq 不得重複(seq =「第幾站」,重複的話「下一站是誰」沒有答案) +// 4. 每位乘客必須**成對**出現 pickup + dropoff +// 5. 同一位乘客的 dropoff.seq 必須 > pickup.seq——不能先下車再上車 +// +// 這些是「司機能不能執行這趟行程」的前提,不是美觀問題: +// 少一半的乘客、或叫司機先送再接,都是無法執行的行程。 +func validateStops(stops []StopInput) error { + if len(stops) == 0 { + return nil // 單點訂單,維持現行行為 + } + if len(stops) > constants.MaxRideStops { + return ErrTooManyStops + } + + seqSeen := make(map[int]bool, len(stops)) + type pair struct{ pickupSeq, dropoffSeq int } + byPassenger := make(map[string]*pair) + + for _, s := range stops { + if !constants.IsValidStopKind(s.Kind) { + return ErrInvalidStopKind + } + if err := validatePickupCoords(s.Lat, s.Lng); err != nil { + return err + } + if s.Seq < 1 { + return ErrDuplicateStopSeq // seq 從 1 起算;0 或負數視同無效順序 + } + if seqSeen[s.Seq] { + return ErrDuplicateStopSeq + } + seqSeen[s.Seq] = true + + // 多停靠點時必須分得出「這站是誰」,否則司機不知道在等誰。 + if s.PassengerLabel == "" { + return ErrMissingPassenger + } + p, ok := byPassenger[s.PassengerLabel] + if !ok { + p = &pair{pickupSeq: -1, dropoffSeq: -1} + byPassenger[s.PassengerLabel] = p + } + switch s.Kind { + case constants.StopKindPickup: + if p.pickupSeq != -1 { + return ErrUnpairedStop // 同一位乘客兩個上車點 + } + p.pickupSeq = s.Seq + case constants.StopKindDropoff: + if p.dropoffSeq != -1 { + return ErrUnpairedStop // 同一位乘客兩個下車點 + } + p.dropoffSeq = s.Seq + } + } + + if len(byPassenger) > constants.MaxRidePassengers { + return ErrTooManyPassengers + } + for _, p := range byPassenger { + if p.pickupSeq == -1 || p.dropoffSeq == -1 { + return ErrUnpairedStop + } + if p.dropoffSeq <= p.pickupSeq { + return ErrDropoffBeforePickup + } + } + return nil +} + +// sortStopsBySeq 回傳依 seq 由小到大排序的副本(不改動呼叫端的 slice)。 +// 建單時客戶端不保證照順序送,但落庫與後續讀取都以 seq 為準。 +func sortStopsBySeq(stops []StopInput) []StopInput { + out := make([]StopInput, len(stops)) + copy(out, stops) + sort.Slice(out, func(i, j int) bool { return out[i].Seq < out[j].Seq }) + return out +} + +// firstPickup 最先的上車點——寫進 rides.pickup_point,派單據此找最近司機(N3 相容性)。 +func firstPickup(sorted []StopInput) (StopInput, bool) { + for _, s := range sorted { + if s.Kind == constants.StopKindPickup { + return s, true + } + } + return StopInput{}, false +} + +// finalDropoff 最終目的地=seq 最大的 dropoff——寫進 rides.dropoff_point。 +// 既有的地圖、司機導航、F3 路線里程退路都讀這個欄位,不必為多停靠點全面改寫。 +func finalDropoff(sorted []StopInput) (StopInput, bool) { + for i := len(sorted) - 1; i >= 0; i-- { + if sorted[i].Kind == constants.StopKindDropoff { + return sorted[i], true + } + } + return StopInput{}, false +} diff --git a/internal/service/ride_stops_validate_test.go b/internal/service/ride_stops_validate_test.go new file mode 100644 index 0000000..3f3c7b5 --- /dev/null +++ b/internal/service/ride_stops_validate_test.go @@ -0,0 +1,217 @@ +package service + +import ( + "errors" + "testing" + + "line-fleet-dispatch/internal/constants" +) + +// stop 測試用的簡便建構。座標一律用合法的台北座標,除非該案就是要測座標。 +func stop(seq int, kind, label string) StopInput { + return StopInput{Seq: seq, Kind: kind, Lat: 25.03, Lng: 121.56, Address: "某處", PassengerLabel: label} +} + +// 一趟合法的兩人四停:A 上 → B 上 → A 下 → B 下(同行乘客依序停靠)。 +func validFourStops() []StopInput { + return []StopInput{ + stop(1, constants.StopKindPickup, "A"), + stop(2, constants.StopKindPickup, "B"), + stop(3, constants.StopKindDropoff, "A"), + stop(4, constants.StopKindDropoff, "B"), + } +} + +func TestValidateStops_合法情境(t *testing.T) { + t.Run("空 stops=單點訂單,直接放行", func(t *testing.T) { + // 這是相容性的根本:既有 App/LINE 建單一律走這條。 + if err := validateStops(nil); err != nil { + t.Fatalf("單點訂單不該被擋:%v", err) + } + if err := validateStops([]StopInput{}); err != nil { + t.Fatalf("空 slice 不該被擋:%v", err) + } + }) + + t.Run("兩人四停交錯", func(t *testing.T) { + if err := validateStops(validFourStops()); err != nil { + t.Fatalf("合法的兩人行程被擋:%v", err) + } + }) + + t.Run("上限 5 位乘客 10 停", func(t *testing.T) { + var stops []StopInput + labels := []string{"A", "B", "C", "D", "E"} + for i, l := range labels { + stops = append(stops, stop(i+1, constants.StopKindPickup, l)) + } + for i, l := range labels { + stops = append(stops, stop(6+i, constants.StopKindDropoff, l)) + } + if err := validateStops(stops); err != nil { + t.Fatalf("5 位乘客 10 停應為合法上限:%v", err) + } + }) + + t.Run("客戶端未依序送也可以", func(t *testing.T) { + // 驗證只看 seq 的值,不看 slice 順序;落庫前會 sortStopsBySeq。 + s := validFourStops() + s[0], s[3] = s[3], s[0] + if err := validateStops(s); err != nil { + t.Fatalf("順序打亂但 seq 正確,不該被擋:%v", err) + } + }) +} + +func TestValidateStops_非法情境(t *testing.T) { + cases := []struct { + name string + stops []StopInput + want error + }{ + { + // 6 位乘客 12 停:先撞停靠點上限。 + name: "超過停靠點上限", + stops: func() []StopInput { + var s []StopInput + for i, l := range []string{"A", "B", "C", "D", "E", "F"} { + s = append(s, stop(i+1, constants.StopKindPickup, l)) + s = append(s, stop(i+7, constants.StopKindDropoff, l)) + } + return s + }(), + want: ErrTooManyStops, + }, + { + // 剛好 10 停但塞了 6 位乘客(有人只有單程)→ 先被配對規則擋下。 + name: "乘客未成對", + stops: []StopInput{ + stop(1, constants.StopKindPickup, "A"), + stop(2, constants.StopKindDropoff, "A"), + stop(3, constants.StopKindPickup, "B"), // B 沒有下車點 + }, + want: ErrUnpairedStop, + }, + { + // 最容易寫錯、也最致命的一條:叫司機先送再接。 + name: "下車排在上車之前", + stops: []StopInput{ + stop(1, constants.StopKindDropoff, "A"), + stop(2, constants.StopKindPickup, "A"), + }, + want: ErrDropoffBeforePickup, + }, + { + name: "同一位乘客兩個上車點", + stops: []StopInput{ + stop(1, constants.StopKindPickup, "A"), + stop(2, constants.StopKindPickup, "A"), + stop(3, constants.StopKindDropoff, "A"), + }, + want: ErrUnpairedStop, + }, + { + // seq =「第幾站」,重複的話「下一站是誰」沒有答案。 + name: "seq 重複", + stops: []StopInput{ + stop(1, constants.StopKindPickup, "A"), + stop(1, constants.StopKindDropoff, "A"), + }, + want: ErrDuplicateStopSeq, + }, + { + name: "seq 從 0 起算", + stops: []StopInput{ + stop(0, constants.StopKindPickup, "A"), + stop(1, constants.StopKindDropoff, "A"), + }, + want: ErrDuplicateStopSeq, + }, + { + name: "kind 非白名單", + stops: []StopInput{ + stop(1, "waypoint", "A"), + stop(2, constants.StopKindDropoff, "A"), + }, + want: ErrInvalidStopKind, + }, + { + name: "沒有乘客標籤", + stops: []StopInput{ + stop(1, constants.StopKindPickup, ""), + stop(2, constants.StopKindDropoff, ""), + }, + want: ErrMissingPassenger, + }, + { + name: "座標非法", + stops: []StopInput{ + {Seq: 1, Kind: constants.StopKindPickup, Lat: 0, Lng: 0, PassengerLabel: "A"}, + stop(2, constants.StopKindDropoff, "A"), + }, + want: ErrInvalidCoords, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + err := validateStops(tc.stops) + if !errors.Is(err, tc.want) { + t.Fatalf("預期 %v,得到 %v", tc.want, err) + } + }) + } +} + +// TestValidateStops_六位乘客 停靠點數在上限內、但乘客數超過 5 位。 +func TestValidateStops_六位乘客(t *testing.T) { + // 6 位乘客共 10 停:4 位完整成對(8 停)+ 2 位只有單程(2 停)→ 先被配對擋下。 + // 要單獨測「乘客數上限」得讓所有人都成對,但那樣必然 >10 停 → 先撞 ErrTooManyStops。 + // 也就是說:5 位乘客各自上下車=10 停,本來就是上限的兩種等價表述(N2 拍板)。 + var stops []StopInput + for i, l := range []string{"A", "B", "C", "D", "E"} { + stops = append(stops, stop(i+1, constants.StopKindPickup, l)) + stops = append(stops, stop(i+6, constants.StopKindDropoff, l)) + } + if err := validateStops(stops); err != nil { + t.Fatalf("5 位成對=10 停應合法:%v", err) + } + // 再加一位 → 12 停 → 撞停靠點上限。 + stops = append(stops, + StopInput{Seq: 11, Kind: constants.StopKindPickup, Lat: 25.03, Lng: 121.56, PassengerLabel: "F"}, + StopInput{Seq: 12, Kind: constants.StopKindDropoff, Lat: 25.03, Lng: 121.56, PassengerLabel: "F"}, + ) + if err := validateStops(stops); !errors.Is(err, ErrTooManyStops) { + t.Fatalf("第 6 位乘客應被擋,得到 %v", err) + } +} + +func TestSortStopsBySeq與推導(t *testing.T) { + s := []StopInput{ + stop(3, constants.StopKindDropoff, "A"), + stop(1, constants.StopKindPickup, "A"), + stop(4, constants.StopKindDropoff, "B"), + stop(2, constants.StopKindPickup, "B"), + } + sorted := sortStopsBySeq(s) + + // 不得改動呼叫端的 slice。 + if s[0].Seq != 3 { + t.Fatal("sortStopsBySeq 不該改動輸入") + } + for i, want := range []int{1, 2, 3, 4} { + if sorted[i].Seq != want { + t.Fatalf("排序錯誤:%+v", sorted) + } + } + + // 這兩個推導撐起 N3 的相容性:rides.pickup_point/dropoff_point 照樣有值, + // 派單、導航、地圖、報表都不用改。 + first, ok := firstPickup(sorted) + if !ok || first.Seq != 1 || first.PassengerLabel != "A" { + t.Fatalf("第一個上車點應為 seq=1 的 A:%+v", first) + } + final, ok := finalDropoff(sorted) + if !ok || final.Seq != 4 || final.PassengerLabel != "B" { + t.Fatalf("最終目的地應為 seq 最大的 dropoff(B):%+v", final) + } +}