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
11 changes: 9 additions & 2 deletions cmd/server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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)
Expand All @@ -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)
Expand Down Expand Up @@ -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)
// 遺失物協尋:對已完成行程建單、查自己的協尋、支付處理費
Expand Down
2 changes: 2 additions & 0 deletions db/migrations/000023_create_ride_ratings.down.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- DROP TABLE 會連帶刪除其上的 CHECK、UNIQUE 索引與 FK。
DROP TABLE IF EXISTS ride_ratings;
28 changes: 28 additions & 0 deletions db/migrations/000023_create_ride_ratings.up.sql
Original file line number Diff line number Diff line change
@@ -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);
39 changes: 39 additions & 0 deletions docs/TODO.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 加入,尚未實作,皆需後端地基先行)**:
Expand Down
6 changes: 3 additions & 3 deletions docs/backend-api-gaps.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 延遲) |
Expand Down
18 changes: 17 additions & 1 deletion internal/handler/driver.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)。
Expand Down
81 changes: 81 additions & 0 deletions internal/handler/rating_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
53 changes: 53 additions & 0 deletions internal/handler/ride.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ type RideHandler struct {
rideService *service.RideService
stops *service.RideStopService
estimate *service.EstimateService
rating *service.RatingService
}

func NewRideHandler(
Expand All @@ -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 {
Expand Down
42 changes: 42 additions & 0 deletions internal/handler/route_shape_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
}
16 changes: 16 additions & 0 deletions internal/model/models.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"`
Expand Down
Loading
Loading