From aa176a2294317203286c7cbbc6b3e45ce5197469 Mon Sep 17 00:00:00 2001 From: awei Date: Thu, 30 Jul 2026 00:16:07 +0800 Subject: [PATCH] =?UTF-8?q?feat(dispatch):=20=E4=B9=98=E5=AE=A2=E7=AB=AF?= =?UTF-8?q?=E6=8E=A8=E6=92=AD=E7=9A=84=E9=80=81=E5=87=BA=E8=B7=AF=E5=BE=91?= =?UTF-8?q?=E2=80=94=E2=80=94=E6=8E=A5=E5=96=AE=EF=BC=8F=E6=8A=B5=E9=81=94?= =?UTF-8?q?=EF=BC=8F=E5=AE=8C=E6=88=90=EF=BC=8F=E5=8F=96=E6=B6=88=E9=83=BD?= =?UTF-8?q?=E9=80=81=E5=BE=97=E5=88=B0=E6=89=8B=E6=A9=9F=EF=BC=88U?= =?UTF-8?q?=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit App 端(fleet-app #78)已經接完線:登入註冊 device token、推播只當對帳訊號。 但後端 `notify.Dispatcher` 只有 `NotifyDriverRideOffer` 一條路徑—— `/api/customer/device-token` 從上線那天起收到的 token 就沒有任何用途, 乘客把 App 收到背景(WS 斷線)後,司機接單/抵達/完成/取消**手機上一則通知都沒有**。 - `AppPusher` 加 `SendRideUpdate`、`Dispatcher` 加 `NotifyCustomerRideUpdate`; 與派單邀請分兩個方法,讓失敗的 log 分得出是哪一條路徑。FCM 兩條共用送出邏輯、 同樣 Priority=high(「司機已抵達」晚到就沒有意義)。 - 接上五種事件:ride.accepted/driver.arrived/ride.completed/ride.cancelled/ ride.redispatched。TrackingService 補 SetAppNotifier(先前只有 DispatchService 有, 抵達與完成因此送不出去)。 - 白名單與 App 端 `_customerPushTypes` 對齊;**不送 driver.location**(每 8 秒一則)。 - data 只帶 type 與 ride_id:App 醒來後重讀 rides/active,車資這類會變的欄位不放 (推播延遲數十秒才到時,內容早就過期)。 - 乘客自己按的取消不推播(他人就在前景);admin/逾時取消才推。 順手修掉:`checkGeofence` 原本把**整個抵達通知(含 WS 事件與審計)**掛在 「查得到 LINE ID」上,改成 LINE 只是其中一條管道。 驗收:go test ./internal/notify 綠;service 四支整合測試(真 PostGIS+Redis)通過, 含「乘客自撤不推播」的負向斷言。反向確認:把 notifyCustomerRide 改成永遠早退,四支全紅。 Co-Authored-By: Claude Opus 5 --- README.md | 3 +- cmd/server/main.go | 3 + docs/TODO.md | 53 ++++- internal/notify/fcm.go | 19 +- internal/notify/notify.go | 46 ++++ internal/notify/notify_test.go | 111 +++++++-- internal/service/customer_push.go | 68 ++++++ internal/service/customer_push_test.go | 315 +++++++++++++++++++++++++ internal/service/dispatch.go | 8 + internal/service/tracking.go | 25 +- 10 files changed, 628 insertions(+), 23 deletions(-) create mode 100644 internal/service/customer_push.go create mode 100644 internal/service/customer_push_test.go diff --git a/README.md b/README.md index 11de6b7..b99acd1 100644 --- a/README.md +++ b/README.md @@ -164,7 +164,8 @@ Redis 鍵:`drivers:geo`(GEO 位置集合)、`driver:{id}:loc`(最新位 - **F9-7 `rides` 月分割**:量體達千萬級時依 `completed_at` 做 declarative partitioning。 - **`drivers`/`membership_invoices` 真分頁**:逼近 `MaxListRows=5000` 時比照 `rides` 改 offset/keyset 伺服器端分頁(含前端)。 -- **聊天訊息 FCM 推播**:App 被殺時收不到 `chat.message`(派單推播 A2 已實作)。 +- **聊天訊息 FCM 推播**:App 被殺時收不到 `chat.message`(司機派單 A2 與**乘客行程狀態** + 推播皆已實作,見 docs/TODO.md「U. 乘客端 App 推播的送出路徑」;缺的只剩聊天這一種)。 - **F3 強化(可選)**:軌跡稀疏偵測目前用「軌跡 vs 路線取大者」,是否再加 「後台手動校正單筆車資」待產品定。 - **評分的營運動作**(B5 下游):目前三端都只「看得到」評分,**沒有低分司機的處理流程** diff --git a/cmd/server/main.go b/cmd/server/main.go index dbe305d..47b2b1c 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -155,6 +155,9 @@ func main() { hub, ) trackingService.SetRideEvents(rideEventRepo) + // 乘客端推播:司機已抵達/行程完成也要送到手機。漏了這行,這兩則只有 WS—— + // 而乘客把 App 收在背景時 WS 早就斷了。 + trackingService.SetAppNotifier(appNotify) trackingService.SetFeeSettings(feeSettings) trackingService.SetOSRM(osrm) // F3:軌跡里程偏低時以 OSRM 路線里程作計費地板 trackingService.SetReports(reportRepo) // F9-3:完成時重算每日彙總 daily_driver_earnings diff --git a/docs/TODO.md b/docs/TODO.md index 85e5779..4bd722e 100644 --- a/docs/TODO.md +++ b/docs/TODO.md @@ -1049,6 +1049,55 @@ admin 端對應:fleet-frontEnd PR #22(司機管理頁評價欄、訂單詳 --- +## 📲 U. 乘客端 App 推播的送出路徑(2026-07-30 補上) + +> 來源:fleet-app 第九輪盤點的「候選 1」。App 端已於 fleet-app PR #78 接完線 +> (登入後 `POST /api/customer/device-token`、推播只當對帳訊號), +> **但後端一則都送不出去**——`notify.Dispatcher` 只有 `NotifyDriverRideOffer` 一個方法。 +> 也就是說 `/api/customer/device-token` 這支端點從上線那天起,收到的 token 就沒有任何用途。 + +**症狀(改之前)**:乘客把 App 收到背景 → WS 斷線 → 司機接單/抵達/完成/取消時 +**手機上完全沒有任何通知**,要等他自己再打開 App、輪詢跑一次才知道。 +LINE 那條管道有推文字訊息,但那是 LINE 官方帳號的對話,不是 App 通知。 + +**做了什麼**: + +- [x] **`AppPusher` 加 `SendRideUpdate`**、`Dispatcher` 加 `NotifyCustomerRideUpdate`。 + 與派單邀請分兩個方法,是為了讓失敗的 log 分得出是哪一條路徑 + (派單失敗記在司機那筆、行程更新失敗記在乘客那筆)。 + `FCMPusher` 兩條共用同一段送出邏輯,同樣 `Priority=high`—— + 「司機已抵達」晚到就沒有意義了。 +- [x] **接上五種事件**:`ride.accepted`(接單)、`driver.arrived`(進圍籬)、 + `ride.completed`(完成)、`ride.cancelled`(逾時無人接單/他人取消)、 + `ride.redispatched`(司機放棄後重派)。`TrackingService` 也補了 `SetAppNotifier` + (先前只有 `DispatchService` 有,抵達與完成這兩則因此送不出去)。 +- [x] **白名單與 App 端對齊**(`lib/core/push/push_payload.dart` 的 `_customerPushTypes`): + App 收到白名單外的 type 直接丟掉,後端多送只是白燒推播額度。 + **特別不送 `driver.location`**——司機每 8 秒回報一次,拿它推播會把電池與額度燒光。 +- [x] **data 只帶 `type` 與 `ride_id`**:App 把推播只當對帳訊號,醒來後重讀 `rides/active`。 + 車資、司機姓名這類會變的欄位一律不放——推播可能延遲數十秒才到, + 內容早就過期,直接顯示反而會讓 App 說謊。 +- [x] **乘客自己按的取消不推播**:他人就在 App 前景、剛按下去,系統匣再跳一則只是噪音。 + admin/系統(逾時)取消才推。 + +**順手修掉的一個洞**:`checkGeofence` 原本是 +`if err != nil || customerLineID == "" { return }`——**整個抵達通知(含 WS 事件與審計記錄) +都掛在 LINE ID 查得到與否**。現行資料下每位乘客都有 `line_user_id`(App 註冊也用它當帳號), +所以還沒有人踩到;但這是一顆定時炸彈:哪天有一條建立乘客的路徑沒填它, +司機到了乘客端會完全無聲。已改成「LINE 只是其中一條管道,查不到就只跳過那一條」。 + +**驗收(2026-07-30 實跑)**:`go test ./internal/notify/` 綠; +service 層四支整合測試(真 PostGIS + Redis 容器)通過——接單、進圍籬、完成、 +admin 取消各驗到一則推播,乘客自己取消驗到**沒有**推播。 +**反向確認**:把 `notifyCustomerRide` 改成永遠早退,四支全部 FAIL, +確認斷言吃的是真的送出路徑而不是別的東西。 + +**還缺的一半(不在後端)**:Firebase 專案憑證(`FCM_CREDENTIALS_FILE`)。 +沒有憑證時走 `LogPusher` stub——這條路徑照樣可驗(log 印得出要送給誰、送什麼 data), +但手機不會真的響。憑證到位後不必再改程式碼。 + +--- + ## 下次任務 **新需求(2026-07-16 加入,尚未實作,皆需後端地基先行)**: @@ -1088,7 +1137,9 @@ admin 端對應:fleet-frontEnd PR #22(司機管理頁評價欄、訂單詳 其餘皆屬「量體上升後才需」的大資料量最佳化,勿過早做: 1. **協尋/對話 Phase 2 剩餘**:遺失物處理費真金流(目前記帳式確認); - 聊天訊息 FCM 推播(App 被殺時)。~~admin 協尋單總覽+對話稽核 UI~~ ✅ 2026-07-15 + 聊天訊息 FCM 推播(App 被殺時)——**送出的地基已在 U 章備妥** + (`Dispatcher.NotifyCustomerRideUpdate`),要做的是決定聊天訊息要不要另立一種 data type, + 以及 App 端收到後怎麼處理(現行白名單只收行程狀態五種)。~~admin 協尋單總覽+對話稽核 UI~~ ✅ 2026-07-15 (後端 H4 `GET /api/admin/lost-items`+前端 fleet-frontEnd#11)。 2. **F9-7 rides 月分割**:量體達千萬級時依 `completed_at` 做 declarative partitioning。 3. **drivers/membership 真分頁**:逼近 `MaxListRows=5000` 上限時,比照 rides 改 offset/keyset 伺服器端分頁(含前端)。 diff --git a/internal/notify/fcm.go b/internal/notify/fcm.go index 122bcf5..6b9b386 100644 --- a/internal/notify/fcm.go +++ b/internal/notify/fcm.go @@ -43,6 +43,21 @@ func NewFCMPusher(ctx context.Context, credentialsFile string) (*FCMPusher, erro // 逐台送、逐台判斷失敗——一台 token 失效(換機、重裝)不該讓其他裝置收不到; // 全部失敗才回錯,讓 Dispatcher 打一條 log(但仍不中斷派單)。 func (p *FCMPusher) SendRideOffer(ctx context.Context, devices []Device, rideID int64, title, body string, data map[string]string) error { + return p.send(ctx, devices, rideID, title, body, data, "派單") +} + +// SendRideUpdate 送乘客端行程狀態更新推播。 +// +// 與派單邀請共用送出邏輯,也同樣 Priority=high——「司機已抵達」晚到就沒有意義了。 +// 差別只在 log 的 kind 標記,讓兩條路徑的成功/失敗在 log 裡分得開。 +func (p *FCMPusher) SendRideUpdate(ctx context.Context, devices []Device, rideID int64, title, body string, data map[string]string) error { + return p.send(ctx, devices, rideID, title, body, data, "行程狀態") +} + +func (p *FCMPusher) send( + ctx context.Context, devices []Device, rideID int64, + title, body string, data map[string]string, kind string, +) error { tokens := make([]string, 0, len(devices)) for _, d := range devices { if d.Platform == PlatformFCM && d.Token != "" { @@ -78,6 +93,7 @@ func (p *FCMPusher) SendRideOffer(ctx context.Context, devices []Device, rideID Err(r.Error). Str("token_prefix", tokenPrefix(tokens[i])). Int64("ride_id", rideID). + Str("kind", kind). Msg("FCM 單台推播失敗(token 可能失效)") } } @@ -89,6 +105,7 @@ func (p *FCMPusher) SendRideOffer(ctx context.Context, devices []Device, rideID Int("success", resp.SuccessCount). Int("failure", resp.FailureCount). Int64("ride_id", rideID). - Msg("FCM 派單推播已送出") + Str("kind", kind). + Msg("FCM 推播已送出") return nil } diff --git a/internal/notify/notify.go b/internal/notify/notify.go index 99ee396..e74e8bc 100644 --- a/internal/notify/notify.go +++ b/internal/notify/notify.go @@ -26,8 +26,13 @@ type Device struct { // **值一律字串**(FCM data payload 限制)。App 端 fleetEventFromPushData 據此 // 直接開接單卡。stops 這種結構化陣列**不放進 data**——App 接單後重讀 rides/active // 以後端補齊全程(見 fleet-app:acceptOffer 重讀 active),推播保持精簡。 +// +// SendRideUpdate 是**乘客端**那條:行程狀態變了(司機已接單/已抵達/完成/取消/重新派車)。 +// 與派單邀請分成兩個方法,是因為兩邊的語意與失敗處理不同——派單失敗要記在司機那筆, +// 行程更新失敗要記在乘客那筆;共用一個方法會讓 log 分不出是哪一條路徑。 type AppPusher interface { SendRideOffer(ctx context.Context, devices []Device, rideID int64, title, body string, data map[string]string) error + SendRideUpdate(ctx context.Context, devices []Device, rideID int64, title, body string, data map[string]string) error } // DeviceLookup 查某角色主體的裝置 token。 @@ -65,6 +70,32 @@ func (d *Dispatcher) NotifyDriverRideOffer(ctx context.Context, driverID, rideID } } +// NotifyCustomerRideUpdate 推播「這趟車的狀態變了」給乘客的所有裝置。 +// +// App 端把這則推播**只當對帳訊號**:醒來後重讀 rides/active,不直接信 data 裡的內容 +// (見 fleet-app:isCustomerRidePush → refreshActive)。所以 data 只需要 type 與 ride_id, +// 車資、司機姓名這類會變的欄位一律不放——推播可能延遲數十秒才到,內容早就過期了。 +// +// 失敗只打 log:乘客收不到推播的後果是「App 在背景時晚一點才知道」, +// 不該讓接單/完成這些主鏈路動作跟著失敗。 +func (d *Dispatcher) NotifyCustomerRideUpdate(ctx context.Context, customerID, rideID int64, title, body string, data map[string]string) { + if d == nil || d.tokens == nil { + return + } + devices, err := d.tokens.ListBySubject(RoleCustomer, customerID) + if err != nil { + log.Error().Err(err).Int64("customer_id", customerID).Msg("查詢乘客裝置 token 失敗") + return + } + if len(devices) == 0 { + return + } + if err := d.push.SendRideUpdate(ctx, devices, rideID, title, body, data); err != nil { + log.Error().Err(err).Int64("customer_id", customerID).Int64("ride_id", rideID). + Msg("App 推播行程狀態失敗") + } +} + // LogPusher 開發用 stub:只記錄將送出的 token,不打外部服務。 type LogPusher struct{} @@ -83,6 +114,21 @@ func (LogPusher) SendRideOffer(ctx context.Context, devices []Device, rideID int return nil } +func (LogPusher) SendRideUpdate(ctx context.Context, devices []Device, rideID int64, title, body string, data map[string]string) error { + _ = ctx + _ = body + for _, d := range devices { + log.Info(). + Str("platform", d.Platform). + Str("token_prefix", tokenPrefix(d.Token)). + Int64("ride_id", rideID). + Str("title", title). + Interface("data", data). + Msg("App 推播(stub):行程狀態更新") + } + return nil +} + func tokenPrefix(token string) string { if len(token) <= 8 { return token diff --git a/internal/notify/notify_test.go b/internal/notify/notify_test.go index c9fe62f..b89a10a 100644 --- a/internal/notify/notify_test.go +++ b/internal/notify/notify_test.go @@ -2,29 +2,34 @@ package notify import ( "context" + "errors" "testing" ) +type pushCall struct { + kind string // "offer"/"update",用來確認走的是哪一條路徑 + devices []Device + rideID int64 + title string + body string + data map[string]string +} + type recordingPusher struct { - calls []struct { - devices []Device - rideID int64 - title string - body string - data map[string]string - } + calls []pushCall + err error // 非 nil 時模擬送出失敗 } func (r *recordingPusher) SendRideOffer(ctx context.Context, devices []Device, rideID int64, title, body string, data map[string]string) error { _ = ctx - r.calls = append(r.calls, struct { - devices []Device - rideID int64 - title string - body string - data map[string]string - }{devices, rideID, title, body, data}) - return nil + r.calls = append(r.calls, pushCall{"offer", devices, rideID, title, body, data}) + return r.err +} + +func (r *recordingPusher) SendRideUpdate(ctx context.Context, devices []Device, rideID int64, title, body string, data map[string]string) error { + _ = ctx + r.calls = append(r.calls, pushCall{"update", devices, rideID, title, body, data}) + return r.err } type mapLookup map[int64][]Device @@ -34,6 +39,20 @@ func (m mapLookup) ListBySubject(role string, subjectID int64) ([]Device, error) return m[subjectID], nil } +// roleLookup 依「角色+主體」查裝置——用來釘住司機/乘客不會查錯人。 +type roleLookup map[string]map[int64][]Device + +func (m roleLookup) ListBySubject(role string, subjectID int64) ([]Device, error) { + return m[role][subjectID], nil +} + +type failingLookup struct{} + +func (failingLookup) ListBySubject(role string, subjectID int64) ([]Device, error) { + _, _ = role, subjectID + return nil, errors.New("db down") +} + func TestDispatcher_NotifyDriverRideOffer(t *testing.T) { pusher := &recordingPusher{} d := NewDispatcher(mapLookup{ @@ -66,3 +85,65 @@ func TestDispatcher_無裝置時不送(t *testing.T) { t.Fatalf("不應送出,得到 %d", len(pusher.calls)) } } + +// 乘客端推播的送出路徑:先前只有司機那一條,乘客註冊了 token 也永遠收不到任何推播。 +func TestDispatcher_NotifyCustomerRideUpdate(t *testing.T) { + pusher := &recordingPusher{} + d := NewDispatcher(roleLookup{ + RoleCustomer: {5: {{Platform: PlatformFCM, Token: "cust-tok"}}}, + RoleDriver: {5: {{Platform: PlatformFCM, Token: "driver-tok"}}}, + }, pusher) + + d.NotifyCustomerRideUpdate(context.Background(), 5, 42, "司機已抵達", "請準備上車", + map[string]string{"type": "driver.arrived", "ride_id": "42"}) + + if len(pusher.calls) != 1 { + t.Fatalf("預期送出 1 次,得到 %d", len(pusher.calls)) + } + call := pusher.calls[0] + // 走的是 update 那條,不是派單邀請。 + if call.kind != "update" { + t.Errorf("kind=%q,預期 update", call.kind) + } + // 同一個 ID 在司機表也有裝置——查錯角色會拿到 driver-tok。 + if len(call.devices) != 1 || call.devices[0].Token != "cust-tok" { + t.Errorf("devices=%v,應只查乘客的裝置", call.devices) + } + if call.rideID != 42 || call.title != "司機已抵達" { + t.Errorf("rideID=%d title=%q", call.rideID, call.title) + } + if call.data["type"] != "driver.arrived" || call.data["ride_id"] != "42" { + t.Errorf("data=%v", call.data) + } +} + +func TestDispatcher_乘客無裝置時不送(t *testing.T) { + pusher := &recordingPusher{} + d := NewDispatcher(roleLookup{}, pusher) + d.NotifyCustomerRideUpdate(context.Background(), 1, 2, "t", "b", nil) + if len(pusher.calls) != 0 { + t.Fatalf("不應送出,得到 %d", len(pusher.calls)) + } +} + +// 查 token 失敗與送出失敗都只打 log——推播不該讓接單/完成這些主鏈路動作跟著爆。 +func TestDispatcher_失敗不中斷(t *testing.T) { + d := NewDispatcher(failingLookup{}, &recordingPusher{}) + d.NotifyCustomerRideUpdate(context.Background(), 1, 2, "t", "b", nil) + + failing := &recordingPusher{err: errors.New("fcm down")} + d2 := NewDispatcher(roleLookup{ + RoleCustomer: {1: {{Platform: PlatformFCM, Token: "tok"}}}, + }, failing) + d2.NotifyCustomerRideUpdate(context.Background(), 1, 2, "t", "b", nil) + if len(failing.calls) != 1 { + t.Fatalf("仍應嘗試送出一次,得到 %d", len(failing.calls)) + } +} + +// nil Dispatcher 也要安全:service 端沒注入 notifier 時就是 nil。 +func TestDispatcher_nil安全(t *testing.T) { + var d *Dispatcher + d.NotifyCustomerRideUpdate(context.Background(), 1, 2, "t", "b", nil) + d.NotifyDriverRideOffer(context.Background(), 1, 2, "t", "b", nil) +} diff --git a/internal/service/customer_push.go b/internal/service/customer_push.go new file mode 100644 index 0000000..3ef2743 --- /dev/null +++ b/internal/service/customer_push.go @@ -0,0 +1,68 @@ +package service + +import ( + "context" + "strconv" + + "line-fleet-dispatch/internal/events" + "line-fleet-dispatch/internal/notify" +) + +// 乘客端 App 推播(第九輪候選 1 的後半)。 +// +// 先前後端只有 `NotifyDriverRideOffer` 一條送出路徑:乘客即使註冊了 device token +// (`POST /api/customer/device-token` 早就存在),也**永遠不會收到任何推播**—— +// App 一離開前景,WS 就斷了,行程狀態要等下次回前景輪詢才知道。 +// +// 這裡補的是「送出」那一半。憑證那一半(Firebase 專案)仍待外部資源; +// 沒有憑證時走 LogPusher stub,這條路徑照樣可驗(log 看得到要送給誰)。 + +// customerPushCopy 依事件型別給推播的標題與內文。 +// +// 白名單刻意與 App 端 `_customerPushTypes` 對齊(fleet-app: lib/core/push/push_payload.dart)—— +// App 收到不在白名單裡的 type 會直接丟掉,後端多送只是白白燒推播額度。 +// 特別**不送 driver.location**:司機每 8 秒回報一次,拿它推播會把電池與額度燒光。 +func customerPushCopy(eventType string) (title, body string, ok bool) { + switch eventType { + case events.TypeRideAccepted: + return "司機已接單", "司機正在前往上車點", true + case events.TypeDriverArrived: + return "司機已抵達", "司機已在上車點等候,請準備上車", true + case events.TypeRideCompleted: + return "行程已完成", "感謝搭乘,可在 App 查看車資明細", true + case events.TypeRideCancelled: + return "行程已取消", "您的行程已取消,請重新叫車", true + case events.TypeRideRedispatched: + return "正在重新為您派車", "原司機取消了行程,系統正在尋找新的司機", true + default: + return "", "", false + } +} + +// customerRidePushData 組裝乘客端推播的 data。 +// +// **只帶 type 與 ride_id**:App 端把這則推播只當對帳訊號,醒來後重讀 rides/active +// 取當下狀態(fleet-app: isCustomerRidePush → refreshActive)。 +// 車資、司機姓名這類會變的欄位一律不放——推播可能延遲數十秒才到,內容早就過期, +// 直接顯示反而會讓 App 說謊。值一律字串(FCM data payload 限制)。 +func customerRidePushData(eventType string, rideID int64) map[string]string { + return map[string]string{ + "type": eventType, + "ride_id": strconv.FormatInt(rideID, 10), + } +} + +// notifyCustomerRide 送一則乘客端行程狀態推播;未注入 notifier 或型別不在白名單時靜默略過。 +// +// 兩個 service(DispatchService/TrackingService)共用,所以寫成自由函式而非方法。 +func notifyCustomerRide(ctx context.Context, n *notify.Dispatcher, customerID, rideID int64, eventType string) { + if n == nil { + return + } + title, body, ok := customerPushCopy(eventType) + if !ok { + return + } + n.NotifyCustomerRideUpdate(ctx, customerID, rideID, title, body, + customerRidePushData(eventType, rideID)) +} diff --git a/internal/service/customer_push_test.go b/internal/service/customer_push_test.go new file mode 100644 index 0000000..cd3ab4f --- /dev/null +++ b/internal/service/customer_push_test.go @@ -0,0 +1,315 @@ +package service + +import ( + "context" + "strconv" + "sync" + "testing" + "time" + + "line-fleet-dispatch/internal/constants" + "line-fleet-dispatch/internal/events" + lineclient "line-fleet-dispatch/internal/line" + "line-fleet-dispatch/internal/model" + "line-fleet-dispatch/internal/notify" + "line-fleet-dispatch/internal/repository" +) + +// ---- 測試替身 ---- + +type recordedPush struct { + rideID int64 + title string + data map[string]string +} + +// fakePusher 記下所有送出的推播;同時實作 notify.AppPusher 與 notify.DeviceLookup, +// 讓測試可以「所有人都有一台裝置」而不必真的寫 device_tokens 表。 +type fakePusher struct { + mu sync.Mutex + offers []recordedPush + updates []recordedPush +} + +func (f *fakePusher) SendRideOffer(ctx context.Context, devices []notify.Device, rideID int64, title, body string, data map[string]string) error { + _, _, _ = ctx, devices, body + f.mu.Lock() + defer f.mu.Unlock() + f.offers = append(f.offers, recordedPush{rideID, title, data}) + return nil +} + +func (f *fakePusher) SendRideUpdate(ctx context.Context, devices []notify.Device, rideID int64, title, body string, data map[string]string) error { + _, _, _ = ctx, devices, body + f.mu.Lock() + defer f.mu.Unlock() + f.updates = append(f.updates, recordedPush{rideID, title, data}) + return nil +} + +func (f *fakePusher) customerPushes() []recordedPush { + f.mu.Lock() + defer f.mu.Unlock() + return append([]recordedPush(nil), f.updates...) +} + +// everyoneHasDevice:任何角色任何 ID 都回一台 FCM 裝置。 +type everyoneHasDevice struct{} + +func (everyoneHasDevice) ListBySubject(role string, subjectID int64) ([]notify.Device, error) { + _, _ = role, subjectID + return []notify.Device{{Platform: notify.PlatformFCM, Token: "tok"}}, nil +} + +func newFakeNotifier() (*notify.Dispatcher, *fakePusher) { + p := &fakePusher{} + return notify.NewDispatcher(everyoneHasDevice{}, p), p +} + +// hasCustomerPush 找出指定型別的推播。 +func hasCustomerPush(pushes []recordedPush, eventType string, rideID int64) *recordedPush { + want := strconv.FormatInt(rideID, 10) + for i := range pushes { + if pushes[i].data["type"] == eventType && pushes[i].data["ride_id"] == want { + return &pushes[i] + } + } + return nil +} + +// ---- 純邏輯:白名單與 data 形狀 ---- + +// 白名單刻意與 App 端 _customerPushTypes 對齊;多送 App 也會丟掉,只是白燒推播額度。 +func TestCustomerPushCopy_白名單(t *testing.T) { + shouldPush := []string{ + events.TypeRideAccepted, + events.TypeDriverArrived, + events.TypeRideCompleted, + events.TypeRideCancelled, + events.TypeRideRedispatched, + } + for _, ty := range shouldPush { + title, body, ok := customerPushCopy(ty) + if !ok { + t.Errorf("%s 應該要推播", ty) + continue + } + if title == "" || body == "" { + t.Errorf("%s 的文案不可為空:title=%q body=%q", ty, title, body) + } + } + + // driver.location 每 8 秒一則,拿它推播會把電池與推播額度燒光; + // ride.picked_up 時乘客人在車上;chat.message 另有管道(未實作)。 + for _, ty := range []string{ + events.TypeDriverLocation, + events.TypeRidePickedUp, + events.TypeChatMessage, + events.TypeRideAssigned, + events.TypeRideTaken, + "", + } { + if _, _, ok := customerPushCopy(ty); ok { + t.Errorf("%q 不該推播給乘客", ty) + } + } +} + +// FCM data 的值一律字串;App 端 fleetEventFromPushData 據此還原成事件。 +func TestCustomerRidePushData_只帶對帳需要的兩個鍵(t *testing.T) { + data := customerRidePushData(events.TypeRideCompleted, 42) + if data["type"] != "ride.completed" || data["ride_id"] != "42" { + t.Fatalf("data=%v", data) + } + // 車資、司機姓名這類會變的欄位不放——推播延遲數十秒才到時內容早就過期。 + if len(data) != 2 { + t.Fatalf("推播 data 應只有 type/ride_id 兩個鍵,得到 %v", data) + } +} + +func TestNotifyCustomerRide_未注入notifier不panic(t *testing.T) { + notifyCustomerRide(context.Background(), nil, 1, 2, events.TypeRideAccepted) +} + +func TestNotifyCustomerRide_白名單外不送(t *testing.T) { + n, p := newFakeNotifier() + notifyCustomerRide(context.Background(), n, 1, 2, events.TypeDriverLocation) + if len(p.customerPushes()) != 0 { + t.Fatalf("不該送出,得到 %v", p.customerPushes()) + } +} + +// ---- 整合:真的走到派單/取消/抵達/完成 ---- + +// 接單後乘客要收到推播——先前只有 WS,App 一離開前景就收不到。 +func TestAcceptRide_推播給乘客(t *testing.T) { + db := newServiceTestDB(t) + redisStore := newServiceTestRedis(t) + customers := repository.NewCustomerRepository(db) + drivers := repository.NewDriverRepository(db) + rides := repository.NewRideRepository(db) + dispatch := NewDispatchService(drivers, rides, customers, redisStore, + lineclient.NewClient(""), NewETAService(nil), NewDispatchSettings(3000, 5, 20, 1, 5), &fakePublisher{}) + n, pusher := newFakeNotifier() + dispatch.SetAppNotifier(n) + + cust, err := customers.FindOrCreateByLineUserID("U_push_cust", "乘客") + if err != nil { + t.Fatalf("建立乘客失敗:%v", err) + } + driver := newApprovedDriver(t, drivers, "U_push_driver", "司機", constants.DriverStatusIdle) + ride := newTestRide(t, rides, cust.ID, constants.RideStatusAssigned) + + if _, err := dispatch.AcceptRide(context.Background(), ride.ID, driver.ID, ""); err != nil { + t.Fatalf("接單失敗:%v", err) + } + + got := hasCustomerPush(pusher.customerPushes(), events.TypeRideAccepted, ride.ID) + if got == nil { + t.Fatalf("乘客沒收到 ride.accepted 推播:%v", pusher.customerPushes()) + } + if got.title == "" { + t.Error("推播標題不可為空(系統匣會顯示它)") + } +} + +// 乘客自己按的取消不推播(他人就在前景),admin/系統取消才推。 +func TestCancel_乘客自己取消不推播_他人取消要推(t *testing.T) { + db := newServiceTestDB(t) + redisStore := newServiceTestRedis(t) + customers := repository.NewCustomerRepository(db) + drivers := repository.NewDriverRepository(db) + rides := repository.NewRideRepository(db) + dispatch := NewDispatchService(drivers, rides, customers, redisStore, + lineclient.NewClient(""), NewETAService(nil), NewDispatchSettings(3000, 5, 20, 1, 5), &fakePublisher{}) + n, pusher := newFakeNotifier() + dispatch.SetAppNotifier(n) + + cust, err := customers.FindOrCreateByLineUserID("U_cancel_cust", "乘客") + if err != nil { + t.Fatalf("建立乘客失敗:%v", err) + } + ctx := context.Background() + + selfCancelled := newTestRide(t, rides, cust.ID, constants.RideStatusRequested) + if _, err := dispatch.CancelByCustomerID(ctx, cust.ID, selfCancelled.ID); err != nil { + t.Fatalf("乘客取消失敗:%v", err) + } + if got := hasCustomerPush(pusher.customerPushes(), events.TypeRideCancelled, selfCancelled.ID); got != nil { + t.Errorf("乘客自己按的取消不該推播:%+v", *got) + } + + adminCancelled := newTestRide(t, rides, cust.ID, constants.RideStatusRequested) + if _, err := dispatch.cancelActiveRide(ctx, adminCancelled, events.ActorAdmin, nil, "admin_cancel"); err != nil { + t.Fatalf("admin 取消失敗:%v", err) + } + if got := hasCustomerPush(pusher.customerPushes(), events.TypeRideCancelled, adminCancelled.ID); got == nil { + t.Errorf("admin 取消應推播給乘客:%v", pusher.customerPushes()) + } +} + +// 司機進上車圍籬 → 乘客收到「司機已抵達」推播。這則最需要推播: +// 乘客多半把 App 收在背景等通知,WS 這時早就斷了。 +func TestGeofence_抵達推播給乘客(t *testing.T) { + svc, rideID, driverID, pusher := trackingPushFixture(t) + + // 上車點(25.03, 121.56)本身一定在圍籬內。 + if err := svc.ReportDriverLocation(context.Background(), driverID, 25.03, 121.56); err != nil { + t.Fatalf("回報位置失敗:%v", err) + } + + if got := hasCustomerPush(pusher.customerPushes(), events.TypeDriverArrived, rideID); got == nil { + t.Fatalf("乘客沒收到 driver.arrived 推播:%v", pusher.customerPushes()) + } +} + +// 行程完成 → 乘客收到推播(App 據此重讀後端拿完成卡與車資)。 +func TestComplete_推播給乘客(t *testing.T) { + svc, rideID, driverID, _ := pickUpFixtureWithPublisher(t, nil, "") + n, pusher := newFakeNotifier() + svc.SetAppNotifier(n) + + ctx := context.Background() + if _, err := svc.PickUp(ctx, rideID, driverID); err != nil { + t.Fatalf("上車標記失敗:%v", err) + } + if err := svc.Complete(ctx, rideID, driverID); err != nil { + t.Fatalf("完成行程失敗:%v", err) + } + + got := hasCustomerPush(pusher.customerPushes(), events.TypeRideCompleted, rideID) + if got == nil { + t.Fatalf("乘客沒收到 ride.completed 推播:%v", pusher.customerPushes()) + } + // 車資不放進推播:金額由 App 重讀後端取得(推播到達時可能已不是同一個數字)。 + if _, ok := got.data["fare_amount_cents"]; ok { + t.Errorf("推播不該帶車資:%v", got.data) + } +} + +// trackingPushFixture 建好「已接單」的訂單與**接上真 DispatchService** 的 TrackingService。 +// +// 不共用 pickUpFixtureWithPublisher:那支的 dispatch 是 nil,一走 ReportDriverLocation +// 就會在 ETA 節流後呼叫 nil 服務。要驗圍籬得走真的位置回報路徑。 +func trackingPushFixture(t *testing.T) (*TrackingService, int64, int64, *fakePusher) { + t.Helper() + db := newServiceTestDB(t) + redisStore := newServiceTestRedis(t) + customers := repository.NewCustomerRepository(db) + drivers := repository.NewDriverRepository(db) + rides := repository.NewRideRepository(db) + tracks := repository.NewTrackRepository(db) + + cust, err := customers.FindOrCreateByLineUserID("U_geofence_cust", "乘客") + if err != nil { + t.Fatalf("建立乘客失敗:%v", err) + } + driver := newApprovedDriver(t, drivers, "U_geofence_driver", "司機", constants.DriverStatusOnTrip) + + 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 := rides.AcceptRide(ride.ID, driver.ID, 300); err != nil { + t.Fatalf("接單失敗:%v", err) + } + + fp := &fakePublisher{} + dispatch := NewDispatchService(drivers, rides, customers, redisStore, + lineclient.NewClient(""), NewETAService(nil), NewDispatchSettings(3000, 5, 20, 1, 5), fp) + svc := NewTrackingService(drivers, rides, tracks, redisStore, lineclient.NewClient(""), + dispatch, 0, 0, fp) + n, pusher := newFakeNotifier() + svc.SetAppNotifier(n) + return svc, ride.ID, driver.ID, pusher +} + +// newApprovedDriver 建一位「車輛已核准」的司機(O5 gate:沒核准車輛接不了單)。 +func newApprovedDriver( + t *testing.T, drivers *repository.DriverRepository, lineUserID, name string, status int16, +) *model.Driver { + t.Helper() + driver, err := drivers.FindOrCreate(lineUserID, name) + if err != nil { + t.Fatalf("建立司機失敗:%v", err) + } + if err := drivers.UpdateStatus(driver.ID, status); err != nil { + t.Fatalf("設定司機狀態失敗:%v", err) + } + if err := drivers.UpdateVehicle(driver.ID, constants.VehicleTypeSedan, "PUSH-01"); err != nil { + t.Fatalf("設定車輛失敗:%v", err) + } + if err := drivers.UpdateVehicleReview(driver.ID, constants.VehicleReviewApproved, ""); err != nil { + t.Fatalf("核准車輛失敗:%v", err) + } + return driver +} diff --git a/internal/service/dispatch.go b/internal/service/dispatch.go index d9bee1c..ac01159 100644 --- a/internal/service/dispatch.go +++ b/internal/service/dispatch.go @@ -370,6 +370,7 @@ func (s *DispatchService) giveUpIfUnaccepted(rideID int64) { RideID: rideID, Payload: payload, }) + notifyCustomerRide(ctx, s.appNotify, ride.CustomerID, rideID, events.TypeRideCancelled) } // giveUpCancelInfo 組出逾時取消的原因、給乘客的文案與 WS payload(P4)。 @@ -454,6 +455,11 @@ func (s *DispatchService) cancelActiveRide( Type: events.TypeRideCancelled, RideID: ride.ID, }) + // 乘客自己按的取消**不推播**:他人就在 App 前景、剛剛才按下去, + // 系統匣再跳一則「行程已取消」只是噪音。admin/系統取消才需要推。 + if actorRole != events.ActorCustomer { + notifyCustomerRide(ctx, s.appNotify, ride.CustomerID, ride.ID, events.TypeRideCancelled) + } // 若已派給司機,通知司機。 // @@ -516,6 +522,7 @@ func (s *DispatchService) CancelByDriver(ctx context.Context, rideID, driverID i Type: events.TypeRideRedispatched, RideID: rideID, }) + notifyCustomerRide(ctx, s.appNotify, ride.CustomerID, rideID, events.TypeRideRedispatched) return "已放棄此訂單", nil } @@ -605,6 +612,7 @@ func (s *DispatchService) AcceptRide(ctx context.Context, rideID, driverID int64 RideID: rideID, Payload: rideAcceptedCustomerPayload(driver, etaSec), }) + notifyCustomerRide(ctx, s.appNotify, ride.CustomerID, rideID, events.TypeRideAccepted) // 沒搶到的司機:把他們的接單卡收掉(T2)。必須在接單者的 ride.accepted 之外另送, // 因為 ride.accepted 的收件人是「接到的那位」。 s.notifyOfferedDrivers(ctx, rideID, events.TypeRideTaken, driverID) diff --git a/internal/service/tracking.go b/internal/service/tracking.go index 62740ef..3f341e2 100644 --- a/internal/service/tracking.go +++ b/internal/service/tracking.go @@ -11,6 +11,7 @@ import ( "line-fleet-dispatch/internal/events" lineclient "line-fleet-dispatch/internal/line" "line-fleet-dispatch/internal/model" + "line-fleet-dispatch/internal/notify" osrmclient "line-fleet-dispatch/internal/osrm" redisstore "line-fleet-dispatch/internal/redis" "line-fleet-dispatch/internal/repository" @@ -40,6 +41,7 @@ type TrackingService struct { osrm *osrmclient.Client reports *repository.ReportRepository stops *repository.RideStopRepository + appNotify *notify.Dispatcher etaMinInterval time.Duration etaDistThreshold float64 @@ -94,6 +96,12 @@ func (s *TrackingService) SetReports(reports *repository.ReportRepository) { s.reports = reports } +// SetAppNotifier 注入 App 推播,讓「司機已抵達」「行程已完成」也送得到乘客手機;可選。 +// 未注入時只有 WS 事件——App 不在前景時 WS 已斷,乘客要等回前景輪詢才知道。 +func (s *TrackingService) SetAppNotifier(d *notify.Dispatcher) { + s.appNotify = d +} + // SetStops 注入停靠點 repo,完成計費時改用全程多點路線(N5);可選—— // 未注入時多停靠點行程會退回兩點直達路線(會低估繞路,但不會失敗)。 func (s *TrackingService) SetStops(stops *repository.RideStopRepository) { @@ -183,12 +191,13 @@ func (s *TrackingService) checkGeofence(ctx context.Context, ride *model.Ride, l s.geofenced[ride.ID] = true s.mu.Unlock() - customerLineID, err := s.rides.GetCustomerLineUserID(ride.ID) - if err != nil || customerLineID == "" { - return - } log.Info().Int64("ride_id", ride.ID).Msg("司機進入上車圍籬") - _ = s.line.PushText(ctx, customerLineID, "司機已抵達上車點,請準備上車") + // LINE 推播是**其中一條**管道,查不到 LINE ID 只跳過這一條。 + // 先前這裡是 `if err != nil || customerLineID == "" { return }`——整個抵達通知 + // (含 WS 事件與審計)都掛在 LINE ID 上,沒有 LINE ID 的乘客等於司機到了卻無聲。 + if customerLineID, err := s.rides.GetCustomerLineUserID(ride.ID); err == nil && customerLineID != "" { + _ = s.line.PushText(ctx, customerLineID, "司機已抵達上車點,請準備上車") + } actor := (*int64)(nil) if ride.DriverID != nil { actor = ride.DriverID @@ -199,6 +208,9 @@ func (s *TrackingService) checkGeofence(ctx context.Context, ride *model.Ride, l Type: events.TypeDriverArrived, RideID: ride.ID, }) + // 這則最需要推播:乘客多半把 App 收在背景等通知,司機到了卻只有 WS 事件, + // App 根本不在線上收不到。 + notifyCustomerRide(ctx, s.appNotify, ride.CustomerID, ride.ID, events.TypeDriverArrived) } // PickUpResult 回給司機端上車後導航去目的地所需的資訊。 @@ -377,6 +389,9 @@ func (s *TrackingService) Complete(ctx context.Context, rideID, driverID int64) RideID: rideID, Payload: completedPayload, }) + // 推播不帶車資:完成卡的金額由 App 重讀後端取得,推播只負責把人叫回 App + // (車資可能在推播抵達前就因清潔費/調整而不同)。 + notifyCustomerRide(ctx, s.appNotify, ride.CustomerID, rideID, events.TypeRideCompleted) s.publish(events.Recipient{Role: events.RoleDriver, ID: driverID}, events.Event{ Type: events.TypeRideCompleted, RideID: rideID,