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
2 changes: 2 additions & 0 deletions cmd/server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,8 @@ func main() {
// 要等他自己再打開 App 才看得到。
chatService.SetAppNotifier(appNotify)
lostItemService := service.NewLostItemService(rideRepo, lostItemRepo, feeSettings, hub)
// 協尋推播:這條流程是小時級的,雙方幾乎都不在 App 前景,只靠 WS 等於沒有通知。
lostItemService.SetAppNotifier(appNotify)

if cfg.AppEnv == "production" {
gin.SetMode(gin.ReleaseMode)
Expand Down
65 changes: 65 additions & 0 deletions docs/TODO.md
Original file line number Diff line number Diff line change
Expand Up @@ -1124,6 +1124,71 @@ admin 取消各驗到一則推播,乘客自己取消驗到**沒有**推播。
(推播 data 沒有訊息本體,餵給 `RideMessage.fromJson` 只會解析失敗被丟掉;
內容等聊天室自己以 REST 補齊)。

### U3. 協尋單每一步也推播(2026-07-30)

> 協尋的節奏是**小時級**(司機要回車上翻、乘客要等),雙方幾乎都不在 App 前景。
> 先前每一步都只走 WS,整條流程等於要靠當事人自己想起來去開 App 看——
> **建了單司機不知道、找到了乘客不知道、付了款司機不知道**。

- [x] `LostItemService` 加 `SetAppNotifier`;建單推司機,之後**每一次狀態轉換推給對方**
(司機標記尋獲/歸還 → 推乘客;乘客付款/取消 → 推司機)。
動作發起者自己剛按完,系統匣再跳一則只是噪音。
- [x] **標題講的是「收訊者接下來要做什麼」**,不是內部狀態名:
`found` 對乘客是「司機找到你的遺失物了」(=該付處理費了)、
`closed` 對乘客是「協尋已結案」但對司機是「乘客取消了協尋」——
同一個狀態對兩邊的意思不一樣,共用一句文案會有一邊看不懂。
- [x] data 只帶 `type`+`ride_id`,內容(物品描述)放通知本文並以 rune 截斷;
App 醒來後重讀協尋清單(狀態可能又變過了)。

**驗收(2026-07-30 實跑)**:`go test ./internal/service -run 'TestLostItem'` ——
整合測試走完 open→found→paid→returned 四步,逐步驗到「推給對方」的標題與 data type;
`TestLostItemPushTitle` 釘住五種標題(含 closed 的兩種說法);
未注入 notifier 仍可建單。

**App 端同批**:`lost_item.created`/`lost_item.updated` 進兩端白名單,收到後**只重讀協尋清單**
(推播 data 沒有協尋單本體;乘客端也不走「重讀行程」那條——協尋單變了不代表行程變了)。

### U4. 整條推播鏈路的實跑驗證(2026-07-30,**不需 Firebase 憑證**)

> U/U2/U3 的證據原本都只到 service 層(單元+整合測試)。這一節補的是
> **整條 HTTP 路徑真的會呼叫送出**——沒有憑證時走 `LogPusher` stub,
> log 會印出收件裝置的 token 前綴、標題與 data,足以判定「推給誰、推了什麼」。

**做法**(本機起 postgis+redis 容器、`go run ./cmd/server`;
`FCM_CREDENTIALS_FILE` 留空 → log 出現「未設定 FCM_CREDENTIALS_FILE,App 推播使用 stub」):
註冊司機/乘客各自的 device token(`DRIVER-FCM-TOKEN`/`CUSTOMER-FCM-TOKEN`
——**token 前綴就是判斷推給誰的依據**),然後用 curl 走完整條鏈路。

**實測結果(2026-07-30,10 則推播,收件人全部正確)**:

| 動作 | 推播 data.type | 標題 | 收件裝置 |
|---|---|---|---|
| 派單 | `ride.assigned` | 新派單 #2 | `DRIVER-F…` |
| 司機接單 | `ride.accepted` | 司機已接單 | `CUSTOMER…` |
| 進上車圍籬 | `driver.arrived` | 司機已抵達 | `CUSTOMER…` |
| 乘客發話 | `chat.message` | 乘客傳來訊息 | `DRIVER-F…` |
| 司機發話 | `chat.message` | 司機傳來訊息 | `CUSTOMER…` |
| 完成行程 | `ride.completed` | 行程已完成 | `CUSTOMER…` |
| 乘客建協尋單 | `lost_item.created` | 乘客回報遺失物 | `DRIVER-F…` |
| 司機標記尋獲 | `lost_item.updated` | 司機找到你的遺失物了 | `CUSTOMER…` |
| 乘客付處理費 | `lost_item.updated` | 乘客已支付處理費 | `DRIVER-F…` |
| 司機標記歸還 | `lost_item.updated` | 遺失物已歸還 | `CUSTOMER…` |

**取消那三條另跑一輪**(同日):
- **乘客自己取消 → 完全沒有推播**(只有先前那則派單邀請)——負向斷言成立。
- **admin 取消 → `ride.cancelled`「行程已取消」給乘客**。
- **司機接單後放棄 → `ride.accepted` 後緊接 `ride.redispatched`「正在重新為您派車」給乘客**。

**踩到的坑(留給下次跑的人)**:
1. **本機 Docker 拉不到 registry**(`load metadata for docker.io/library/golang:1.25-alpine` 會卡死),
所以 `docker compose up --build` 起不來。**改用 `docker compose up -d postgis redis`
+本機 `go run ./cmd/server`**(DB_HOST=localhost DB_PORT=5433)——postgis/redis 映像本機已有。
2. `PUT /api/driver/vehicle` 的車牌有**長度上限**,拿 epoch 當後綴會被 400「車牌格式錯誤」擋下。
3. `POST /api/admin/drivers/:id/vehicle-review` 的參數是 **`{"approve":true}`**,不是 `{"status":"approved"}`。
4. `POST /api/rides` 回的是 **`ride_id`** 不是 `id`。

**仍未做**:真 Firebase 憑證下的端到端(手機真的響),那是 A2 的同一個卡點。

---

## 下次任務
Expand Down
64 changes: 64 additions & 0 deletions internal/service/lost_item.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
package service

import (
"context"
"errors"
"strconv"
"strings"
"time"
"unicode/utf8"

"line-fleet-dispatch/internal/constants"
"line-fleet-dispatch/internal/events"
"line-fleet-dispatch/internal/model"
"line-fleet-dispatch/internal/notify"
"line-fleet-dispatch/internal/repository"
)

Expand All @@ -30,6 +33,15 @@ type LostItemService struct {
items *repository.LostItemRepository
fees *FeeSettings
publisher events.Publisher
appNotify *notify.Dispatcher
}

// SetAppNotifier 注入 App 推播;可選。
//
// 協尋的節奏是**小時級**(司機要回車上翻、乘客要等),雙方幾乎都不在 App 前景——
// 沒有推播的話,每一步都要靠當事人自己想起來去開 App 看,整條流程就停在那裡。
func (s *LostItemService) SetAppNotifier(d *notify.Dispatcher) {
s.appNotify = d
}

func NewLostItemService(rides *repository.RideRepository, items *repository.LostItemRepository, fees *FeeSettings, publisher events.Publisher) *LostItemService {
Expand Down Expand Up @@ -81,6 +93,8 @@ func (s *LostItemService) CreateByCustomer(customerID, rideID int64, description
return nil, err
}
s.publishItem(item, events.TypeLostItemCreated)
// 建單的是乘客,所以推給司機。
s.pushLostItem(item, events.TypeLostItemCreated, events.RoleDriver, "乘客回報遺失物", item.Description)
return item, nil
}

Expand Down Expand Up @@ -166,9 +180,59 @@ func (s *LostItemService) transition(role string, subjectID, itemID int64, from
return nil, err
}
s.publishItem(item, events.TypeLostItemUpdated)
// 推給**對方**:司機標記尋獲/歸還時推乘客,乘客付款/取消時推司機。
// 動作發起者自己剛按完,系統匣再跳一則只是噪音。
if role == events.RoleDriver {
s.pushLostItem(item, events.TypeLostItemUpdated, events.RoleCustomer,
lostItemPushTitle(events.RoleCustomer, to), item.Description)
} else {
s.pushLostItem(item, events.TypeLostItemUpdated, events.RoleDriver,
lostItemPushTitle(events.RoleDriver, to), item.Description)
}
return item, nil
}

// lostItemPushTitle 依「推給誰」與「轉成什麼狀態」給標題。
//
// 標題要講**收訊者接下來要做什麼**——「已尋獲」對乘客的意思是「該付處理費了」。
func lostItemPushTitle(recipientRole, status string) string {
switch status {
case constants.LostItemStatusFound:
return "司機找到你的遺失物了"
case constants.LostItemStatusPaid:
return "乘客已支付處理費"
case constants.LostItemStatusReturned:
return "遺失物已歸還"
case constants.LostItemStatusClosed:
if recipientRole == events.RoleCustomer {
return "協尋已結案"
}
return "乘客取消了協尋"
default:
return "協尋單有更新"
}
}

// pushLostItem 推一則協尋通知給指定角色。
//
// data 只帶 type 與 ride_id:App 醒來後重讀協尋清單(狀態可能又變過了),
// 與行程狀態推播同一條原則。用 context.Background()——推播是回應之後的背景動作。
func (s *LostItemService) pushLostItem(item *model.LostItemRequest, eventType, recipientRole, title, body string) {
if s.appNotify == nil {
return
}
ctx := context.Background()
data := map[string]string{
"type": eventType,
"ride_id": strconv.FormatInt(item.RideID, 10),
}
if recipientRole == events.RoleDriver {
s.appNotify.NotifyDriverRideUpdate(ctx, item.DriverID, item.RideID, title, previewText(body), data)
return
}
s.appNotify.NotifyCustomerRideUpdate(ctx, item.CustomerID, item.RideID, title, previewText(body), data)
}

// publishItem 推播協尋單事件給行程雙方。
func (s *LostItemService) publishItem(item *model.LostItemRequest, eventType string) {
if s.publisher == nil {
Expand Down
161 changes: 161 additions & 0 deletions internal/service/lost_item_push_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
package service

import (
"testing"

"gorm.io/gorm"

"line-fleet-dispatch/internal/constants"
"line-fleet-dispatch/internal/events"
"line-fleet-dispatch/internal/repository"
)

// 協尋的節奏是小時級(司機要回車上翻、乘客要等),雙方幾乎都不在 App 前景——
// 先前每一步都只走 WS,等於整條流程要靠當事人自己想起來去開 App 看。
//
// 這組測試釘住「每一步推給對方、不推給動作發起者」。

func TestLostItem_每一步推給對方(t *testing.T) {
db := newServiceTestDB(t)
customers := repository.NewCustomerRepository(db)
drivers := repository.NewDriverRepository(db)
rides := repository.NewRideRepository(db)
items := repository.NewLostItemRepository(db)

cust, err := customers.FindOrCreateByLineUserID("U_lostpush_cust", "乘客")
if err != nil {
t.Fatalf("建立乘客失敗:%v", err)
}
driver, err := drivers.FindOrCreate("U_lostpush_driver", "司機")
if err != nil {
t.Fatalf("建立司機失敗:%v", err)
}
ride := newTestRide(t, rides, cust.ID, constants.RideStatusRequested)
if err := rides.AcceptRide(ride.ID, driver.ID, 300); err != nil {
t.Fatalf("指派司機失敗:%v", err)
}
if err := rides.MarkPickedUp(ride.ID); err != nil {
t.Fatalf("上車失敗:%v", err)
}
fare, comm, net := int64(10000), int64(1500), int64(8500)
if err := rides.CompleteRide(ride.ID, 3000, &fare, &comm, &net, nil); err != nil {
t.Fatalf("完成行程失敗:%v", err)
}

svc := NewLostItemService(rides, items, newTestFees(t, db), &fakePublisher{})
n, pusher := newFakeNotifier()
svc.SetAppNotifier(n)

// 1) 乘客建單 → 推司機
item, err := svc.CreateByCustomer(cust.ID, ride.ID, "黑色錢包")
if err != nil {
t.Fatalf("建立協尋單失敗:%v", err)
}
pushes := pusher.customerPushes()
if len(pushes) != 1 {
t.Fatalf("建單應推一則給司機,得到 %d:%v", len(pushes), pushes)
}
if pushes[0].data["type"] != events.TypeLostItemCreated {
t.Errorf("data.type=%q,預期 lost_item.created", pushes[0].data["type"])
}
if pushes[0].title != "乘客回報遺失物" {
t.Errorf("title=%q", pushes[0].title)
}

// 2) 司機標記尋獲 → 推乘客,標題要講「乘客接下來要做什麼」
if _, err := svc.MarkFound(driver.ID, item.ID); err != nil {
t.Fatalf("標記尋獲失敗:%v", err)
}
pushes = pusher.customerPushes()
if len(pushes) != 2 {
t.Fatalf("尋獲後應累計 2 則,得到 %d", len(pushes))
}
if pushes[1].title != "司機找到你的遺失物了" {
t.Errorf("title=%q", pushes[1].title)
}
if pushes[1].data["type"] != events.TypeLostItemUpdated {
t.Errorf("data.type=%q,預期 lost_item.updated", pushes[1].data["type"])
}

// 3) 乘客付款 → 推司機
if _, err := svc.Pay(cust.ID, item.ID); err != nil {
t.Fatalf("支付處理費失敗:%v", err)
}
pushes = pusher.customerPushes()
if len(pushes) != 3 || pushes[2].title != "乘客已支付處理費" {
t.Fatalf("付款後的推播不對:%v", pushes)
}

// 4) 司機歸還 → 推乘客
if _, err := svc.MarkReturned(driver.ID, item.ID); err != nil {
t.Fatalf("標記歸還失敗:%v", err)
}
pushes = pusher.customerPushes()
if len(pushes) != 4 || pushes[3].title != "遺失物已歸還" {
t.Fatalf("歸還後的推播不對:%v", pushes)
}
}

// 標題要講「收訊者接下來要做什麼」——同一個 closed 對兩邊的意思不一樣。
func TestLostItemPushTitle(t *testing.T) {
cases := []struct {
recipient string
status string
want string
}{
{events.RoleCustomer, constants.LostItemStatusFound, "司機找到你的遺失物了"},
{events.RoleDriver, constants.LostItemStatusPaid, "乘客已支付處理費"},
{events.RoleCustomer, constants.LostItemStatusReturned, "遺失物已歸還"},
{events.RoleCustomer, constants.LostItemStatusClosed, "協尋已結案"},
{events.RoleDriver, constants.LostItemStatusClosed, "乘客取消了協尋"},
}
for _, c := range cases {
if got := lostItemPushTitle(c.recipient, c.status); got != c.want {
t.Errorf("lostItemPushTitle(%q, %q)=%q,預期 %q", c.recipient, c.status, got, c.want)
}
}
}

// 未注入 notifier(既有測試與舊部署)照常運作。
func TestLostItem_未注入notifier仍可建單(t *testing.T) {
db := newServiceTestDB(t)
customers := repository.NewCustomerRepository(db)
drivers := repository.NewDriverRepository(db)
rides := repository.NewRideRepository(db)
items := repository.NewLostItemRepository(db)

cust, err := customers.FindOrCreateByLineUserID("U_lostpush_nonotify", "乘客")
if err != nil {
t.Fatalf("建立乘客失敗:%v", err)
}
driver, err := drivers.FindOrCreate("U_lostpush_nonotify_d", "司機")
if err != nil {
t.Fatalf("建立司機失敗:%v", err)
}
ride := newTestRide(t, rides, cust.ID, constants.RideStatusRequested)
if err := rides.AcceptRide(ride.ID, driver.ID, 300); err != nil {
t.Fatalf("指派司機失敗:%v", err)
}
if err := rides.MarkPickedUp(ride.ID); err != nil {
t.Fatalf("上車失敗:%v", err)
}
fare, comm, net := int64(10000), int64(1500), int64(8500)
if err := rides.CompleteRide(ride.ID, 3000, &fare, &comm, &net, nil); err != nil {
t.Fatalf("完成行程失敗:%v", err)
}

svc := NewLostItemService(rides, items, newTestFees(t, db), &fakePublisher{})
if _, err := svc.CreateByCustomer(cust.ID, ride.ID, "雨傘"); err != nil {
t.Fatalf("沒有推播也要能建單:%v", err)
}
}

// newTestFees 載入費率設定(migration 已填預設值)。
func newTestFees(t *testing.T, db *gorm.DB) *FeeSettings {
t.Helper()
fees, err := NewFeeSettings(repository.NewFeeSettingsRepository(db))
if err != nil {
t.Fatalf("載入費率設定失敗:%v", err)
}
return fees
}
Loading
Loading