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
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 下游):目前三端都只「看得到」評分,**沒有低分司機的處理流程**
Expand Down
3 changes: 3 additions & 0 deletions cmd/server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
53 changes: 52 additions & 1 deletion docs/TODO.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 加入,尚未實作,皆需後端地基先行)**:
Expand Down Expand Up @@ -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 伺服器端分頁(含前端)。
Expand Down
19 changes: 18 additions & 1 deletion internal/notify/fcm.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 != "" {
Expand Down Expand Up @@ -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 可能失效)")
}
}
Expand All @@ -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
}
46 changes: 46 additions & 0 deletions internal/notify/notify.go
Original file line number Diff line number Diff line change
Expand Up @@ -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。
Expand Down Expand Up @@ -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{}

Expand All @@ -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
Expand Down
111 changes: 96 additions & 15 deletions internal/notify/notify_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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{
Expand Down Expand Up @@ -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)
}
Loading
Loading