Merge pull request #6 from huabeitech/feature/agent-team-schedule-batch

Feature/agent team schedule batch
This commit is contained in:
Bob
2026-04-30 09:48:45 +08:00
committed by GitHub
20 changed files with 3033 additions and 231 deletions
+1 -1
Submodule docs updated: a4aee8582d...1b6ac267ac
@@ -0,0 +1,39 @@
package builders
import (
"cs-agent/internal/pkg/dto/response"
"cs-agent/internal/services"
"time"
)
func BuildAgentTeamScheduleBatchPreviewResponse(result *services.AgentTeamScheduleBatchPreviewResult) *response.AgentTeamScheduleBatchPreviewResponse {
if result == nil {
return nil
}
items := make([]response.AgentTeamScheduleBatchPreviewItem, 0, len(result.Items))
for _, item := range result.Items {
items = append(items, response.AgentTeamScheduleBatchPreviewItem{
TeamID: item.TeamID,
TeamName: item.TeamName,
Date: item.Date.Format(time.DateOnly),
Weekday: item.Weekday,
StartAt: item.StartAt.Format(time.DateTime),
EndAt: item.EndAt.Format(time.DateTime),
Remark: item.Remark,
Conflict: item.Conflict,
ConflictReason: item.ConflictReason,
})
}
return &response.AgentTeamScheduleBatchPreviewResponse{
Total: result.Total,
Conflict: result.Conflict,
Items: items,
}
}
func BuildAgentTeamScheduleBatchGenerateResponse(result *services.AgentTeamScheduleBatchGenerateResult) *response.AgentTeamScheduleBatchGenerateResponse {
if result == nil {
return nil
}
return &response.AgentTeamScheduleBatchGenerateResponse{Created: result.Created}
}
@@ -1,6 +1,7 @@
package dashboard
import (
"cs-agent/internal/builders"
"cs-agent/internal/models"
"cs-agent/internal/pkg/constants"
"cs-agent/internal/pkg/dto/request"
@@ -31,6 +32,60 @@ func (c *AgentTeamScheduleController) AnyList() *web.JsonResult {
return web.JsonData(&web.PageResult{Results: results, Page: paging})
}
func (c *AgentTeamScheduleController) AnyCalendar() *web.JsonResult {
if _, err := services.AuthService.RequirePermission(c.Ctx, constants.PermissionAgentTeamScheduleView); err != nil {
return web.JsonError(err)
}
startAt, _ := params.Get(c.Ctx, "startAt")
endAt, _ := params.Get(c.Ctx, "endAt")
teamID, _ := params.GetInt64(c.Ctx, "teamId")
list, err := services.AgentTeamScheduleService.FindCalendarSchedules(request.AgentTeamScheduleCalendarRequest{
StartAt: startAt,
EndAt: endAt,
TeamID: teamID,
})
if err != nil {
return web.JsonError(err)
}
results := make([]response.AgentTeamScheduleResponse, 0, len(list))
for _, item := range list {
results = append(results, buildAgentTeamScheduleResponse(&item))
}
return web.JsonData(results)
}
func (c *AgentTeamScheduleController) PostBatch_preview() *web.JsonResult {
operator, err := services.AuthService.RequirePermission(c.Ctx, constants.PermissionAgentTeamScheduleBatchGenerate)
if err != nil {
return web.JsonError(err)
}
req := request.AgentTeamScheduleBatchRequest{}
if err := params.ReadJSON(c.Ctx, &req); err != nil {
return web.JsonError(err)
}
ret, err := services.AgentTeamScheduleService.BatchPreview(req, operator)
if err != nil {
return web.JsonError(err)
}
return web.JsonData(builders.BuildAgentTeamScheduleBatchPreviewResponse(ret))
}
func (c *AgentTeamScheduleController) PostBatch_generate() *web.JsonResult {
operator, err := services.AuthService.RequirePermission(c.Ctx, constants.PermissionAgentTeamScheduleBatchGenerate)
if err != nil {
return web.JsonError(err)
}
req := request.AgentTeamScheduleBatchRequest{}
if err := params.ReadJSON(c.Ctx, &req); err != nil {
return web.JsonError(err)
}
ret, err := services.AgentTeamScheduleService.BatchGenerate(req, operator)
if err != nil {
return web.JsonError(err)
}
return web.JsonData(builders.BuildAgentTeamScheduleBatchGenerateResponse(ret))
}
func (c *AgentTeamScheduleController) GetBy(id int64) *web.JsonResult {
if _, err := services.AuthService.RequirePermission(c.Ctx, constants.PermissionAgentTeamScheduleView); err != nil {
return web.JsonError(err)
@@ -89,12 +144,11 @@ func (c *AgentTeamScheduleController) PostDelete() *web.JsonResult {
func buildAgentTeamScheduleResponse(item *models.AgentTeamSchedule) response.AgentTeamScheduleResponse {
ret := response.AgentTeamScheduleResponse{
ID: item.ID,
TeamID: item.TeamID,
StartAt: item.StartAt.Format("2006-01-02 15:04:05"),
EndAt: item.EndAt.Format("2006-01-02 15:04:05"),
SourceType: item.SourceType,
Remark: item.Remark,
ID: item.ID,
TeamID: item.TeamID,
StartAt: item.StartAt.Format("2006-01-02 15:04:05"),
EndAt: item.EndAt.Format("2006-01-02 15:04:05"),
Remark: item.Remark,
}
if team := services.AgentTeamService.Get(item.TeamID); team != nil {
ret.TeamName = team.Name
+6 -7
View File
@@ -742,13 +742,12 @@ type AgentTeam struct {
// AgentTeamSchedule 客服组排班。
type AgentTeamSchedule struct {
ID int64 `gorm:"primaryKey;autoIncrement"` // ID 为组排班主键。
TeamID int64 `gorm:"type:bigint;not null;index"` // TeamID 为被排班的客服组ID。
StartAt time.Time `gorm:"type:datetime;not null;index"` // StartAt 为班次开始时间。
EndAt time.Time `gorm:"type:datetime;not null;index"` // EndAt 为班次结束时间。
SourceType string `gorm:"type:varchar(30);not null;default:'';index"` // SourceType 表示排班来源,如 manual、batch_import、template_generate
Remark string `gorm:"type:varchar(255);not null;default:''"` // Remark 记录排班备注
Status enums.Status `gorm:"type:int;not null;default:0;index"` // Status 表示组排班记录状态。
ID int64 `gorm:"primaryKey;autoIncrement"` // ID 为组排班主键。
TeamID int64 `gorm:"type:bigint;not null;index"` // TeamID 为被排班的客服组ID。
StartAt time.Time `gorm:"type:datetime;not null;index"` // StartAt 为班次开始时间。
EndAt time.Time `gorm:"type:datetime;not null;index"` // EndAt 为班次结束时间。
Remark string `gorm:"type:varchar(255);not null;default:''"` // Remark 记录排班备注
Status enums.Status `gorm:"type:int;not null;default:0;index"` // Status 表示组排班记录状态
AuditFields
}
+20 -5
View File
@@ -47,11 +47,10 @@ type DeleteAgentTeamRequest struct {
}
type CreateAgentTeamScheduleRequest struct {
TeamID int64 `json:"teamId"`
StartAt string `json:"startAt"`
EndAt string `json:"endAt"`
SourceType string `json:"sourceType"`
Remark string `json:"remark"`
TeamID int64 `json:"teamId"`
StartAt string `json:"startAt"`
EndAt string `json:"endAt"`
Remark string `json:"remark"`
}
type UpdateAgentTeamScheduleRequest struct {
@@ -62,3 +61,19 @@ type UpdateAgentTeamScheduleRequest struct {
type DeleteAgentTeamScheduleRequest struct {
ID int64 `json:"id"`
}
type AgentTeamScheduleCalendarRequest struct {
StartAt string `json:"startAt"`
EndAt string `json:"endAt"`
TeamID int64 `json:"teamId"`
}
type AgentTeamScheduleBatchRequest struct {
TeamIDs []int64 `json:"teamIds"`
StartDate string `json:"startDate"`
EndDate string `json:"endDate"`
Weekdays []int `json:"weekdays"`
StartTime string `json:"startTime"`
EndTime string `json:"endTime"`
Remark string `json:"remark"`
}
+28 -7
View File
@@ -34,11 +34,32 @@ type AgentTeamResponse struct {
}
type AgentTeamScheduleResponse struct {
ID int64 `json:"id"`
TeamID int64 `json:"teamId"`
TeamName string `json:"teamName,omitempty"`
StartAt string `json:"startAt"`
EndAt string `json:"endAt"`
SourceType string `json:"sourceType"`
Remark string `json:"remark"`
ID int64 `json:"id"`
TeamID int64 `json:"teamId"`
TeamName string `json:"teamName,omitempty"`
StartAt string `json:"startAt"`
EndAt string `json:"endAt"`
Remark string `json:"remark"`
}
type AgentTeamScheduleBatchPreviewResponse struct {
Total int `json:"total"`
Conflict bool `json:"conflict"`
Items []AgentTeamScheduleBatchPreviewItem `json:"items"`
}
type AgentTeamScheduleBatchPreviewItem struct {
TeamID int64 `json:"teamId"`
TeamName string `json:"teamName"`
Date string `json:"date"`
Weekday int `json:"weekday"`
StartAt string `json:"startAt"`
EndAt string `json:"endAt"`
Remark string `json:"remark"`
Conflict bool `json:"conflict"`
ConflictReason string `json:"conflictReason"`
}
type AgentTeamScheduleBatchGenerateResponse struct {
Created int `json:"created"`
}
@@ -0,0 +1,27 @@
package response
import (
"encoding/json"
"testing"
)
func TestAgentTeamScheduleResponseOmitsSourceType(t *testing.T) {
payload, err := json.Marshal(AgentTeamScheduleResponse{
ID: 1,
TeamID: 2,
StartAt: "2026-04-29 09:00:00",
EndAt: "2026-04-29 18:00:00",
Remark: "test",
})
if err != nil {
t.Fatalf("marshal response error = %v", err)
}
var decoded map[string]any
if err := json.Unmarshal(payload, &decoded); err != nil {
t.Fatalf("unmarshal response error = %v", err)
}
if _, ok := decoded["sourceType"]; ok {
t.Fatalf("sourceType should not be exposed: %s", payload)
}
}
@@ -2,6 +2,8 @@ package repositories
import (
"cs-agent/internal/models"
"cs-agent/internal/pkg/enums"
"time"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
@@ -38,6 +40,36 @@ func (r *agentTeamScheduleRepository) Find(db *gorm.DB, cnd *sqls.Cnd) (list []m
return
}
func (r *agentTeamScheduleRepository) FindByTimeRange(db *gorm.DB, startAt, endAt time.Time, teamID int64) (list []models.AgentTeamSchedule) {
query := db.Model(&models.AgentTeamSchedule{}).
Where("start_at < ? AND end_at > ?", endAt, startAt)
if teamID > 0 {
query = query.Where("team_id = ?", teamID)
}
query.Order("team_id ASC").Order("start_at ASC").Order("id ASC").Find(&list)
return
}
func (r *agentTeamScheduleRepository) FindOverlappingByTeamIDsAndTimeRange(db *gorm.DB, teamIDs []int64, startAt, endAt time.Time) (list []models.AgentTeamSchedule) {
if len(teamIDs) == 0 {
return
}
db.Model(&models.AgentTeamSchedule{}).
Where("team_id IN ? AND status = ? AND start_at < ? AND end_at > ?", teamIDs, enums.StatusOk, endAt, startAt).
Order("team_id ASC").
Order("start_at ASC").
Order("id ASC").
Find(&list)
return
}
func (r *agentTeamScheduleRepository) CreateBatch(db *gorm.DB, list []models.AgentTeamSchedule) error {
if len(list) == 0 {
return nil
}
return db.Create(&list).Error
}
func (r *agentTeamScheduleRepository) FindOne(db *gorm.DB, cnd *sqls.Cnd) *models.AgentTeamSchedule {
ret := &models.AgentTeamSchedule{}
if err := cnd.FindOne(db, &ret); err != nil {
@@ -62,12 +94,12 @@ func (r *agentTeamScheduleRepository) FindPageByCnd(db *gorm.DB, cnd *sqls.Cnd)
return
}
func (r *agentTeamScheduleRepository) FindBySql(db *gorm.DB, sqlStr string, paramArr... interface{}) (list []models.AgentTeamSchedule) {
func (r *agentTeamScheduleRepository) FindBySql(db *gorm.DB, sqlStr string, paramArr ...interface{}) (list []models.AgentTeamSchedule) {
db.Raw(sqlStr, paramArr...).Scan(&list)
return
}
func (r *agentTeamScheduleRepository) CountBySql(db *gorm.DB, sqlStr string, paramArr... interface{}) (count int64) {
func (r *agentTeamScheduleRepository) CountBySql(db *gorm.DB, sqlStr string, paramArr ...interface{}) (count int64) {
db.Raw(sqlStr, paramArr...).Count(&count)
return
}
@@ -99,4 +131,3 @@ func (r *agentTeamScheduleRepository) UpdateColumn(db *gorm.DB, id int64, name s
func (r *agentTeamScheduleRepository) Delete(db *gorm.DB, id int64) {
db.Delete(&models.AgentTeamSchedule{}, "id = ?", id)
}
+371 -19
View File
@@ -8,12 +8,15 @@ import (
"cs-agent/internal/pkg/errorsx"
"cs-agent/internal/pkg/utils"
"cs-agent/internal/repositories"
"fmt"
"slices"
"strings"
"sync"
"time"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
"gorm.io/gorm"
)
var AgentTeamScheduleService = newAgentTeamScheduleService()
@@ -23,6 +26,40 @@ func newAgentTeamScheduleService() *agentTeamScheduleService {
}
type agentTeamScheduleService struct {
writeMu sync.Mutex
}
const maxAgentTeamScheduleBatchItems = 500
type AgentTeamScheduleBatchPreviewResult struct {
Total int
Conflict bool
Items []AgentTeamScheduleBatchPreviewItem
}
type AgentTeamScheduleBatchPreviewItem struct {
TeamID int64
TeamName string
Date time.Time
Weekday int
StartAt time.Time
EndAt time.Time
Remark string
Conflict bool
ConflictReason string
}
type AgentTeamScheduleBatchGenerateResult struct {
Created int
}
type batchScheduleCandidate struct {
TeamID int64
TeamName string
Date time.Time
StartAt time.Time
EndAt time.Time
Remark string
}
func (s *agentTeamScheduleService) Get(id int64) *models.AgentTeamSchedule {
@@ -53,6 +90,21 @@ func (s *agentTeamScheduleService) Count(cnd *sqls.Cnd) int64 {
return repositories.AgentTeamScheduleRepository.Count(sqls.DB(), cnd)
}
func (s *agentTeamScheduleService) FindCalendarSchedules(req request.AgentTeamScheduleCalendarRequest) ([]models.AgentTeamSchedule, error) {
startAtValue, err := parseRequiredDateTime(req.StartAt, "开始时间格式错误")
if err != nil {
return nil, err
}
endAtValue, err := parseRequiredDateTime(req.EndAt, "结束时间格式错误")
if err != nil {
return nil, err
}
if !endAtValue.After(startAtValue) {
return nil, errorsx.InvalidParam("结束时间必须晚于开始时间")
}
return repositories.AgentTeamScheduleRepository.FindByTimeRange(sqls.DB(), startAtValue, endAtValue, req.TeamID), nil
}
func (s *agentTeamScheduleService) Create(t *models.AgentTeamSchedule) error {
return repositories.AgentTeamScheduleRepository.Create(sqls.DB(), t)
}
@@ -77,14 +129,18 @@ func (s *agentTeamScheduleService) CreateAgentTeamSchedule(req request.CreateAge
if operator == nil {
return nil, errorsx.Unauthorized("未登录或登录已过期")
}
item, err := s.buildScheduleModel(0, req.TeamID, req.StartAt, req.EndAt, req.SourceType, req.Remark)
s.writeMu.Lock()
item, err := s.buildScheduleModel(0, req.TeamID, req.StartAt, req.EndAt, req.Remark)
if err != nil {
s.writeMu.Unlock()
return nil, err
}
item.AuditFields = utils.BuildAuditFields(operator)
if err := repositories.AgentTeamScheduleRepository.Create(sqls.DB(), item); err != nil {
s.writeMu.Unlock()
return nil, err
}
s.writeMu.Unlock()
s.dispatchPendingConversationsIfActive(item)
return item, nil
}
@@ -93,25 +149,29 @@ func (s *agentTeamScheduleService) UpdateAgentTeamSchedule(req request.UpdateAge
if operator == nil {
return errorsx.Unauthorized("未登录或登录已过期")
}
s.writeMu.Lock()
if s.Get(req.ID) == nil {
s.writeMu.Unlock()
return errorsx.InvalidParam("客服组排班不存在")
}
item, err := s.buildScheduleModel(req.ID, req.TeamID, req.StartAt, req.EndAt, req.SourceType, req.Remark)
item, err := s.buildScheduleModel(req.ID, req.TeamID, req.StartAt, req.EndAt, req.Remark)
if err != nil {
s.writeMu.Unlock()
return err
}
if err := repositories.AgentTeamScheduleRepository.Updates(sqls.DB(), req.ID, map[string]any{
"team_id": item.TeamID,
"start_at": item.StartAt,
"end_at": item.EndAt,
"source_type": item.SourceType,
"remark": item.Remark,
"update_user_id": operator.UserID,
"update_user_name": operator.Username,
"updated_at": time.Now(),
}); err != nil {
s.writeMu.Unlock()
return err
}
s.writeMu.Unlock()
s.dispatchPendingConversationsIfActive(item)
return nil
}
@@ -124,7 +184,67 @@ func (s *agentTeamScheduleService) DeleteAgentTeamSchedule(id int64) error {
return nil
}
func (s *agentTeamScheduleService) buildScheduleModel(id, teamID int64, startAt, endAt, sourceType, remark string) (*models.AgentTeamSchedule, error) {
func (s *agentTeamScheduleService) BatchPreview(req request.AgentTeamScheduleBatchRequest, operator *dto.AuthPrincipal) (*AgentTeamScheduleBatchPreviewResult, error) {
if operator == nil {
return nil, errorsx.Unauthorized("未登录或登录已过期")
}
candidates, err := s.buildBatchScheduleCandidates(req)
if err != nil {
return nil, err
}
conflicts := s.findBatchConflict(candidates)
return buildBatchPreviewResult(candidates, conflicts), nil
}
func (s *agentTeamScheduleService) BatchGenerate(req request.AgentTeamScheduleBatchRequest, operator *dto.AuthPrincipal) (*AgentTeamScheduleBatchGenerateResult, error) {
if operator == nil {
return nil, errorsx.Unauthorized("未登录或登录已过期")
}
s.writeMu.Lock()
candidates, err := s.buildBatchScheduleCandidates(req)
if err != nil {
s.writeMu.Unlock()
return nil, err
}
conflicts := s.findBatchConflict(candidates)
for _, conflict := range conflicts {
if conflict != "" {
s.writeMu.Unlock()
return nil, errorsx.InvalidParam("存在冲突排班,请先处理冲突")
}
}
schedules := make([]models.AgentTeamSchedule, 0, len(candidates))
for _, candidate := range candidates {
schedules = append(schedules, models.AgentTeamSchedule{
TeamID: candidate.TeamID,
StartAt: candidate.StartAt,
EndAt: candidate.EndAt,
Remark: candidate.Remark,
Status: enums.StatusOk,
AuditFields: utils.BuildAuditFields(operator),
})
}
if err := sqls.WithTransaction(func(ctx *sqls.TxContext) error {
conflicts := s.findBatchConflictByDB(ctx.Tx, candidates)
for _, conflict := range conflicts {
if conflict != "" {
return errorsx.InvalidParam("存在冲突排班,请先处理冲突")
}
}
return repositories.AgentTeamScheduleRepository.CreateBatch(ctx.Tx, schedules)
}); err != nil {
s.writeMu.Unlock()
return nil, err
}
s.writeMu.Unlock()
for i := range schedules {
s.dispatchPendingConversationsIfActive(&schedules[i])
}
return &AgentTeamScheduleBatchGenerateResult{Created: len(schedules)}, nil
}
func (s *agentTeamScheduleService) buildScheduleModel(id, teamID int64, startAt, endAt, remark string) (*models.AgentTeamSchedule, error) {
if teamID <= 0 {
return nil, errorsx.InvalidParam("请选择客服组")
}
@@ -135,10 +255,6 @@ func (s *agentTeamScheduleService) buildScheduleModel(id, teamID int64, startAt,
if !slices.Contains(enums.StatusValues, team.Status) {
return nil, errorsx.InvalidParam("客服组状态不合法")
}
sourceType = strings.TrimSpace(sourceType)
if sourceType == "" {
return nil, errorsx.InvalidParam("排班来源不能为空")
}
startAtValue, err := parseRequiredDateTime(startAt, "开始时间格式错误")
if err != nil {
return nil, err
@@ -150,22 +266,247 @@ func (s *agentTeamScheduleService) buildScheduleModel(id, teamID int64, startAt,
if !endAtValue.After(startAtValue) {
return nil, errorsx.InvalidParam("结束时间必须晚于开始时间")
}
var count int64
sqls.DB().Model(&models.AgentTeamSchedule{}).
Where("team_id = ? AND id <> ? AND start_at < ? AND end_at > ?", teamID, id, endAtValue, startAtValue).
Count(&count)
if count > 0 {
return nil, errorsx.InvalidParam("该客服组在所选时间段已存在排班")
if !sameLocalDay(startAtValue, endAtValue) {
return nil, errorsx.InvalidParam("单条排班记录不能跨天")
}
if startAtValue.Before(startOfLocalDay(time.Now())) {
return nil, errorsx.InvalidParam("不能添加或修改历史日期的排班")
}
overlapping := repositories.AgentTeamScheduleRepository.FindOverlappingByTeamIDsAndTimeRange(sqls.DB(), []int64{teamID}, startAtValue, endAtValue)
for _, item := range overlapping {
if item.ID != id {
return nil, errorsx.InvalidParam("该客服组在所选时间段已存在排班")
}
}
return &models.AgentTeamSchedule{
TeamID: teamID,
StartAt: startAtValue,
EndAt: endAtValue,
SourceType: sourceType,
Remark: strings.TrimSpace(remark),
TeamID: teamID,
StartAt: startAtValue,
EndAt: endAtValue,
Remark: strings.TrimSpace(remark),
}, nil
}
func (s *agentTeamScheduleService) buildBatchScheduleCandidates(req request.AgentTeamScheduleBatchRequest) ([]batchScheduleCandidate, error) {
teamIDs := uniquePositiveInt64s(req.TeamIDs)
if len(teamIDs) == 0 {
return nil, errorsx.InvalidParam("请选择客服组")
}
weekdays, err := normalizeBatchWeekdays(req.Weekdays)
if err != nil {
return nil, err
}
startDate, err := parseRequiredDate(req.StartDate, "开始日期格式错误")
if err != nil {
return nil, err
}
endDate, err := parseRequiredDate(req.EndDate, "结束日期格式错误")
if err != nil {
return nil, err
}
if endDate.Before(startDate) {
return nil, errorsx.InvalidParam("结束日期必须晚于或等于开始日期")
}
if startDate.Before(startOfLocalDay(time.Now())) {
return nil, errorsx.InvalidParam("不能添加或修改历史日期的排班")
}
startClock, err := parseRequiredClock(req.StartTime, "开始时间格式错误")
if err != nil {
return nil, err
}
endClock, err := parseRequiredClock(req.EndTime, "结束时间格式错误")
if err != nil {
return nil, err
}
firstStartAt := combineDateAndClock(startDate, startClock)
firstEndAt := combineDateAndClock(startDate, endClock)
if !firstEndAt.After(firstStartAt) {
return nil, errorsx.InvalidParam("结束时间必须晚于开始时间")
}
teams := AgentTeamService.FindByIds(teamIDs)
teamsByID := make(map[int64]models.AgentTeam, len(teams))
for _, team := range teams {
teamsByID[team.ID] = team
}
for _, teamID := range teamIDs {
team, ok := teamsByID[teamID]
if !ok || team.Status == enums.StatusDeleted {
return nil, errorsx.InvalidParam("客服组不存在")
}
if !slices.Contains(enums.StatusValues, team.Status) {
return nil, errorsx.InvalidParam("客服组状态不合法")
}
}
weekdaySet := make(map[int]struct{}, len(weekdays))
for _, weekday := range weekdays {
weekdaySet[weekday] = struct{}{}
}
candidates := make([]batchScheduleCandidate, 0)
remark := strings.TrimSpace(req.Remark)
for _, teamID := range teamIDs {
team := teamsByID[teamID]
for date := startDate; !date.After(endDate); date = date.AddDate(0, 0, 1) {
if _, ok := weekdaySet[weekdayForBatchRequest(date)]; !ok {
continue
}
if len(candidates) >= maxAgentTeamScheduleBatchItems {
return nil, errorsx.InvalidParam(fmt.Sprintf("单次最多生成 %d 条排班", maxAgentTeamScheduleBatchItems))
}
candidates = append(candidates, batchScheduleCandidate{
TeamID: teamID,
TeamName: team.Name,
Date: date,
StartAt: combineDateAndClock(date, startClock),
EndAt: combineDateAndClock(date, endClock),
Remark: remark,
})
}
}
if len(candidates) == 0 {
return nil, errorsx.InvalidParam("未生成任何排班")
}
return candidates, nil
}
func parseRequiredDate(value, message string) (time.Time, error) {
value = strings.TrimSpace(value)
if value == "" {
return time.Time{}, errorsx.InvalidParam(message)
}
ret, err := time.ParseInLocation(time.DateOnly, value, time.Local)
if err != nil {
return time.Time{}, errorsx.InvalidParam(message + ",请使用 yyyy-MM-dd")
}
return startOfLocalDay(ret), nil
}
func parseRequiredClock(value, message string) (time.Time, error) {
value = strings.TrimSpace(value)
if value == "" {
return time.Time{}, errorsx.InvalidParam(message)
}
layouts := []string{"15:04", "15:04:05"}
for _, layout := range layouts {
if ret, err := time.ParseInLocation(layout, value, time.Local); err == nil {
return ret, nil
}
}
return time.Time{}, errorsx.InvalidParam(message + ",请使用 HH:mm 或 HH:mm:ss")
}
func combineDateAndClock(date, clock time.Time) time.Time {
year, month, day := date.In(time.Local).Date()
hour, minute, second := clock.In(time.Local).Clock()
return time.Date(year, month, day, hour, minute, second, 0, time.Local)
}
func buildBatchPreviewResult(candidates []batchScheduleCandidate, conflicts map[int]string) *AgentTeamScheduleBatchPreviewResult {
items := make([]AgentTeamScheduleBatchPreviewItem, 0, len(candidates))
hasConflict := false
for i, candidate := range candidates {
conflictReason := conflicts[i]
conflict := conflictReason != ""
if conflict {
hasConflict = true
}
items = append(items, AgentTeamScheduleBatchPreviewItem{
TeamID: candidate.TeamID,
TeamName: candidate.TeamName,
Date: candidate.Date,
Weekday: weekdayForBatchRequest(candidate.Date),
StartAt: candidate.StartAt,
EndAt: candidate.EndAt,
Remark: candidate.Remark,
Conflict: conflict,
ConflictReason: conflictReason,
})
}
return &AgentTeamScheduleBatchPreviewResult{
Total: len(items),
Conflict: hasConflict,
Items: items,
}
}
func (s *agentTeamScheduleService) findBatchConflict(candidates []batchScheduleCandidate) map[int]string {
return s.findBatchConflictByDB(sqls.DB(), candidates)
}
func (s *agentTeamScheduleService) findBatchConflictByDB(db *gorm.DB, candidates []batchScheduleCandidate) map[int]string {
conflicts := make(map[int]string)
if len(candidates) == 0 {
return conflicts
}
teamIDs := make([]int64, 0, len(candidates))
startAt := candidates[0].StartAt
endAt := candidates[0].EndAt
for _, candidate := range candidates {
teamIDs = append(teamIDs, candidate.TeamID)
if candidate.StartAt.Before(startAt) {
startAt = candidate.StartAt
}
if candidate.EndAt.After(endAt) {
endAt = candidate.EndAt
}
}
existing := repositories.AgentTeamScheduleRepository.FindOverlappingByTeamIDsAndTimeRange(db, uniquePositiveInt64s(teamIDs), startAt, endAt)
for i, candidate := range candidates {
for _, item := range existing {
if item.TeamID != candidate.TeamID {
continue
}
if item.StartAt.Before(candidate.EndAt) && item.EndAt.After(candidate.StartAt) {
conflicts[i] = fmt.Sprintf("该客服组在 %s 至 %s 已存在排班", item.StartAt.Format(time.DateTime), item.EndAt.Format(time.DateTime))
break
}
}
}
return conflicts
}
func normalizeBatchWeekdays(values []int) ([]int, error) {
seen := make(map[int]struct{}, len(values))
ret := make([]int, 0, len(values))
for _, value := range values {
if value < 1 || value > 7 {
return nil, errorsx.InvalidParam("星期必须在 1 到 7 之间")
}
if _, ok := seen[value]; ok {
continue
}
seen[value] = struct{}{}
ret = append(ret, value)
}
if len(ret) == 0 {
return nil, errorsx.InvalidParam("请选择星期")
}
return ret, nil
}
func weekdayForBatchRequest(value time.Time) int {
if value.Weekday() == time.Sunday {
return 7
}
return int(value.Weekday())
}
func uniquePositiveInt64s(values []int64) []int64 {
seen := make(map[int64]struct{}, len(values))
ret := make([]int64, 0, len(values))
for _, value := range values {
if value <= 0 {
continue
}
if _, ok := seen[value]; ok {
continue
}
seen[value] = struct{}{}
ret = append(ret, value)
}
return ret
}
func parseRequiredDateTime(value, message string) (time.Time, error) {
value = strings.TrimSpace(value)
if value == "" {
@@ -193,6 +534,17 @@ func parseDateTimeValue(value string) (time.Time, error) {
return time.Time{}, errorsx.InvalidParam("时间格式错误")
}
func startOfLocalDay(value time.Time) time.Time {
year, month, day := value.In(time.Local).Date()
return time.Date(year, month, day, 0, 0, 0, 0, time.Local)
}
func sameLocalDay(a, b time.Time) bool {
aYear, aMonth, aDay := a.In(time.Local).Date()
bYear, bMonth, bDay := b.In(time.Local).Date()
return aYear == bYear && aMonth == bMonth && aDay == bDay
}
func (s *agentTeamScheduleService) dispatchPendingConversationsIfActive(item *models.AgentTeamSchedule) {
if item == nil {
return
@@ -0,0 +1,591 @@
package services_test
import (
"strings"
"testing"
"time"
"cs-agent/internal/models"
"cs-agent/internal/pkg/dto"
"cs-agent/internal/pkg/dto/request"
"cs-agent/internal/pkg/enums"
"cs-agent/internal/services"
"github.com/glebarez/sqlite"
"github.com/mlogclub/simple/sqls"
"gorm.io/gorm"
"gorm.io/gorm/schema"
)
func TestAgentTeamScheduleServiceFindCalendarSchedulesReturnsIntersectingSchedules(t *testing.T) {
db := setupAgentTeamScheduleTestDB(t)
createAgentTeamScheduleTestData(t, db)
list, err := services.AgentTeamScheduleService.FindCalendarSchedules(request.AgentTeamScheduleCalendarRequest{
StartAt: "2026-04-27 00:00:00",
EndAt: "2026-05-04 00:00:00",
})
if err != nil {
t.Fatalf("FindCalendarSchedules() error = %v", err)
}
if len(list) != 3 {
t.Fatalf("expected 3 intersecting schedules, got %d: %+v", len(list), list)
}
gotIDs := make([]int64, 0, len(list))
for _, item := range list {
gotIDs = append(gotIDs, item.ID)
}
wantIDs := []int64{1, 2, 3}
for i, want := range wantIDs {
if gotIDs[i] != want {
t.Fatalf("expected ids %v, got %v", wantIDs, gotIDs)
}
}
}
func TestAgentTeamScheduleServiceFindCalendarSchedulesFiltersTeamID(t *testing.T) {
db := setupAgentTeamScheduleTestDB(t)
createAgentTeamScheduleTestData(t, db)
list, err := services.AgentTeamScheduleService.FindCalendarSchedules(request.AgentTeamScheduleCalendarRequest{
StartAt: "2026-04-27 00:00:00",
EndAt: "2026-05-04 00:00:00",
TeamID: 2,
})
if err != nil {
t.Fatalf("FindCalendarSchedules() error = %v", err)
}
if len(list) != 1 {
t.Fatalf("expected 1 schedule for team 2, got %d: %+v", len(list), list)
}
if list[0].ID != 3 || list[0].TeamID != 2 {
t.Fatalf("unexpected schedule: %+v", list[0])
}
}
func TestAgentTeamScheduleServiceFindCalendarSchedulesValidatesTimeRange(t *testing.T) {
setupAgentTeamScheduleTestDB(t)
_, err := services.AgentTeamScheduleService.FindCalendarSchedules(request.AgentTeamScheduleCalendarRequest{
StartAt: "2026-05-04 00:00:00",
EndAt: "2026-04-27 00:00:00",
})
if err == nil {
t.Fatalf("expected invalid time range to fail")
}
}
func TestAgentTeamScheduleServiceCreateRejectsCrossDaySchedule(t *testing.T) {
setupAgentTeamScheduleTestDB(t)
createAgentTeamScheduleTestTeams(t, sqls.DB())
tomorrow := time.Now().AddDate(0, 0, 1)
_, err := services.AgentTeamScheduleService.CreateAgentTeamSchedule(request.CreateAgentTeamScheduleRequest{
TeamID: 1,
StartAt: formatTestDateTime(tomorrow, "22:00:00"),
EndAt: formatTestDateTime(tomorrow.AddDate(0, 0, 1), "08:00:00"),
}, testOperator())
if err == nil {
t.Fatalf("expected cross-day schedule to fail")
}
if !strings.Contains(err.Error(), "不能跨天") {
t.Fatalf("expected cross-day error, got %v", err)
}
}
func TestAgentTeamScheduleServiceCreateRejectsHistoricalScheduleByDay(t *testing.T) {
setupAgentTeamScheduleTestDB(t)
createAgentTeamScheduleTestTeams(t, sqls.DB())
yesterday := time.Now().AddDate(0, 0, -1)
_, err := services.AgentTeamScheduleService.CreateAgentTeamSchedule(request.CreateAgentTeamScheduleRequest{
TeamID: 1,
StartAt: formatTestDateTime(yesterday, "09:00:00"),
EndAt: formatTestDateTime(yesterday, "18:00:00"),
}, testOperator())
if err == nil {
t.Fatalf("expected historical schedule to fail")
}
if !strings.Contains(err.Error(), "历史日期") {
t.Fatalf("expected historical date error, got %v", err)
}
}
func TestAgentTeamScheduleServiceCreateAllowsTodayEarlierThanCurrentTime(t *testing.T) {
setupAgentTeamScheduleTestDB(t)
createAgentTeamScheduleTestTeams(t, sqls.DB())
today := time.Now()
item, err := services.AgentTeamScheduleService.CreateAgentTeamSchedule(request.CreateAgentTeamScheduleRequest{
TeamID: 1,
StartAt: formatTestDateTime(today, "00:00:00"),
EndAt: formatTestDateTime(today, "01:00:00"),
}, testOperator())
if err != nil {
t.Fatalf("expected today's schedule to pass, got %v", err)
}
if item == nil || item.ID == 0 {
t.Fatalf("expected created schedule, got %+v", item)
}
}
func TestAgentTeamScheduleServiceUpdateRejectsCrossDaySchedule(t *testing.T) {
db := setupAgentTeamScheduleTestDB(t)
createAgentTeamScheduleTestTeams(t, db)
existingID := createFutureAgentTeamSchedule(t, db)
tomorrow := time.Now().AddDate(0, 0, 1)
err := services.AgentTeamScheduleService.UpdateAgentTeamSchedule(request.UpdateAgentTeamScheduleRequest{
ID: existingID,
CreateAgentTeamScheduleRequest: request.CreateAgentTeamScheduleRequest{
TeamID: 1,
StartAt: formatTestDateTime(tomorrow, "22:00:00"),
EndAt: formatTestDateTime(tomorrow.AddDate(0, 0, 1), "08:00:00"),
},
}, testOperator())
if err == nil {
t.Fatalf("expected cross-day update to fail")
}
if !strings.Contains(err.Error(), "不能跨天") {
t.Fatalf("expected cross-day error, got %v", err)
}
}
func TestAgentTeamScheduleServiceUpdateRejectsHistoricalScheduleByDay(t *testing.T) {
db := setupAgentTeamScheduleTestDB(t)
createAgentTeamScheduleTestTeams(t, db)
existingID := createFutureAgentTeamSchedule(t, db)
yesterday := time.Now().AddDate(0, 0, -1)
err := services.AgentTeamScheduleService.UpdateAgentTeamSchedule(request.UpdateAgentTeamScheduleRequest{
ID: existingID,
CreateAgentTeamScheduleRequest: request.CreateAgentTeamScheduleRequest{
TeamID: 1,
StartAt: formatTestDateTime(yesterday, "09:00:00"),
EndAt: formatTestDateTime(yesterday, "18:00:00"),
},
}, testOperator())
if err == nil {
t.Fatalf("expected historical update to fail")
}
if !strings.Contains(err.Error(), "历史日期") {
t.Fatalf("expected historical date error, got %v", err)
}
}
func TestAgentTeamScheduleServiceBatchPreviewExpandsSharedRule(t *testing.T) {
setupAgentTeamScheduleTestDB(t)
createAgentTeamScheduleTestTeams(t, sqls.DB())
nextMonday := nextTestWeekday(time.Monday)
nextWednesday := nextMonday.AddDate(0, 0, 2)
preview, err := services.AgentTeamScheduleService.BatchPreview(request.AgentTeamScheduleBatchRequest{
TeamIDs: []int64{1, 2},
StartDate: nextMonday.Format(time.DateOnly),
EndDate: nextMonday.AddDate(0, 0, 6).Format(time.DateOnly),
Weekdays: []int{1, 3},
StartTime: "09:00",
EndTime: "18:00",
Remark: "工作日白班",
}, testOperator())
if err != nil {
t.Fatalf("BatchPreview() error = %v", err)
}
if preview.Total != 4 || len(preview.Items) != 4 {
t.Fatalf("expected 4 preview items, got total=%d len=%d", preview.Total, len(preview.Items))
}
if preview.Conflict {
t.Fatalf("expected no conflict, got %+v", preview.Items)
}
teamNames := make(map[int64]string)
for _, item := range preview.Items {
if item.TeamName == "" {
t.Fatalf("expected all preview items to have team names: %+v", preview.Items)
}
teamNames[item.TeamID] = item.TeamName
}
if teamNames[1] == "" || teamNames[2] == "" {
t.Fatalf("expected team ids 1 and 2 with names, got %v", teamNames)
}
type previewKey struct {
teamID int64
date string
}
itemsByKey := make(map[previewKey]services.AgentTeamScheduleBatchPreviewItem)
for _, item := range preview.Items {
itemsByKey[previewKey{teamID: item.TeamID, date: item.Date.Format(time.DateOnly)}] = item
}
expected := []struct {
teamID int64
date time.Time
weekday int
}{
{teamID: 1, date: nextMonday, weekday: 1},
{teamID: 1, date: nextWednesday, weekday: 3},
{teamID: 2, date: nextMonday, weekday: 1},
{teamID: 2, date: nextWednesday, weekday: 3},
}
for _, want := range expected {
wantDate := want.date.Format(time.DateOnly)
item, ok := itemsByKey[previewKey{teamID: want.teamID, date: wantDate}]
if !ok {
t.Fatalf("expected preview item for teamID=%d date=%s, got %+v", want.teamID, wantDate, preview.Items)
}
if item.Weekday != want.weekday ||
item.StartAt.Format(time.DateTime) != formatTestDateTime(want.date, "09:00:00") ||
item.EndAt.Format(time.DateTime) != formatTestDateTime(want.date, "18:00:00") ||
item.Remark != "工作日白班" {
t.Fatalf("unexpected preview item for teamID=%d date=%s: %+v", want.teamID, wantDate, item)
}
}
}
func TestAgentTeamScheduleServiceBatchPreviewRejectsHistoricalDate(t *testing.T) {
setupAgentTeamScheduleTestDB(t)
createAgentTeamScheduleTestTeams(t, sqls.DB())
yesterday := time.Now().AddDate(0, 0, -1)
_, err := services.AgentTeamScheduleService.BatchPreview(request.AgentTeamScheduleBatchRequest{
TeamIDs: []int64{1},
StartDate: yesterday.Format(time.DateOnly),
EndDate: yesterday.Format(time.DateOnly),
Weekdays: []int{weekdayForRequest(yesterday)},
StartTime: "09:00",
EndTime: "18:00",
}, testOperator())
if err == nil {
t.Fatalf("expected historical batch preview to fail")
}
if !strings.Contains(err.Error(), "历史日期") {
t.Fatalf("expected historical date error, got %v", err)
}
}
func TestAgentTeamScheduleServiceBatchPreviewRejectsInvalidTimeRange(t *testing.T) {
setupAgentTeamScheduleTestDB(t)
createAgentTeamScheduleTestTeams(t, sqls.DB())
tomorrow := time.Now().AddDate(0, 0, 1)
_, err := services.AgentTeamScheduleService.BatchPreview(request.AgentTeamScheduleBatchRequest{
TeamIDs: []int64{1},
StartDate: tomorrow.Format(time.DateOnly),
EndDate: tomorrow.Format(time.DateOnly),
Weekdays: []int{weekdayForRequest(tomorrow)},
StartTime: "18:00",
EndTime: "09:00",
}, testOperator())
if err == nil {
t.Fatalf("expected invalid time range to fail")
}
if !strings.Contains(err.Error(), "结束时间必须晚于开始时间") {
t.Fatalf("expected invalid time range error, got %v", err)
}
}
func TestAgentTeamScheduleServiceBatchPreviewRejectsOverLimit(t *testing.T) {
setupAgentTeamScheduleTestDB(t)
createAgentTeamScheduleTestTeams(t, sqls.DB())
today := time.Now()
_, err := services.AgentTeamScheduleService.BatchPreview(request.AgentTeamScheduleBatchRequest{
TeamIDs: []int64{1, 2},
StartDate: today.Format(time.DateOnly),
EndDate: today.AddDate(0, 0, 260).Format(time.DateOnly),
Weekdays: []int{1, 2, 3, 4, 5, 6, 7},
StartTime: "09:00",
EndTime: "18:00",
}, testOperator())
if err == nil {
t.Fatalf("expected over-limit preview to fail")
}
if !strings.Contains(err.Error(), "500") {
t.Fatalf("expected 500 limit error, got %v", err)
}
}
func TestAgentTeamScheduleServiceBatchPreviewMarksConflicts(t *testing.T) {
db := setupAgentTeamScheduleTestDB(t)
createAgentTeamScheduleTestTeams(t, db)
targetDay := time.Now().AddDate(0, 0, 2)
existing := models.AgentTeamSchedule{
TeamID: 1,
StartAt: parseTestDateTime(t, formatTestDateTime(targetDay, "10:00:00")),
EndAt: parseTestDateTime(t, formatTestDateTime(targetDay, "12:00:00")),
Status: enums.StatusOk,
}
if err := db.Create(&existing).Error; err != nil {
t.Fatalf("create existing schedule error = %v", err)
}
preview, err := services.AgentTeamScheduleService.BatchPreview(request.AgentTeamScheduleBatchRequest{
TeamIDs: []int64{1, 2},
StartDate: targetDay.Format(time.DateOnly),
EndDate: targetDay.Format(time.DateOnly),
Weekdays: []int{weekdayForRequest(targetDay)},
StartTime: "09:00",
EndTime: "18:00",
}, testOperator())
if err != nil {
t.Fatalf("BatchPreview() error = %v", err)
}
if !preview.Conflict {
t.Fatalf("expected preview conflict, got %+v", preview)
}
itemsByTeamID := make(map[int64]services.AgentTeamScheduleBatchPreviewItem)
for _, item := range preview.Items {
itemsByTeamID[item.TeamID] = item
}
team1Item, ok := itemsByTeamID[1]
if !ok {
t.Fatalf("expected team 1 preview item, got %+v", preview.Items)
}
team2Item, ok := itemsByTeamID[2]
if !ok {
t.Fatalf("expected team 2 preview item, got %+v", preview.Items)
}
if !team1Item.Conflict || team1Item.ConflictReason == "" {
t.Fatalf("expected team 1 preview item to be marked as conflict: %+v", team1Item)
}
if team2Item.Conflict {
t.Fatalf("expected team 2 preview item to have no conflict: %+v", team2Item)
}
}
func TestAgentTeamScheduleServiceBatchPreviewIgnoresDisabledOverlappingSchedule(t *testing.T) {
db := setupAgentTeamScheduleTestDB(t)
createAgentTeamScheduleTestTeams(t, db)
targetDay := time.Now().AddDate(0, 0, 2)
existing := models.AgentTeamSchedule{
TeamID: 1,
StartAt: parseTestDateTime(t, formatTestDateTime(targetDay, "10:00:00")),
EndAt: parseTestDateTime(t, formatTestDateTime(targetDay, "12:00:00")),
Status: enums.StatusDisabled,
}
if err := db.Create(&existing).Error; err != nil {
t.Fatalf("create existing schedule error = %v", err)
}
preview, err := services.AgentTeamScheduleService.BatchPreview(request.AgentTeamScheduleBatchRequest{
TeamIDs: []int64{1},
StartDate: targetDay.Format(time.DateOnly),
EndDate: targetDay.Format(time.DateOnly),
Weekdays: []int{weekdayForRequest(targetDay)},
StartTime: "09:00",
EndTime: "18:00",
}, testOperator())
if err != nil {
t.Fatalf("BatchPreview() error = %v", err)
}
if preview.Conflict {
t.Fatalf("expected disabled overlapping schedule to be ignored, got %+v", preview)
}
if len(preview.Items) != 1 || preview.Items[0].Conflict {
t.Fatalf("expected one non-conflicting preview item, got %+v", preview.Items)
}
}
func TestAgentTeamScheduleServiceBatchGenerateCreatesAllSchedules(t *testing.T) {
db := setupAgentTeamScheduleTestDB(t)
createAgentTeamScheduleTestTeams(t, db)
nextMonday := nextTestWeekday(time.Monday)
result, err := services.AgentTeamScheduleService.BatchGenerate(request.AgentTeamScheduleBatchRequest{
TeamIDs: []int64{1, 2},
StartDate: nextMonday.Format(time.DateOnly),
EndDate: nextMonday.AddDate(0, 0, 2).Format(time.DateOnly),
Weekdays: []int{1, 3},
StartTime: "09:00",
EndTime: "18:00",
Remark: "批量生成",
}, testOperator())
if err != nil {
t.Fatalf("BatchGenerate() error = %v", err)
}
if result.Created != 4 {
t.Fatalf("expected 4 created schedules, got %d", result.Created)
}
var schedules []models.AgentTeamSchedule
if err := db.Where("remark = ?", "批量生成").
Order("team_id ASC, start_at ASC").
Find(&schedules).Error; err != nil {
t.Fatalf("query generated schedules error = %v", err)
}
if len(schedules) != 4 {
t.Fatalf("expected 4 stored schedules, got %d: %+v", len(schedules), schedules)
}
expected := []struct {
teamID int64
startAt string
endAt string
}{
{teamID: 1, startAt: formatTestDateTime(nextMonday, "09:00:00"), endAt: formatTestDateTime(nextMonday, "18:00:00")},
{teamID: 1, startAt: formatTestDateTime(nextMonday.AddDate(0, 0, 2), "09:00:00"), endAt: formatTestDateTime(nextMonday.AddDate(0, 0, 2), "18:00:00")},
{teamID: 2, startAt: formatTestDateTime(nextMonday, "09:00:00"), endAt: formatTestDateTime(nextMonday, "18:00:00")},
{teamID: 2, startAt: formatTestDateTime(nextMonday.AddDate(0, 0, 2), "09:00:00"), endAt: formatTestDateTime(nextMonday.AddDate(0, 0, 2), "18:00:00")},
}
for i, want := range expected {
got := schedules[i]
if got.TeamID != want.teamID ||
got.StartAt.Format(time.DateTime) != want.startAt ||
got.EndAt.Format(time.DateTime) != want.endAt {
t.Fatalf("unexpected schedule at index %d: got teamID=%d startAt=%s endAt=%s, want teamID=%d startAt=%s endAt=%s",
i,
got.TeamID,
got.StartAt.Format(time.DateTime),
got.EndAt.Format(time.DateTime),
want.teamID,
want.startAt,
want.endAt,
)
}
}
}
func TestAgentTeamScheduleServiceBatchGenerateRejectsConflictsWithoutPartialCreate(t *testing.T) {
db := setupAgentTeamScheduleTestDB(t)
createAgentTeamScheduleTestTeams(t, db)
targetDay := time.Now().AddDate(0, 0, 2)
existing := models.AgentTeamSchedule{
TeamID: 1,
StartAt: parseTestDateTime(t, formatTestDateTime(targetDay, "10:00:00")),
EndAt: parseTestDateTime(t, formatTestDateTime(targetDay, "12:00:00")),
Status: enums.StatusOk,
}
if err := db.Create(&existing).Error; err != nil {
t.Fatalf("create existing schedule error = %v", err)
}
_, err := services.AgentTeamScheduleService.BatchGenerate(request.AgentTeamScheduleBatchRequest{
TeamIDs: []int64{1, 2},
StartDate: targetDay.Format(time.DateOnly),
EndDate: targetDay.Format(time.DateOnly),
Weekdays: []int{weekdayForRequest(targetDay)},
StartTime: "09:00",
EndTime: "18:00",
Remark: "不应创建",
}, testOperator())
if err == nil {
t.Fatalf("expected conflict batch generate to fail")
}
var count int64
db.Model(&models.AgentTeamSchedule{}).Where("remark = ?", "不应创建").Count(&count)
if count != 0 {
t.Fatalf("expected no partial creates, got %d", count)
}
}
func setupAgentTeamScheduleTestDB(t *testing.T) *gorm.DB {
t.Helper()
dbName := strings.NewReplacer("/", "_", " ", "_").Replace(t.Name())
db, err := gorm.Open(sqlite.Open("file:"+dbName+"?mode=memory&cache=shared"), &gorm.Config{
NamingStrategy: schema.NamingStrategy{
TablePrefix: "t_",
SingularTable: true,
},
})
if err != nil {
t.Fatalf("open sqlite error = %v", err)
}
t.Cleanup(func() {
sqlDB, err := db.DB()
if err == nil {
_ = sqlDB.Close()
}
})
if err := db.AutoMigrate(&models.AgentTeam{}, &models.AgentTeamSchedule{}); err != nil {
t.Fatalf("auto migrate error = %v", err)
}
sqls.SetDB(db)
return db
}
func createAgentTeamScheduleTestData(t *testing.T, db *gorm.DB) {
t.Helper()
createAgentTeamScheduleTestTeams(t, db)
parse := func(value string) time.Time {
t.Helper()
ret, err := time.ParseInLocation(time.DateTime, value, time.Local)
if err != nil {
t.Fatalf("parse time %q error = %v", value, err)
}
return ret
}
schedules := []models.AgentTeamSchedule{
{ID: 1, TeamID: 1, StartAt: parse("2026-04-26 20:00:00"), EndAt: parse("2026-04-27 10:00:00"), Status: enums.StatusOk},
{ID: 2, TeamID: 1, StartAt: parse("2026-04-28 09:00:00"), EndAt: parse("2026-04-28 18:00:00"), Status: enums.StatusOk},
{ID: 3, TeamID: 2, StartAt: parse("2026-05-03 20:00:00"), EndAt: parse("2026-05-04 08:00:00"), Status: enums.StatusOk},
{ID: 4, TeamID: 1, StartAt: parse("2026-04-20 09:00:00"), EndAt: parse("2026-04-20 18:00:00"), Status: enums.StatusOk},
{ID: 5, TeamID: 2, StartAt: parse("2026-05-04 09:00:00"), EndAt: parse("2026-05-04 18:00:00"), Status: enums.StatusOk},
}
if err := db.Create(&schedules).Error; err != nil {
t.Fatalf("create schedules error = %v", err)
}
}
func createAgentTeamScheduleTestTeams(t *testing.T, db *gorm.DB) {
t.Helper()
teams := []models.AgentTeam{
{ID: 1, Name: "售前组", Status: enums.StatusOk},
{ID: 2, Name: "售后组", Status: enums.StatusOk},
}
if err := db.Create(&teams).Error; err != nil {
t.Fatalf("create teams error = %v", err)
}
}
func formatTestDateTime(date time.Time, clock string) string {
return date.Format(time.DateOnly) + " " + clock
}
func nextTestWeekday(target time.Weekday) time.Time {
ret := startOfTestDay(time.Now()).AddDate(0, 0, 1)
for ret.Weekday() != target {
ret = ret.AddDate(0, 0, 1)
}
return ret
}
func startOfTestDay(value time.Time) time.Time {
year, month, day := value.In(time.Local).Date()
return time.Date(year, month, day, 0, 0, 0, 0, time.Local)
}
func weekdayForRequest(value time.Time) int {
if value.Weekday() == time.Sunday {
return 7
}
return int(value.Weekday())
}
func createFutureAgentTeamSchedule(t *testing.T, db *gorm.DB) int64 {
t.Helper()
tomorrow := time.Now().AddDate(0, 0, 1)
item := models.AgentTeamSchedule{
TeamID: 1,
StartAt: parseTestDateTime(t, formatTestDateTime(tomorrow, "09:00:00")),
EndAt: parseTestDateTime(t, formatTestDateTime(tomorrow, "18:00:00")),
Status: enums.StatusOk,
}
if err := db.Create(&item).Error; err != nil {
t.Fatalf("create future schedule error = %v", err)
}
return item.ID
}
func parseTestDateTime(t *testing.T, value string) time.Time {
t.Helper()
ret, err := time.ParseInLocation(time.DateTime, value, time.Local)
if err != nil {
t.Fatalf("parse time %q error = %v", value, err)
}
return ret
}
func testOperator() *dto.AuthPrincipal {
return &dto.AuthPrincipal{UserID: 1, Username: "tester", Status: enums.StatusOk}
}
@@ -0,0 +1,533 @@
"use client"
import { useEffect, useMemo, useRef, useState } from "react"
import { ArrowLeftIcon, CheckIcon, Loader2Icon, XIcon } from "lucide-react"
import { toast } from "sonner"
import { OptionCombobox } from "@/components/option-combobox"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table"
import { Textarea } from "@/components/ui/textarea"
import {
fetchAgentTeamsAll,
generateAgentTeamScheduleBatch,
previewAgentTeamScheduleBatch,
type AdminAgentTeam,
type AdminAgentTeamScheduleBatchPreview,
type BatchAdminAgentTeamSchedulePayload,
} from "@/lib/api/admin"
import { cn } from "@/lib/utils"
type BatchScheduleDialogProps = {
open: boolean
onOpenChange: (open: boolean) => void
onSuccess: (created: number) => void | Promise<void>
}
const weekdayOptions = [
{ value: 1, label: "周一" },
{ value: 2, label: "周二" },
{ value: 3, label: "周三" },
{ value: 4, label: "周四" },
{ value: 5, label: "周五" },
{ value: 6, label: "周六" },
{ value: 7, label: "周日" },
]
function todayDateValue() {
const today = new Date()
const year = today.getFullYear()
const month = String(today.getMonth() + 1).padStart(2, "0")
const day = String(today.getDate()).padStart(2, "0")
return `${year}-${month}-${day}`
}
function defaultFormState() {
const today = todayDateValue()
return {
selectedTeamIds: [] as number[],
startDate: today,
endDate: today,
weekdays: [1, 2, 3, 4, 5],
startTime: "09:00",
endTime: "18:00",
remark: "",
}
}
type BatchFormState = ReturnType<typeof defaultFormState>
type DialogStep = "form" | "preview"
function buildPayload(form: BatchFormState): BatchAdminAgentTeamSchedulePayload {
return {
teamIds: [...form.selectedTeamIds],
startDate: form.startDate,
endDate: form.endDate,
weekdays: [...form.weekdays],
startTime: form.startTime,
endTime: form.endTime,
remark: form.remark.trim(),
}
}
function getWeekdayLabel(value: number) {
return weekdayOptions.find((option) => option.value === value)?.label ?? `${value}`
}
function validateForm(form: BatchFormState) {
const today = todayDateValue()
if (form.selectedTeamIds.length === 0) {
return "请选择至少一个客服组"
}
if (!form.startDate || !form.endDate) {
return "请选择日期范围"
}
if (form.startDate < today) {
return "开始日期不能早于今天"
}
if (form.endDate < form.startDate) {
return "结束日期不能早于开始日期"
}
if (form.weekdays.length === 0) {
return "请选择至少一个星期"
}
if (!form.startTime || !form.endTime) {
return "请选择开始和结束时间"
}
if (form.endTime <= form.startTime) {
return "结束时间必须晚于开始时间"
}
return ""
}
export function BatchScheduleDialog({
open,
onOpenChange,
onSuccess,
}: BatchScheduleDialogProps) {
const [teams, setTeams] = useState<AdminAgentTeam[]>([])
const [form, setForm] = useState(defaultFormState)
const [step, setStep] = useState<DialogStep>("form")
const [preview, setPreview] = useState<AdminAgentTeamScheduleBatchPreview | null>(null)
const [previewPayload, setPreviewPayload] = useState<BatchAdminAgentTeamSchedulePayload | null>(null)
const [loadingTeams, setLoadingTeams] = useState(false)
const [previewing, setPreviewing] = useState(false)
const [submitting, setSubmitting] = useState(false)
const openRef = useRef(open)
const previewRequestIdRef = useRef(0)
const busy = loadingTeams || previewing || submitting
const teamOptions = useMemo(
() =>
teams
.filter((team) => !form.selectedTeamIds.includes(team.id))
.map((team) => ({ value: String(team.id), label: team.name })),
[form.selectedTeamIds, teams]
)
const selectedTeams = useMemo(() => {
const teamMap = new Map(teams.map((team) => [team.id, team]))
return form.selectedTeamIds.map((teamId) => teamMap.get(teamId)).filter(Boolean) as AdminAgentTeam[]
}, [form.selectedTeamIds, teams])
const selectedWeekdays = useMemo(
() => new Set(form.weekdays),
[form.weekdays]
)
const hasConflict = preview?.conflict === true
useEffect(() => {
openRef.current = open
}, [open])
useEffect(() => {
if (!open) {
previewRequestIdRef.current += 1
setForm(defaultFormState())
setStep("form")
setPreview(null)
setPreviewPayload(null)
setPreviewing(false)
setSubmitting(false)
return
}
let ignore = false
async function loadTeams() {
setLoadingTeams(true)
try {
const data = await fetchAgentTeamsAll()
if (!ignore) {
setTeams(data)
}
} catch (error) {
if (!ignore) {
toast.error(error instanceof Error ? error.message : "加载客服组选项失败")
}
} finally {
if (!ignore) {
setLoadingTeams(false)
}
}
}
void loadTeams()
return () => {
ignore = true
}
}, [open])
function updateForm(values: Partial<BatchFormState>) {
previewRequestIdRef.current += 1
setForm((current) => ({ ...current, ...values }))
setPreview(null)
setPreviewPayload(null)
setPreviewing(false)
setStep("form")
}
function handleOpenChange(nextOpen: boolean) {
if (!nextOpen && busy) {
return
}
onOpenChange(nextOpen)
}
function handleTeamSelect(value: string) {
const teamId = Number(value)
if (!Number.isFinite(teamId) || form.selectedTeamIds.includes(teamId)) {
return
}
updateForm({ selectedTeamIds: [...form.selectedTeamIds, teamId] })
}
function removeTeam(teamId: number) {
updateForm({
selectedTeamIds: form.selectedTeamIds.filter((selectedTeamId) => selectedTeamId !== teamId),
})
}
function toggleWeekday(weekday: number) {
const nextWeekdays = selectedWeekdays.has(weekday)
? form.weekdays.filter((value) => value !== weekday)
: [...form.weekdays, weekday].sort((a, b) => a - b)
updateForm({ weekdays: nextWeekdays })
}
async function handlePreview() {
const validationMessage = validateForm(form)
if (validationMessage) {
toast.error(validationMessage)
return
}
const payload = buildPayload(form)
const requestId = previewRequestIdRef.current + 1
previewRequestIdRef.current = requestId
setPreviewing(true)
try {
const data = await previewAgentTeamScheduleBatch(payload)
if (!openRef.current || previewRequestIdRef.current !== requestId) {
return
}
setPreview(data)
setPreviewPayload(payload)
setStep("preview")
} catch (error) {
if (openRef.current && previewRequestIdRef.current === requestId) {
toast.error(error instanceof Error ? error.message : "预览批量排班失败")
}
} finally {
if (openRef.current && previewRequestIdRef.current === requestId) {
setPreviewing(false)
}
}
}
async function handleSubmit() {
if (!preview || !previewPayload) {
toast.error("请先预览批量排班")
return
}
if (preview.conflict) {
toast.error("存在冲突排班,不能提交")
return
}
const payload = previewPayload
setSubmitting(true)
try {
const data = await generateAgentTeamScheduleBatch(payload)
toast.success(`已创建 ${data.created} 条客服组排班`)
setPreview(null)
setPreviewPayload(null)
onOpenChange(false)
try {
await onSuccess(data.created)
} catch (error) {
toast.error(error instanceof Error ? `排班已生成,但刷新列表失败:${error.message}` : "排班已生成,但刷新列表失败")
}
} catch (error) {
toast.error(error instanceof Error ? error.message : "生成批量排班失败")
} finally {
setSubmitting(false)
}
}
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogContent className="flex max-h-[calc(100vh-2rem)] flex-col gap-0 overflow-hidden p-0 sm:max-w-4xl">
<DialogHeader className="shrink-0 px-6 pt-6">
<DialogTitle></DialogTitle>
<DialogDescription>
</DialogDescription>
</DialogHeader>
<div className="min-h-0 flex-1 overflow-y-auto px-6 py-5">
{step === "form" ? (
<div className="space-y-5">
<div className="space-y-2">
<Label></Label>
<div className="flex gap-2">
<div className="min-w-0 flex-1">
<OptionCombobox
value=""
options={teamOptions}
placeholder={loadingTeams ? "加载客服组中..." : "添加客服组"}
searchPlaceholder="搜索客服组"
emptyText={teams.length === 0 ? "暂无客服组" : "已选择全部客服组"}
disabled={loadingTeams}
onChange={handleTeamSelect}
/>
</div>
</div>
{selectedTeams.length > 0 ? (
<div className="flex flex-wrap gap-2">
{selectedTeams.map((team) => (
<Badge key={team.id} variant="secondary" className="gap-1 pr-1">
<span className="max-w-44 truncate">{team.name}</span>
<Button
type="button"
variant="ghost"
size="icon-sm"
className="size-5 rounded-sm"
onClick={() => removeTeam(team.id)}
aria-label={`移除${team.name}`}
>
<XIcon className="size-3" />
</Button>
</Badge>
))}
</div>
) : (
<div className="text-sm text-muted-foreground"></div>
)}
</div>
<div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-2">
<Label htmlFor="batch-schedule-start-date"></Label>
<Input
id="batch-schedule-start-date"
type="date"
min={todayDateValue()}
value={form.startDate}
onChange={(event) => updateForm({ startDate: event.target.value })}
/>
</div>
<div className="space-y-2">
<Label htmlFor="batch-schedule-end-date"></Label>
<Input
id="batch-schedule-end-date"
type="date"
min={form.startDate || todayDateValue()}
value={form.endDate}
onChange={(event) => updateForm({ endDate: event.target.value })}
/>
</div>
</div>
<div className="space-y-2">
<Label></Label>
<div className="flex flex-wrap gap-2">
{weekdayOptions.map((option) => {
const selected = selectedWeekdays.has(option.value)
return (
<Button
key={option.value}
type="button"
variant={selected ? "default" : "outline"}
size="sm"
aria-pressed={selected}
onClick={() => toggleWeekday(option.value)}
>
{selected ? <CheckIcon className="size-4" /> : null}
{option.label}
</Button>
)
})}
</div>
</div>
<div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-2">
<Label htmlFor="batch-schedule-start-time"></Label>
<Input
id="batch-schedule-start-time"
type="time"
value={form.startTime}
onChange={(event) => updateForm({ startTime: event.target.value })}
/>
</div>
<div className="space-y-2">
<Label htmlFor="batch-schedule-end-time"></Label>
<Input
id="batch-schedule-end-time"
type="time"
value={form.endTime}
onChange={(event) => updateForm({ endTime: event.target.value })}
/>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="batch-schedule-remark"></Label>
<Textarea
id="batch-schedule-remark"
rows={4}
placeholder="请输入备注"
value={form.remark}
onChange={(event) => updateForm({ remark: event.target.value })}
/>
</div>
</div>
) : (
<div className="space-y-4">
<div className="flex flex-wrap items-center justify-between gap-2">
<div className="text-sm text-muted-foreground">
{preview?.total ?? 0}
{hasConflict ? ",存在冲突,请返回调整" : ",确认无冲突后可生成"}
</div>
{hasConflict ? (
<Badge variant="destructive"></Badge>
) : (
<Badge variant="secondary"></Badge>
)}
</div>
<div className="overflow-x-auto rounded-lg border">
<div className="min-w-[760px]">
<Table>
<TableHeader className="bg-muted/40">
<TableRow>
<TableHead></TableHead>
<TableHead></TableHead>
<TableHead></TableHead>
<TableHead></TableHead>
<TableHead></TableHead>
<TableHead></TableHead>
</TableRow>
</TableHeader>
<TableBody>
{preview?.items.map((item, index) => (
<TableRow
key={`${item.teamId}-${item.startAt}-${index}`}
className={cn(
item.conflict && "bg-destructive/10 text-destructive hover:bg-destructive/10"
)}
>
<TableCell>
<div className="font-medium">{item.teamName || `客服组#${item.teamId}`}</div>
<div className="text-xs text-muted-foreground">ID{item.teamId}</div>
</TableCell>
<TableCell>{item.date}</TableCell>
<TableCell>{getWeekdayLabel(item.weekday)}</TableCell>
<TableCell>
{item.startAt.slice(11, 16)} - {item.endAt.slice(11, 16)}
</TableCell>
<TableCell className="max-w-56 truncate">{item.remark || "-"}</TableCell>
<TableCell>
{item.conflict ? (
<span className="font-medium">
{item.conflictReason || "排班冲突"}
</span>
) : (
<span className="text-muted-foreground"></span>
)}
</TableCell>
</TableRow>
))}
{preview && preview.items.length === 0 ? (
<TableRow>
<TableCell colSpan={6} className="py-10 text-center text-muted-foreground">
</TableCell>
</TableRow>
) : null}
</TableBody>
</Table>
</div>
</div>
</div>
)}
</div>
<DialogFooter className="mx-0 mb-0 shrink-0 border-t px-6 py-4">
{step === "preview" ? (
<Button
type="button"
variant="outline"
onClick={() => setStep("form")}
disabled={submitting}
>
<ArrowLeftIcon />
</Button>
) : null}
<Button
type="button"
variant="outline"
onClick={() => handleOpenChange(false)}
disabled={busy}
>
</Button>
{step === "form" ? (
<Button type="button" onClick={() => void handlePreview()} disabled={busy}>
{previewing ? <Loader2Icon className="animate-spin" /> : <CheckIcon />}
</Button>
) : (
<Button
type="button"
onClick={() => void handleSubmit()}
disabled={submitting || hasConflict || !preview || !previewPayload || preview.items.length === 0}
>
{submitting ? <Loader2Icon className="animate-spin" /> : <CheckIcon />}
</Button>
)}
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,19 @@
import assert from "node:assert/strict"
import test from "node:test"
import { addDays, formatWeekTitle, isSameLocalDay, startOfWeek } from "./calendar-date-range.ts"
test("builds Monday-based week range and title", () => {
const start = startOfWeek(new Date(2026, 3, 29, 14, 0, 0))
assert.equal(start.getFullYear(), 2026)
assert.equal(start.getMonth(), 3)
assert.equal(start.getDate(), 27)
assert.equal(formatWeekTitle(start), "2026-04-27 - 2026-05-03")
assert.equal(addDays(start, 7).getDate(), 4)
})
test("compares local calendar dates", () => {
assert.equal(isSameLocalDay(new Date(2026, 3, 29, 0, 0), new Date(2026, 3, 29, 23, 59)), true)
assert.equal(isSameLocalDay(new Date(2026, 3, 29, 23, 59), new Date(2026, 3, 30, 0, 0)), false)
})
@@ -0,0 +1,72 @@
export function startOfDay(date: Date) {
const ret = new Date(date)
ret.setHours(0, 0, 0, 0)
return ret
}
export function startOfWeek(date: Date) {
const ret = startOfDay(date)
const day = ret.getDay()
const offset = day === 0 ? -6 : 1 - day
ret.setDate(ret.getDate() + offset)
return ret
}
export function isSameLocalDay(a: Date, b: Date) {
return a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate()
}
export function startOfMonth(date: Date) {
const ret = startOfDay(date)
ret.setDate(1)
return ret
}
export function startOfMonthCalendar(date: Date) {
return startOfWeek(startOfMonth(date))
}
export function endOfMonthCalendar(date: Date) {
const monthEnd = startOfMonth(date)
monthEnd.setMonth(monthEnd.getMonth() + 1)
const ret = startOfWeek(monthEnd)
if (ret.getTime() < monthEnd.getTime()) {
ret.setDate(ret.getDate() + 7)
}
return ret
}
export function addDays(date: Date, days: number) {
const ret = new Date(date)
ret.setDate(ret.getDate() + days)
return ret
}
export function addMonths(date: Date, months: number) {
const ret = startOfMonth(date)
ret.setMonth(ret.getMonth() + months)
return ret
}
export function formatDateTimeValue(date: Date) {
const month = String(date.getMonth() + 1).padStart(2, "0")
const day = String(date.getDate()).padStart(2, "0")
const hour = String(date.getHours()).padStart(2, "0")
const minute = String(date.getMinutes()).padStart(2, "0")
const second = String(date.getSeconds()).padStart(2, "0")
return `${date.getFullYear()}-${month}-${day} ${hour}:${minute}:${second}`
}
export function formatMonthTitle(monthStart: Date) {
return `${monthStart.getFullYear()}${String(monthStart.getMonth() + 1).padStart(2, "0")}`
}
function formatDate(date: Date) {
const month = String(date.getMonth() + 1).padStart(2, "0")
const day = String(date.getDate()).padStart(2, "0")
return `${date.getFullYear()}-${month}-${day}`
}
export function formatWeekTitle(weekStart: Date) {
return `${formatDate(weekStart)} - ${formatDate(addDays(weekStart, 6))}`
}
@@ -0,0 +1,59 @@
import assert from "node:assert/strict"
import test from "node:test"
import { buildDayTimeLayout } from "./calendar-time-layout.ts"
test("scales schedule bars by the visible span of that day", () => {
const layout = buildDayTimeLayout(
[
{ id: 1, startAt: "2026-04-29 07:00:00", endAt: "2026-04-29 17:00:00" },
{ id: 2, startAt: "2026-04-29 09:00:00", endAt: "2026-04-29 12:00:00" },
{ id: 3, startAt: "2026-04-29 13:00:00", endAt: "2026-04-29 17:00:00" },
],
new Date(2026, 3, 29)
)
assert.equal(layout.rangeLabel, "07:00 - 17:00")
assert.deepEqual(layout.items.get(1), {
leftPercent: 0,
widthPercent: 100,
startLabel: "07:00",
endLabel: "17:00",
})
assert.deepEqual(layout.items.get(2), {
leftPercent: 20,
widthPercent: 30,
startLabel: "09:00",
endLabel: "12:00",
})
assert.deepEqual(layout.items.get(3), {
leftPercent: 60,
widthPercent: 40,
startLabel: "13:00",
endLabel: "17:00",
})
})
test("clips cross-day schedules to the current day before scaling", () => {
const layout = buildDayTimeLayout(
[
{ id: 1, startAt: "2026-04-28 22:00:00", endAt: "2026-04-29 08:00:00" },
{ id: 2, startAt: "2026-04-29 07:00:00", endAt: "2026-04-29 17:00:00" },
],
new Date(2026, 3, 29)
)
assert.equal(layout.rangeLabel, "00:00 - 17:00")
assert.deepEqual(layout.items.get(1), {
leftPercent: 0,
widthPercent: 47.06,
startLabel: "00:00",
endLabel: "08:00",
})
assert.deepEqual(layout.items.get(2), {
leftPercent: 41.18,
widthPercent: 58.82,
startLabel: "07:00",
endLabel: "17:00",
})
})
@@ -0,0 +1,87 @@
const dayMs = 24 * 60 * 60 * 1000
export type TimeLayoutSchedule = {
id: number
startAt: string
endAt: string
}
export type TimeLayoutItem = {
leftPercent: number
widthPercent: number
startLabel: string
endLabel: string
}
export type DayTimeLayout = {
rangeLabel: string
items: Map<number, TimeLayoutItem>
}
function parseLocalDateTime(value: string) {
const match = value.match(/^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2})(?::(\d{2}))?/)
if (!match) {
return new Date(value)
}
return new Date(
Number(match[1]),
Number(match[2]) - 1,
Number(match[3]),
Number(match[4]),
Number(match[5]),
Number(match[6] ?? 0)
)
}
function startOfDay(date: Date) {
const ret = new Date(date)
ret.setHours(0, 0, 0, 0)
return ret
}
function formatTime(date: Date) {
const hour = String(date.getHours()).padStart(2, "0")
const minute = String(date.getMinutes()).padStart(2, "0")
return `${hour}:${minute}`
}
function roundPercent(value: number) {
return Math.round(value * 100) / 100
}
export function buildDayTimeLayout(schedules: TimeLayoutSchedule[], day: Date): DayTimeLayout {
const dayStart = startOfDay(day)
const dayEnd = new Date(dayStart.getTime() + dayMs)
const visibleItems = schedules
.map((item) => {
const scheduleStart = parseLocalDateTime(item.startAt)
const scheduleEnd = parseLocalDateTime(item.endAt)
const visibleStart = new Date(Math.max(scheduleStart.getTime(), dayStart.getTime()))
const visibleEnd = new Date(Math.min(scheduleEnd.getTime(), dayEnd.getTime()))
return { item, visibleStart, visibleEnd }
})
.filter(({ visibleStart, visibleEnd }) => visibleEnd > visibleStart)
if (visibleItems.length === 0) {
return { rangeLabel: "", items: new Map() }
}
const rangeStart = new Date(Math.min(...visibleItems.map(({ visibleStart }) => visibleStart.getTime())))
const rangeEnd = new Date(Math.max(...visibleItems.map(({ visibleEnd }) => visibleEnd.getTime())))
const rangeMs = Math.max(rangeEnd.getTime() - rangeStart.getTime(), 1)
const items = new Map<number, TimeLayoutItem>()
visibleItems.forEach(({ item, visibleStart, visibleEnd }) => {
items.set(item.id, {
leftPercent: roundPercent(((visibleStart.getTime() - rangeStart.getTime()) / rangeMs) * 100),
widthPercent: roundPercent(((visibleEnd.getTime() - visibleStart.getTime()) / rangeMs) * 100),
startLabel: formatTime(visibleStart),
endLabel: formatTime(visibleEnd),
})
})
return {
rangeLabel: `${formatTime(rangeStart)} - ${formatTime(rangeEnd)}`,
items,
}
}
@@ -0,0 +1,591 @@
"use client"
import { CalendarPlusIcon, GripVerticalIcon } from "lucide-react"
import { useState, type PointerEvent as ReactPointerEvent } from "react"
import type {
AdminAgentTeam,
AdminAgentTeamSchedule,
CreateAdminAgentTeamSchedulePayload,
UpdateAdminAgentTeamSchedulePayload,
} from "@/lib/api/admin"
import { cn, formatDateTime } from "@/lib/utils"
import { isSameLocalDay } from "./calendar-date-range"
import { buildDayTimeLayout } from "./calendar-time-layout"
const weekDayNames = ["一", "二", "三", "四", "五", "六", "日"]
const dayMs = 24 * 60 * 60 * 1000
const minuteMs = 60 * 1000
const minDurationMs = 15 * minuteMs
type ScheduleCalendarProps = {
variant?: "month" | "week"
monthStart: Date
calendarStart: Date
calendarEnd: Date
teams: AdminAgentTeam[]
schedules: AdminAgentTeamSchedule[]
loading: boolean
savingId: number | null
onCreate: (defaults: Partial<CreateAdminAgentTeamSchedulePayload>) => void
onEdit: (item: AdminAgentTeamSchedule) => void
onMove: (payload: UpdateAdminAgentTeamSchedulePayload) => Promise<void>
onResize: (payload: UpdateAdminAgentTeamSchedulePayload) => Promise<void>
}
type DragState =
| {
type: "move"
item: AdminAgentTeamSchedule
startX: number
startY: number
moved: boolean
}
| {
type: "resize"
edge: "start" | "end"
item: AdminAgentTeamSchedule
moved: boolean
}
type InteractionPreview = {
itemId: number
date: string | null
label: string
invalid: boolean
x: number
y: number
}
function addDays(date: Date, days: number) {
const ret = new Date(date)
ret.setDate(ret.getDate() + days)
return ret
}
function startOfDay(date: Date) {
const ret = new Date(date)
ret.setHours(0, 0, 0, 0)
return ret
}
function parseLocalDateTime(value: string) {
const match = value.match(/^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2})(?::(\d{2}))?/)
if (!match) {
return new Date(value)
}
return new Date(
Number(match[1]),
Number(match[2]) - 1,
Number(match[3]),
Number(match[4]),
Number(match[5]),
Number(match[6] ?? 0)
)
}
function formatDate(date: Date) {
const month = String(date.getMonth() + 1).padStart(2, "0")
const day = String(date.getDate()).padStart(2, "0")
return `${date.getFullYear()}-${month}-${day}`
}
function formatDateTimeValue(date: Date) {
const month = String(date.getMonth() + 1).padStart(2, "0")
const day = String(date.getDate()).padStart(2, "0")
const hour = String(date.getHours()).padStart(2, "0")
const minute = String(date.getMinutes()).padStart(2, "0")
const second = String(date.getSeconds()).padStart(2, "0")
return `${date.getFullYear()}-${month}-${day} ${hour}:${minute}:${second}`
}
function formatTime(dateTime: string) {
return formatDateTime(dateTime).slice(11, 16)
}
function clamp(value: number, min: number, max: number) {
return Math.min(Math.max(value, min), max)
}
function roundToQuarterHour(date: Date) {
const ret = new Date(date)
ret.setSeconds(0, 0)
const minutes = ret.getHours() * 60 + ret.getMinutes()
const rounded = Math.round(minutes / 15) * 15
ret.setHours(Math.floor(rounded / 60), rounded % 60, 0, 0)
return ret
}
function getPointerDateInCell(event: PointerEvent, cell: Element) {
const rect = cell.getBoundingClientRect()
const day = startOfDay(parseLocalDateTime(`${cell.getAttribute("data-date")} 00:00:00`))
const ratio = clamp((event.clientX - rect.left) / rect.width, 0, 1)
return roundToQuarterHour(new Date(day.getTime() + ratio * dayMs))
}
function getDropCell(event: PointerEvent) {
const element = document.elementFromPoint(event.clientX, event.clientY)
return element?.closest("[data-schedule-cell]")
}
function isHistoricalDay(day: Date) {
return startOfDay(day).getTime() < startOfDay(new Date()).getTime()
}
function buildMovePayload(item: AdminAgentTeamSchedule, date: string): UpdateAdminAgentTeamSchedulePayload {
const originalStart = parseLocalDateTime(item.startAt)
const originalEnd = parseLocalDateTime(item.endAt)
const duration = originalEnd.getTime() - originalStart.getTime()
const nextDay = startOfDay(parseLocalDateTime(`${date} 00:00:00`))
const nextStart = new Date(nextDay)
nextStart.setHours(originalStart.getHours(), originalStart.getMinutes(), originalStart.getSeconds(), 0)
const nextEnd = new Date(nextStart.getTime() + duration)
return {
id: item.id,
teamId: item.teamId,
startAt: formatDateTimeValue(nextStart),
endAt: formatDateTimeValue(nextEnd),
remark: item.remark,
}
}
function buildResizePayload(
item: AdminAgentTeamSchedule,
edge: "start" | "end",
nextTime: Date
): UpdateAdminAgentTeamSchedulePayload | null {
const startAt = parseLocalDateTime(item.startAt)
const endAt = parseLocalDateTime(item.endAt)
if (!isSameLocalDay(startAt, nextTime)) {
return null
}
if (edge === "start") {
if (endAt.getTime() - nextTime.getTime() < minDurationMs) {
return null
}
startAt.setTime(nextTime.getTime())
} else {
if (nextTime.getTime() - startAt.getTime() < minDurationMs) {
return null
}
endAt.setTime(nextTime.getTime())
}
return {
id: item.id,
teamId: item.teamId,
startAt: formatDateTimeValue(startAt),
endAt: formatDateTimeValue(endAt),
remark: item.remark,
}
}
function buildPreviewFromPayload(
itemId: number,
date: string | null,
payload: UpdateAdminAgentTeamSchedulePayload | null,
point: { x: number; y: number },
fallbackLabel: string
): InteractionPreview {
return {
itemId,
date,
label: payload ? `${formatTime(payload.startAt)} - ${formatTime(payload.endAt)}` : fallbackLabel,
invalid: !payload,
x: point.x,
y: point.y,
}
}
function intersectsDay(item: AdminAgentTeamSchedule, day: Date) {
const dayStart = startOfDay(day)
const dayEnd = addDays(dayStart, 1)
const scheduleStart = parseLocalDateTime(item.startAt)
const scheduleEnd = parseLocalDateTime(item.endAt)
return scheduleStart < dayEnd && scheduleEnd > dayStart
}
function buildCalendarDays(calendarStart: Date, calendarEnd: Date) {
const days: Date[] = []
for (let current = startOfDay(calendarStart); current < calendarEnd; current = addDays(current, 1)) {
days.push(current)
}
return days
}
export function ScheduleCalendar({
variant = "month",
monthStart,
calendarStart,
calendarEnd,
teams,
schedules,
loading,
savingId,
onCreate,
onEdit,
onMove,
onResize,
}: ScheduleCalendarProps) {
const days = buildCalendarDays(calendarStart, calendarEnd)
const defaultTeamID = teams[0]?.id ?? 0
const [interactionPreview, setInteractionPreview] = useState<InteractionPreview | null>(null)
function handleBlankCellClick(day: Date) {
const startAt = new Date(day)
startAt.setHours(9, 0, 0, 0)
const endAt = new Date(day)
endAt.setHours(18, 0, 0, 0)
onCreate({
teamId: defaultTeamID || undefined,
startAt: formatDateTimeValue(startAt),
endAt: formatDateTimeValue(endAt),
remark: "",
})
}
function buildInteractionPreview(state: DragState, pointerEvent: PointerEvent): InteractionPreview | null {
const cell = getDropCell(pointerEvent)
if (!cell) {
return {
itemId: state.item.id,
date: null,
label: "拖到日历日期格内",
invalid: true,
x: pointerEvent.clientX,
y: pointerEvent.clientY,
}
}
const date = cell.getAttribute("data-date")
if (!date) {
return null
}
if (isHistoricalDay(parseLocalDateTime(`${date} 00:00:00`))) {
return {
itemId: state.item.id,
date,
label: "不能修改历史日期",
invalid: true,
x: pointerEvent.clientX,
y: pointerEvent.clientY,
}
}
const point = { x: pointerEvent.clientX, y: pointerEvent.clientY }
if (state.type === "move") {
return buildPreviewFromPayload(state.item.id, date, buildMovePayload(state.item, date), point, "无法移动到这里")
}
const payload = buildResizePayload(state.item, state.edge, getPointerDateInCell(pointerEvent, cell))
return buildPreviewFromPayload(state.item.id, date, payload, point, "不能跨天或少于 15 分钟")
}
function cleanupPointerInteraction(
target: HTMLElement,
pointerId: number,
handlePointerMove: (moveEvent: PointerEvent) => void,
handlePointerUp: (upEvent: PointerEvent) => void,
handlePointerCancel: () => void
) {
if (target.hasPointerCapture(pointerId)) {
target.releasePointerCapture(pointerId)
}
window.removeEventListener("pointermove", handlePointerMove)
window.removeEventListener("pointerup", handlePointerUp)
window.removeEventListener("pointercancel", handlePointerCancel)
setInteractionPreview(null)
}
function handlePointerDown(event: ReactPointerEvent, item: AdminAgentTeamSchedule, type: DragState["type"], edge?: "start" | "end") {
event.preventDefault()
event.stopPropagation()
const target = event.currentTarget as HTMLElement
if (target.isConnected) {
try {
target.setPointerCapture(event.pointerId)
} catch {
// Some synthetic/browser edge events do not expose a capturable pointer id.
}
}
const state: DragState =
type === "resize"
? { type: "resize", edge: edge ?? "end", item, moved: false }
: { type: "move", item, startX: event.clientX, startY: event.clientY, moved: false }
function handlePointerMove(moveEvent: PointerEvent) {
if (state.type === "move") {
if (Math.abs(moveEvent.clientX - state.startX) > 4 || Math.abs(moveEvent.clientY - state.startY) > 4) {
state.moved = true
} else {
return
}
} else {
state.moved = true
}
setInteractionPreview(buildInteractionPreview(state, moveEvent))
}
async function handlePointerUp(upEvent: PointerEvent) {
cleanupPointerInteraction(target, event.pointerId, handlePointerMove, handlePointerUp, handlePointerCancel)
if (!state.moved) {
onEdit(item)
return
}
const cell = getDropCell(upEvent)
if (!cell) {
return
}
if (state.type === "move") {
const date = cell.getAttribute("data-date")
if (!date) {
return
}
if (isHistoricalDay(parseLocalDateTime(`${date} 00:00:00`))) {
return
}
await onMove(buildMovePayload(item, date))
return
}
const payload = buildResizePayload(item, state.edge, getPointerDateInCell(upEvent, cell))
if (payload) {
await onResize(payload)
}
}
function handlePointerCancel() {
cleanupPointerInteraction(target, event.pointerId, handlePointerMove, handlePointerUp, handlePointerCancel)
}
window.addEventListener("pointermove", handlePointerMove)
window.addEventListener("pointerup", handlePointerUp)
window.addEventListener("pointercancel", handlePointerCancel)
}
if (teams.length === 0 && !loading) {
return (
<div className="flex min-h-64 items-center justify-center rounded-lg border bg-background text-sm text-muted-foreground">
</div>
)
}
function renderDayCell(day: Date, dayIndex: number, options?: { inMonth?: boolean; className?: string; showFullDate?: boolean }) {
const date = formatDate(day)
const inMonth = options?.inMonth ?? day.getMonth() === monthStart.getMonth()
const historical = isHistoricalDay(day)
const today = isSameLocalDay(day, new Date())
const daySchedules = schedules
.filter((item) => intersectsDay(item, day))
.sort((a, b) => parseLocalDateTime(a.startAt).getTime() - parseLocalDateTime(b.startAt).getTime())
const dayTimeLayout = buildDayTimeLayout(daySchedules, day)
return (
<div
key={date}
data-schedule-cell
data-date={date}
role="button"
tabIndex={0}
className={cn(
"border-l border-t bg-background p-2 text-left outline-none transition-colors first:border-l-0 hover:bg-muted/20 focus-visible:ring-2 focus-visible:ring-ring",
dayIndex % 7 === 0 && "border-l-0",
!inMonth && "bg-muted/20 text-muted-foreground",
historical && "cursor-not-allowed bg-muted/30 hover:bg-muted/30",
interactionPreview?.date === date &&
(interactionPreview.invalid ? "bg-destructive/5 ring-2 ring-destructive/30" : "bg-primary/5 ring-2 ring-primary/35"),
options?.className
)}
onClick={(event) => {
if ((event.target as HTMLElement).closest("[data-schedule-block]")) {
return
}
if (historical) {
return
}
handleBlankCellClick(day)
}}
onKeyDown={(event) => {
if (historical) {
return
}
if (event.key === "Enter" || event.key === " ") {
event.preventDefault()
handleBlankCellClick(day)
}
}}
>
<div className="mb-2 flex items-start justify-between gap-2">
<div>
<div className={cn("text-sm font-medium", !inMonth && "text-muted-foreground")}>
{options?.showFullDate ? date : day.getDate()}
</div>
{dayTimeLayout.rangeLabel ? (
<div className="mt-0.5 text-[10px] leading-none text-muted-foreground">{dayTimeLayout.rangeLabel}</div>
) : null}
</div>
<div className="flex shrink-0 items-center gap-1">
{today ? (
<span className="rounded-sm bg-primary px-1.5 py-0.5 text-[10px] font-medium leading-none text-primary-foreground">
</span>
) : null}
{historical ? null : <CalendarPlusIcon className="size-3.5 text-muted-foreground" />}
</div>
</div>
<div className="space-y-1">
{daySchedules.slice(0, 5).map((item) => {
const teamName = item.teamName || teams.find((team) => team.id === item.teamId)?.name || `客服组#${item.teamId}`
const busy = savingId === item.id
const active = interactionPreview?.itemId === item.id
const timeLayout = dayTimeLayout.items.get(item.id)
const readonly = historical || isHistoricalDay(parseLocalDateTime(item.startAt))
return (
<div key={`${item.id}-${date}`} className="relative h-10 rounded-sm bg-muted/25">
<div
data-schedule-block
data-time-left={timeLayout?.leftPercent ?? 0}
data-time-width={timeLayout?.widthPercent ?? 100}
role="button"
tabIndex={0}
className={cn(
"absolute inset-y-0 cursor-grab overflow-hidden rounded-md border border-primary/20 bg-primary/10 px-2 py-1.5 pl-4 pr-4 text-primary shadow-sm outline-none transition active:cursor-grabbing",
active && "scale-[0.98] border-primary/50 bg-primary/15 opacity-80 ring-2 ring-primary/30",
readonly && "cursor-not-allowed opacity-60",
busy && "pointer-events-none opacity-60"
)}
style={{
left: `${timeLayout?.leftPercent ?? 0}%`,
width: `${timeLayout?.widthPercent ?? 100}%`,
minWidth: 34,
}}
onPointerDown={(event) => {
if (readonly) {
event.preventDefault()
event.stopPropagation()
return
}
handlePointerDown(event, item, "move")
}}
onKeyDown={(event) => {
if (readonly) {
return
}
if (event.key === "Enter" || event.key === " ") {
event.preventDefault()
onEdit(item)
}
}}
>
<div
className="absolute left-0 top-0 flex h-full w-3 cursor-ew-resize items-center justify-center bg-primary/15"
onPointerDown={(event) => {
if (readonly) {
event.preventDefault()
event.stopPropagation()
return
}
handlePointerDown(event, item, "resize", "start")
}}
>
<GripVerticalIcon className="size-3" />
</div>
<div
className="absolute right-0 top-0 flex h-full w-3 cursor-ew-resize items-center justify-center bg-primary/15"
onPointerDown={(event) => {
if (readonly) {
event.preventDefault()
event.stopPropagation()
return
}
handlePointerDown(event, item, "resize", "end")
}}
>
<GripVerticalIcon className="size-3" />
</div>
<div className="truncate text-xs font-medium">{teamName}</div>
<div className="truncate text-xs">
{timeLayout ? `${timeLayout.startLabel} - ${timeLayout.endLabel}` : `${formatTime(item.startAt)} - ${formatTime(item.endAt)}`}
</div>
{item.remark ? <div className="truncate text-[11px] text-primary/80">{item.remark}</div> : null}
</div>
</div>
)
})}
{daySchedules.length > 5 ? (
<div className="text-xs text-muted-foreground"> {daySchedules.length - 5} </div>
) : null}
</div>
</div>
)
}
if (variant === "week") {
return (
<div className="min-w-[760px] overflow-hidden rounded-lg border bg-background">
<div className={cn("divide-y", loading && "opacity-60")}>
{days.map((day, dayIndex) => {
const date = formatDate(day)
return (
<div key={date} className="grid grid-cols-[112px_minmax(0,1fr)]">
<div className="border-r bg-muted/40 px-3 py-3 text-sm font-medium">
<div>{weekDayNames[dayIndex] ?? ""}</div>
<div className="mt-1 text-xs font-normal text-muted-foreground">{date.slice(5)}</div>
</div>
{renderDayCell(day, dayIndex, {
inMonth: true,
className: "min-h-24 border-l-0 border-t-0",
showFullDate: false,
})}
</div>
)
})}
</div>
{interactionPreview ? (
<div
data-schedule-preview
className={cn(
"pointer-events-none fixed z-50 rounded-md border bg-popover px-3 py-2 text-xs font-medium text-popover-foreground shadow-md",
interactionPreview.invalid && "border-destructive/40 bg-destructive text-destructive-foreground"
)}
style={{
left: interactionPreview.x + 12,
top: interactionPreview.y + 12,
}}
>
{interactionPreview.label}
</div>
) : null}
</div>
)
}
return (
<div className="min-w-[960px] overflow-hidden rounded-lg border bg-background">
<div className="grid grid-cols-7 border-b bg-muted/40">
{weekDayNames.map((name) => (
<div key={name} className="flex h-10 items-center justify-center border-l first:border-l-0 text-sm font-medium">
{name}
</div>
))}
</div>
<div className={cn("grid grid-cols-7", loading && "opacity-60")}>
{days.map((day, dayIndex) => renderDayCell(day, dayIndex, { className: "min-h-36" }))}
</div>
{interactionPreview ? (
<div
data-schedule-preview
className={cn(
"pointer-events-none fixed z-50 rounded-md border bg-popover px-3 py-2 text-xs font-medium text-popover-foreground shadow-md",
interactionPreview.invalid && "border-destructive/40 bg-destructive text-destructive-foreground"
)}
style={{
left: interactionPreview.x + 12,
top: interactionPreview.y + 12,
}}
>
{interactionPreview.label}
</div>
) : null}
</div>
)
}
@@ -21,7 +21,6 @@ import {
} from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import { OptionCombobox } from "@/components/option-combobox"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Textarea } from "@/components/ui/textarea"
import {
type AdminAgentTeam,
@@ -35,21 +34,16 @@ type ScheduleEditDialogProps = {
open: boolean
saving: boolean
itemId: number | null
defaultValues?: Partial<CreateAdminAgentTeamSchedulePayload> | null
onOpenChange: (open: boolean) => void
onSubmit: (payload: CreateAdminAgentTeamSchedulePayload) => Promise<void>
onDelete?: (id: number) => Promise<void>
}
const sourceTypeOptions = [
{ value: "manual", label: "手工录入" },
{ value: "batch_import", label: "批量导入" },
{ value: "template_generate", label: "模板生成" },
] as const
const emptyForm: EditForm = {
teamId: "",
startAt: "",
endAt: "",
sourceType: "manual",
remark: "",
}
@@ -57,8 +51,35 @@ const editFormSchema = z.object({
teamId: z.string().trim().regex(/^\d+$/, "请选择客服组"),
startAt: z.string().trim().min(1, "开始时间不能为空"),
endAt: z.string().trim().min(1, "结束时间不能为空"),
sourceType: z.enum(["manual", "batch_import", "template_generate"], { message: "请选择排班来源" }),
remark: z.string().trim(),
}).superRefine((value, ctx) => {
const startAt = parseDateTimeLocal(value.startAt)
const endAt = parseDateTimeLocal(value.endAt)
if (!startAt || !endAt) {
return
}
if (!endAt || endAt <= startAt) {
ctx.addIssue({
code: "custom",
path: ["endAt"],
message: "结束时间必须晚于开始时间",
})
return
}
if (!isSameLocalDay(startAt, endAt)) {
ctx.addIssue({
code: "custom",
path: ["endAt"],
message: "单条排班记录不能跨天",
})
}
if (startAt < startOfLocalDay(new Date())) {
ctx.addIssue({
code: "custom",
path: ["startAt"],
message: "不能添加或修改历史日期的排班",
})
}
})
type EditForm = z.infer<typeof editFormSchema>
@@ -75,15 +96,41 @@ function toDateTimeLocal(value?: string) {
return value.replace(" ", "T").slice(0, 16)
}
function buildForm(item: AdminAgentTeamSchedule | null): EditForm {
function parseDateTimeLocal(value: string) {
const ret = new Date(value)
return Number.isNaN(ret.getTime()) ? null : ret
}
function startOfLocalDay(value: Date) {
const ret = new Date(value)
ret.setHours(0, 0, 0, 0)
return ret
}
function isSameLocalDay(a: Date, b: Date) {
return a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate()
}
function todayDateTimeLocalMin() {
const today = startOfLocalDay(new Date())
const month = String(today.getMonth() + 1).padStart(2, "0")
const day = String(today.getDate()).padStart(2, "0")
return `${today.getFullYear()}-${month}-${day}T00:00`
}
function buildForm(item: AdminAgentTeamSchedule | null, defaultValues?: Partial<CreateAdminAgentTeamSchedulePayload> | null): EditForm {
if (!item) {
return emptyForm
return {
teamId: defaultValues?.teamId ? String(defaultValues.teamId) : emptyForm.teamId,
startAt: toDateTimeLocal(defaultValues?.startAt),
endAt: toDateTimeLocal(defaultValues?.endAt),
remark: defaultValues?.remark ?? emptyForm.remark,
}
}
return {
teamId: String(item.teamId),
startAt: toDateTimeLocal(item.startAt),
endAt: toDateTimeLocal(item.endAt),
sourceType: item.sourceType as EditForm["sourceType"],
remark: item.remark || "",
}
}
@@ -93,7 +140,6 @@ function buildPayload(form: EditForm): CreateAdminAgentTeamSchedulePayload {
teamId: Number(form.teamId),
startAt: form.startAt.trim(),
endAt: form.endAt.trim(),
sourceType: form.sourceType,
remark: form.remark.trim(),
}
}
@@ -102,8 +148,10 @@ export function EditDialog({
open,
saving,
itemId,
defaultValues,
onOpenChange,
onSubmit,
onDelete,
}: ScheduleEditDialogProps) {
return (
<Dialog open={open} onOpenChange={onOpenChange}>
@@ -111,9 +159,11 @@ export function EditDialog({
<ScheduleEditDialogBody
key={itemId ? `edit-${itemId}` : "create"}
itemId={itemId}
defaultValues={defaultValues}
saving={saving}
onOpenChange={onOpenChange}
onSubmit={onSubmit}
onDelete={onDelete}
/>
) : null}
</Dialog>
@@ -125,8 +175,10 @@ type ScheduleEditDialogBodyProps = Omit<ScheduleEditDialogProps, "open">
function ScheduleEditDialogBody({
saving,
itemId,
defaultValues,
onOpenChange,
onSubmit,
onDelete,
}: ScheduleEditDialogBodyProps) {
const [teams, setTeams] = useState<AdminAgentTeam[]>([])
const [loading, setLoading] = useState(false)
@@ -153,11 +205,12 @@ function ScheduleEditDialogBody({
register,
formState: { errors },
} = form
const minDateTime = todayDateTimeLocalMin()
useEffect(() => {
async function loadDetail() {
if (!itemId) {
reset(emptyForm)
reset(buildForm(null, defaultValues))
return
}
setLoading(true)
@@ -171,7 +224,7 @@ function ScheduleEditDialogBody({
}
}
void loadDetail()
}, [itemId, reset])
}, [defaultValues, itemId, reset])
useEffect(() => {
void loadOptions()
@@ -221,46 +274,18 @@ function ScheduleEditDialogBody({
<Field data-invalid={!!errors.startAt}>
<FieldLabel htmlFor="agent-team-schedule-start-at"></FieldLabel>
<FieldContent>
<Input id="agent-team-schedule-start-at" type="datetime-local" {...register("startAt")} />
<Input id="agent-team-schedule-start-at" type="datetime-local" min={minDateTime} {...register("startAt")} />
<FieldError errors={[errors.startAt]} />
</FieldContent>
</Field>
<Field data-invalid={!!errors.endAt}>
<FieldLabel htmlFor="agent-team-schedule-end-at"></FieldLabel>
<FieldContent>
<Input id="agent-team-schedule-end-at" type="datetime-local" {...register("endAt")} />
<Input id="agent-team-schedule-end-at" type="datetime-local" min={minDateTime} {...register("endAt")} />
<FieldError errors={[errors.endAt]} />
</FieldContent>
</Field>
</div>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<Field data-invalid={!!errors.sourceType}>
<FieldLabel></FieldLabel>
<FieldContent>
<Controller
control={control}
name="sourceType"
render={({ field }) => (
<Select value={field.value} onValueChange={field.onChange} modal={false}>
<SelectTrigger className="w-full">
<SelectValue>
{sourceTypeOptions.find((item) => item.value === field.value)?.label ?? "请选择来源"}
</SelectValue>
</SelectTrigger>
<SelectContent>
{sourceTypeOptions.map((option) => (
<SelectItem key={option.value} value={option.value}>
{option.label}
</SelectItem>
))}
</SelectContent>
</Select>
)}
/>
<FieldError errors={[errors.sourceType]} />
</FieldContent>
</Field>
</div>
<Field>
<FieldLabel htmlFor="agent-team-schedule-remark"></FieldLabel>
<FieldContent>
@@ -269,6 +294,11 @@ function ScheduleEditDialogBody({
</Field>
</div>
<DialogFooter className="mx-0 mb-0 px-6 py-4">
{itemId && onDelete ? (
<Button type="button" variant="destructive" onClick={() => void onDelete(itemId)} disabled={saving}>
</Button>
) : null}
<Button type="button" variant="outline" onClick={() => onOpenChange(false)} disabled={saving}>
</Button>
+356 -133
View File
@@ -1,8 +1,15 @@
"use client"
import { useCallback, useEffect, useState } from "react"
import { useCallback, useEffect, useMemo, useState } from "react"
import {
CalendarClockIcon,
CalendarDaysIcon,
CalendarRangeIcon,
CalendarSearchIcon,
ChevronLeftIcon,
ChevronRightIcon,
LayersIcon,
ListIcon,
MoreHorizontalIcon,
PlusIcon,
RefreshCwIcon,
@@ -11,30 +18,16 @@ import {
} from "lucide-react"
import { toast } from "sonner"
import {
createAgentTeamSchedule,
deleteAgentTeamSchedule,
fetchAgentTeamSchedules,
fetchAgentTeams,
updateAgentTeamSchedule,
type AdminAgentTeam,
type AdminAgentTeamSchedule,
type CreateAdminAgentTeamSchedulePayload,
type PageResult,
} from "@/lib/api/admin"
import { formatDateTime } from "@/lib/utils"
import { EditDialog } from "./_components/edit"
import { ListPagination } from "@/components/list-pagination"
import { Button } from "@/components/ui/button"
import { ButtonGroup } from "@/components/ui/button-group"
import { OptionCombobox } from "@/components/option-combobox"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { Input } from "@/components/ui/input"
import { ListPagination } from "@/components/list-pagination"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import {
Table,
TableBody,
@@ -43,23 +36,78 @@ import {
TableHeader,
TableRow,
} from "@/components/ui/table"
import {
createAgentTeamSchedule,
deleteAgentTeamSchedule,
fetchAgentTeamScheduleCalendar,
fetchAgentTeamSchedules,
fetchAgentTeamsAll,
updateAgentTeamSchedule,
type AdminAgentTeam,
type AdminAgentTeamSchedule,
type CreateAdminAgentTeamSchedulePayload,
type PageResult,
type UpdateAdminAgentTeamSchedulePayload,
} from "@/lib/api/admin"
import { formatDateTime } from "@/lib/utils"
import { BatchScheduleDialog } from "./_components/batch-schedule-dialog"
import { ScheduleCalendar } from "./_components/calendar"
import {
addDays,
addMonths,
formatDateTimeValue,
formatMonthTitle,
formatWeekTitle,
startOfDay,
startOfMonth,
startOfMonthCalendar,
startOfWeek,
endOfMonthCalendar,
} from "./_components/calendar-date-range"
import { EditDialog } from "./_components/edit"
type ViewMode = "month" | "week" | "list"
function parseLocalDateTime(value: string) {
const ret = new Date(value.replace(" ", "T"))
return Number.isNaN(ret.getTime()) ? null : ret
}
function isHistoricalSchedule(item: AdminAgentTeamSchedule) {
const startAt = parseLocalDateTime(item.startAt)
return !!startAt && startAt < startOfDay(new Date())
}
export default function DashboardAgentTeamSchedulesPage() {
const [viewMode, setViewMode] = useState<ViewMode>("month")
const [teamFilterInput, setTeamFilterInput] = useState("all")
const [teamFilter, setTeamFilter] = useState("all")
const [monthStart, setMonthStart] = useState(() => startOfMonth(new Date()))
const [weekStart, setWeekStart] = useState(() => startOfWeek(new Date()))
const [page, setPage] = useState(1)
const [limit, setLimit] = useState(20)
const [loading, setLoading] = useState(true)
const [calendarLoading, setCalendarLoading] = useState(true)
const [saving, setSaving] = useState(false)
const [actionLoadingId, setActionLoadingId] = useState<number | null>(null)
const [dialogOpen, setDialogOpen] = useState(false)
const [batchDialogOpen, setBatchDialogOpen] = useState(false)
const [editingItem, setEditingItem] = useState<AdminAgentTeamSchedule | null>(null)
const [dialogDefaults, setDialogDefaults] = useState<Partial<CreateAdminAgentTeamSchedulePayload> | null>(null)
const [teams, setTeams] = useState<AdminAgentTeam[]>([])
const [calendarItems, setCalendarItems] = useState<AdminAgentTeamSchedule[]>([])
const [result, setResult] = useState<PageResult<AdminAgentTeamSchedule>>({
results: [],
page: { page: 1, limit: 20, total: 0 },
})
const visibleTeams = useMemo(() => {
if (teamFilter === "all") {
return teams
}
return teams.filter((team) => String(team.id) === teamFilter)
}, [teamFilter, teams])
const loadData = useCallback(async () => {
setLoading(true)
try {
@@ -76,18 +124,49 @@ export default function DashboardAgentTeamSchedulesPage() {
}
}, [limit, page, teamFilter])
const loadCalendarData = useCallback(async () => {
setCalendarLoading(true)
const rangeStart = viewMode === "week" ? weekStart : startOfMonthCalendar(monthStart)
const rangeEnd = viewMode === "week" ? addDays(weekStart, 7) : endOfMonthCalendar(monthStart)
try {
const data = await fetchAgentTeamScheduleCalendar({
startAt: formatDateTimeValue(rangeStart),
endAt: formatDateTimeValue(rangeEnd),
teamId: teamFilter === "all" ? undefined : teamFilter,
})
setCalendarItems(data)
} catch (error) {
toast.error(error instanceof Error ? error.message : "加载客服组排班日历失败")
} finally {
setCalendarLoading(false)
}
}, [monthStart, teamFilter, viewMode, weekStart])
const loadTeams = useCallback(async () => {
try {
const data = await fetchAgentTeams()
const data = await fetchAgentTeamsAll()
setTeams(data)
} catch (error) {
toast.error(error instanceof Error ? error.message : "加载客服组选项失败")
}
}, [])
const refreshActiveView = useCallback(async () => {
await Promise.all([
loadCalendarData(),
viewMode === "list" ? loadData() : Promise.resolve(),
])
}, [loadCalendarData, loadData, viewMode])
useEffect(() => {
void loadData()
}, [loadData])
void loadCalendarData()
}, [loadCalendarData])
useEffect(() => {
if (viewMode === "list") {
void loadData()
}
}, [loadData, viewMode])
useEffect(() => {
void loadTeams()
@@ -105,12 +184,18 @@ export default function DashboardAgentTeamSchedulesPage() {
setPage(nextPage)
}
function openCreateDialog() {
function openCreateDialog(defaults?: Partial<CreateAdminAgentTeamSchedulePayload>) {
setEditingItem(null)
setDialogDefaults(defaults ?? null)
setDialogOpen(true)
}
function openEditDialog(item: AdminAgentTeamSchedule) {
if (isHistoricalSchedule(item)) {
toast.error("不能修改历史日期的排班")
return
}
setDialogDefaults(null)
setEditingItem(item)
setDialogOpen(true)
}
@@ -121,6 +206,7 @@ export default function DashboardAgentTeamSchedulesPage() {
}
if (!open) {
setEditingItem(null)
setDialogDefaults(null)
}
setDialogOpen(open)
}
@@ -140,7 +226,8 @@ export default function DashboardAgentTeamSchedulesPage() {
}
setDialogOpen(false)
setEditingItem(null)
await loadData()
setDialogDefaults(null)
await refreshActiveView()
} catch (error) {
toast.error(error instanceof Error ? error.message : "保存客服组排班失败")
} finally {
@@ -148,12 +235,19 @@ export default function DashboardAgentTeamSchedulesPage() {
}
}
async function handleDelete(item: AdminAgentTeamSchedule) {
setActionLoadingId(item.id)
async function handleBatchSuccess() {
await refreshActiveView()
}
async function handleDeleteById(id: number) {
setActionLoadingId(id)
try {
await deleteAgentTeamSchedule(item.id)
await deleteAgentTeamSchedule(id)
toast.success("已删除客服组排班")
await loadData()
setDialogOpen(false)
setEditingItem(null)
setDialogDefaults(null)
await refreshActiveView()
} catch (error) {
toast.error(error instanceof Error ? error.message : "删除客服组排班失败")
} finally {
@@ -161,123 +255,252 @@ export default function DashboardAgentTeamSchedulesPage() {
}
}
async function handleDelete(item: AdminAgentTeamSchedule) {
await handleDeleteById(item.id)
}
async function handleCalendarUpdate(payload: UpdateAdminAgentTeamSchedulePayload) {
const startAt = parseLocalDateTime(payload.startAt)
if (startAt && startAt < startOfDay(new Date())) {
toast.error("不能修改历史日期的排班")
return
}
setActionLoadingId(payload.id)
try {
await updateAgentTeamSchedule(payload)
toast.success("已更新客服组排班")
await loadCalendarData()
} catch (error) {
toast.error(error instanceof Error ? error.message : "更新客服组排班失败")
await loadCalendarData()
} finally {
setActionLoadingId(null)
}
}
function goToToday() {
const today = new Date()
setMonthStart(startOfMonth(today))
setWeekStart(startOfWeek(today))
}
return (
<>
<div className="flex flex-1 flex-col gap-6 p-4 lg:p-6">
<div className="flex flex-col gap-2 xl:flex-row xl:items-center xl:justify-end">
<Select value={teamFilterInput} onValueChange={(value) => setTeamFilterInput(value ?? "all")}>
<SelectTrigger className="w-full xl:w-48">
<SelectValue placeholder="筛选客服组" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all"></SelectItem>
{teams.map((team) => (
<SelectItem key={team.id} value={String(team.id)}>
{team.name}
</SelectItem>
))}
</SelectContent>
</Select>
<Button variant="outline" onClick={applyFilters} disabled={loading}>
<SearchIcon />
</Button>
<Button variant="outline" onClick={() => void loadData()} disabled={loading}>
<RefreshCwIcon className={loading ? "animate-spin" : ""} />
</Button>
<Button onClick={openCreateDialog}>
<PlusIcon />
</Button>
</div>
<div className="space-y-4">
<div className="overflow-hidden rounded-2xl border bg-background">
<Table>
<TableHeader className="bg-muted/40">
<TableRow>
<TableHead></TableHead>
<TableHead></TableHead>
<TableHead></TableHead>
<TableHead className="w-[92px] text-right"></TableHead>
</TableRow>
</TableHeader>
<TableBody>
{result.results.map((item) => (
<TableRow key={item.id}>
<TableCell>
<div className="flex items-start gap-3">
<div className="mt-0.5 flex size-10 items-center justify-center rounded-2xl bg-muted text-muted-foreground">
<CalendarClockIcon className="size-4" />
</div>
<div className="min-w-0">
<div className="font-medium">{item.teamName || `客服组#${item.teamId}`}</div>
<div className="text-xs text-muted-foreground">ID{item.teamId}</div>
</div>
</div>
</TableCell>
<TableCell>
<div className="text-sm">{formatDateTime(item.startAt)}</div>
<div className="text-sm text-muted-foreground">{formatDateTime(item.endAt)}</div>
</TableCell>
<TableCell>
<div className="text-sm">{item.sourceType}</div>
</TableCell>
<TableCell className="text-right">
<ButtonGroup className="ml-auto">
<Button variant="outline" size="sm" onClick={() => openEditDialog(item)}>
</Button>
<DropdownMenu>
<DropdownMenuTrigger
render={<Button variant="outline" size="icon-sm" />}
aria-label={`更多操作 ${item.startAt}`}
>
<MoreHorizontalIcon />
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-40 min-w-40">
<DropdownMenuItem
onClick={() => void handleDelete(item)}
className="text-destructive focus:text-destructive"
>
<Trash2Icon />
{actionLoadingId === item.id ? "删除中..." : "删除"}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</ButtonGroup>
</TableCell>
</TableRow>
))}
{!loading && result.results.length === 0 ? (
<TableRow>
<TableCell colSpan={4} className="py-12 text-center text-muted-foreground">
</TableCell>
</TableRow>
) : null}
</TableBody>
</Table>
<div className="flex h-[calc(100vh-var(--header-height))] min-h-0 flex-1 flex-col gap-4 overflow-hidden p-4 lg:p-6">
<div className="shrink-0 flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between">
<div className="flex flex-wrap items-center gap-2">
<ButtonGroup>
<Button
variant={viewMode === "month" ? "default" : "outline"}
size="sm"
onClick={() => setViewMode("month")}
>
<CalendarDaysIcon />
</Button>
<Button
variant={viewMode === "week" ? "default" : "outline"}
size="sm"
onClick={() => setViewMode("week")}
>
<CalendarRangeIcon />
</Button>
<Button
variant={viewMode === "list" ? "default" : "outline"}
size="sm"
onClick={() => setViewMode("list")}
>
<ListIcon />
</Button>
</ButtonGroup>
{viewMode === "month" ? (
<ButtonGroup>
<Button variant="outline" size="icon-sm" onClick={() => setMonthStart(addMonths(monthStart, -1))} aria-label="上一月">
<ChevronLeftIcon />
</Button>
<Button variant="outline" size="sm" onClick={() => setMonthStart(startOfMonth(new Date()))}>
</Button>
<Button variant="outline" size="icon-sm" onClick={() => setMonthStart(addMonths(monthStart, 1))} aria-label="下一月">
<ChevronRightIcon />
</Button>
</ButtonGroup>
) : null}
{viewMode === "week" ? (
<ButtonGroup>
<Button variant="outline" size="icon-sm" onClick={() => setWeekStart(addDays(weekStart, -7))} aria-label="上一周">
<ChevronLeftIcon />
</Button>
<Button variant="outline" size="sm" onClick={() => setWeekStart(startOfWeek(new Date()))}>
</Button>
<Button variant="outline" size="icon-sm" onClick={() => setWeekStart(addDays(weekStart, 7))} aria-label="下一周">
<ChevronRightIcon />
</Button>
</ButtonGroup>
) : null}
{viewMode === "month" ? (
<div className="text-sm text-muted-foreground">{formatMonthTitle(monthStart)}</div>
) : null}
{viewMode === "week" ? (
<div className="text-sm text-muted-foreground">{formatWeekTitle(weekStart)}</div>
) : null}
{viewMode !== "list" ? (
<Button variant="outline" size="sm" onClick={goToToday}>
<CalendarSearchIcon />
</Button>
) : null}
</div>
<div className="flex flex-col gap-2 sm:flex-row sm:items-center xl:justify-end">
<div className="w-full sm:w-48">
<OptionCombobox
value={teamFilterInput}
options={[
{ value: "all", label: "全部客服组" },
...teams.map((team) => ({ value: String(team.id), label: team.name })),
]}
placeholder="筛选客服组"
searchPlaceholder="搜索客服组"
emptyText="未找到客服组"
onChange={(value) => setTeamFilterInput(value)}
/>
</div>
<Button variant="outline" onClick={applyFilters} disabled={loading || calendarLoading}>
<SearchIcon />
</Button>
<Button
variant="outline"
onClick={() => void refreshActiveView()}
disabled={loading || calendarLoading}
>
<RefreshCwIcon className={loading || calendarLoading ? "animate-spin" : ""} />
</Button>
<Button variant="outline" onClick={() => setBatchDialogOpen(true)}>
<LayersIcon />
</Button>
<Button onClick={() => openCreateDialog()}>
<PlusIcon />
</Button>
</div>
<ListPagination
page={result.page.page}
total={result.page.total}
limit={limit}
loading={loading}
onPageChange={handlePageChange}
onLimitChange={(nextLimit) => {
setLimit(nextLimit)
setPage(1)
}}
/>
</div>
{viewMode === "month" || viewMode === "week" ? (
<div className="min-h-0 flex-1 overflow-auto">
<ScheduleCalendar
variant={viewMode}
monthStart={monthStart}
calendarStart={viewMode === "week" ? weekStart : startOfMonthCalendar(monthStart)}
calendarEnd={viewMode === "week" ? addDays(weekStart, 7) : endOfMonthCalendar(monthStart)}
teams={visibleTeams}
schedules={calendarItems}
loading={calendarLoading}
savingId={actionLoadingId}
onCreate={openCreateDialog}
onEdit={openEditDialog}
onMove={handleCalendarUpdate}
onResize={handleCalendarUpdate}
/>
</div>
) : (
<div className="min-h-0 flex-1 space-y-4 overflow-auto">
<div className="min-w-[720px] overflow-hidden rounded-lg border bg-background">
<Table>
<TableHeader className="bg-muted/40">
<TableRow>
<TableHead></TableHead>
<TableHead></TableHead>
<TableHead className="w-[92px] text-right"></TableHead>
</TableRow>
</TableHeader>
<TableBody>
{result.results.map((item) => (
<TableRow key={item.id} className={isHistoricalSchedule(item) ? "opacity-60" : undefined}>
<TableCell>
<div className="flex items-start gap-3">
<div className="mt-0.5 flex size-10 items-center justify-center rounded-md bg-muted text-muted-foreground">
<CalendarClockIcon className="size-4" />
</div>
<div className="min-w-0">
<div className="font-medium">{item.teamName || `客服组#${item.teamId}`}</div>
<div className="text-xs text-muted-foreground">ID{item.teamId}</div>
</div>
</div>
</TableCell>
<TableCell>
<div className="text-sm">{formatDateTime(item.startAt)}</div>
<div className="text-sm text-muted-foreground">{formatDateTime(item.endAt)}</div>
</TableCell>
<TableCell className="text-right">
<ButtonGroup className="ml-auto">
<Button variant="outline" size="sm" onClick={() => openEditDialog(item)} disabled={isHistoricalSchedule(item)}>
</Button>
<DropdownMenu>
<DropdownMenuTrigger
render={<Button variant="outline" size="icon-sm" />}
aria-label={`更多操作 ${item.startAt}`}
>
<MoreHorizontalIcon />
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-40 min-w-40">
<DropdownMenuItem
onClick={() => void handleDelete(item)}
className="text-destructive focus:text-destructive"
>
<Trash2Icon />
{actionLoadingId === item.id ? "删除中..." : "删除"}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</ButtonGroup>
</TableCell>
</TableRow>
))}
{!loading && result.results.length === 0 ? (
<TableRow>
<TableCell colSpan={3} className="py-12 text-center text-muted-foreground">
</TableCell>
</TableRow>
) : null}
</TableBody>
</Table>
</div>
<ListPagination
page={result.page.page}
total={result.page.total}
limit={limit}
loading={loading}
onPageChange={handlePageChange}
onLimitChange={(nextLimit) => {
setLimit(nextLimit)
setPage(1)
}}
/>
</div>
)}
</div>
<EditDialog
open={dialogOpen}
saving={saving}
saving={saving || actionLoadingId === editingItem?.id}
itemId={editingItem?.id ?? null}
defaultValues={dialogDefaults}
onOpenChange={handleDialogOpenChange}
onSubmit={handleSubmit}
onDelete={handleDeleteById}
/>
<BatchScheduleDialog
open={batchDialogOpen}
onOpenChange={setBatchDialogOpen}
onSuccess={handleBatchSuccess}
/>
</>
)
+4 -3
View File
@@ -51,6 +51,7 @@ export default function DashboardLayout({
return (
<SidebarProvider
className="h-svh min-h-0 overflow-hidden"
style={
{
"--sidebar-width": "calc(var(--spacing) * 54)",
@@ -60,10 +61,10 @@ export default function DashboardLayout({
>
<NotificationProvider>
<AppSidebar variant="inset" />
<SidebarInset>
<SidebarInset className="min-h-0 overflow-hidden">
<SiteHeader />
<div className="flex flex-1 flex-col">
<div className="@container/main flex flex-1 flex-col gap-2">
<div className="flex min-h-0 flex-1 flex-col overflow-hidden">
<div className="@container/main flex min-h-0 flex-1 flex-col gap-2 overflow-hidden">
{children}
</div>
</div>
+60 -2
View File
@@ -510,7 +510,6 @@ export type AdminAgentTeamSchedule = {
teamName?: string
startAt: string
endAt: string
sourceType: string
remark: string
}
@@ -518,7 +517,6 @@ export type CreateAdminAgentTeamSchedulePayload = {
teamId: number
startAt: string
endAt: string
sourceType: string
remark: string
}
@@ -527,6 +525,38 @@ export type UpdateAdminAgentTeamSchedulePayload =
id: number
}
export type BatchAdminAgentTeamSchedulePayload = {
teamIds: number[]
startDate: string
endDate: string
weekdays: number[]
startTime: string
endTime: string
remark: string
}
export type AdminAgentTeamScheduleBatchPreviewItem = {
teamId: number
teamName: string
date: string
weekday: number
startAt: string
endAt: string
remark: string
conflict: boolean
conflictReason: string
}
export type AdminAgentTeamScheduleBatchPreview = {
total: number
conflict: boolean
items: AdminAgentTeamScheduleBatchPreviewItem[]
}
export type AdminAgentTeamScheduleBatchGenerateResult = {
created: number
}
function toQueryString(query?: Record<string, string | number | undefined>) {
if (!query) {
return ""
@@ -1092,6 +1122,14 @@ export function fetchAgentTeamSchedules(
)
}
export function fetchAgentTeamScheduleCalendar(
query: Record<string, string | number | undefined>
) {
return request<AdminAgentTeamSchedule[]>(
`/api/dashboard/agent-team-schedule/calendar${toQueryString(query)}`
)
}
export function fetchAgentTeamSchedule(id: number) {
return request<AdminAgentTeamSchedule>(`/api/dashboard/agent-team-schedule/${id}`)
}
@@ -1117,6 +1155,26 @@ export function deleteAgentTeamSchedule(id: number) {
})
}
export function previewAgentTeamScheduleBatch(payload: BatchAdminAgentTeamSchedulePayload) {
return request<AdminAgentTeamScheduleBatchPreview>(
"/api/dashboard/agent-team-schedule/batch_preview",
{
method: "POST",
body: JSON.stringify(payload),
}
)
}
export function generateAgentTeamScheduleBatch(payload: BatchAdminAgentTeamSchedulePayload) {
return request<AdminAgentTeamScheduleBatchGenerateResult>(
"/api/dashboard/agent-team-schedule/batch_generate",
{
method: "POST",
body: JSON.stringify(payload),
}
)
}
export type AIConfig = {
id: number
name: string