From 087406b9428a4690ab80bf6f19ab50b737149532 Mon Sep 17 00:00:00 2001 From: awei Date: Mon, 27 Jul 2026 19:13:13 +0800 Subject: [PATCH] =?UTF-8?q?feat(S):=20=E4=B9=98=E5=AE=A2=E8=A9=95=E5=88=86?= =?UTF-8?q?=E5=8F=B8=E6=A9=9F=EF=BC=88B5=EF=BC=89=E2=80=94=E2=80=94ride=5F?= =?UTF-8?q?ratings=20=EF=BC=8B=20=E8=A9=95=E5=88=86=E7=AB=AF=E9=BB=9E=20?= =?UTF-8?q?=EF=BC=8B=20=E4=B8=89=E8=99=95=E8=AE=80=E5=9B=9E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit App 完成卡的「留下評分(即將開放)」從 2026-07-08 佔位至今,註記「真實 API 待 Phase C」。後端當時確實沒有評分資料表與端點(grep -i rating 全 repo 零命中), 本批補齊。對應 backend-api-gaps.md P4 #16。付款(#19)仍待真金流,不在本批。 - migration 000023 ride_ratings:一趟一評、不可重評(唯一索引 uq_ride_ratings_ride_id)。 允許改分會讓司機平均分變成可被事後情緒左右的浮動值,也讓「評過沒」失去明確答案。 customer_id/driver_id 是寫入當下的快照,不靠 rides 反查——行程資料日後若調整 不該改寫歷史評分。CHECK:score 1–5、comment ≤ 500 字(服務層另有 200 字上限)。 - POST /api/customer/rides/:id/rating(customer JWT):驗證順序「輸入 → 歸屬 → 狀態 → 重複」。非本人 403(訂單存在,只是不是你的)、不存在 404、 已評過/未完成 409(狀態衝突不是輸入格式錯,App 據此知道不必改參數重送)。 - 讀回三處(沒有讀回,App 無從知道評過沒): · CustomerRideView.rating——只在 status=completed 時才查,這條路徑也服務乘客端的 active 輪詢,對永遠不可能有評分的進行中訂單每幾秒打一次 ride_ratings 是純浪費。 · CustomerRideRow.rating_score(歷史列表 LEFT JOIN)——完成卡關掉後唯一的補評路徑。 · GET /driver/me 的 rating_avg/rating_count,查失敗不擋 /me(加值資訊,不該讓 司機因此載不出首頁);新司機無評分回 (0,0) 而非錯誤。 - 三處注入都是可選的 SetRating/SetRatings,未注入時既有回應形狀一個欄位不少。 驗收:go build/go vet/gofmt 乾淨。 - internal/service/rating_test.go 3 案(主流程+四道守門與 trim/平均分含無評分 (0,0)/ 訂單視圖與歷史列表讀回),真 PostGIS 跑全部 migration,順帶驗證 000023 可套用。 - internal/handler/rating_test.go 2 案(401/403/壞 id 400/壞 JSON 400/星等越界 含缺 score 等同 0 也擋/未啟用 503)。 - internal/handler/route_shape_test.go:POST /customer/rides/estimate(靜態)與 /customer/rides/:id/rating(參數)同層並存——gin 舊版對此在註冊當下 panic, 是啟動即死、單元測試照樣全綠的失敗模式。gin 1.12 實測四條路徑都解析正確。 - 既有 ride_history_customer_integration_test(涵蓋改過的 ListRecentByCustomer) 與 handler 的 Driver/Me/Profile/Vehicle 測試皆綠。 App 端對應:fleet-app PR #45。 Co-Authored-By: Claude Opus 4.8 --- cmd/server/main.go | 11 +- .../000023_create_ride_ratings.down.sql | 2 + .../000023_create_ride_ratings.up.sql | 28 +++ docs/TODO.md | 39 ++++ docs/backend-api-gaps.md | 6 +- internal/handler/driver.go | 18 +- internal/handler/rating_test.go | 81 +++++++ internal/handler/ride.go | 53 +++++ internal/handler/route_shape_test.go | 42 ++++ internal/model/models.go | 16 ++ internal/repository/repository.go | 8 +- internal/repository/ride_rating.go | 69 ++++++ internal/service/rating.go | 81 +++++++ internal/service/rating_test.go | 209 ++++++++++++++++++ internal/service/ride.go | 33 ++- 15 files changed, 683 insertions(+), 13 deletions(-) create mode 100644 db/migrations/000023_create_ride_ratings.down.sql create mode 100644 db/migrations/000023_create_ride_ratings.up.sql create mode 100644 internal/handler/rating_test.go create mode 100644 internal/handler/route_shape_test.go create mode 100644 internal/repository/ride_rating.go create mode 100644 internal/service/rating.go create mode 100644 internal/service/rating_test.go diff --git a/cmd/server/main.go b/cmd/server/main.go index 6739c91..379eaf4 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -75,6 +75,7 @@ func main() { rideMessageRepo := repository.NewRideMessageRepository(db) rideStopRepo := repository.NewRideStopRepository(db) lostItemRepo := repository.NewLostItemRepository(db) + rideRatingRepo := repository.NewRideRatingRepository(db) // 軌跡分區維護:啟動時預建未來月分區 + 每日排程(避免跨月寫入失敗) if err := trackRepo.EnsureTrackPartitions(cfg.TrackPartitionMonthsAhead); err != nil { @@ -159,8 +160,10 @@ func main() { trackingService.SetStops(rideStopRepo) // N5:多停靠點行程改用全程多點路線計費 driverRegistry := service.NewDriverRegistry(driverRepo) rideQueryService := service.NewRideQueryService(trackRepo, rideRepo) - rideQueryService.SetDrivers(driverRepo) // O4/O7:乘客查自己訂單時附司機姓名/電話 - rideQueryService.SetStops(rideStopRepo) // N6:司機端 active 帶全程停靠點 + rideQueryService.SetDrivers(driverRepo) // O4/O7:乘客查自己訂單時附司機姓名/電話 + rideQueryService.SetStops(rideStopRepo) // N6:司機端 active 帶全程停靠點 + rideQueryService.SetRatings(rideRatingRepo) // B5:乘客查自己訂單時帶回已給過的評分 + ratingService := service.NewRatingService(rideRepo, rideRatingRepo) rideStopService := service.NewRideStopService(rideRepo, rideStopRepo) rideStopService.SetPublisher(hub) // N7:到站/跳過即時推給乘客(行程進度) chatService := service.NewChatService(rideRepo, rideMessageRepo, hub) @@ -179,9 +182,11 @@ func main() { lineHandler := handler.NewLineWebhookHandler(rideService, dispatchService, driverRepo, lineClient) driverHandler := handler.NewDriverHandler(trackingService, driverRegistry, rideQueryService, cfg.JWTSecret, cfg.JWTExpiryHours) driverHandler.SetEarnings(reportRepo, feeSettings) + driverHandler.SetRating(ratingService) // B5:/driver/me 帶司機自己的平均分 rideHandler := handler.NewRideHandler(dispatchService, trackingService, rideQueryService, rideService) rideHandler.SetStops(rideStopService) // N7:司機標記到達/跳過停靠點 rideHandler.SetEstimate(service.NewEstimateService(osrm, feeSettings)) // 懸而未決 #1:建單前車資預估 + rideHandler.SetRating(ratingService) // B5:乘客評分司機 deviceTokenHandler := handler.NewDeviceTokenHandler(deviceTokenService) wsHandler := handler.NewWSHandler(hub, cfg.JWTSecret, cfg.WSWriteWaitSec, cfg.WSPongWaitSec, cfg.WSMaxMessageBytes) chatHandler := handler.NewChatHandler(chatService) @@ -237,6 +242,8 @@ func main() { customerAuthed.GET("/customer/rides/active", rideHandler.ActiveByCustomer) customerAuthed.GET("/customer/rides/:id", rideHandler.GetByCustomer) customerAuthed.POST("/rides/:id/cancel-by-customer", rideHandler.CancelByCustomer) + // B5:乘客對已完成行程評分司機(一趟一評) + customerAuthed.POST("/customer/rides/:id/rating", rideHandler.RateByCustomer) customerAuthed.POST("/customer/device-token", deviceTokenHandler.RegisterByCustomer) customerAuthed.DELETE("/customer/device-token", deviceTokenHandler.UnregisterByCustomer) // 遺失物協尋:對已完成行程建單、查自己的協尋、支付處理費 diff --git a/db/migrations/000023_create_ride_ratings.down.sql b/db/migrations/000023_create_ride_ratings.down.sql new file mode 100644 index 0000000..5eba2cf --- /dev/null +++ b/db/migrations/000023_create_ride_ratings.down.sql @@ -0,0 +1,2 @@ +-- DROP TABLE 會連帶刪除其上的 CHECK、UNIQUE 索引與 FK。 +DROP TABLE IF EXISTS ride_ratings; diff --git a/db/migrations/000023_create_ride_ratings.up.sql b/db/migrations/000023_create_ride_ratings.up.sql new file mode 100644 index 0000000..b89576b --- /dev/null +++ b/db/migrations/000023_create_ride_ratings.up.sql @@ -0,0 +1,28 @@ +-- 乘客評分司機(B5):一趟行程一則評分,1–5 星+選填評論。 +-- +-- **一趟一評、不可重評**(uq_ride_ratings_ride):分數一旦送出就是該趟的定論。 +-- 允許改分會讓「司機平均分」變成可被事後情緒左右的浮動值, +-- 也讓「評過沒」失去明確答案(App 完成卡要據此決定顯示星星還是評分按鈕)。 +-- +-- customer_id/driver_id 是**寫入當下的快照**,不靠 rides 反查: +-- 評分屬於「這位乘客給這位司機」的事實,行程資料日後若調整(如改派)不該改寫歷史評分。 +CREATE TABLE IF NOT EXISTS ride_ratings ( + id BIGSERIAL PRIMARY KEY, + ride_id BIGINT NOT NULL REFERENCES rides(id) ON DELETE CASCADE, + customer_id BIGINT NOT NULL, + driver_id BIGINT NOT NULL, + score SMALLINT NOT NULL, + -- 評論選填;空字串=只給星等不留言(不用 NULL,省掉 App 端的三態判斷)。 + comment TEXT NOT NULL DEFAULT '', + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + + CONSTRAINT chk_ride_ratings_score CHECK (score BETWEEN 1 AND 5), + -- 服務層另有較嚴格的字數上限;這是直打 DB 也擋得住的最後防線(比照 lost_item_requests)。 + CONSTRAINT chk_ride_ratings_comment_len CHECK (char_length(comment) <= 500) +); + +-- 一趟一評的真正把關(UNIQUE 索引,服務層先查一次、此為競態下的最後防線)。 +CREATE UNIQUE INDEX IF NOT EXISTS uq_ride_ratings_ride_id ON ride_ratings(ride_id); + +-- 司機平均分(GET /api/driver/me)是對 driver_id 的聚合,資料量長期只增不減。 +CREATE INDEX IF NOT EXISTS idx_ride_ratings_driver_id ON ride_ratings(driver_id); diff --git a/docs/TODO.md b/docs/TODO.md index 1a2f64e..e3e23e4 100644 --- a/docs/TODO.md +++ b/docs/TODO.md @@ -896,6 +896,45 @@ App 建單 ride #24(429m)完成卡「車資 NT$94」= 同座標預估 NT$94。 繞路時走 N5 既有 `max(軌跡, 路線)`,故「實際依行駛路線可能不同」的免責成立。 +## ⭐ S. 乘客評分司機(B5,2026-07-27) + +> App 端 B5 從 2026-07-08 起就在完成卡放著 disabled 的「留下評分(即將開放)」佔位, +> 標註「真實 API 待 Phase C」——這是全 App **最後一個**還印著「即將開放」的功能。 +> 後端從無評分資料表與端點(`grep -i rating` 全 repo 零命中),本批補齊。 +> 對應 [backend-api-gaps.md](backend-api-gaps.md) P4 #16。 + +- [x] **migration 000023 `ride_ratings`** ✅ 2026-07-27 + `ride_id`(FK rides,ON DELETE CASCADE)/`customer_id`/`driver_id`/`score`/`comment`/`created_at`。 + - **一趟一評、不可重評**(唯一索引 `uq_ride_ratings_ride_id`):分數送出即定論。 + 允許改分會讓司機平均分變成可被事後情緒左右的浮動值,也讓「評過沒」失去明確答案 + (App 完成卡要據此決定顯示星星還是評分按鈕)。 + - `customer_id`/`driver_id` 是**寫入當下的快照**,不靠 rides 反查——評分屬於 + 「這位乘客給這位司機」的事實,行程資料日後若調整不該改寫歷史評分。 + - CHECK:`score BETWEEN 1 AND 5`、`char_length(comment) <= 500`(服務層另有 200 字上限, + DB 這層是直打 SQL 也擋得住的最後防線,比照 `lost_item_requests`)。 +- [x] **`POST /api/customer/rides/:id/rating`(customer JWT)** ✅ 2026-07-27 + `service.RatingService.RateByCustomer` 驗證順序刻意是「輸入 → 歸屬 → 狀態 → 重複」: + 先擋不必查 DB 的輸入錯誤,再依序回答「這趟是不是你的」「完成了沒」「你評過了沒」。 + - 錯誤對應:星等越界/評論過長 → 400;非本人 → **403**(訂單存在,只是不是你的); + 不存在 → 404;**已評過/行程未完成 → 409**(狀態衝突而非輸入格式錯, + App 據此知道不必請乘客改參數重送)。 + - 沒司機的行程(派單前取消)沒有評分對象,與「未完成」同走 `ErrRideNotCompleted`。 +- [x] **讀回路徑**(沒有讀回,App 無從知道評過沒)✅ 2026-07-27 + - `CustomerRideView` 加 `rating`(`GET /customer/rides/:id`/`active`);**未評分時整個鍵不出現**。 + (App 目前從歷史列表的 `rating_score` 判斷評過沒;這個欄位供訂單詳情路徑使用。) + - `CustomerRideRow` 加 `rating_score`(`GET /customer/rides` 歷史列表,LEFT JOIN + `ride_ratings`;一趟至多一則故不會讓行程重複出現)——**完成卡關掉後這是唯一的補評路徑**。 + - `GET /api/driver/me` 加 `rating_avg`/`rating_count`,司機看得到自己被評幾分。 + **查失敗不擋 /me**(加值資訊,不該讓司機因此載不出首頁);新司機無評分回 (0, 0) 而非錯誤。 + - 三處注入都是可選的 `SetRating`/`SetRatings`,未注入時既有回應形狀一個欄位不少。 +- [x] **驗收** ✅ 2026-07-27:`go build ./...`+`go vet ./...` 乾淨; + `internal/service/rating_test.go` 3 案(主流程+四道守門與 trim/平均分含無評分 (0,0)/ + 訂單視圖與歷史列表讀回,真 PostGIS 跑全部 migration,順帶驗證 000023 本身可套用)+ + `internal/handler/rating_test.go` 2 案(401/403/壞 id 400/壞 JSON 400/ + 星等越界含**缺 score 等同 0 也擋**/未啟用 503)。 +- App 端對應(fleet-app 同批):完成卡「留下評分」開 1–5 星+評論的 bottom sheet; + 歷史清單未評給「評分」、已評顯示星等;司機收入頁顯示「服務評價 4.5 / 5.0(12 則)」。 + ## 下次任務 **新需求(2026-07-16 加入,尚未實作,皆需後端地基先行)**: diff --git a/docs/backend-api-gaps.md b/docs/backend-api-gaps.md index 1bf6f32..61d1330 100644 --- a/docs/backend-api-gaps.md +++ b/docs/backend-api-gaps.md @@ -91,9 +91,9 @@ | # | Method | Path | 認證 | 說明 | |---|---|---|---|---| -| 15 | POST | `/api/rides/estimate` | customer JWT | 下單前試算車資(里程 PostGIS 已能算 + 費率表) | -| 16 | POST | `/api/rides/:id/rating` | customer JWT | 乘客評分司機 1~5 星 + 評論 | -| 17 | GET | `/api/customer/rides` | customer JWT | 乘客歷史訂單列表(分頁) | +| 15 | POST | `/api/customer/rides/estimate` | customer JWT | ✅ 2026-07-23(R;`EstimateService`,與完成計費共用 `FeeSettings.Quote`) | +| 16 | POST | `/api/customer/rides/:id/rating` | customer JWT | ✅ 2026-07-27(S;1–5 星+評論,**一趟一評**。讀回:`CustomerRideView.rating`/歷史列 `rating_score`/`/driver/me` 的 `rating_avg`) | +| 17 | GET | `/api/customer/rides` | customer JWT | ✅ 2026-07-19(H;`ListRecentByCustomer`,新到舊、只回本人) | | 18 | GET | `/api/driver/rides` | driver JWT | 司機歷史/收入列表 | | 19 | POST | `/api/rides/:id/payment` | customer JWT | 金流請款(預授權→行程後扣款) | | 20 | GET | `/metrics` | 內網/無 | Prometheus 指標(派單成功率、接單耗時、在線司機數、API 延遲) | diff --git a/internal/handler/driver.go b/internal/handler/driver.go index d69466c..1094e6a 100644 --- a/internal/handler/driver.go +++ b/internal/handler/driver.go @@ -21,10 +21,17 @@ type DriverHandler struct { rides *service.RideQueryService reports *repository.ReportRepository feeSettings *service.FeeSettings + rating *service.RatingService jwtSecret string jwtExpiryHours int } +// SetRating 注入評分服務(司機在 /driver/me 看自己的平均分,B5);可選—— +// 未注入時 /driver/me 不帶 rating 欄位,其餘欄位一個不少。 +func (h *DriverHandler) SetRating(rating *service.RatingService) { + h.rating = rating +} + // SetEarnings 注入收入查詢所需的報表 repo 與費率設定(供 /driver/earnings);可選。 func (h *DriverHandler) SetEarnings(reports *repository.ReportRepository, fees *service.FeeSettings) { h.reports = reports @@ -65,7 +72,16 @@ func (h *DriverHandler) Me(c *gin.Context) { c.JSON(http.StatusNotFound, gin.H{"error": "找不到司機"}) return } - c.JSON(http.StatusOK, driverPublic(d)) + body := driverPublic(d) + // 評分彙總(B5):司機看得到自己被評幾分。**查失敗不擋 /me**—— + // 這是加值資訊,讓司機因為它而載不出首頁是本末倒置。 + if h.rating != nil { + if summary, err := h.rating.SummaryByDriver(driverID); err == nil { + body["rating_avg"] = summary.Average + body["rating_count"] = summary.Count + } + } + c.JSON(http.StatusOK, body) } // UpdateProfile PUT /api/driver/profile — 司機自己的聯絡資料(目前只有電話,O7)。 diff --git a/internal/handler/rating_test.go b/internal/handler/rating_test.go new file mode 100644 index 0000000..06eca2f --- /dev/null +++ b/internal/handler/rating_test.go @@ -0,0 +1,81 @@ +package handler + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/gin-gonic/gin" + + "line-fleet-dispatch/internal/auth" + "line-fleet-dispatch/internal/middleware" + "line-fleet-dispatch/internal/service" +) + +// 驗 RideHandler.RateByCustomer 的授權/綁定/值域邊界(401/403/400/503)。 +// 擁有權、行程狀態、一趟一評等需要 DB 的守門由 service 層整合測試 +// (internal/service/rating_test.go,真 PostGIS)覆蓋——這裡只確認 HTTP 邊界, +// 故用 repo=nil 的 RatingService:星等值域在碰到 repo **之前**就返回,不會 panic。 +func setupRatingRouter(withRating bool) *gin.Engine { + gin.SetMode(gin.TestMode) + h := NewRideHandler(nil, nil, nil, service.NewRideService(nil, nil, nil, nil)) + if withRating { + h.SetRating(service.NewRatingService(nil, nil)) + } + r := gin.New() + r.POST("/api/customer/rides/:id/rating", middleware.CustomerAuth("s"), h.RateByCustomer) + return r +} + +func postRating(t *testing.T, r *gin.Engine, token, id, body string) int { + t.Helper() + w := httptest.NewRecorder() + req, _ := http.NewRequest("POST", "/api/customer/rides/"+id+"/rating", strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + if token != "" { + req.Header.Set("Authorization", "Bearer "+token) + } + r.ServeHTTP(w, req) + return w.Code +} + +func TestRateByCustomer_授權與綁定邊界(t *testing.T) { + r := setupRatingRouter(true) + ctok, _ := auth.GenerateToken("customer", 9, "s", time.Hour) + dtok, _ := auth.GenerateToken("driver", 7, "s", time.Hour) + + // 無 token → 401(中介層攔截) + if code := postRating(t, r, "", "1", `{"score":5}`); code != http.StatusUnauthorized { + t.Fatalf("無 token 預期 401,得到 %d", code) + } + // driver token → 403(角色不符;司機不能替乘客評自己) + if code := postRating(t, r, dtok, "1", `{"score":5}`); code != http.StatusForbidden { + t.Fatalf("driver token 預期 403,得到 %d", code) + } + // 非數字的 ride id → 400 + if code := postRating(t, r, ctok, "abc", `{"score":5}`); code != http.StatusBadRequest { + t.Fatalf("壞 id 預期 400,得到 %d", code) + } + // 壞 JSON → 400(綁定失敗即返回) + if code := postRating(t, r, ctok, "1", `{bad`); code != http.StatusBadRequest { + t.Fatalf("壞 JSON 預期 400,得到 %d", code) + } + // 星等越界 → 400。**沒帶 score 等同 0**,同樣被擋—— + // 少一個欄位不該被當成「給 0 分」寫進去。 + for _, body := range []string{`{"score":0}`, `{"score":6}`, `{}`} { + if code := postRating(t, r, ctok, "1", body); code != http.StatusBadRequest { + t.Fatalf("星等越界 %s 預期 400,得到 %d", body, code) + } + } +} + +// 未呼叫 SetRating(rating==nil)→ handler 早退 503,不 panic。 +func TestRateByCustomer_未啟用回503(t *testing.T) { + r := setupRatingRouter(false) + ctok, _ := auth.GenerateToken("customer", 9, "s", time.Hour) + if code := postRating(t, r, ctok, "1", `{"score":5}`); code != http.StatusServiceUnavailable { + t.Fatalf("未啟用預期 503,得到 %d", code) + } +} diff --git a/internal/handler/ride.go b/internal/handler/ride.go index 8bed144..3240b68 100644 --- a/internal/handler/ride.go +++ b/internal/handler/ride.go @@ -19,6 +19,7 @@ type RideHandler struct { rideService *service.RideService stops *service.RideStopService estimate *service.EstimateService + rating *service.RatingService } func NewRideHandler( @@ -40,6 +41,58 @@ func (h *RideHandler) SetEstimate(estimate *service.EstimateService) { h.estimate = estimate } +// SetRating 注入評分服務(B5 乘客評分司機);可選。 +func (h *RideHandler) SetRating(rating *service.RatingService) { + h.rating = rating +} + +// RateByCustomer POST /api/customer/rides/:id/rating — 乘客對已完成行程評分(B5)。 +// 一趟一評、不可重評;星等必填 1–5,評論選填。 +func (h *RideHandler) RateByCustomer(c *gin.Context) { + if h.rating == nil { + c.JSON(http.StatusServiceUnavailable, gin.H{"error": "評分功能未啟用"}) + return + } + rideID, err := strconv.ParseInt(c.Param("id"), 10, 64) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "id 格式錯誤"}) + return + } + var req struct { + Score int `json:"score"` + Comment string `json:"comment"` + } + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "參數錯誤"}) + return + } + customerID := middleware.CustomerIDFromCtx(c) + rating, err := h.rating.RateByCustomer(customerID, rideID, req.Score, req.Comment) + if err != nil { + c.JSON(ratingStatusForErr(err), gin.H{"error": err.Error()}) + return + } + c.JSON(http.StatusOK, gin.H{"rating": rating}) +} + +// ratingStatusForErr 評分錯誤對應 HTTP 狀態碼。 +// 「已評過」與「行程未完成」都是**狀態衝突而非輸入格式錯誤**(409), +// App 端據此知道不必請乘客改參數重送。 +func ratingStatusForErr(err error) int { + switch { + case errors.Is(err, service.ErrInvalidScore), errors.Is(err, service.ErrCommentTooLong): + return http.StatusBadRequest + case errors.Is(err, service.ErrForbidden): + return http.StatusForbidden + case errors.Is(err, service.ErrNotFound): + return http.StatusNotFound + case errors.Is(err, service.ErrRatingExists), errors.Is(err, service.ErrRideNotCompleted): + return http.StatusConflict + default: + return http.StatusInternalServerError + } +} + // stopStatusForErr 停靠點標記的錯誤對應。 func stopStatusForErr(err error) int { switch { diff --git a/internal/handler/route_shape_test.go b/internal/handler/route_shape_test.go new file mode 100644 index 0000000..ffb2f1e --- /dev/null +++ b/internal/handler/route_shape_test.go @@ -0,0 +1,42 @@ +package handler + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/gin-gonic/gin" +) + +// 乘客訂單路由同一層同時有靜態段(estimate/active)與參數段(:id), +// **gin 舊版對此會在註冊當下 panic**——那是啟動即死、單元測試照樣全綠的失敗模式, +// 一路到部署才會發現。B5 新增 POST /customer/rides/:id/rating 讓 POST 這一側 +// 首次出現同樣的混用,故補這道守門。 +// +// 這裡重建的是**路由形狀**而非 main.go 的實際路由表(無法從 handler 套件取用), +// 形狀變了要同步改這裡。 +func TestCustomerRideRoutesStaticAndParamCoexist(t *testing.T) { + gin.SetMode(gin.TestMode) + r := gin.New() + g := r.Group("/api") + g.POST("/rides", func(c *gin.Context) { c.String(200, "create") }) + g.POST("/customer/rides/estimate", func(c *gin.Context) { c.String(200, "estimate") }) + g.GET("/customer/rides", func(c *gin.Context) { c.String(200, "history") }) + g.GET("/customer/rides/active", func(c *gin.Context) { c.String(200, "active") }) + g.GET("/customer/rides/:id", func(c *gin.Context) { c.String(200, "detail") }) + g.POST("/customer/rides/:id/rating", func(c *gin.Context) { c.String(200, "rating:"+c.Param("id")) }) + + for _, tc := range []struct{ method, path, want string }{ + {"POST", "/api/customer/rides/estimate", "estimate"}, + {"POST", "/api/customer/rides/42/rating", "rating:42"}, + {"GET", "/api/customer/rides/active", "active"}, + {"GET", "/api/customer/rides/42", "detail"}, + } { + w := httptest.NewRecorder() + req, _ := http.NewRequest(tc.method, tc.path, nil) + r.ServeHTTP(w, req) + if w.Body.String() != tc.want { + t.Fatalf("%s %s → %q,預期 %q(code=%d)", tc.method, tc.path, w.Body.String(), tc.want, w.Code) + } + } +} diff --git a/internal/model/models.go b/internal/model/models.go index 2240927..9f86c7b 100644 --- a/internal/model/models.go +++ b/internal/model/models.go @@ -292,6 +292,22 @@ func (LostItemRequest) TableName() string { return "lost_item_requests" } +// RideRating 乘客對已完成行程的司機評分(B5):一趟一則,1–5 星+選填評論。 +// customer_id/driver_id 為寫入當下的快照,不靠 rides 反查(見 migration 000023 說明)。 +type RideRating struct { + ID int64 `gorm:"primaryKey" json:"id"` + RideID int64 `gorm:"column:ride_id;not null" json:"ride_id"` + CustomerID int64 `gorm:"column:customer_id;not null" json:"customer_id"` + DriverID int64 `gorm:"column:driver_id;not null" json:"driver_id"` + Score int16 `gorm:"not null" json:"score"` + Comment string `gorm:"not null;default:''" json:"comment"` + CreatedAt time.Time `gorm:"not null" json:"created_at"` +} + +func (RideRating) TableName() string { + return "ride_ratings" +} + type Admin struct { ID int64 `gorm:"primaryKey"` Username string `gorm:"column:username;uniqueIndex;not null"` diff --git a/internal/repository/repository.go b/internal/repository/repository.go index 859886d..08c1b2f 100644 --- a/internal/repository/repository.go +++ b/internal/repository/repository.go @@ -903,6 +903,9 @@ type CustomerRideRow struct { FareAmountCents *int64 `json:"fare_amount_cents"` DriverID *int64 `json:"driver_id"` DriverName *string `json:"driver_name"` + // RatingScore 乘客給過的星等(B5);**nil =尚未評分**,前端據此在歷史清單 + // 給「評分」入口而非只顯示星星。完成卡關掉後,這裡是唯一的補評路徑。 + RatingScore *int16 `json:"rating_score"` } const CustomerRideListDefaultLimit = 20 @@ -920,8 +923,11 @@ func (r *RideRepository) ListRecentByCustomer(customerID int64, limit int) ([]Cu err := r.db.Model(&model.Ride{}). Select("rides.id", "rides.status", "rides.pickup_address", "rides.dropoff_address", "rides.requested_at", "rides.completed_at", "rides.fare_amount_cents", - "rides.driver_id", "drivers.name AS driver_name"). + "rides.driver_id", "drivers.name AS driver_name", + "ride_ratings.score AS rating_score"). Joins("LEFT JOIN drivers ON drivers.id = rides.driver_id"). + // 一趟至多一則評分(uq_ride_ratings_ride_id),故 LEFT JOIN 不會讓行程重複出現。 + Joins("LEFT JOIN ride_ratings ON ride_ratings.ride_id = rides.id"). Where("rides.customer_id = ?", customerID). Order("rides.id DESC").Limit(limit). Scan(&rows).Error diff --git a/internal/repository/ride_rating.go b/internal/repository/ride_rating.go new file mode 100644 index 0000000..758ba7a --- /dev/null +++ b/internal/repository/ride_rating.go @@ -0,0 +1,69 @@ +package repository + +import ( + "time" + + "gorm.io/gorm" + + "line-fleet-dispatch/internal/model" +) + +// RideRatingRepository 乘客對司機的行程評分讀寫(B5)。 +type RideRatingRepository struct { + db *gorm.DB +} + +func NewRideRatingRepository(db *gorm.DB) *RideRatingRepository { + return &RideRatingRepository{db: db} +} + +// Create 寫入評分。同一趟重複評分會撞唯一索引 uq_ride_ratings_ride_id +// (服務層先行檢查,此為競態下的最後防線)。 +func (r *RideRatingRepository) Create(rating *model.RideRating) error { + if rating.CreatedAt.IsZero() { + rating.CreatedAt = time.Now() + } + return r.db.Create(rating).Error +} + +// FindByRide 取該行程的評分;未評分回 (nil, nil)——「還沒評」不是錯誤, +// 它是完成卡決定顯示星星還是評分按鈕的正常輸入。 +func (r *RideRatingRepository) FindByRide(rideID int64) (*model.RideRating, error) { + var rating model.RideRating + err := r.db.Where("ride_id = ?", rideID).First(&rating).Error + if err == gorm.ErrRecordNotFound { + return nil, nil + } + if err != nil { + return nil, err + } + return &rating, nil +} + +// DriverRatingSummary 司機的評分彙總(平均分與則數)。 +type DriverRatingSummary struct { + // Average 平均分,未經四捨五入(呈現端自行決定小數位)。無評分時為 0。 + Average float64 `json:"rating_avg"` + Count int64 `json:"rating_count"` +} + +// SummaryByDriver 司機平均分與評分則數。**無評分時回 (0, 0) 而非錯誤**—— +// 新司機沒有評分是常態,不該讓司機主頁查詢失敗。 +func (r *RideRatingRepository) SummaryByDriver(driverID int64) (DriverRatingSummary, error) { + var row struct { + Avg *float64 + Count int64 + } + err := r.db.Model(&model.RideRating{}). + Select("AVG(score) AS avg", "COUNT(*) AS count"). + Where("driver_id = ?", driverID). + Scan(&row).Error + if err != nil { + return DriverRatingSummary{}, err + } + summary := DriverRatingSummary{Count: row.Count} + if row.Avg != nil { + summary.Average = *row.Avg + } + return summary, nil +} diff --git a/internal/service/rating.go b/internal/service/rating.go new file mode 100644 index 0000000..f5a2cf8 --- /dev/null +++ b/internal/service/rating.go @@ -0,0 +1,81 @@ +package service + +import ( + "errors" + "strings" + "unicode/utf8" + + "line-fleet-dispatch/internal/constants" + "line-fleet-dispatch/internal/model" + "line-fleet-dispatch/internal/repository" +) + +var ( + // ErrInvalidScore 星等超出 1–5。App 端只給得出 1–5,這是直打 API 的防線。 + ErrInvalidScore = errors.New("評分必須是 1 到 5 顆星") + // ErrRatingExists 一趟一評、不可重評(見 migration 000023 的理由)。 + ErrRatingExists = errors.New("此行程已評分過") + // ErrCommentTooLong 評論字數超過上限。 + ErrCommentTooLong = errors.New("評論長度超過上限") +) + +// ratingCommentMaxRunes 評論字數上限(DB 另有 char_length ≤ 500 的最後防線)。 +const ratingCommentMaxRunes = 200 + +// RatingService 乘客評分司機(B5):只有該趟乘客、只有已完成行程、一趟只能評一次。 +type RatingService struct { + rides *repository.RideRepository + ratings *repository.RideRatingRepository +} + +func NewRatingService(rides *repository.RideRepository, ratings *repository.RideRatingRepository) *RatingService { + return &RatingService{rides: rides, ratings: ratings} +} + +// RateByCustomer 乘客對自己的已完成行程評分。 +// +// 驗證順序刻意是「輸入 → 歸屬 → 狀態 → 重複」:先擋掉不必查 DB 的輸入錯誤, +// 再依序回答「這趟是不是你的」「這趟完成了沒」「你評過了沒」—— +// 每一步的錯誤訊息都直接對應乘客該知道的下一步。 +func (s *RatingService) RateByCustomer(customerID, rideID int64, score int, comment string) (*model.RideRating, error) { + if score < 1 || score > 5 { + return nil, ErrInvalidScore + } + comment = strings.TrimSpace(comment) + if utf8.RuneCountInString(comment) > ratingCommentMaxRunes { + return nil, ErrCommentTooLong + } + ride, err := s.rides.GetByID(rideID) + if err != nil { + return nil, ErrNotFound + } + if ride.CustomerID != customerID { + return nil, ErrForbidden + } + // 沒司機的行程(派單前取消)沒有評分對象;未完成的行程還沒有可評的服務。 + if ride.Status != constants.RideStatusCompleted || ride.DriverID == nil { + return nil, ErrRideNotCompleted + } + if existing, err := s.ratings.FindByRide(rideID); err != nil { + return nil, err + } else if existing != nil { + return nil, ErrRatingExists + } + + rating := &model.RideRating{ + RideID: rideID, + CustomerID: customerID, + DriverID: *ride.DriverID, + Score: int16(score), + Comment: comment, + } + if err := s.ratings.Create(rating); err != nil { + return nil, err + } + return rating, nil +} + +// SummaryByDriver 司機的平均分與則數(司機主頁自己看)。 +func (s *RatingService) SummaryByDriver(driverID int64) (repository.DriverRatingSummary, error) { + return s.ratings.SummaryByDriver(driverID) +} diff --git a/internal/service/rating_test.go b/internal/service/rating_test.go new file mode 100644 index 0000000..485745b --- /dev/null +++ b/internal/service/rating_test.go @@ -0,0 +1,209 @@ +package service + +import ( + "errors" + "strings" + "testing" + + "line-fleet-dispatch/internal/constants" + "line-fleet-dispatch/internal/repository" +) + +// completedRideForRating 造一趟「已完成且有司機」的行程,供評分測試使用。 +func completedRideForRating(t *testing.T, rides *repository.RideRepository, customerID, driverID int64) int64 { + t.Helper() + ride := newTestRide(t, rides, customerID, constants.RideStatusRequested) + if err := rides.AcceptRide(ride.ID, driverID, 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) + } + return ride.ID +} + +// TestRatingFlow 驗證 B5 評分主流程與四道守門: +// 星等值域、只有本人、只有已完成行程、一趟一評。 +func TestRatingFlow(t *testing.T) { + db := newServiceTestDB(t) + customers := repository.NewCustomerRepository(db) + drivers := repository.NewDriverRepository(db) + rides := repository.NewRideRepository(db) + ratings := repository.NewRideRatingRepository(db) + + owner, err := customers.FindOrCreateByLineUserID("U_rating_owner", "評分乘客") + if err != nil { + t.Fatalf("建立乘客失敗:%v", err) + } + other, err := customers.FindOrCreateByLineUserID("U_rating_other", "路人乘客") + if err != nil { + t.Fatalf("建立乘客失敗:%v", err) + } + driver, err := drivers.FindOrCreate("U_rating_driver", "被評分司機") + if err != nil { + t.Fatalf("建立司機失敗:%v", err) + } + + svc := NewRatingService(rides, ratings) + rideID := completedRideForRating(t, rides, owner.ID, driver.ID) + + // 星等值域:0 與 6 都不可接受(App 只給得出 1–5,這是直打 API 的防線) + for _, bad := range []int{0, 6, -1} { + if _, err := svc.RateByCustomer(owner.ID, rideID, bad, ""); !errors.Is(err, ErrInvalidScore) { + t.Fatalf("星等 %d 應被拒,got %v", bad, err) + } + } + + // 評論字數上限(DB CHECK 之前先擋,錯誤訊息才說得清楚) + if _, err := svc.RateByCustomer(owner.ID, rideID, 5, strings.Repeat("啊", ratingCommentMaxRunes+1)); !errors.Is(err, ErrCommentTooLong) { + t.Fatalf("超長評論應被拒,got %v", err) + } + + // 非本人的行程:403 而非 404——訂單存在,只是不是你的 + if _, err := svc.RateByCustomer(other.ID, rideID, 5, ""); !errors.Is(err, ErrForbidden) { + t.Fatalf("他人行程評分應被拒,got %v", err) + } + + // 不存在的行程 + if _, err := svc.RateByCustomer(owner.ID, 999999, 5, ""); !errors.Is(err, ErrNotFound) { + t.Fatalf("不存在的行程應回 ErrNotFound,got %v", err) + } + + // 未完成的行程沒有可評的服務 + activeRide := newTestRide(t, rides, owner.ID, constants.RideStatusPickedUp) + if _, err := svc.RateByCustomer(owner.ID, activeRide.ID, 5, ""); !errors.Is(err, ErrRideNotCompleted) { + t.Fatalf("未完成行程評分應被拒,got %v", err) + } + + // 主流程:評論前後空白會被 trim + rating, err := svc.RateByCustomer(owner.ID, rideID, 4, " 司機很準時 ") + if err != nil { + t.Fatalf("評分失敗:%v", err) + } + if rating.Score != 4 || rating.Comment != "司機很準時" { + t.Fatalf("評分內容錯誤:%+v", rating) + } + if rating.DriverID != driver.ID || rating.CustomerID != owner.ID { + t.Fatalf("評分歸屬錯誤:%+v", rating) + } + + // 一趟一評:不可重評(分數送出即定論,見 migration 000023) + if _, err := svc.RateByCustomer(owner.ID, rideID, 1, "反悔了"); !errors.Is(err, ErrRatingExists) { + t.Fatalf("重複評分應被拒,got %v", err) + } + + // 回讀:FindByRide 拿得到剛才那筆 + got, err := ratings.FindByRide(rideID) + if err != nil || got == nil || got.Score != 4 { + t.Fatalf("回讀評分失敗:%v / %+v", err, got) + } +} + +// TestRatingSummaryByDriver 司機平均分:無評分回 (0,0),多筆取平均。 +func TestRatingSummaryByDriver(t *testing.T) { + db := newServiceTestDB(t) + customers := repository.NewCustomerRepository(db) + drivers := repository.NewDriverRepository(db) + rides := repository.NewRideRepository(db) + ratings := repository.NewRideRatingRepository(db) + + owner, err := customers.FindOrCreateByLineUserID("U_summary_owner", "評分乘客") + if err != nil { + t.Fatalf("建立乘客失敗:%v", err) + } + driver, err := drivers.FindOrCreate("U_summary_driver", "被評分司機") + if err != nil { + t.Fatalf("建立司機失敗:%v", err) + } + svc := NewRatingService(rides, ratings) + + // 新司機沒有評分是常態,不該是錯誤 + summary, err := svc.SummaryByDriver(driver.ID) + if err != nil { + t.Fatalf("無評分時查詢不該失敗:%v", err) + } + if summary.Count != 0 || summary.Average != 0 { + t.Fatalf("無評分應回 (0,0),得到 %+v", summary) + } + + for _, score := range []int{5, 4, 3} { + rideID := completedRideForRating(t, rides, owner.ID, driver.ID) + if _, err := svc.RateByCustomer(owner.ID, rideID, score, ""); err != nil { + t.Fatalf("評分 %d 失敗:%v", score, err) + } + } + summary, err = svc.SummaryByDriver(driver.ID) + if err != nil { + t.Fatalf("查詢平均分失敗:%v", err) + } + if summary.Count != 3 || summary.Average != 4 { + t.Fatalf("平均分應為 4(3 則),得到 %+v", summary) + } +} + +// TestCustomerRideViewCarriesRating 乘客查自己訂單時帶回已給過的評分(B5 讀回路徑); +// 未評分時 Rating 為 nil,App 端據此顯示評分入口。 +func TestCustomerRideViewCarriesRating(t *testing.T) { + db := newServiceTestDB(t) + customers := repository.NewCustomerRepository(db) + drivers := repository.NewDriverRepository(db) + rides := repository.NewRideRepository(db) + tracks := repository.NewTrackRepository(db) + ratings := repository.NewRideRatingRepository(db) + + owner, err := customers.FindOrCreateByLineUserID("U_view_owner", "評分乘客") + if err != nil { + t.Fatalf("建立乘客失敗:%v", err) + } + driver, err := drivers.FindOrCreate("U_view_driver", "被評分司機") + if err != nil { + t.Fatalf("建立司機失敗:%v", err) + } + + query := NewRideQueryService(tracks, rides) + query.SetRatings(ratings) + rideID := completedRideForRating(t, rides, owner.ID, driver.ID) + + view, err := query.GetRideForCustomer(owner.ID, rideID) + if err != nil { + t.Fatalf("查訂單失敗:%v", err) + } + if view.Rating != nil { + t.Fatalf("尚未評分時 Rating 應為 nil,得到 %+v", view.Rating) + } + + svc := NewRatingService(rides, ratings) + if _, err := svc.RateByCustomer(owner.ID, rideID, 5, "很棒"); err != nil { + t.Fatalf("評分失敗:%v", err) + } + view, err = query.GetRideForCustomer(owner.ID, rideID) + if err != nil { + t.Fatalf("查訂單失敗:%v", err) + } + if view.Rating == nil || view.Rating.Score != 5 || view.Rating.Comment != "很棒" { + t.Fatalf("評分未帶回訂單視圖:%+v", view.Rating) + } + + // 歷史列表也要看得出評過沒(完成卡關掉後的唯一補評路徑) + rows, err := query.ListRecentByCustomer(owner.ID, 0) + if err != nil { + t.Fatalf("查歷史列表失敗:%v", err) + } + var found bool + for _, row := range rows { + if row.ID != rideID { + continue + } + found = true + if row.RatingScore == nil || *row.RatingScore != 5 { + t.Fatalf("歷史列表未帶回星等:%+v", row.RatingScore) + } + } + if !found { + t.Fatalf("歷史列表沒有這趟行程(%d)", rideID) + } +} diff --git a/internal/service/ride.go b/internal/service/ride.go index 087870c..02314b0 100644 --- a/internal/service/ride.go +++ b/internal/service/ride.go @@ -253,6 +253,7 @@ type RideQueryService struct { rides *repository.RideRepository drivers *repository.DriverRepository stops *repository.RideStopRepository + ratings *repository.RideRatingRepository } func NewRideQueryService(tracks *repository.TrackRepository, rides *repository.RideRepository) *RideQueryService { @@ -272,6 +273,12 @@ func (s *RideQueryService) SetDrivers(drivers *repository.DriverRepository) { s.drivers = drivers } +// SetRatings 注入評分 repo(乘客查單筆訂單時帶回自己給過的評分,B5);可選—— +// 未注入時查詢仍可用,只是不帶 rating(App 端等同「尚未評分」,會顯示評分入口)。 +func (s *RideQueryService) SetRatings(ratings *repository.RideRatingRepository) { + s.ratings = ratings +} + // CustomerRideView 乘客視角的訂單:ride 全欄位(含 O7 車輛快照)+司機姓名/電話。 // // 內嵌 *model.Ride 讓 JSON 攤平,既有欄位一個不少——App 讀到的形狀只多不變。 @@ -289,6 +296,10 @@ type CustomerRideView struct { // 走到哪一站——形狀與司機端的 DriverRideView.Stops **完全相同**, // App 端兩邊共用同一套解析。單點訂單為 nil(omitempty),既有形狀不變。 Stops []map[string]any `json:"stops,omitempty"` + // Rating 乘客自己對這趟給過的評分(B5);**尚未評分時為 nil**(omitempty)。 + // App 端據此決定完成/歷史畫面顯示「留下評分」按鈕還是既有星等, + // 不必再打一支「評過沒」的查詢。 + Rating *model.RideRating `json:"rating,omitempty"` } // withDriverContact 補上司機姓名/電話;未接單或未注入 drivers 時原樣回傳。 @@ -309,17 +320,27 @@ func (s *RideQueryService) withDriverContact(ride *model.Ride) *CustomerRideView return view } -// customerRideView 乘客視角的完整訂單:司機聯絡資訊 + 全程停靠點。 +// customerRideView 乘客視角的完整訂單:司機聯絡資訊 + 全程停靠點 + 自己給過的評分。 // -// 停靠點讀失敗**不擋**整筆查詢——乘客仍能看到行程狀態與司機資訊, -// 這與司機端 GetActiveRideByDriver 的處理一致(stops 是加值資訊,不是行程本體)。 +// 停靠點與評分讀失敗**都不擋**整筆查詢——乘客仍能看到行程狀態與司機資訊, +// 這與司機端 GetActiveRideByDriver 的處理一致(兩者都是加值資訊,不是行程本體)。 func (s *RideQueryService) customerRideView(ride *model.Ride) *CustomerRideView { view := s.withDriverContact(ride) - if view == nil || s.stops == nil { + if view == nil { return view } - if stops, err := s.stops.ListByRide(ride.ID); err == nil { - view.Stops = stopViews(stops) + if s.stops != nil { + if stops, err := s.stops.ListByRide(ride.ID); err == nil { + view.Stops = stopViews(stops) + } + } + // 評分只存在於已完成的行程(RateByCustomer 的守門),所以**只在完成時才查**—— + // 這條路徑也服務乘客端的 active 輪詢,對永遠不可能有評分的進行中訂單 + // 每幾秒打一次 ride_ratings 是純浪費。 + if s.ratings != nil && ride.Status == constants.RideStatusCompleted { + if rating, err := s.ratings.FindByRide(ride.ID); err == nil { + view.Rating = rating + } } return view }