feat: add party-size queueing and call modes
This commit is contained in:
@@ -70,10 +70,14 @@ func (s *Server) createProject(w http.ResponseWriter, r *http.Request) {
|
||||
project := model.Project{
|
||||
ID: uuid.NewString(), Name: input.Name, Code: input.Code, Timezone: input.Timezone, TicketPrefix: input.TicketPrefix,
|
||||
Status: model.ProjectNotOpen, CallBatchSize: 1, GracePeriodMinutes: 5, ETAMode: model.ETAFixedBatch,
|
||||
CallMode: model.CallModeBoth, MaxCallTicketCount: 100,
|
||||
DefaultCallPeopleCount: 1, MaxCallPeopleCount: 100,
|
||||
MinPartySize: 1, MaxPartySize: 10,
|
||||
AverageBatchIntervalSeconds: 300, ContinuousRatePerMinute: 1, ETABufferMinutes: 0,
|
||||
ETAIntervalSeconds: 60,
|
||||
VisitorNotice: model.DefaultVisitorNotice,
|
||||
DeviceSimulationMode: "DISABLED", CreatedAt: now, UpdatedAt: now,
|
||||
ETAIntervalSeconds: 60,
|
||||
ExperiencedPeopleStart: 0,
|
||||
VisitorNotice: model.DefaultVisitorNotice,
|
||||
DeviceSimulationMode: "DISABLED", CreatedAt: now, UpdatedAt: now,
|
||||
}
|
||||
err = s.db.WithContext(r.Context()).Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.Create(&project).Error; err != nil {
|
||||
@@ -153,6 +157,9 @@ func (s *Server) adminUsers(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
views := make([]map[string]any, 0, len(users))
|
||||
for _, user := range users {
|
||||
if user.Username == model.PublicVisitorUsername {
|
||||
continue
|
||||
}
|
||||
views = append(views, adminUserView(user, projects[user.ID]))
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"users": views})
|
||||
@@ -256,6 +263,9 @@ func (s *Server) updateAdminUser(w http.ResponseWriter, r *http.Request) {
|
||||
if user.Username == model.SuperAdminUsername {
|
||||
return &apiError{Status: 403, Code: "PROTECTED_SUPER_ADMIN", Message: "超级管理员账号不能编辑"}
|
||||
}
|
||||
if user.Username == model.PublicVisitorUsername {
|
||||
return &apiError{Status: 403, Code: "PROTECTED_SYSTEM_USER", Message: "系统游客账号不能编辑"}
|
||||
}
|
||||
nextRole := user.Role
|
||||
if input.Role != "" {
|
||||
nextRole = input.Role
|
||||
@@ -318,16 +328,20 @@ func (s *Server) adminOverview(w http.ResponseWriter, r *http.Request) {
|
||||
type totalRow struct {
|
||||
Projects int64
|
||||
ActiveSessions int64
|
||||
Waiting int64
|
||||
Called int64
|
||||
WaitingTickets int64
|
||||
WaitingPeople int64
|
||||
CalledTickets int64
|
||||
CalledPeople int64
|
||||
}
|
||||
var totals totalRow
|
||||
if err := s.db.WithContext(r.Context()).Raw(`
|
||||
SELECT
|
||||
(SELECT count(*) FROM projects) AS projects,
|
||||
(SELECT count(*) FROM queue_sessions WHERE status IN ('RUNNING','PAUSED')) AS active_sessions,
|
||||
(SELECT count(*) FROM queue_tickets WHERE status = 'WAITING') AS waiting,
|
||||
(SELECT count(*) FROM queue_tickets WHERE status IN ('CALLED','ARRIVED')) AS called
|
||||
(SELECT count(*) FROM queue_tickets WHERE status = 'WAITING') AS waiting_tickets,
|
||||
(SELECT COALESCE(sum(party_size), 0) FROM queue_tickets WHERE status = 'WAITING') AS waiting_people,
|
||||
(SELECT count(*) FROM queue_tickets WHERE status IN ('CALLED','ARRIVED')) AS called_tickets,
|
||||
(SELECT COALESCE(sum(party_size), 0) FROM queue_tickets WHERE status IN ('CALLED','ARRIVED')) AS called_people
|
||||
`).Scan(&totals).Error; err != nil {
|
||||
writeError(w, err)
|
||||
return
|
||||
@@ -363,15 +377,16 @@ func (s *Server) adminOverview(w http.ResponseWriter, r *http.Request) {
|
||||
activeTicketViews = append(activeTicketViews, view)
|
||||
}
|
||||
projectProjections := make([]map[string]any, 0, len(projects))
|
||||
var runningProjects, anomalyProjects, offlineDevices, projectedWaiting int64
|
||||
var runningProjects, anomalyProjects, offlineDevices, projectedWaitingTickets, projectedWaitingPeople int64
|
||||
for _, project := range projects {
|
||||
projection, anomaly, offline, waiting, err := s.adminProjectProjection(r.Context(), project)
|
||||
projection, anomaly, offline, waitingTickets, waitingPeople, err := s.adminProjectProjection(r.Context(), project)
|
||||
if err != nil {
|
||||
writeError(w, err)
|
||||
return
|
||||
}
|
||||
projectProjections = append(projectProjections, projection)
|
||||
projectedWaiting += waiting
|
||||
projectedWaitingTickets += waitingTickets
|
||||
projectedWaitingPeople += waitingPeople
|
||||
if project.Status == model.ProjectRunning {
|
||||
runningProjects++
|
||||
}
|
||||
@@ -384,12 +399,15 @@ func (s *Server) adminOverview(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"summary": map[string]int64{
|
||||
"running_projects": runningProjects, "waiting_count": projectedWaiting,
|
||||
"running_projects": runningProjects, "waiting_count": projectedWaitingTickets,
|
||||
"waiting_ticket_count": projectedWaitingTickets, "waiting_people_count": projectedWaitingPeople,
|
||||
"anomaly_projects": anomalyProjects, "offline_devices": offlineDevices,
|
||||
},
|
||||
"totals": map[string]int64{
|
||||
"projects": totals.Projects, "active_sessions": totals.ActiveSessions,
|
||||
"waiting": totals.Waiting, "called": totals.Called,
|
||||
"waiting": totals.WaitingTickets, "called": totals.CalledTickets,
|
||||
"waiting_ticket_count": totals.WaitingTickets, "waiting_people_count": totals.WaitingPeople,
|
||||
"called_ticket_count": totals.CalledTickets, "called_people_count": totals.CalledPeople,
|
||||
},
|
||||
"projects": projectProjections, "active_tickets": activeTicketViews,
|
||||
"recent_device_simulations": simulations, "server_time": s.now(),
|
||||
@@ -404,11 +422,11 @@ func (s *Server) adminActiveTicketView(ticket model.QueueTicket, projectName str
|
||||
return map[string]any{
|
||||
"id": ticket.ID, "project_id": ticket.ProjectID, "project_name": projectName,
|
||||
"ticket_number": ticket.DisplayNumber, "phone": phone, "last_name": lastName,
|
||||
"honorific": ticket.Honorific, "status": ticket.Status, "created_at": ticket.CreatedAt,
|
||||
"honorific": ticket.Honorific, "party_size": ticket.PartySize, "status": ticket.Status, "created_at": ticket.CreatedAt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *Server) adminProjectProjection(ctx context.Context, project model.Project) (map[string]any, bool, bool, int64, error) {
|
||||
func (s *Server) adminProjectProjection(ctx context.Context, project model.Project) (map[string]any, bool, bool, int64, int64, error) {
|
||||
view := projectView(project)
|
||||
lastUpdated := project.UpdatedAt
|
||||
deviceStatus := map[string]any{
|
||||
@@ -432,7 +450,7 @@ func (s *Server) adminProjectProjection(ctx context.Context, project model.Proje
|
||||
anomaly = true
|
||||
}
|
||||
} else if !errors.Is(simulationErr, gorm.ErrRecordNotFound) {
|
||||
return nil, false, false, 0, simulationErr
|
||||
return nil, false, false, 0, 0, simulationErr
|
||||
}
|
||||
if project.DeviceSimulationMode == "DISABLED" {
|
||||
deviceStatus = map[string]any{"mode": "DISABLED", "status": "DISABLED", "label": "设备模拟器已停用"}
|
||||
@@ -442,48 +460,91 @@ func (s *Server) adminProjectProjection(ctx context.Context, project model.Proje
|
||||
sessionErr := s.db.WithContext(ctx).Where("project_id = ? AND status IN ?", project.ID, []string{"RUNNING", "PAUSED"}).
|
||||
Order("business_date DESC").First(&session).Error
|
||||
if errors.Is(sessionErr, gorm.ErrRecordNotFound) {
|
||||
experiencedPeople, err := s.displayedExperiencedPeople(ctx, project, nil)
|
||||
if err != nil {
|
||||
return nil, false, false, 0, 0, err
|
||||
}
|
||||
view["waiting_count"] = int64(0)
|
||||
view["waiting_ticket_count"] = int64(0)
|
||||
view["waiting_people_count"] = int64(0)
|
||||
view["issued_ticket_count"] = int64(0)
|
||||
view["latest_ticket_number"] = nil
|
||||
view["experienced_people"] = experiencedPeople
|
||||
view["current_batch"] = nil
|
||||
view["estimated_wait"] = domain.ETAResult{Available: false, Reason: "queue_not_running"}
|
||||
view["last_updated_at"] = lastUpdated
|
||||
view["device_status"] = deviceStatus
|
||||
return view, anomaly, offline, 0, nil
|
||||
return view, anomaly, offline, 0, 0, nil
|
||||
}
|
||||
if sessionErr != nil {
|
||||
return nil, false, false, 0, sessionErr
|
||||
return nil, false, false, 0, 0, sessionErr
|
||||
}
|
||||
if session.UpdatedAt.After(lastUpdated) {
|
||||
lastUpdated = session.UpdatedAt
|
||||
}
|
||||
var waitingCount int64
|
||||
if err := s.db.WithContext(ctx).Model(&model.QueueTicket{}).
|
||||
Where("project_id = ? AND queue_session_id = ? AND status = ?", project.ID, session.ID, model.TicketWaiting).
|
||||
Count(&waitingCount).Error; err != nil {
|
||||
return nil, false, false, 0, err
|
||||
waiting, err := queueTotals(s.db.WithContext(ctx), project.ID, session.ID, model.TicketWaiting)
|
||||
if err != nil {
|
||||
return nil, false, false, 0, 0, err
|
||||
}
|
||||
currentBatch, err := s.currentDisplayBatch(ctx, project.ID, session.ID)
|
||||
if err != nil {
|
||||
return nil, false, false, 0, err
|
||||
return nil, false, false, 0, 0, err
|
||||
}
|
||||
var lastWaiting model.QueueTicket
|
||||
lastWaitingErr := s.db.WithContext(ctx).Select("id", "party_size").
|
||||
Where("project_id = ? AND queue_session_id = ? AND status = ?", project.ID, session.ID, model.TicketWaiting).
|
||||
Order("ticket_number DESC").First(&lastWaiting).Error
|
||||
if lastWaitingErr != nil && !errors.Is(lastWaitingErr, gorm.ErrRecordNotFound) {
|
||||
return nil, false, false, 0, 0, lastWaitingErr
|
||||
}
|
||||
peopleAhead := int(waiting.PeopleCount)
|
||||
if lastWaitingErr == nil {
|
||||
peopleAhead = max(0, peopleAhead-lastWaiting.PartySize)
|
||||
}
|
||||
estimatedWait, err := domain.CalculateETA(domain.ETAInput{
|
||||
PeopleAhead: max(0, int(waitingCount)-1), IntervalPerNumber: time.Duration(project.ETAIntervalSeconds) * time.Second,
|
||||
Running: project.Status == model.ProjectRunning && session.Status == "RUNNING" && waitingCount > 0,
|
||||
PeopleAhead: peopleAhead, IntervalPerPerson: time.Duration(project.ETAIntervalSeconds) * time.Second,
|
||||
Running: project.Status == model.ProjectRunning && session.Status == "RUNNING" && waiting.TicketCount > 0,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, false, false, 0, err
|
||||
return nil, false, false, 0, 0, err
|
||||
}
|
||||
view["waiting_count"] = waitingCount
|
||||
experiencedPeople, err := s.displayedExperiencedPeople(ctx, project, &session)
|
||||
if err != nil {
|
||||
return nil, false, false, 0, 0, err
|
||||
}
|
||||
issuedTicketCount := max(0, session.NextTicketNumber-1)
|
||||
var latestTicketNumber any
|
||||
if issuedTicketCount > 0 {
|
||||
latestTicketNumber, err = domain.DisplayNumber("", issuedTicketCount)
|
||||
if err != nil {
|
||||
return nil, false, false, 0, 0, err
|
||||
}
|
||||
}
|
||||
view["waiting_count"] = waiting.TicketCount
|
||||
view["waiting_ticket_count"] = waiting.TicketCount
|
||||
view["waiting_people_count"] = waiting.PeopleCount
|
||||
view["issued_ticket_count"] = issuedTicketCount
|
||||
view["latest_ticket_number"] = latestTicketNumber
|
||||
view["experienced_people"] = experiencedPeople
|
||||
view["current_batch"] = currentBatch
|
||||
view["estimated_wait"] = estimatedWait
|
||||
view["last_updated_at"] = lastUpdated
|
||||
view["device_status"] = deviceStatus
|
||||
return view, anomaly, offline, waitingCount, nil
|
||||
return view, anomaly, offline, waiting.TicketCount, waiting.PeopleCount, nil
|
||||
}
|
||||
|
||||
type updateProjectSettingsRequest struct {
|
||||
Status *string `json:"status"`
|
||||
CallBatchSize *int `json:"call_batch_size"`
|
||||
DefaultCallTicketCount *int `json:"default_call_ticket_count"`
|
||||
MaxCallTicketCount *int `json:"max_call_ticket_count"`
|
||||
DefaultCallPeopleCount *int `json:"default_call_people_count"`
|
||||
MaxCallPeopleCount *int `json:"max_call_people_count"`
|
||||
CallMode *string `json:"call_mode"`
|
||||
MinPartySize *int `json:"min_party_size"`
|
||||
MaxPartySize *int `json:"max_party_size"`
|
||||
GracePeriodMinutes *int `json:"grace_period_minutes"`
|
||||
ExperiencedPeopleStart *int `json:"experienced_people_start"`
|
||||
ETAMode *string `json:"eta_mode"`
|
||||
AverageBatchIntervalSeconds *int `json:"average_batch_interval_seconds"`
|
||||
ContinuousRatePerMinute *float64 `json:"continuous_rate_per_minute"`
|
||||
@@ -516,6 +577,9 @@ func (s *Server) updateProjectSettings(w http.ResponseWriter, r *http.Request) {
|
||||
return mapNotFound(err, "PROJECT_NOT_FOUND", "项目不存在")
|
||||
}
|
||||
before := projectView(project)
|
||||
if err := validateProjectSettingsCombination(project, updates); err != nil {
|
||||
return err
|
||||
}
|
||||
updates["updated_at"] = s.now()
|
||||
if err := tx.Model(&model.Project{}).Where("id = ?", projectID).Updates(updates).Error; err != nil {
|
||||
return err
|
||||
@@ -542,11 +606,54 @@ func validateProjectSettings(input updateProjectSettingsRequest) (map[string]any
|
||||
}
|
||||
updates["status"] = value
|
||||
}
|
||||
if input.CallBatchSize != nil {
|
||||
if *input.CallBatchSize < 1 || *input.CallBatchSize > 100 {
|
||||
return nil, invalidSetting("call_batch_size")
|
||||
ticketDefault := input.DefaultCallTicketCount
|
||||
if ticketDefault == nil {
|
||||
ticketDefault = input.CallBatchSize
|
||||
} else if input.CallBatchSize != nil && *input.CallBatchSize != *ticketDefault {
|
||||
return nil, invalidSetting("default_call_ticket_count")
|
||||
}
|
||||
if ticketDefault != nil {
|
||||
if *ticketDefault < 1 || *ticketDefault > 10000 {
|
||||
return nil, invalidSetting("default_call_ticket_count")
|
||||
}
|
||||
updates["call_batch_size"] = *input.CallBatchSize
|
||||
updates["call_batch_size"] = *ticketDefault
|
||||
}
|
||||
if input.MaxCallTicketCount != nil {
|
||||
if *input.MaxCallTicketCount < 1 || *input.MaxCallTicketCount > 10000 {
|
||||
return nil, invalidSetting("max_call_ticket_count")
|
||||
}
|
||||
updates["max_call_ticket_count"] = *input.MaxCallTicketCount
|
||||
}
|
||||
if input.DefaultCallPeopleCount != nil {
|
||||
if *input.DefaultCallPeopleCount < 1 || *input.DefaultCallPeopleCount > 10000 {
|
||||
return nil, invalidSetting("default_call_people_count")
|
||||
}
|
||||
updates["default_call_people_count"] = *input.DefaultCallPeopleCount
|
||||
}
|
||||
if input.MaxCallPeopleCount != nil {
|
||||
if *input.MaxCallPeopleCount < 1 || *input.MaxCallPeopleCount > 10000 {
|
||||
return nil, invalidSetting("max_call_people_count")
|
||||
}
|
||||
updates["max_call_people_count"] = *input.MaxCallPeopleCount
|
||||
}
|
||||
if input.CallMode != nil {
|
||||
value := strings.ToUpper(strings.TrimSpace(*input.CallMode))
|
||||
if value != model.CallModeTicket && value != model.CallModePeople && value != model.CallModeBoth {
|
||||
return nil, invalidSetting("call_mode")
|
||||
}
|
||||
updates["call_mode"] = value
|
||||
}
|
||||
if input.MinPartySize != nil {
|
||||
if *input.MinPartySize < 1 || *input.MinPartySize > 10000 {
|
||||
return nil, invalidSetting("min_party_size")
|
||||
}
|
||||
updates["min_party_size"] = *input.MinPartySize
|
||||
}
|
||||
if input.MaxPartySize != nil {
|
||||
if *input.MaxPartySize < 1 || *input.MaxPartySize > 10000 {
|
||||
return nil, invalidSetting("max_party_size")
|
||||
}
|
||||
updates["max_party_size"] = *input.MaxPartySize
|
||||
}
|
||||
if input.GracePeriodMinutes != nil {
|
||||
if *input.GracePeriodMinutes < 0 || *input.GracePeriodMinutes > 120 {
|
||||
@@ -554,6 +661,12 @@ func validateProjectSettings(input updateProjectSettingsRequest) (map[string]any
|
||||
}
|
||||
updates["grace_period_minutes"] = *input.GracePeriodMinutes
|
||||
}
|
||||
if input.ExperiencedPeopleStart != nil {
|
||||
if *input.ExperiencedPeopleStart < 0 || *input.ExperiencedPeopleStart > 1000000000 {
|
||||
return nil, invalidSetting("experienced_people_start")
|
||||
}
|
||||
updates["experienced_people_start"] = *input.ExperiencedPeopleStart
|
||||
}
|
||||
if input.ETAMode != nil {
|
||||
value := strings.ToUpper(strings.TrimSpace(*input.ETAMode))
|
||||
if value != model.ETAFixedBatch && value != model.ETAContinuous {
|
||||
@@ -605,6 +718,43 @@ func validateProjectSettings(input updateProjectSettingsRequest) (map[string]any
|
||||
return updates, nil
|
||||
}
|
||||
|
||||
func validateProjectSettingsCombination(project model.Project, updates map[string]any) error {
|
||||
ticketDefault := project.CallBatchSize
|
||||
maxTicketCount := project.MaxCallTicketCount
|
||||
peopleDefault := project.DefaultCallPeopleCount
|
||||
maxPeopleCount := project.MaxCallPeopleCount
|
||||
minPartySize := project.MinPartySize
|
||||
maxPartySize := project.MaxPartySize
|
||||
if value, ok := updates["call_batch_size"].(int); ok {
|
||||
ticketDefault = value
|
||||
}
|
||||
if value, ok := updates["max_call_ticket_count"].(int); ok {
|
||||
maxTicketCount = value
|
||||
}
|
||||
if value, ok := updates["default_call_people_count"].(int); ok {
|
||||
peopleDefault = value
|
||||
}
|
||||
if value, ok := updates["max_call_people_count"].(int); ok {
|
||||
maxPeopleCount = value
|
||||
}
|
||||
if value, ok := updates["min_party_size"].(int); ok {
|
||||
minPartySize = value
|
||||
}
|
||||
if value, ok := updates["max_party_size"].(int); ok {
|
||||
maxPartySize = value
|
||||
}
|
||||
if ticketDefault > maxTicketCount {
|
||||
return invalidSetting("default_call_ticket_count")
|
||||
}
|
||||
if peopleDefault > maxPeopleCount {
|
||||
return invalidSetting("default_call_people_count")
|
||||
}
|
||||
if minPartySize > maxPartySize {
|
||||
return invalidSetting("min_party_size")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func invalidSetting(field string) error {
|
||||
return &apiError{Status: http.StatusUnprocessableEntity, Code: "INVALID_SETTING", Message: "项目设置值不正确", Details: map[string]string{"field": field}}
|
||||
}
|
||||
|
||||
@@ -94,3 +94,74 @@ func TestValidateProjectSettingsETAInterval(t *testing.T) {
|
||||
t.Fatal("expected interval validation")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateProjectSettingsExperiencedPeopleStart(t *testing.T) {
|
||||
start := 120
|
||||
updates, err := validateProjectSettings(updateProjectSettingsRequest{ExperiencedPeopleStart: &start})
|
||||
if err != nil || updates["experienced_people_start"] != 120 {
|
||||
t.Fatalf("unexpected experienced people start result: %#v, %v", updates, err)
|
||||
}
|
||||
negative := -1
|
||||
if _, err := validateProjectSettings(updateProjectSettingsRequest{ExperiencedPeopleStart: &negative}); err == nil {
|
||||
t.Fatal("expected negative experienced people start to be rejected")
|
||||
}
|
||||
tooLarge := 1000000001
|
||||
if _, err := validateProjectSettings(updateProjectSettingsRequest{ExperiencedPeopleStart: &tooLarge}); err == nil {
|
||||
t.Fatal("expected oversized experienced people start to be rejected")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateProjectSettingsPeopleAndCallModes(t *testing.T) {
|
||||
mode := model.CallModeBoth
|
||||
minParty, maxParty := 1, 8
|
||||
ticketDefault, ticketLimit := 5, 20
|
||||
peopleDefault, peopleLimit := 12, 40
|
||||
updates, err := validateProjectSettings(updateProjectSettingsRequest{
|
||||
CallMode: &mode, MinPartySize: &minParty, MaxPartySize: &maxParty,
|
||||
DefaultCallTicketCount: &ticketDefault, MaxCallTicketCount: &ticketLimit,
|
||||
DefaultCallPeopleCount: &peopleDefault, MaxCallPeopleCount: &peopleLimit,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
project := model.Project{CallBatchSize: 1, MaxCallTicketCount: 100, DefaultCallPeopleCount: 1, MaxCallPeopleCount: 100, MinPartySize: 1, MaxPartySize: 10}
|
||||
if err := validateProjectSettingsCombination(project, updates); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if updates["call_mode"] != model.CallModeBoth || updates["max_party_size"] != 8 || updates["call_batch_size"] != 5 {
|
||||
t.Fatalf("unexpected updates: %#v", updates)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateProjectSettingsAllowsTicketDefaultAboveLegacyLimit(t *testing.T) {
|
||||
value := 250
|
||||
updates, err := validateProjectSettings(updateProjectSettingsRequest{DefaultCallTicketCount: &value})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if updates["call_batch_size"] != 250 {
|
||||
t.Fatalf("updates = %#v", updates)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateProjectSettingsRejectsInvalidCombinedRanges(t *testing.T) {
|
||||
project := model.Project{CallBatchSize: 5, MaxCallTicketCount: 10, DefaultCallPeopleCount: 5, MaxCallPeopleCount: 10, MinPartySize: 1, MaxPartySize: 6}
|
||||
if err := validateProjectSettingsCombination(project, map[string]any{"max_call_ticket_count": 4}); err == nil {
|
||||
t.Fatal("expected ticket default above limit to fail")
|
||||
}
|
||||
if err := validateProjectSettingsCombination(project, map[string]any{"min_party_size": 7}); err == nil {
|
||||
t.Fatal("expected invalid party range to fail")
|
||||
}
|
||||
}
|
||||
|
||||
func TestProjectAllowsConfiguredCallModes(t *testing.T) {
|
||||
if !projectAllowsCallMode(model.CallModeBoth, model.CallModeTicket) || !projectAllowsCallMode(model.CallModeBoth, model.CallModePeople) {
|
||||
t.Fatal("BOTH must allow ticket and people calls")
|
||||
}
|
||||
if !projectAllowsCallMode(model.CallModeTicket, model.CallModeTicket) || projectAllowsCallMode(model.CallModeTicket, model.CallModePeople) {
|
||||
t.Fatal("TICKET must allow only ticket calls")
|
||||
}
|
||||
if !projectAllowsCallMode(model.CallModePeople, model.CallModePeople) || projectAllowsCallMode(model.CallModePeople, model.CallModeTicket) {
|
||||
t.Fatal("PEOPLE must allow only people calls")
|
||||
}
|
||||
}
|
||||
|
||||
34
server/internal/httpapi/experienced_people.go
Normal file
34
server/internal/httpapi/experienced_people.go
Normal file
@@ -0,0 +1,34 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"calllinesystem/server/internal/domain"
|
||||
"calllinesystem/server/internal/model"
|
||||
)
|
||||
|
||||
// displayedExperiencedPeople returns the current project's public daily
|
||||
// metric. A queue session is created lazily on the first ticket, so a nil
|
||||
// session intentionally still returns the configured starting display value.
|
||||
func (s *Server) displayedExperiencedPeople(ctx context.Context, project model.Project, session *model.QueueSession) (int64, error) {
|
||||
var actual int64
|
||||
if session != nil {
|
||||
location, err := time.LoadLocation(project.Timezone)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("invalid project timezone: %w", err)
|
||||
}
|
||||
businessDate := s.now().In(location).Format("2006-01-02")
|
||||
if session.BusinessDate.Format("2006-01-02") != businessDate {
|
||||
return domain.DisplayExperiencedPeople(project.ExperiencedPeopleStart, 0), nil
|
||||
}
|
||||
if err := s.db.WithContext(ctx).Model(&model.QueueTicket{}).
|
||||
Select("COALESCE(sum(party_size), 0)").
|
||||
Where("project_id = ? AND queue_session_id = ?", project.ID, session.ID).
|
||||
Scan(&actual).Error; err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
return domain.DisplayExperiencedPeople(project.ExperiencedPeopleStart, actual), nil
|
||||
}
|
||||
@@ -35,6 +35,45 @@ func (s *Server) publicStatus(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, view)
|
||||
}
|
||||
|
||||
func (s *Server) publicProjects(w http.ResponseWriter, r *http.Request) {
|
||||
var projects []model.Project
|
||||
if err := s.db.WithContext(r.Context()).
|
||||
Where("status = ?", model.ProjectRunning).
|
||||
Order("name ASC").Find(&projects).Error; err != nil {
|
||||
writeError(w, err)
|
||||
return
|
||||
}
|
||||
views := make([]map[string]any, 0, len(projects))
|
||||
for _, project := range projects {
|
||||
views = append(views, map[string]any{
|
||||
"id": project.ID, "name": project.Name, "status": project.Status,
|
||||
"visitor_notice": project.VisitorNotice,
|
||||
"min_party_size": project.MinPartySize, "max_party_size": project.MaxPartySize,
|
||||
})
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"projects": views})
|
||||
}
|
||||
|
||||
func (s *Server) publicCreateTicket(w http.ResponseWriter, r *http.Request) {
|
||||
projectID := r.PathValue("id")
|
||||
if err := validateUUID(projectID); err != nil {
|
||||
writeError(w, err)
|
||||
return
|
||||
}
|
||||
if s.publicTicketLimiter != nil {
|
||||
if allowed, retry := s.publicTicketLimiter.allow("ip:" + publicQueryClientKey(r)); !allowed {
|
||||
writePublicTicketRateLimit(w, retry)
|
||||
return
|
||||
}
|
||||
}
|
||||
var actor model.User
|
||||
if err := s.db.WithContext(r.Context()).Where("username = ?", model.PublicVisitorUsername).First(&actor).Error; err != nil {
|
||||
writeError(w, err)
|
||||
return
|
||||
}
|
||||
s.createTicketForActor(w, r, actor.ID, true)
|
||||
}
|
||||
|
||||
type publicPhoneQueryRequest struct {
|
||||
Phone string `json:"phone"`
|
||||
}
|
||||
@@ -114,6 +153,15 @@ func writePublicQueryRateLimit(w http.ResponseWriter, retry time.Duration) {
|
||||
writeError(w, &apiError{Status: http.StatusTooManyRequests, Code: "PUBLIC_QUERY_RATE_LIMITED", Message: "查询次数过多,请稍后再试"})
|
||||
}
|
||||
|
||||
func writePublicTicketRateLimit(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_TICKET_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
|
||||
@@ -123,19 +171,26 @@ func (s *Server) publicStatusView(ctx context.Context, ticket model.QueueTicket)
|
||||
if err := s.db.WithContext(ctx).First(&session, "id = ? AND project_id = ?", ticket.QueueSessionID, ticket.ProjectID).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
experiencedPeople, err := s.displayedExperiencedPeople(ctx, project, &session)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
phoneSuffix, err := s.ticketPhoneLast4(ticket)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ticketsAhead := 0
|
||||
peopleAhead := 0
|
||||
if ticket.Status == model.TicketWaiting {
|
||||
var count int64
|
||||
var totals ticketPeopleTotals
|
||||
if err := s.db.WithContext(ctx).Model(&model.QueueTicket{}).
|
||||
Select("count(*) AS ticket_count, COALESCE(sum(party_size), 0) AS people_count").
|
||||
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 {
|
||||
ticket.ProjectID, ticket.QueueSessionID, model.TicketWaiting, ticket.TicketNumber).Scan(&totals).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
peopleAhead = int(count)
|
||||
ticketsAhead = int(totals.TicketCount)
|
||||
peopleAhead = int(totals.PeopleCount)
|
||||
}
|
||||
var latestCalledTicket struct {
|
||||
DisplayNumber string `gorm:"column:display_number"`
|
||||
@@ -150,7 +205,7 @@ func (s *Server) publicStatusView(ctx context.Context, ticket model.QueueTicket)
|
||||
latestCalledNumber = latestCalledTicket.DisplayNumber
|
||||
}
|
||||
eta, err := domain.CalculateETA(domain.ETAInput{
|
||||
PeopleAhead: peopleAhead, IntervalPerNumber: time.Duration(project.ETAIntervalSeconds) * time.Second,
|
||||
PeopleAhead: peopleAhead, IntervalPerPerson: time.Duration(project.ETAIntervalSeconds) * time.Second,
|
||||
Running: project.Status == model.ProjectRunning && session.Status == "RUNNING" && ticket.Status == model.TicketWaiting,
|
||||
})
|
||||
if err != nil {
|
||||
@@ -161,25 +216,26 @@ func (s *Server) publicStatusView(ctx context.Context, ticket model.QueueTicket)
|
||||
}
|
||||
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,
|
||||
"last_updated_at": s.now(), "called_at": ticket.CalledAt,
|
||||
"project_name": project.Name, "status": ticket.Status, "party_size": ticket.PartySize, "phone_last4": phoneSuffix, "estimated_wait": eta,
|
||||
"visitor_notice": project.VisitorNotice,
|
||||
"experienced_people": experiencedPeople,
|
||||
"last_updated_at": s.now(), "called_at": ticket.CalledAt,
|
||||
"ticket": map[string]any{
|
||||
"display_number": ticket.DisplayNumber, "status": ticket.Status, "joined_at": ticket.JoinedAt,
|
||||
"display_number": ticket.DisplayNumber, "status": ticket.Status, "party_size": ticket.PartySize, "joined_at": ticket.JoinedAt,
|
||||
"called_at": ticket.CalledAt, "arrived_at": ticket.ArrivedAt, "completed_at": ticket.CompletedAt, "missed_at": ticket.MissedAt,
|
||||
},
|
||||
"project": map[string]any{"id": project.ID, "name": project.Name, "status": project.Status},
|
||||
"people_ahead": peopleAhead, "queue_position": queuePosition(ticket.Status, peopleAhead),
|
||||
"project": map[string]any{"id": project.ID, "name": project.Name, "status": project.Status},
|
||||
"tickets_ahead": ticketsAhead, "people_ahead": peopleAhead, "queue_position": queuePosition(ticket.Status, ticketsAhead),
|
||||
"latest_called_number": latestCalledNumber,
|
||||
"eta": eta, "revision": session.Revision, "server_time": s.now(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func queuePosition(status string, peopleAhead int) any {
|
||||
func queuePosition(status string, ticketsAhead int) any {
|
||||
if status != model.TicketWaiting {
|
||||
return nil
|
||||
}
|
||||
return peopleAhead + 1
|
||||
return ticketsAhead + 1
|
||||
}
|
||||
|
||||
// displayTicketDTO is the complete public ticket shape for a display. Keeping
|
||||
@@ -189,14 +245,19 @@ type displayTicketDTO struct {
|
||||
TicketNumber string `json:"ticket_number"`
|
||||
DisplayNumber string `json:"display_number"`
|
||||
Status string `json:"status"`
|
||||
PartySize int `json:"party_size"`
|
||||
}
|
||||
|
||||
type displayBatchDTO struct {
|
||||
BatchNumber int `json:"batch_number"`
|
||||
Sequence int `json:"sequence"`
|
||||
Status string `json:"status"`
|
||||
CalledAt time.Time `json:"called_at"`
|
||||
Tickets []displayTicketDTO `json:"tickets"`
|
||||
BatchNumber int `json:"batch_number"`
|
||||
Sequence int `json:"sequence"`
|
||||
Status string `json:"status"`
|
||||
CallMode string `json:"call_mode"`
|
||||
RequestedCount int `json:"requested_count"`
|
||||
TicketCount int `json:"ticket_count"`
|
||||
PeopleCount int `json:"people_count"`
|
||||
CalledAt time.Time `json:"called_at"`
|
||||
Tickets []displayTicketDTO `json:"tickets"`
|
||||
}
|
||||
|
||||
type displayProjectDTO struct {
|
||||
@@ -206,16 +267,19 @@ type displayProjectDTO struct {
|
||||
}
|
||||
|
||||
type displaySnapshotDTO struct {
|
||||
ProjectName string `json:"project_name"`
|
||||
Status string `json:"status"`
|
||||
Project displayProjectDTO `json:"project"`
|
||||
Revision int64 `json:"revision"`
|
||||
WaitingCount int64 `json:"waiting_count"`
|
||||
CurrentBatch *displayBatchDTO `json:"current_batch"`
|
||||
RecentBatches []displayBatchDTO `json:"recent_batches"`
|
||||
EstimatedWait domain.ETAResult `json:"estimated_wait"`
|
||||
ServerTime time.Time `json:"server_time"`
|
||||
LastUpdatedAt time.Time `json:"last_updated_at"`
|
||||
ProjectName string `json:"project_name"`
|
||||
Status string `json:"status"`
|
||||
Project displayProjectDTO `json:"project"`
|
||||
Revision int64 `json:"revision"`
|
||||
WaitingCount int64 `json:"waiting_count"`
|
||||
WaitingTicketCount int64 `json:"waiting_ticket_count"`
|
||||
WaitingPeopleCount int64 `json:"waiting_people_count"`
|
||||
ExperiencedPeople int64 `json:"experienced_people"`
|
||||
CurrentBatch *displayBatchDTO `json:"current_batch"`
|
||||
RecentBatches []displayBatchDTO `json:"recent_batches"`
|
||||
EstimatedWait domain.ETAResult `json:"estimated_wait"`
|
||||
ServerTime time.Time `json:"server_time"`
|
||||
LastUpdatedAt time.Time `json:"last_updated_at"`
|
||||
}
|
||||
|
||||
func (s *Server) displaySnapshot(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -234,10 +298,15 @@ func (s *Server) displaySnapshot(w http.ResponseWriter, r *http.Request) {
|
||||
err = s.db.WithContext(r.Context()).Where("project_id = ? AND status IN ?", project.ID, []string{"RUNNING", "PAUSED"}).
|
||||
Order("business_date DESC").First(&session).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
experiencedPeople, metricErr := s.displayedExperiencedPeople(r.Context(), project, nil)
|
||||
if metricErr != nil {
|
||||
writeError(w, metricErr)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, displaySnapshotDTO{
|
||||
ProjectName: project.Name, Status: project.Status,
|
||||
Project: displayProjectDTO{ID: project.ID, Name: project.Name, Status: project.Status},
|
||||
RecentBatches: []displayBatchDTO{}, EstimatedWait: domain.ETAResult{Available: false, Reason: "queue_not_running"},
|
||||
Project: displayProjectDTO{ID: project.ID, Name: project.Name, Status: project.Status},
|
||||
ExperiencedPeople: experiencedPeople, RecentBatches: []displayBatchDTO{}, EstimatedWait: domain.ETAResult{Available: false, Reason: "queue_not_running"},
|
||||
ServerTime: s.now(), LastUpdatedAt: project.UpdatedAt,
|
||||
})
|
||||
return
|
||||
@@ -246,10 +315,8 @@ func (s *Server) displaySnapshot(w http.ResponseWriter, r *http.Request) {
|
||||
writeError(w, err)
|
||||
return
|
||||
}
|
||||
var waitingCount int64
|
||||
if err := s.db.WithContext(r.Context()).Model(&model.QueueTicket{}).
|
||||
Where("project_id = ? AND queue_session_id = ? AND status = ?", project.ID, session.ID, model.TicketWaiting).
|
||||
Count(&waitingCount).Error; err != nil {
|
||||
waiting, err := queueTotals(s.db.WithContext(r.Context()), project.ID, session.ID, model.TicketWaiting)
|
||||
if err != nil {
|
||||
writeError(w, err)
|
||||
return
|
||||
}
|
||||
@@ -263,15 +330,31 @@ func (s *Server) displaySnapshot(w http.ResponseWriter, r *http.Request) {
|
||||
writeError(w, err)
|
||||
return
|
||||
}
|
||||
peopleAhead := max(0, int(waitingCount)-1)
|
||||
var lastWaiting model.QueueTicket
|
||||
lastWaitingErr := s.db.WithContext(r.Context()).Select("id", "party_size").
|
||||
Where("project_id = ? AND queue_session_id = ? AND status = ?", project.ID, session.ID, model.TicketWaiting).
|
||||
Order("ticket_number DESC").First(&lastWaiting).Error
|
||||
if lastWaitingErr != nil && !errors.Is(lastWaitingErr, gorm.ErrRecordNotFound) {
|
||||
writeError(w, lastWaitingErr)
|
||||
return
|
||||
}
|
||||
peopleAhead := int(waiting.PeopleCount)
|
||||
if lastWaitingErr == nil {
|
||||
peopleAhead = max(0, peopleAhead-lastWaiting.PartySize)
|
||||
}
|
||||
estimatedWait, err := domain.CalculateETA(domain.ETAInput{
|
||||
PeopleAhead: peopleAhead, IntervalPerNumber: time.Duration(project.ETAIntervalSeconds) * time.Second,
|
||||
Running: project.Status == model.ProjectRunning && session.Status == "RUNNING" && waitingCount > 0,
|
||||
PeopleAhead: peopleAhead, IntervalPerPerson: time.Duration(project.ETAIntervalSeconds) * time.Second,
|
||||
Running: project.Status == model.ProjectRunning && session.Status == "RUNNING" && waiting.TicketCount > 0,
|
||||
})
|
||||
if err != nil {
|
||||
writeError(w, err)
|
||||
return
|
||||
}
|
||||
experiencedPeople, err := s.displayedExperiencedPeople(r.Context(), project, &session)
|
||||
if err != nil {
|
||||
writeError(w, err)
|
||||
return
|
||||
}
|
||||
lastUpdated := project.UpdatedAt
|
||||
if session.UpdatedAt.After(lastUpdated) {
|
||||
lastUpdated = session.UpdatedAt
|
||||
@@ -279,7 +362,9 @@ func (s *Server) displaySnapshot(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, displaySnapshotDTO{
|
||||
ProjectName: project.Name, Status: project.Status,
|
||||
Project: displayProjectDTO{ID: project.ID, Name: project.Name, Status: project.Status},
|
||||
Revision: session.Revision, WaitingCount: waitingCount, CurrentBatch: batch, RecentBatches: recentBatches,
|
||||
Revision: session.Revision, WaitingCount: waiting.TicketCount,
|
||||
WaitingTicketCount: waiting.TicketCount, WaitingPeopleCount: waiting.PeopleCount,
|
||||
ExperiencedPeople: experiencedPeople, CurrentBatch: batch, RecentBatches: recentBatches,
|
||||
EstimatedWait: estimatedWait, ServerTime: s.now(), LastUpdatedAt: lastUpdated,
|
||||
})
|
||||
}
|
||||
@@ -321,7 +406,7 @@ func (s *Server) recentDisplayBatches(r *http.Request, projectID, sessionID stri
|
||||
|
||||
func displayBatchTickets(db *gorm.DB, batchID, projectID string, calledOnly bool) ([]displayTicketDTO, error) {
|
||||
query := db.Table("queue_tickets").
|
||||
Select("queue_tickets.display_number, queue_tickets.status").
|
||||
Select("queue_tickets.display_number, queue_tickets.status, queue_tickets.party_size").
|
||||
Joins("JOIN call_batch_tickets cbt ON cbt.ticket_id = queue_tickets.id AND cbt.project_id = queue_tickets.project_id").
|
||||
Where("cbt.call_batch_id = ? AND cbt.project_id = ?", batchID, projectID).
|
||||
Order("cbt.position ASC")
|
||||
@@ -331,6 +416,7 @@ func displayBatchTickets(db *gorm.DB, batchID, projectID string, calledOnly bool
|
||||
type row struct {
|
||||
DisplayNumber string
|
||||
Status string
|
||||
PartySize int
|
||||
}
|
||||
var rows []row
|
||||
if err := query.Scan(&rows).Error; err != nil {
|
||||
@@ -339,7 +425,7 @@ func displayBatchTickets(db *gorm.DB, batchID, projectID string, calledOnly bool
|
||||
tickets := make([]displayTicketDTO, 0, len(rows))
|
||||
for _, item := range rows {
|
||||
tickets = append(tickets, displayTicketDTO{
|
||||
TicketNumber: item.DisplayNumber, DisplayNumber: item.DisplayNumber, Status: item.Status,
|
||||
TicketNumber: item.DisplayNumber, DisplayNumber: item.DisplayNumber, Status: item.Status, PartySize: item.PartySize,
|
||||
})
|
||||
}
|
||||
return tickets, nil
|
||||
@@ -348,6 +434,8 @@ func displayBatchTickets(db *gorm.DB, batchID, projectID string, calledOnly bool
|
||||
func newDisplayBatchDTO(batch model.CallBatch, tickets []displayTicketDTO) displayBatchDTO {
|
||||
return displayBatchDTO{
|
||||
BatchNumber: batch.BatchSequence, Sequence: batch.BatchSequence, Status: batch.Status,
|
||||
CallMode: batch.CallMode, RequestedCount: batch.RequestedCount,
|
||||
TicketCount: batch.TicketCount, PeopleCount: batch.PeopleCount,
|
||||
CalledAt: batch.CalledAt, Tickets: tickets,
|
||||
}
|
||||
}
|
||||
|
||||
29
server/internal/httpapi/queue_counts.go
Normal file
29
server/internal/httpapi/queue_counts.go
Normal file
@@ -0,0 +1,29 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"calllinesystem/server/internal/model"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type ticketPeopleTotals struct {
|
||||
TicketCount int64 `gorm:"column:ticket_count"`
|
||||
PeopleCount int64 `gorm:"column:people_count"`
|
||||
}
|
||||
|
||||
func queueTotals(db *gorm.DB, projectID, sessionID, status string) (ticketPeopleTotals, error) {
|
||||
var totals ticketPeopleTotals
|
||||
err := db.Model(&model.QueueTicket{}).
|
||||
Select("count(*) AS ticket_count, COALESCE(sum(party_size), 0) AS people_count").
|
||||
Where("project_id = ? AND queue_session_id = ? AND status = ?", projectID, sessionID, status).
|
||||
Scan(&totals).Error
|
||||
return totals, err
|
||||
}
|
||||
|
||||
func ticketsPartySize(tickets []model.QueueTicket) int {
|
||||
total := 0
|
||||
for _, ticket := range tickets {
|
||||
total += ticket.PartySize
|
||||
}
|
||||
return total
|
||||
}
|
||||
@@ -128,7 +128,7 @@ func (s *Server) reissueTicket(w http.ResponseWriter, r *http.Request) {
|
||||
now := s.now()
|
||||
newTicket := model.QueueTicket{
|
||||
ID: uuid.NewString(), ProjectID: initial.ProjectID, QueueSessionID: session.ID,
|
||||
ReissuedFromTicketID: &original.ID, TicketNumber: session.NextTicketNumber, DisplayNumber: displayNumber,
|
||||
ReissuedFromTicketID: &original.ID, TicketNumber: session.NextTicketNumber, DisplayNumber: displayNumber, PartySize: original.PartySize,
|
||||
PublicTokenHash: security.HashToken(publicToken),
|
||||
PhoneCiphertext: append([]byte(nil), original.PhoneCiphertext...), PhoneNonce: append([]byte(nil), original.PhoneNonce...),
|
||||
PhoneHMAC: cloneStringPointer(original.PhoneHMAC), LastNameCiphertext: append([]byte(nil), original.LastNameCiphertext...),
|
||||
@@ -147,7 +147,7 @@ func (s *Server) reissueTicket(w http.ResponseWriter, r *http.Request) {
|
||||
if err := s.addAudit(tx, r, &initial.ProjectID, &user.ID, "TICKET_REISSUED", "QUEUE_TICKET", &newTicket.ID,
|
||||
map[string]any{
|
||||
"reissued_from_ticket_id": original.ID, "old_display_number": original.DisplayNumber,
|
||||
"new_display_number": newTicket.DisplayNumber, "revision": revision,
|
||||
"new_display_number": newTicket.DisplayNumber, "party_size": newTicket.PartySize, "revision": revision,
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -27,15 +27,16 @@ const (
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
db *gorm.DB
|
||||
config config.Config
|
||||
cipher *security.Cipher
|
||||
logger *slog.Logger
|
||||
hub eventPublisher
|
||||
loginLimiter *loginLimiter
|
||||
publicQueryLimiter *queryLimiter
|
||||
dummyPassword string
|
||||
now func() time.Time
|
||||
db *gorm.DB
|
||||
config config.Config
|
||||
cipher *security.Cipher
|
||||
logger *slog.Logger
|
||||
hub eventPublisher
|
||||
loginLimiter *loginLimiter
|
||||
publicQueryLimiter *queryLimiter
|
||||
publicTicketLimiter *queryLimiter
|
||||
dummyPassword string
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
func New(db *gorm.DB, cfg config.Config, logger *slog.Logger) (*Server, error) {
|
||||
@@ -56,15 +57,16 @@ 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),
|
||||
publicQueryLimiter: newQueryLimiter(now, 120, time.Minute),
|
||||
dummyPassword: dummy,
|
||||
now: now,
|
||||
db: db,
|
||||
config: cfg,
|
||||
cipher: fieldCipher,
|
||||
logger: logger,
|
||||
hub: publisher,
|
||||
loginLimiter: newLoginLimiter(now),
|
||||
publicQueryLimiter: newQueryLimiter(now, 120, time.Minute),
|
||||
publicTicketLimiter: newQueryLimiter(now, 20, time.Minute),
|
||||
dummyPassword: dummy,
|
||||
now: now,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -83,6 +85,8 @@ 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("GET /api/public/projects", s.publicProjects)
|
||||
mux.HandleFunc("POST /api/public/projects/{id}/tickets", s.publicCreateTicket)
|
||||
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)))
|
||||
|
||||
@@ -39,11 +39,17 @@ func projectViews(projects []model.Project) []map[string]any {
|
||||
func projectView(project model.Project) map[string]any {
|
||||
return map[string]any{
|
||||
"id": project.ID, "code": project.Code, "name": project.Name, "status": project.Status,
|
||||
"timezone": project.Timezone, "ticket_prefix": project.TicketPrefix, "call_batch_size": project.CallBatchSize, "batch_size": project.CallBatchSize,
|
||||
"grace_period_minutes": project.GracePeriodMinutes,
|
||||
"visitor_notice": project.VisitorNotice,
|
||||
"timezone": project.Timezone, "ticket_prefix": project.TicketPrefix,
|
||||
"call_mode": project.CallMode,
|
||||
"default_call_ticket_count": project.CallBatchSize, "call_batch_size": project.CallBatchSize, "batch_size": project.CallBatchSize,
|
||||
"max_call_ticket_count": project.MaxCallTicketCount,
|
||||
"default_call_people_count": project.DefaultCallPeopleCount, "max_call_people_count": project.MaxCallPeopleCount,
|
||||
"min_party_size": project.MinPartySize, "max_party_size": project.MaxPartySize,
|
||||
"grace_period_minutes": project.GracePeriodMinutes,
|
||||
"experienced_people_start": project.ExperiencedPeopleStart,
|
||||
"visitor_notice": project.VisitorNotice,
|
||||
"eta": map[string]any{
|
||||
"interval_per_number_seconds": project.ETAIntervalSeconds,
|
||||
"interval_per_person_seconds": project.ETAIntervalSeconds,
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -69,8 +75,12 @@ func (s *Server) queueSnapshot(w http.ResponseWriter, r *http.Request) {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"project": projectView(project), "session": nil, "revision": 0,
|
||||
"counts": map[string]int64{}, "waiting": []any{}, "current_batch": nil, "recent_batches": []any{},
|
||||
"metrics": map[string]any{"waiting_count": 0, "called_count": 0, "estimated_wait": nil, "last_ticket_number": nil, "next_ticket_number": nil},
|
||||
"counts": map[string]int64{}, "people_counts": map[string]int64{}, "waiting": []any{}, "current_batch": nil, "recent_batches": []any{},
|
||||
"metrics": map[string]any{
|
||||
"waiting_count": 0, "waiting_ticket_count": 0, "waiting_people_count": 0,
|
||||
"called_count": 0, "called_ticket_count": 0, "called_people_count": 0,
|
||||
"estimated_wait": nil, "last_ticket_number": nil, "next_ticket_number": nil,
|
||||
},
|
||||
"server_time": s.now(), "last_success_at": s.now(),
|
||||
})
|
||||
return
|
||||
@@ -81,19 +91,22 @@ func (s *Server) queueSnapshot(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
type statusCount struct {
|
||||
Status string
|
||||
Count int64
|
||||
Status string
|
||||
TicketCount int64 `gorm:"column:ticket_count"`
|
||||
PeopleCount int64 `gorm:"column:people_count"`
|
||||
}
|
||||
var grouped []statusCount
|
||||
if err := s.db.WithContext(r.Context()).Model(&model.QueueTicket{}).
|
||||
Select("status, count(*) AS count").Where("project_id = ? AND queue_session_id = ?", projectID, session.ID).
|
||||
Select("status, count(*) AS ticket_count, COALESCE(sum(party_size), 0) AS people_count").Where("project_id = ? AND queue_session_id = ?", projectID, session.ID).
|
||||
Group("status").Scan(&grouped).Error; err != nil {
|
||||
writeError(w, err)
|
||||
return
|
||||
}
|
||||
counts := make(map[string]int64, len(grouped))
|
||||
ticketCounts := make(map[string]int64, len(grouped))
|
||||
peopleCounts := make(map[string]int64, len(grouped))
|
||||
for _, row := range grouped {
|
||||
counts[row.Status] = row.Count
|
||||
ticketCounts[row.Status] = row.TicketCount
|
||||
peopleCounts[row.Status] = row.PeopleCount
|
||||
}
|
||||
var waiting []model.QueueTicket
|
||||
if err := s.db.WithContext(r.Context()).Where("project_id = ? AND queue_session_id = ? AND status = ?", projectID, session.ID, model.TicketWaiting).
|
||||
@@ -130,10 +143,24 @@ func (s *Server) queueSnapshot(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
lastTicketNumber = formatted
|
||||
}
|
||||
var lastWaiting model.QueueTicket
|
||||
lastWaitingErr := s.db.WithContext(r.Context()).
|
||||
Select("id", "party_size").
|
||||
Where("project_id = ? AND queue_session_id = ? AND status = ?", projectID, session.ID, model.TicketWaiting).
|
||||
Order("ticket_number DESC").First(&lastWaiting).Error
|
||||
if lastWaitingErr != nil && !errors.Is(lastWaitingErr, gorm.ErrRecordNotFound) {
|
||||
writeError(w, lastWaitingErr)
|
||||
return
|
||||
}
|
||||
waitingPeople := peopleCounts[model.TicketWaiting]
|
||||
peopleAheadOfLast := int(waitingPeople)
|
||||
if lastWaitingErr == nil {
|
||||
peopleAheadOfLast = max(0, peopleAheadOfLast-lastWaiting.PartySize)
|
||||
}
|
||||
estimatedWait, err := domain.CalculateETA(domain.ETAInput{
|
||||
PeopleAhead: max(0, int(counts[model.TicketWaiting])-1),
|
||||
IntervalPerNumber: time.Duration(project.ETAIntervalSeconds) * time.Second,
|
||||
Running: project.Status == model.ProjectRunning && session.Status == "RUNNING" && counts[model.TicketWaiting] > 0,
|
||||
PeopleAhead: peopleAheadOfLast,
|
||||
IntervalPerPerson: time.Duration(project.ETAIntervalSeconds) * time.Second,
|
||||
Running: project.Status == model.ProjectRunning && session.Status == "RUNNING" && ticketCounts[model.TicketWaiting] > 0,
|
||||
})
|
||||
if err != nil {
|
||||
writeError(w, err)
|
||||
@@ -142,13 +169,17 @@ func (s *Server) queueSnapshot(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"project": projectView(project),
|
||||
"session": map[string]any{"id": session.ID, "business_date": session.BusinessDate.Format("2006-01-02"), "status": session.Status},
|
||||
"revision": session.Revision, "counts": counts, "waiting": waitingViews, "current_batch": batchView,
|
||||
"revision": session.Revision, "counts": ticketCounts, "people_counts": peopleCounts, "waiting": waitingViews, "current_batch": batchView,
|
||||
"metrics": map[string]any{
|
||||
"waiting_count": counts[model.TicketWaiting],
|
||||
"called_count": counts[model.TicketCalled] + counts[model.TicketArrived],
|
||||
"estimated_wait": estimatedWait,
|
||||
"last_ticket_number": lastTicketNumber,
|
||||
"next_ticket_number": nextTicketNumber,
|
||||
"waiting_count": ticketCounts[model.TicketWaiting],
|
||||
"waiting_ticket_count": ticketCounts[model.TicketWaiting],
|
||||
"waiting_people_count": peopleCounts[model.TicketWaiting],
|
||||
"called_count": ticketCounts[model.TicketCalled] + ticketCounts[model.TicketArrived],
|
||||
"called_ticket_count": ticketCounts[model.TicketCalled] + ticketCounts[model.TicketArrived],
|
||||
"called_people_count": peopleCounts[model.TicketCalled] + peopleCounts[model.TicketArrived],
|
||||
"estimated_wait": estimatedWait,
|
||||
"last_ticket_number": lastTicketNumber,
|
||||
"next_ticket_number": nextTicketNumber,
|
||||
},
|
||||
"server_time": s.now(), "last_success_at": s.now(),
|
||||
})
|
||||
@@ -175,6 +206,7 @@ type createTicketRequest struct {
|
||||
Phone string `json:"phone"`
|
||||
LastName string `json:"last_name"`
|
||||
Honorific string `json:"honorific"`
|
||||
PartySize *int `json:"party_size"`
|
||||
AllowDuplicate bool `json:"allow_duplicate"`
|
||||
}
|
||||
|
||||
@@ -188,6 +220,12 @@ func (s *Server) createTicket(w http.ResponseWriter, r *http.Request) {
|
||||
writeError(w, err)
|
||||
return
|
||||
}
|
||||
user := currentPrincipal(r.Context()).User
|
||||
s.createTicketForActor(w, r, user.ID, false)
|
||||
}
|
||||
|
||||
func (s *Server) createTicketForActor(w http.ResponseWriter, r *http.Request, actorID string, publicView bool) {
|
||||
projectID := r.PathValue("id")
|
||||
key, err := readIdempotencyKey(r)
|
||||
if err != nil {
|
||||
writeError(w, err)
|
||||
@@ -198,6 +236,10 @@ func (s *Server) createTicket(w http.ResponseWriter, r *http.Request) {
|
||||
writeError(w, err)
|
||||
return
|
||||
}
|
||||
if input.PartySize == nil || *input.PartySize < 1 {
|
||||
writeError(w, &apiError{Status: http.StatusUnprocessableEntity, Code: "INVALID_PARTY_SIZE", Message: "请选择本号人数"})
|
||||
return
|
||||
}
|
||||
phone, err := security.NormalizePhone(input.Phone)
|
||||
if err != nil {
|
||||
writeError(w, &apiError{Status: http.StatusUnprocessableEntity, Code: "INVALID_PHONE", Message: err.Error()})
|
||||
@@ -223,16 +265,30 @@ func (s *Server) createTicket(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
user := currentPrincipal(r.Context()).User
|
||||
scope := "CREATE_TICKET"
|
||||
auditAction := "TICKET_CREATED"
|
||||
duplicateMessage := "该手机号已有活动号码,请员工确认后继续"
|
||||
if publicView {
|
||||
scope = "PUBLIC_CREATE_TICKET"
|
||||
auditAction = "PUBLIC_TICKET_CREATED"
|
||||
duplicateMessage = "该手机号已有活动号码,请确认后继续"
|
||||
}
|
||||
var responseBody []byte
|
||||
responseCode := http.StatusCreated
|
||||
var revision int64
|
||||
err = s.db.WithContext(r.Context()).Transaction(func(tx *gorm.DB) error {
|
||||
_, session, err := s.lockRunningProjectAndSession(tx, projectID)
|
||||
project, session, err := s.lockRunningProjectAndSession(tx, projectID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if stored, code, found, err := loadIdempotent(tx, projectID, user.ID, "CREATE_TICKET", key, hash, s.now()); err != nil {
|
||||
if *input.PartySize < project.MinPartySize || *input.PartySize > project.MaxPartySize {
|
||||
return &apiError{
|
||||
Status: http.StatusUnprocessableEntity, Code: "INVALID_PARTY_SIZE",
|
||||
Message: fmt.Sprintf("本项目每个号码可绑定 %d 到 %d 人", project.MinPartySize, project.MaxPartySize),
|
||||
Details: map[string]any{"min_party_size": project.MinPartySize, "max_party_size": project.MaxPartySize},
|
||||
}
|
||||
}
|
||||
if stored, code, found, err := loadIdempotent(tx, projectID, actorID, scope, key, hash, s.now()); err != nil {
|
||||
return err
|
||||
} else if found {
|
||||
responseBody, responseCode = stored, code
|
||||
@@ -252,7 +308,11 @@ func (s *Server) createTicket(w http.ResponseWriter, r *http.Request) {
|
||||
for _, duplicate := range duplicates {
|
||||
existing = append(existing, map[string]any{"id": duplicate.ID, "display_number": duplicate.DisplayNumber, "status": duplicate.Status})
|
||||
}
|
||||
return &apiError{Status: http.StatusConflict, Code: "DUPLICATE_PHONE", Message: "该手机号已有活动号码,请员工确认后继续", Details: map[string]any{"tickets": existing}}
|
||||
var details any = map[string]any{"tickets": existing}
|
||||
if publicView {
|
||||
details = nil
|
||||
}
|
||||
return &apiError{Status: http.StatusConflict, Code: "DUPLICATE_PHONE", Message: duplicateMessage, Details: details}
|
||||
}
|
||||
|
||||
publicToken, err := security.GenerateToken()
|
||||
@@ -277,11 +337,11 @@ func (s *Server) createTicket(w http.ResponseWriter, r *http.Request) {
|
||||
now := s.now()
|
||||
ticket := model.QueueTicket{
|
||||
ID: uuid.NewString(), ProjectID: projectID, QueueSessionID: session.ID,
|
||||
TicketNumber: session.NextTicketNumber, DisplayNumber: displayNumber,
|
||||
TicketNumber: session.NextTicketNumber, DisplayNumber: displayNumber, PartySize: *input.PartySize,
|
||||
PublicTokenHash: security.HashToken(publicToken), PhoneCiphertext: phoneCiphertext, PhoneNonce: phoneNonce,
|
||||
PhoneHMAC: stringPointer(phoneDigest), LastNameCiphertext: lastNameCiphertext, LastNameNonce: lastNameNonce,
|
||||
Honorific: input.Honorific, Status: model.TicketWaiting, JoinedAt: now,
|
||||
PersonalDataPurgeAt: now.Add(30 * 24 * time.Hour), CreatedBy: user.ID, CreatedAt: now, UpdatedAt: now,
|
||||
PersonalDataPurgeAt: now.Add(30 * 24 * time.Hour), CreatedBy: actorID, CreatedAt: now, UpdatedAt: now,
|
||||
}
|
||||
if err := tx.Create(&ticket).Error; err != nil {
|
||||
return err
|
||||
@@ -291,25 +351,39 @@ func (s *Server) createTicket(w http.ResponseWriter, r *http.Request) {
|
||||
Updates(map[string]any{"next_ticket_number": session.NextTicketNumber + 1, "revision": revision, "updated_at": now}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.addAudit(tx, r, &projectID, &user.ID, "TICKET_CREATED", "QUEUE_TICKET", &ticket.ID,
|
||||
map[string]any{"display_number": displayNumber, "duplicate_count": len(duplicates), "duplicate_confirmed": input.AllowDuplicate}); err != nil {
|
||||
if err := s.addAudit(tx, r, &projectID, &actorID, auditAction, "QUEUE_TICKET", &ticket.ID,
|
||||
map[string]any{"display_number": displayNumber, "party_size": ticket.PartySize, "duplicate_count": len(duplicates), "duplicate_confirmed": input.AllowDuplicate}); err != nil {
|
||||
return err
|
||||
}
|
||||
ticketResponse, err := s.staffTicketView(ticket)
|
||||
if err != nil {
|
||||
return err
|
||||
var ticketResponse map[string]any
|
||||
if publicView {
|
||||
phoneLast4, err := s.ticketPhoneLast4(ticket)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ticketResponse = map[string]any{
|
||||
"id": ticket.ID, "display_number": ticket.DisplayNumber, "ticket_number": ticket.DisplayNumber,
|
||||
"status": ticket.Status, "party_size": ticket.PartySize, "phone_last4": phoneLast4, "created_at": ticket.JoinedAt,
|
||||
}
|
||||
} else {
|
||||
ticketResponse, err = s.staffTicketView(ticket)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if !publicView {
|
||||
ticketResponse["public_token"] = publicToken
|
||||
ticketResponse["public_url"] = "/visitor/" + publicToken
|
||||
}
|
||||
ticketResponse["public_token"] = publicToken
|
||||
ticketResponse["public_url"] = "/visitor/" + publicToken
|
||||
response := map[string]any{
|
||||
"ticket": ticketResponse, "public_token": publicToken,
|
||||
"ticket": ticketResponse, "public_token": publicToken, "public_url": "/visitor/" + publicToken,
|
||||
"status_path": "/api/public/status/" + publicToken, "revision": revision,
|
||||
}
|
||||
responseBody, err = marshalResponse(response)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return saveIdempotent(tx, projectID, user.ID, "CREATE_TICKET", key, hash, responseCode, responseBody, &ticket.ID, now)
|
||||
return saveIdempotent(tx, projectID, actorID, scope, key, hash, responseCode, responseBody, &ticket.ID, now)
|
||||
})
|
||||
if err != nil {
|
||||
writeError(w, err)
|
||||
@@ -323,6 +397,7 @@ func (s *Server) createTicket(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
type callNextRequest struct {
|
||||
ExpectedRevision *int64 `json:"expected_revision"`
|
||||
Mode string `json:"mode"`
|
||||
Count *int `json:"count"`
|
||||
}
|
||||
|
||||
@@ -345,12 +420,20 @@ func (s *Server) callNext(w http.ResponseWriter, r *http.Request) {
|
||||
writeError(w, &apiError{Status: http.StatusUnprocessableEntity, Code: "EXPECTED_REVISION_REQUIRED", Message: "必须提供当前队列 revision"})
|
||||
return
|
||||
}
|
||||
mode := strings.ToUpper(strings.TrimSpace(input.Mode))
|
||||
if mode == "" {
|
||||
mode = model.CallModeTicket
|
||||
}
|
||||
if mode != model.CallModeTicket && mode != model.CallModePeople {
|
||||
writeError(w, &apiError{Status: http.StatusUnprocessableEntity, Code: "INVALID_CALL_MODE", Message: "叫号方式不正确"})
|
||||
return
|
||||
}
|
||||
count := 1
|
||||
if input.Count != nil {
|
||||
count = *input.Count
|
||||
}
|
||||
if count < 1 || count > 100 {
|
||||
writeError(w, &apiError{Status: http.StatusUnprocessableEntity, Code: "INVALID_CALL_COUNT", Message: "叫号数量必须在 1 到 100 之间"})
|
||||
if count < 1 || count > 10000 {
|
||||
writeError(w, &apiError{Status: http.StatusUnprocessableEntity, Code: "INVALID_CALL_COUNT", Message: "叫号数量必须是有效的正整数"})
|
||||
return
|
||||
}
|
||||
key, err := readIdempotencyKey(r)
|
||||
@@ -358,7 +441,7 @@ func (s *Server) callNext(w http.ResponseWriter, r *http.Request) {
|
||||
writeError(w, err)
|
||||
return
|
||||
}
|
||||
hash, _ := requestHash(map[string]any{"operation": "CALL_NEXT", "project_id": projectID, "expected_revision": *input.ExpectedRevision, "count": count})
|
||||
hash, _ := requestHash(map[string]any{"operation": "CALL_NEXT", "project_id": projectID, "expected_revision": *input.ExpectedRevision, "mode": mode, "count": count})
|
||||
user := currentPrincipal(r.Context()).User
|
||||
var responseBody []byte
|
||||
responseCode := http.StatusOK
|
||||
@@ -380,15 +463,42 @@ func (s *Server) callNext(w http.ResponseWriter, r *http.Request) {
|
||||
Details: map[string]any{"expected_revision": *input.ExpectedRevision, "current_revision": session.Revision},
|
||||
}
|
||||
}
|
||||
var tickets []model.QueueTicket
|
||||
if !projectAllowsCallMode(project.CallMode, mode) {
|
||||
return &apiError{Status: http.StatusUnprocessableEntity, Code: "CALL_MODE_NOT_ALLOWED", Message: "当前项目不支持该叫号方式"}
|
||||
}
|
||||
limit := project.MaxCallTicketCount
|
||||
unit := "个号码"
|
||||
if mode == model.CallModePeople {
|
||||
limit = project.MaxCallPeopleCount
|
||||
unit = "人"
|
||||
}
|
||||
if count > limit {
|
||||
return &apiError{
|
||||
Status: http.StatusUnprocessableEntity, Code: "CALL_COUNT_EXCEEDS_LIMIT",
|
||||
Message: fmt.Sprintf("本次最多可输入 %d %s", limit, unit),
|
||||
Details: map[string]any{"mode": mode, "max_count": limit},
|
||||
}
|
||||
}
|
||||
var waitingTickets []model.QueueTicket
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
|
||||
Where("project_id = ? AND queue_session_id = ? AND status = ?", projectID, session.ID, model.TicketWaiting).
|
||||
Order("ticket_number ASC").Limit(count).Find(&tickets).Error; err != nil {
|
||||
Order("ticket_number ASC").Limit(count).Find(&waitingTickets).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if len(tickets) == 0 {
|
||||
if len(waitingTickets) == 0 {
|
||||
return &apiError{Status: http.StatusConflict, Code: "QUEUE_EMPTY", Message: "当前没有等待中的号码"}
|
||||
}
|
||||
tickets, peopleCount, err := domain.SelectTicketsForCall(waitingTickets, mode, count)
|
||||
if errors.Is(err, domain.ErrFirstTicketExceedsPeopleTarget) {
|
||||
return &apiError{
|
||||
Status: http.StatusConflict, Code: "NEXT_TICKET_EXCEEDS_PEOPLE_TARGET",
|
||||
Message: fmt.Sprintf("队首号码有 %d 人,请输入不少于 %d 人", waitingTickets[0].PartySize, waitingTickets[0].PartySize),
|
||||
Details: map[string]any{"next_ticket_number": waitingTickets[0].DisplayNumber, "party_size": waitingTickets[0].PartySize},
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
now := s.now()
|
||||
autoCompletedBatchIDs, autoCompletedTicketCount, err := autoCompleteActiveBatches(tx, projectID, now)
|
||||
if err != nil {
|
||||
@@ -403,6 +513,7 @@ func (s *Server) callNext(w http.ResponseWriter, r *http.Request) {
|
||||
batch := model.CallBatch{
|
||||
ID: uuid.NewString(), ProjectID: projectID, QueueSessionID: session.ID,
|
||||
BatchSequence: lastSequence + 1, Revision: revision, Status: "CALLED",
|
||||
CallMode: mode, RequestedCount: count, TicketCount: len(tickets), PeopleCount: peopleCount,
|
||||
RequestedBy: user.ID, CalledAt: now, CreatedAt: now,
|
||||
}
|
||||
if err := tx.Create(&batch).Error; err != nil {
|
||||
@@ -438,7 +549,8 @@ func (s *Server) callNext(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
if err := s.addAudit(tx, r, &projectID, &user.ID, "CALL_NEXT", "CALL_BATCH", &batch.ID,
|
||||
map[string]any{
|
||||
"ticket_count": len(tickets), "revision": revision, "device_outcome": outcome,
|
||||
"call_mode": mode, "requested_count": count, "ticket_count": len(tickets), "people_count": peopleCount,
|
||||
"revision": revision, "device_outcome": outcome,
|
||||
"auto_completed_batch_ids": autoCompletedBatchIDs, "auto_completed_ticket_count": autoCompletedTicketCount,
|
||||
}); err != nil {
|
||||
return err
|
||||
@@ -469,6 +581,10 @@ func (s *Server) callNext(w http.ResponseWriter, r *http.Request) {
|
||||
writeRawJSON(w, responseCode, responseBody)
|
||||
}
|
||||
|
||||
func projectAllowsCallMode(projectMode, requestedMode string) bool {
|
||||
return projectMode == model.CallModeBoth || projectMode == requestedMode
|
||||
}
|
||||
|
||||
func autoCompleteActiveBatches(tx *gorm.DB, projectID string, now time.Time) ([]string, int64, error) {
|
||||
var batches []model.CallBatch
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
|
||||
@@ -693,6 +809,7 @@ func (s *Server) staffTicketView(ticket model.QueueTicket) (map[string]any, erro
|
||||
}
|
||||
return map[string]any{
|
||||
"id": ticket.ID, "display_number": ticket.DisplayNumber, "ticket_number": ticket.DisplayNumber, "status": ticket.Status,
|
||||
"party_size": ticket.PartySize,
|
||||
"reissued_from_ticket_id": ticket.ReissuedFromTicketID,
|
||||
"phone": phone, "last_name": lastName, "honorific": ticket.Honorific,
|
||||
"joined_at": ticket.JoinedAt, "called_at": ticket.CalledAt,
|
||||
@@ -712,6 +829,8 @@ func (s *Server) staffCallBatchView(batch model.CallBatch, tickets []model.Queue
|
||||
}
|
||||
return map[string]any{
|
||||
"id": batch.ID, "sequence": batch.BatchSequence, "batch_number": batch.BatchSequence, "status": batch.Status,
|
||||
"call_mode": batch.CallMode, "requested_count": batch.RequestedCount,
|
||||
"ticket_count": batch.TicketCount, "people_count": batch.PeopleCount,
|
||||
"called_at": batch.CalledAt, "revision": batch.Revision, "tickets": views,
|
||||
}, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user