Add visitor phone lookup flow

This commit is contained in:
wangxuming
2026-07-15 11:26:37 +08:00
parent 331e30894b
commit 7f751bebae
21 changed files with 971 additions and 104 deletions

View File

@@ -35,6 +35,11 @@ If a phone already has active tickets, ticket creation returns
`DUPLICATE_PHONE`; repeat with the same request body except
`allow_duplicate: true` and a new idempotency key after the employee confirms.
`POST /api/public/status/search` is a temporary non-production operational-test
endpoint. It accepts `{ "phone": "..." }` and returns all current active
tickets associated with that phone. It is disabled when `APP_ENV=production`;
replace it with OTP or an external identity interface before formal launch.
## Tests
```sh

View File

@@ -17,6 +17,52 @@ type loginLimiter struct {
now func() time.Time
}
type queryLimitEntry struct {
windowStart time.Time
count int
}
// queryLimiter is deliberately small and in-memory for the temporary public
// phone lookup. The production replacement will be an OTP or external
// identity provider, so this limiter is only a safety net for the test flow.
type queryLimiter struct {
mu sync.Mutex
entries map[string]queryLimitEntry
now func() time.Time
limit int
window time.Duration
}
func newQueryLimiter(now func() time.Time, limit int, window time.Duration) *queryLimiter {
return &queryLimiter{
entries: make(map[string]queryLimitEntry), now: now, limit: limit, window: window,
}
}
func (l *queryLimiter) allow(key string) (bool, time.Duration) {
if l == nil || l.limit <= 0 || l.window <= 0 {
return true, 0
}
l.mu.Lock()
defer l.mu.Unlock()
now := l.now()
entry, ok := l.entries[key]
if !ok || now.Sub(entry.windowStart) >= l.window {
entry = queryLimitEntry{windowStart: now}
}
if entry.count >= l.limit {
retry := l.window - now.Sub(entry.windowStart)
if retry < 0 {
retry = 0
}
return false, retry
}
entry.count++
l.entries[key] = entry
return true, 0
}
func newLoginLimiter(now func() time.Time) *loginLimiter {
return &loginLimiter{attempts: make(map[string]loginAttempt), now: now}
}

View File

@@ -0,0 +1,26 @@
package httpapi
import (
"testing"
"time"
)
func TestQueryLimiterResetsAfterWindow(t *testing.T) {
now := time.Unix(100, 0)
limiter := newQueryLimiter(func() time.Time { return now }, 2, time.Minute)
if allowed, _ := limiter.allow("phone:test"); !allowed {
t.Fatal("first query should be allowed")
}
if allowed, _ := limiter.allow("phone:test"); !allowed {
t.Fatal("second query should be allowed")
}
if allowed, retry := limiter.allow("phone:test"); allowed || retry <= 0 {
t.Fatalf("third query should be limited with a retry duration, got allowed=%v retry=%s", allowed, retry)
}
now = now.Add(time.Minute)
if allowed, _ := limiter.allow("phone:test"); !allowed {
t.Fatal("query should be allowed after the window resets")
}
}

View File

@@ -27,29 +27,113 @@ func (s *Server) publicStatus(w http.ResponseWriter, r *http.Request) {
writeError(w, mapNotFound(err, "STATUS_NOT_FOUND", "排队状态不存在或链接已失效"))
return
}
var project model.Project
var session model.QueueSession
if err := s.db.WithContext(r.Context()).First(&project, "id = ?", ticket.ProjectID).Error; err != nil {
writeError(w, err)
return
}
if err := s.db.WithContext(r.Context()).First(&session, "id = ? AND project_id = ?", ticket.QueueSessionID, ticket.ProjectID).Error; err != nil {
writeError(w, err)
return
}
phoneSuffix, err := s.ticketPhoneLast4(ticket)
view, err := s.publicStatusView(r.Context(), ticket)
if err != nil {
writeError(w, err)
return
}
writeJSON(w, http.StatusOK, view)
}
type publicPhoneQueryRequest struct {
Phone string `json:"phone"`
}
// publicStatusByPhone is a temporary operational-test flow. It must be
// replaced by OTP or an external identity provider before production use.
func (s *Server) publicStatusByPhone(w http.ResponseWriter, r *http.Request) {
if s.config.Environment == "production" {
writeError(w, &apiError{Status: http.StatusNotFound, Code: "STATUS_NOT_FOUND", Message: "排队状态不存在或链接已失效"})
return
}
if s.publicQueryLimiter != nil {
if allowed, retry := s.publicQueryLimiter.allow("ip:" + publicQueryClientKey(r)); !allowed {
writePublicQueryRateLimit(w, retry)
return
}
}
var input publicPhoneQueryRequest
if err := decodeJSON(r, &input); err != nil {
writeError(w, err)
return
}
phone, err := security.NormalizePhone(input.Phone)
if err != nil {
writeError(w, &apiError{Status: http.StatusUnprocessableEntity, Code: "INVALID_PHONE", Message: "请输入有效的手机号"})
return
}
phoneDigest := s.cipher.Digest(phone)
if s.publicQueryLimiter != nil {
if allowed, retry := s.publicQueryLimiter.allow("phone:" + phoneDigest); !allowed {
writePublicQueryRateLimit(w, retry)
return
}
}
var tickets []model.QueueTicket
if err := s.db.WithContext(r.Context()).Model(&model.QueueTicket{}).
Joins("JOIN projects ON projects.id = queue_tickets.project_id").
Joins("JOIN queue_sessions ON queue_sessions.id = queue_tickets.queue_session_id AND queue_sessions.project_id = queue_tickets.project_id").
Where("queue_tickets.phone_hmac = ? AND queue_tickets.status IN ? AND queue_sessions.status IN ? AND projects.status IN ?",
phoneDigest,
[]string{model.TicketWaiting, model.TicketCalled, model.TicketArrived},
[]string{"RUNNING", "PAUSED"},
[]string{model.ProjectRunning, model.ProjectPaused}).
Order("projects.name ASC, queue_tickets.ticket_number ASC").
Find(&tickets).Error; err != nil {
writeError(w, err)
return
}
views := make([]map[string]any, 0, len(tickets))
for _, ticket := range tickets {
view, err := s.publicStatusView(r.Context(), ticket)
if err != nil {
writeError(w, err)
return
}
views = append(views, view)
}
writeJSON(w, http.StatusOK, map[string]any{"tickets": views})
}
func publicQueryClientKey(r *http.Request) string {
if ip := remoteIP(r); ip != nil {
return *ip
}
return "unknown"
}
func writePublicQueryRateLimit(w http.ResponseWriter, retry time.Duration) {
seconds := int((retry + time.Second - 1) / time.Second)
if seconds < 1 {
seconds = 1
}
w.Header().Set("Retry-After", fmt.Sprintf("%d", seconds))
writeError(w, &apiError{Status: http.StatusTooManyRequests, Code: "PUBLIC_QUERY_RATE_LIMITED", Message: "查询次数过多,请稍后再试"})
}
func (s *Server) publicStatusView(ctx context.Context, ticket model.QueueTicket) (map[string]any, error) {
var project model.Project
var session model.QueueSession
if err := s.db.WithContext(ctx).First(&project, "id = ?", ticket.ProjectID).Error; err != nil {
return nil, err
}
if err := s.db.WithContext(ctx).First(&session, "id = ? AND project_id = ?", ticket.QueueSessionID, ticket.ProjectID).Error; err != nil {
return nil, err
}
phoneSuffix, err := s.ticketPhoneLast4(ticket)
if err != nil {
return nil, err
}
peopleAhead := 0
if ticket.Status == model.TicketWaiting {
var count int64
if err := s.db.WithContext(r.Context()).Model(&model.QueueTicket{}).
if err := s.db.WithContext(ctx).Model(&model.QueueTicket{}).
Where("project_id = ? AND queue_session_id = ? AND status = ? AND ticket_number < ?",
ticket.ProjectID, ticket.QueueSessionID, model.TicketWaiting, ticket.TicketNumber).Count(&count).Error; err != nil {
writeError(w, err)
return
return nil, err
}
peopleAhead = int(count)
}
@@ -57,12 +141,11 @@ func (s *Server) publicStatus(w http.ResponseWriter, r *http.Request) {
DisplayNumber string `gorm:"column:display_number"`
}
latestCalledNumber := any(nil)
if err := s.db.WithContext(r.Context()).Model(&model.QueueTicket{}).
if err := s.db.WithContext(ctx).Model(&model.QueueTicket{}).
Select("display_number").
Where("project_id = ? AND queue_session_id = ? AND called_at IS NOT NULL", ticket.ProjectID, ticket.QueueSessionID).
Order("called_at DESC, ticket_number DESC").First(&latestCalledTicket).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
writeError(w, err)
return
return nil, err
} else if latestCalledTicket.DisplayNumber != "" {
latestCalledNumber = latestCalledTicket.DisplayNumber
}
@@ -71,13 +154,12 @@ func (s *Server) publicStatus(w http.ResponseWriter, r *http.Request) {
Running: project.Status == model.ProjectRunning && session.Status == "RUNNING" && ticket.Status == model.TicketWaiting,
})
if err != nil {
writeError(w, err)
return
return nil, err
}
if ticket.Status != model.TicketWaiting {
eta = domain.ETAResult{Available: false, Reason: "ticket_not_waiting"}
}
writeJSON(w, http.StatusOK, map[string]any{
return map[string]any{
"ticket_number": ticket.DisplayNumber, "display_number": ticket.DisplayNumber,
"project_name": project.Name, "status": ticket.Status, "phone_last4": phoneSuffix, "estimated_wait": eta,
"visitor_notice": project.VisitorNotice,
@@ -90,7 +172,7 @@ func (s *Server) publicStatus(w http.ResponseWriter, r *http.Request) {
"people_ahead": peopleAhead, "queue_position": queuePosition(ticket.Status, peopleAhead),
"latest_called_number": latestCalledNumber,
"eta": eta, "revision": session.Revision, "server_time": s.now(),
})
}, nil
}
func queuePosition(status string, peopleAhead int) any {

View File

@@ -2,10 +2,12 @@ package httpapi
import (
"encoding/json"
"net/http/httptest"
"strings"
"testing"
"time"
"calllinesystem/server/internal/config"
"calllinesystem/server/internal/model"
)
@@ -28,3 +30,27 @@ func TestDisplayBatchDTOCannotSerializePersonalFields(t *testing.T) {
t.Fatalf("public ticket number missing: %s", encoded)
}
}
func TestPublicPhoneLookupIsDisabledInProduction(t *testing.T) {
server := &Server{config: config.Config{Environment: "production"}}
recorder := httptest.NewRecorder()
request := httptest.NewRequest("POST", "/api/public/status/search", strings.NewReader(`{"phone":"13800138000"}`))
server.publicStatusByPhone(recorder, request)
if recorder.Code != 404 {
t.Fatalf("production phone lookup status = %d, want 404", recorder.Code)
}
}
func TestPublicPhoneLookupRejectsInvalidPhone(t *testing.T) {
server := &Server{config: config.Config{Environment: "development"}}
recorder := httptest.NewRecorder()
request := httptest.NewRequest("POST", "/api/public/status/search", strings.NewReader(`{"phone":"123"}`))
server.publicStatusByPhone(recorder, request)
if recorder.Code != 422 {
t.Fatalf("invalid phone lookup status = %d, want 422", recorder.Code)
}
}

View File

@@ -27,14 +27,15 @@ const (
)
type Server struct {
db *gorm.DB
config config.Config
cipher *security.Cipher
logger *slog.Logger
hub eventPublisher
loginLimiter *loginLimiter
dummyPassword string
now func() time.Time
db *gorm.DB
config config.Config
cipher *security.Cipher
logger *slog.Logger
hub eventPublisher
loginLimiter *loginLimiter
publicQueryLimiter *queryLimiter
dummyPassword string
now func() time.Time
}
func New(db *gorm.DB, cfg config.Config, logger *slog.Logger) (*Server, error) {
@@ -55,14 +56,15 @@ func NewWithEventPublisher(db *gorm.DB, cfg config.Config, logger *slog.Logger,
}
now := func() time.Time { return time.Now().UTC() }
return &Server{
db: db,
config: cfg,
cipher: fieldCipher,
logger: logger,
hub: publisher,
loginLimiter: newLoginLimiter(now),
dummyPassword: dummy,
now: now,
db: db,
config: cfg,
cipher: fieldCipher,
logger: logger,
hub: publisher,
loginLimiter: newLoginLimiter(now),
publicQueryLimiter: newQueryLimiter(now, 120, time.Minute),
dummyPassword: dummy,
now: now,
}, nil
}
@@ -81,6 +83,7 @@ func (s *Server) Handler() http.Handler {
mux.Handle("POST /api/staff/projects/{id}/tickets", s.requireStaff(http.HandlerFunc(s.createTicket)))
mux.Handle("POST /api/staff/projects/{id}/call-next", s.requireStaff(http.HandlerFunc(s.callNext)))
mux.HandleFunc("GET /api/public/status/{token}", s.publicStatus)
mux.HandleFunc("POST /api/public/status/search", s.publicStatusByPhone)
mux.HandleFunc("GET /api/display/{token}/snapshot", s.displaySnapshot)
mux.Handle("GET /api/events", s.requireStaff(http.HandlerFunc(s.events)))
mux.Handle("GET /api/admin/overview", s.requireAdmin(http.HandlerFunc(s.adminOverview)))