diff --git a/cmd/server/main.go b/cmd/server/main.go index fc8cb52..8d057bb 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -162,6 +162,7 @@ func main() { rideQueryService.SetDrivers(driverRepo) // O4/O7:乘客查自己訂單時附司機姓名/電話 rideQueryService.SetStops(rideStopRepo) // N6:司機端 active 帶全程停靠點 rideStopService := service.NewRideStopService(rideRepo, rideStopRepo) + rideStopService.SetPublisher(hub) // N7:到站/跳過即時推給乘客(行程進度) chatService := service.NewChatService(rideRepo, rideMessageRepo, hub) lostItemService := service.NewLostItemService(rideRepo, lostItemRepo, feeSettings, hub) diff --git a/docs/TODO.md b/docs/TODO.md index 2481105..6b3ef62 100644 --- a/docs/TODO.md +++ b/docs/TODO.md @@ -375,6 +375,30 @@ 以及 `arrived_at`/`skipped_at`(**只在真的發生時帶**,兩者皆無=待處理)—— 司機據此知道「下一站是誰、在哪、處理了沒」。 +- [x] **N8. 乘客端行程 API 帶 stops + 進度事件** ✅ **已實作(2026-07-21)** + **缺口是 App 端回報的**:乘客送得出 stops(建單時),卻**看不到自己排的行程**—— + `CustomerRideView` 只加了司機聯絡資訊,帶 stops 的只有 `DriverRideView`。 + 乘客端因此做不出多停靠點地圖與行程進度。 + + 1. **`CustomerRideView` 加 `Stops`**(`omitempty`): + `GET /api/customer/rides/active` 與 `GET /api/customer/rides/:id` 都帶, + **形狀與 `DriverRideView.Stops` 完全相同**(實跑比對過欄位集合一致), + App 端兩邊共用同一套解析。單筆查詢也帶,歷史行程/遺失物協尋回頭查才看得到當時全程。 + 讀 stops 失敗**不擋**整筆查詢(stops 是加值資訊,不是行程本體), + 未注入 `stops` repo 時查詢照樣成功。 + 2. **新事件 `ride.stop_updated`**:司機標記到達/跳過時推給**本趟乘客**。 + payload 帶**整趟 stops** 而非單一 stop——乘客端收到直接覆蓋即可, + 不必在客戶端套用差異,漏收一則事件也不會讓狀態永遠對不上。 + **標記失敗(重複標記回 409)時不推事件**,否則乘客會收到「進度更新」卻什麼都沒變。 + publisher 未注入時標記照樣成功(只是乘客要等下一次輪詢)。 + + **驗收**:`go test ./internal/service/`(新增 9 項,含反向確認—— + 把乘客路徑改回 `withDriverContact` 會 FAIL)、events/handler 測試綠; + **docker live E2E**:乘客建 2 人 4 站訂單 → 乘客 active 回 4 站 → + 司機接單 → `arrive` 第 1 站 → **乘客 WS 即時收到 `ride.stop_updated`(帶整趟+`arrived_at`)** + → `skip` 第 2 站 → 乘客 active 顯示「已到達/已跳過/待處理/待處理」, + 與司機端 `GET /api/driver/rides/active` 欄位形狀一致。 + - [x] **N7. 到站/跳過標記** ✅ **已實作(2026-07-17)** (原標「可選」;因 2026-07-17 拍板「司機可跳過缺席乘客」而成為必要) `POST /api/rides/:id/stops/:stop_id/arrive`/`POST /api/rides/:id/stops/:stop_id/skip` diff --git a/internal/events/event.go b/internal/events/event.go index 4f3d8a2..43ac841 100644 --- a/internal/events/event.go +++ b/internal/events/event.go @@ -25,6 +25,9 @@ const ( TypeChatMessage = "chat.message" // 行程內對話訊息(乘客↔司機即時遞送) TypeLostItemCreated = "lost_item.created" // 乘客建立遺失物協尋單 TypeLostItemUpdated = "lost_item.updated" // 協尋單狀態變更(found/paid/returned/closed) + // TypeRideStopUpdated 司機標記到達/跳過某一站(N7)。payload 帶**整趟 stops**, + // 收到整批覆蓋即可,不必自己套用差異——乘客端據此顯示「走到第幾站」。 + TypeRideStopUpdated = "ride.stop_updated" ) // 審計 actor_role diff --git a/internal/service/ride.go b/internal/service/ride.go index a903f19..087870c 100644 --- a/internal/service/ride.go +++ b/internal/service/ride.go @@ -259,7 +259,8 @@ func NewRideQueryService(tracks *repository.TrackRepository, rides *repository.R return &RideQueryService{tracks: tracks, rides: rides} } -// SetStops 注入停靠點 repo(供司機端 active 帶 stops,N6);可選—— +// SetStops 注入停靠點 repo(司機端 active 帶 stops=N6;乘客端 active/單筆查詢 +// 也帶同樣的 stops,供乘客看自己排的行程進度);可選—— // 未注入時單點與多停靠點行程皆可查,只是後者不帶 stops。 func (s *RideQueryService) SetStops(stops *repository.RideStopRepository) { s.stops = stops @@ -284,6 +285,10 @@ type CustomerRideView struct { // DriverPhone 明碼(O7 拍板)。**僅該趟乘客可見**——本 struct 只由 // 「乘客查自己訂單」的路徑產生,絕不可用於任何列表或對其他角色的回應。 DriverPhone string `json:"driver_phone,omitempty"` + // Stops 全程停靠點(N)。乘客送得出 stops(建單時),也要看得到自己排的行程 + // 走到哪一站——形狀與司機端的 DriverRideView.Stops **完全相同**, + // App 端兩邊共用同一套解析。單點訂單為 nil(omitempty),既有形狀不變。 + Stops []map[string]any `json:"stops,omitempty"` } // withDriverContact 補上司機姓名/電話;未接單或未注入 drivers 時原樣回傳。 @@ -304,6 +309,21 @@ func (s *RideQueryService) withDriverContact(ride *model.Ride) *CustomerRideView return view } +// customerRideView 乘客視角的完整訂單:司機聯絡資訊 + 全程停靠點。 +// +// 停靠點讀失敗**不擋**整筆查詢——乘客仍能看到行程狀態與司機資訊, +// 這與司機端 GetActiveRideByDriver 的處理一致(stops 是加值資訊,不是行程本體)。 +func (s *RideQueryService) customerRideView(ride *model.Ride) *CustomerRideView { + view := s.withDriverContact(ride) + if view == nil || s.stops == nil { + return view + } + if stops, err := s.stops.ListByRide(ride.ID); err == nil { + view.Stops = stopViews(stops) + } + return view +} + func (s *RideQueryService) TrackGeoJSON(rideID int64) (string, error) { geojson, err := s.tracks.GeoJSON(rideID) if err != nil { @@ -323,7 +343,7 @@ func (s *RideQueryService) GetActiveRideByCustomer(customerID int64) (*CustomerR if err != nil || ride == nil { return nil, err } - return s.withDriverContact(ride), nil + return s.customerRideView(ride), nil } // GetActiveRideByDriver 找司機目前進行中的訂單(已接/載客中),供 App 中途重啟恢復行程;無則回 (nil, nil) @@ -378,5 +398,5 @@ func (s *RideQueryService) GetRideForCustomer(customerID, rideID int64) (*Custom } // 這條路徑也是遺失物協尋回頭查「當時搭哪台車、怎麼聯絡司機」的來源(O7), // 沒有時間限制:行程完成很久之後,本人仍查得到。 - return s.withDriverContact(ride), nil + return s.customerRideView(ride), nil } diff --git a/internal/service/ride_query_customer_stops_test.go b/internal/service/ride_query_customer_stops_test.go new file mode 100644 index 0000000..609d279 --- /dev/null +++ b/internal/service/ride_query_customer_stops_test.go @@ -0,0 +1,183 @@ +package service + +import ( + "testing" + + "line-fleet-dispatch/internal/constants" + "line-fleet-dispatch/internal/repository" +) + +// 乘客送得出 stops(建單時),也要看得到自己排的行程走到哪一站。 +// 形狀必須與司機端 DriverRideView.Stops 完全相同,App 端才能共用同一套解析。 + +func TestGetActiveRideByCustomer_多停靠點應帶stops(t *testing.T) { + db := newServiceTestDB(t) + customers := repository.NewCustomerRepository(db) + tracks := repository.NewTrackRepository(db) + rides := repository.NewRideRepository(db) + stops := repository.NewRideStopRepository(db) + + cust, err := customers.FindOrCreateByLineUserID("U_cust_stops", "測試乘客") + if err != nil { + t.Fatalf("建立乘客失敗:%v", err) + } + ride := newTestRide(t, rides, cust.ID, constants.RideStatusAccepted) + if err := stops.CreateForRide(ride.ID, []repository.StopRow{ + {Seq: 1, Kind: "pickup", Lat: 25.033, Lng: 121.5654, Address: "台北101", PassengerLabel: "A"}, + {Seq: 2, Kind: "dropoff", Lat: 25.0478, Lng: 121.517, Address: "台北車站", PassengerLabel: "A"}, + }); err != nil { + t.Fatalf("建立停靠點失敗:%v", err) + } + + q := NewRideQueryService(tracks, rides) + q.SetStops(stops) + + got, err := q.GetActiveRideByCustomer(cust.ID) + if err != nil { + t.Fatalf("查詢失敗:%v", err) + } + if got == nil { + t.Fatal("預期查到進行中訂單") + } + if len(got.Stops) != 2 { + t.Fatalf("預期帶 2 個停靠點,得到 %d", len(got.Stops)) + } + // 欄位形狀與司機端一致:座標攤平成 lat/lng,App 端不必另寫一套解析。 + first := got.Stops[0] + for _, key := range []string{"id", "seq", "kind", "lat", "lng", "passenger_label", "address"} { + if _, ok := first[key]; !ok { + t.Errorf("停靠點缺少欄位 %s:%v", key, first) + } + } + // 待處理的站不該帶到達/跳過時間——App 靠「兩者皆無」判斷待處理。 + if _, ok := first["arrived_at"]; ok { + t.Errorf("未到達的站不該有 arrived_at:%v", first) + } +} + +func TestGetActiveRideByCustomer_到站標記要反映在乘客端(t *testing.T) { + // 這是「行程進度」的核心:乘客要看得出司機走到第幾站。 + db := newServiceTestDB(t) + customers := repository.NewCustomerRepository(db) + tracks := repository.NewTrackRepository(db) + rides := repository.NewRideRepository(db) + stops := repository.NewRideStopRepository(db) + + cust, err := customers.FindOrCreateByLineUserID("U_cust_stops_progress", "測試乘客") + if err != nil { + t.Fatalf("建立乘客失敗:%v", err) + } + ride := newTestRide(t, rides, cust.ID, constants.RideStatusPickedUp) + if err := stops.CreateForRide(ride.ID, []repository.StopRow{ + {Seq: 1, Kind: "pickup", Lat: 25.033, Lng: 121.5654, PassengerLabel: "A"}, + {Seq: 2, Kind: "pickup", Lat: 25.036, Lng: 121.568, PassengerLabel: "B"}, + {Seq: 3, Kind: "dropoff", Lat: 25.0478, Lng: 121.517, PassengerLabel: "A"}, + }); err != nil { + t.Fatalf("建立停靠點失敗:%v", err) + } + rows, err := stops.ListByRide(ride.ID) + if err != nil { + t.Fatalf("讀停靠點失敗:%v", err) + } + if ok, err := stops.MarkArrived(rows[0].ID); err != nil || !ok { + t.Fatalf("標記到達失敗:ok=%v err=%v", ok, err) + } + if ok, err := stops.MarkSkipped(rows[1].ID); err != nil || !ok { + t.Fatalf("標記跳過失敗:ok=%v err=%v", ok, err) + } + + q := NewRideQueryService(tracks, rides) + q.SetStops(stops) + + got, err := q.GetActiveRideByCustomer(cust.ID) + if err != nil || got == nil { + t.Fatalf("查詢失敗:got=%v err=%v", got, err) + } + if _, ok := got.Stops[0]["arrived_at"]; !ok { + t.Errorf("已到達的站要帶 arrived_at:%v", got.Stops[0]) + } + if _, ok := got.Stops[1]["skipped_at"]; !ok { + t.Errorf("已跳過的站要帶 skipped_at:%v", got.Stops[1]) + } + if _, ok := got.Stops[2]["arrived_at"]; ok { + t.Errorf("尚未處理的站不該有 arrived_at:%v", got.Stops[2]) + } +} + +func TestGetRideForCustomer_多停靠點應帶stops(t *testing.T) { + // 單筆查詢(含遺失物協尋回頭查)也要帶,否則歷史行程看不到當時的全程。 + db := newServiceTestDB(t) + customers := repository.NewCustomerRepository(db) + tracks := repository.NewTrackRepository(db) + rides := repository.NewRideRepository(db) + stops := repository.NewRideStopRepository(db) + + cust, err := customers.FindOrCreateByLineUserID("U_cust_stops_single", "測試乘客") + if err != nil { + t.Fatalf("建立乘客失敗:%v", err) + } + ride := newTestRide(t, rides, cust.ID, constants.RideStatusCompleted) + if err := stops.CreateForRide(ride.ID, []repository.StopRow{ + {Seq: 1, Kind: "pickup", Lat: 25.033, Lng: 121.5654, PassengerLabel: "A"}, + {Seq: 2, Kind: "dropoff", Lat: 25.0478, Lng: 121.517, PassengerLabel: "A"}, + }); err != nil { + t.Fatalf("建立停靠點失敗:%v", err) + } + + q := NewRideQueryService(tracks, rides) + q.SetStops(stops) + + got, err := q.GetRideForCustomer(cust.ID, ride.ID) + if err != nil { + t.Fatalf("查詢失敗:%v", err) + } + if len(got.Stops) != 2 { + t.Fatalf("預期帶 2 個停靠點,得到 %d", len(got.Stops)) + } +} + +func TestCustomerRideView_單點訂單不帶stops鍵(t *testing.T) { + // omitempty:單點訂單的回應形狀一個位元組都不該變,舊版 App 不受影響。 + db := newServiceTestDB(t) + customers := repository.NewCustomerRepository(db) + tracks := repository.NewTrackRepository(db) + rides := repository.NewRideRepository(db) + stops := repository.NewRideStopRepository(db) + + cust, err := customers.FindOrCreateByLineUserID("U_cust_single_point", "測試乘客") + if err != nil { + t.Fatalf("建立乘客失敗:%v", err) + } + newTestRide(t, rides, cust.ID, constants.RideStatusRequested) + + q := NewRideQueryService(tracks, rides) + q.SetStops(stops) + + got, err := q.GetActiveRideByCustomer(cust.ID) + if err != nil || got == nil { + t.Fatalf("查詢失敗:got=%v err=%v", got, err) + } + if got.Stops != nil { + t.Fatalf("單點訂單不該有 stops,得到 %v", got.Stops) + } +} + +func TestCustomerRideView_未注入stops仍可查(t *testing.T) { + // stops 是加值資訊,不是行程本體:沒注入 repo 時查詢照樣要成功。 + db := newServiceTestDB(t) + customers := repository.NewCustomerRepository(db) + tracks := repository.NewTrackRepository(db) + rides := repository.NewRideRepository(db) + + cust, err := customers.FindOrCreateByLineUserID("U_cust_no_stop_repo", "測試乘客") + if err != nil { + t.Fatalf("建立乘客失敗:%v", err) + } + ride := newTestRide(t, rides, cust.ID, constants.RideStatusRequested) + + q := NewRideQueryService(tracks, rides) // 刻意不 SetStops + got, err := q.GetActiveRideByCustomer(cust.ID) + if err != nil || got == nil || got.ID != ride.ID { + t.Fatalf("未注入 stops repo 時查詢仍應成功:got=%v err=%v", got, err) + } +} diff --git a/internal/service/ride_stops.go b/internal/service/ride_stops.go index f405b01..1dc81f6 100644 --- a/internal/service/ride_stops.go +++ b/internal/service/ride_stops.go @@ -4,6 +4,7 @@ import ( "errors" "line-fleet-dispatch/internal/constants" + "line-fleet-dispatch/internal/events" "line-fleet-dispatch/internal/model" "line-fleet-dispatch/internal/repository" ) @@ -66,14 +67,21 @@ type DriverRideView struct { // RideStopService 停靠點的讀取與標記(N6/N7)。 type RideStopService struct { - rides *repository.RideRepository - stops *repository.RideStopRepository + rides *repository.RideRepository + stops *repository.RideStopRepository + publisher events.Publisher } func NewRideStopService(rides *repository.RideRepository, stops *repository.RideStopRepository) *RideStopService { return &RideStopService{rides: rides, stops: stops} } +// SetPublisher 注入事件發佈器,讓到站/跳過即時推給乘客;可選—— +// 未注入時標記照樣成功,乘客只是要等下一次輪詢才看得到進度。 +func (s *RideStopService) SetPublisher(p events.Publisher) { + s.publisher = p +} + // ListForDriver 司機讀取自己那趟的停靠點;非被指派司機回 ErrForbidden。 func (s *RideStopService) ListForDriver(driverID, rideID int64) ([]model.RideStop, error) { ride, err := s.rides.GetByID(rideID) @@ -127,5 +135,29 @@ func (s *RideStopService) mark(driverID, rideID, stopID int64, do func(int64) (b if !ok { return ErrStopAlreadyHandled // 已到達或已跳過,不覆寫 } + s.publishStops(ride.ID, ride.CustomerID) return nil } + +// publishStops 把**整趟**最新停靠點推給乘客(司機端剛做完動作、會自己重讀 active)。 +// +// 帶整批而非單一 stop:乘客端收到直接覆蓋即可,不必在客戶端套用差異, +// 也不怕漏收某一則事件後狀態就永遠對不上。 +// 讀失敗/未注入 publisher 都不影響標記本身——標記已經寫進 DB 了。 +func (s *RideStopService) publishStops(rideID, customerID int64) { + if s.publisher == nil { + return + } + stops, err := s.stops.ListByRide(rideID) + if err != nil { + return + } + s.publisher.Publish( + events.Recipient{Role: events.RoleCustomer, ID: customerID}, + events.Event{ + Type: events.TypeRideStopUpdated, + RideID: rideID, + Payload: map[string]any{"stops": stopViews(stops)}, + }, + ) +} diff --git a/internal/service/ride_stops_publish_test.go b/internal/service/ride_stops_publish_test.go new file mode 100644 index 0000000..c0bf403 --- /dev/null +++ b/internal/service/ride_stops_publish_test.go @@ -0,0 +1,143 @@ +package service + +import ( + "testing" + "time" + + "line-fleet-dispatch/internal/constants" + "line-fleet-dispatch/internal/events" + "line-fleet-dispatch/internal/model" + "line-fleet-dispatch/internal/repository" +) + +// 到站/跳過要即時推給乘客,否則乘客只能等下一次輪詢才知道司機走到第幾站。 + +type publishFixture struct { + svc *RideStopService + pub *fakePublisher + rideID int64 + driverID int64 + customerID int64 + stopIDs []int64 +} + +func newPublishFixture(t *testing.T, prefix string) *publishFixture { + t.Helper() + db := newServiceTestDB(t) + customers := repository.NewCustomerRepository(db) + drivers := repository.NewDriverRepository(db) + rides := repository.NewRideRepository(db) + stopsRepo := repository.NewRideStopRepository(db) + + cust, err := customers.FindOrCreateByLineUserID(prefix+"_cust", "乘客") + if err != nil { + t.Fatalf("建立乘客失敗:%v", err) + } + driver, err := drivers.FindOrCreate(prefix+"_drv", "司機") + if err != nil { + t.Fatalf("建立司機失敗:%v", err) + } + now := time.Now() + ride := &model.Ride{ + CustomerID: cust.ID, Status: constants.RideStatusRequested, + PickupPoint: model.GeoPoint{Lat: 25.03, Lng: 121.56}, PickupAddress: "台北車站", + RequestedAt: now, CreatedAt: now, UpdatedAt: now, + } + if err := rides.Create(ride); err != nil { + t.Fatalf("建立訂單失敗:%v", err) + } + if err := stopsRepo.CreateForRide(ride.ID, []repository.StopRow{ + {Seq: 1, Kind: constants.StopKindPickup, Lat: 25.03, Lng: 121.56, PassengerLabel: "A"}, + {Seq: 2, Kind: constants.StopKindDropoff, Lat: 25.05, Lng: 121.58, PassengerLabel: "A"}, + }); err != nil { + t.Fatalf("建立停靠點失敗:%v", err) + } + if err := rides.AcceptRide(ride.ID, driver.ID, 300); err != nil { + t.Fatalf("接單失敗:%v", err) + } + stops, err := stopsRepo.ListByRide(ride.ID) + if err != nil { + t.Fatalf("讀停靠點失敗:%v", err) + } + ids := make([]int64, 0, len(stops)) + for _, s := range stops { + ids = append(ids, s.ID) + } + + pub := &fakePublisher{} + svc := NewRideStopService(rides, stopsRepo) + svc.SetPublisher(pub) + return &publishFixture{ + svc: svc, pub: pub, + rideID: ride.ID, driverID: driver.ID, customerID: cust.ID, stopIDs: ids, + } +} + +func TestMarkArrived_推ride_stop_updated給乘客(t *testing.T) { + f := newPublishFixture(t, "U_stop_pub") + + if err := f.svc.MarkArrived(f.driverID, f.rideID, f.stopIDs[0]); err != nil { + t.Fatalf("標記到達失敗:%v", err) + } + if f.pub.count() != 1 { + t.Fatalf("預期推 1 則事件,得到 %d", f.pub.count()) + } + got := f.pub.recv[0] + if got.Rec.Role != events.RoleCustomer || got.Rec.ID != f.customerID { + t.Errorf("事件要送給本趟乘客,得到 %+v", got.Rec) + } + if got.Ev.Type != events.TypeRideStopUpdated || got.Ev.RideID != f.rideID { + t.Errorf("事件型別/ride_id 不符:%+v", got.Ev) + } + // payload 帶整趟 stops:乘客端收到直接覆蓋,不必自己套用差異、也不怕漏收事件。 + stops, ok := got.Ev.Payload["stops"].([]map[string]any) + if !ok || len(stops) != 2 { + t.Fatalf("payload 應帶整趟 2 個停靠點,得到 %v", got.Ev.Payload["stops"]) + } + if _, ok := stops[0]["arrived_at"]; !ok { + t.Errorf("剛標記到達的站要帶 arrived_at:%v", stops[0]) + } + if _, ok := stops[1]["arrived_at"]; ok { + t.Errorf("未處理的站不該有 arrived_at:%v", stops[1]) + } +} + +func TestMarkSkipped_也要推事件(t *testing.T) { + f := newPublishFixture(t, "U_stop_pub_skip") + + if err := f.svc.MarkSkipped(f.driverID, f.rideID, f.stopIDs[0]); err != nil { + t.Fatalf("標記跳過失敗:%v", err) + } + if f.pub.count() != 1 { + t.Fatalf("預期推 1 則事件,得到 %d", f.pub.count()) + } + stops := f.pub.recv[0].Ev.Payload["stops"].([]map[string]any) + if _, ok := stops[0]["skipped_at"]; !ok { + t.Errorf("跳過的站要帶 skipped_at:%v", stops[0]) + } +} + +func TestMark_失敗時不推事件(t *testing.T) { + f := newPublishFixture(t, "U_stop_pub_fail") + + // 重複標記:第二次回 ErrStopAlreadyHandled,狀態沒變就不該再推事件 + // (否則乘客端會收到「進度更新」卻什麼都沒變)。 + if err := f.svc.MarkArrived(f.driverID, f.rideID, f.stopIDs[0]); err != nil { + t.Fatalf("第一次標記應成功:%v", err) + } + if err := f.svc.MarkArrived(f.driverID, f.rideID, f.stopIDs[0]); err == nil { + t.Fatal("重複標記應回錯誤") + } + if f.pub.count() != 1 { + t.Fatalf("失敗的標記不該推事件,總共推了 %d 則", f.pub.count()) + } +} + +func TestMark_未注入publisher仍可標記(t *testing.T) { + f := newPublishFixture(t, "U_stop_pub_nil") + f.svc.SetPublisher(nil) // 推播是加值,不是標記的前提 + + if err := f.svc.MarkArrived(f.driverID, f.rideID, f.stopIDs[0]); err != nil { + t.Fatalf("未注入 publisher 時標記仍應成功:%v", err) + } +}