feat: add calendar scheduling feature for agent teams

- Implemented FindCalendarSchedules method in agentTeamScheduleService to retrieve schedules within a specified time range.
- Added new API endpoint fetchAgentTeamScheduleCalendar to fetch schedules for the calendar view.
- Created ScheduleCalendar component to display agent team schedules in a calendar format with drag-and-drop functionality for moving and resizing schedules.
- Updated EditDialog component to support deleting schedules and handling default values for new entries.
- Enhanced DashboardAgentTeamSchedulesPage to toggle between calendar and list views, and to load calendar data based on selected week.
- Added tests for FindCalendarSchedules to ensure correct schedule retrieval and validation of time ranges.
This commit is contained in:
mlogclub
2026-04-29 09:23:54 +08:00
parent ce8a8d5bcc
commit 8646b002c1
10 changed files with 895 additions and 139 deletions
@@ -0,0 +1,374 @@
"use client"
import { CalendarPlusIcon, GripVerticalIcon } from "lucide-react"
import type {
AdminAgentTeam,
AdminAgentTeamSchedule,
CreateAdminAgentTeamSchedulePayload,
UpdateAdminAgentTeamSchedulePayload,
} from "@/lib/api/admin"
import { cn, formatDateTime } from "@/lib/utils"
const dayNames = ["一", "二", "三", "四", "五", "六", "日"]
const dayMs = 24 * 60 * 60 * 1000
const minuteMs = 60 * 1000
const minDurationMs = 15 * minuteMs
type ScheduleCalendarProps = {
weekStart: 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
}
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 formatDayTitle(date: Date) {
return `${date.getMonth() + 1}/${date.getDate()}`
}
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 | React.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 | React.PointerEvent) {
const element = document.elementFromPoint(event.clientX, event.clientY)
return element?.closest("[data-schedule-cell]")
}
function getCellTeamAndDate(cell: Element) {
const teamID = Number(cell.getAttribute("data-team-id"))
const date = cell.getAttribute("data-date") ?? ""
return { teamID, date }
}
function buildMovePayload(item: AdminAgentTeamSchedule, teamId: number, 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,
startAt: formatDateTimeValue(nextStart),
endAt: formatDateTimeValue(nextEnd),
sourceType: item.sourceType,
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 (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),
sourceType: item.sourceType,
remark: item.remark,
}
}
function sliceScheduleForDay(item: AdminAgentTeamSchedule, day: Date) {
const dayStart = startOfDay(day)
const dayEnd = addDays(dayStart, 1)
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()))
if (!visibleEnd.getTime() || visibleEnd <= visibleStart) {
return null
}
const left = ((visibleStart.getTime() - dayStart.getTime()) / dayMs) * 100
const width = ((visibleEnd.getTime() - visibleStart.getTime()) / dayMs) * 100
return { left, width, visibleStart, visibleEnd }
}
export function ScheduleCalendar({
weekStart,
teams,
schedules,
loading,
savingId,
onCreate,
onEdit,
onMove,
onResize,
}: ScheduleCalendarProps) {
const days = Array.from({ length: 7 }, (_, index) => startOfDay(addDays(weekStart, index)))
function handleBlankCellClick(teamId: number, 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,
startAt: formatDateTimeValue(startAt),
endAt: formatDateTimeValue(endAt),
sourceType: "manual",
remark: "",
})
}
function handlePointerDown(event: React.PointerEvent, item: AdminAgentTeamSchedule, type: DragState["type"], edge?: "start" | "end") {
event.preventDefault()
event.stopPropagation()
const target = event.currentTarget as HTMLElement
target.setPointerCapture(event.pointerId)
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 {
state.moved = true
}
}
async function handlePointerUp(upEvent: PointerEvent) {
target.releasePointerCapture(event.pointerId)
window.removeEventListener("pointermove", handlePointerMove)
window.removeEventListener("pointerup", handlePointerUp)
if (!state.moved) {
onEdit(item)
return
}
const cell = getDropCell(upEvent)
if (!cell) {
return
}
if (state.type === "move") {
const next = getCellTeamAndDate(cell)
if (!next.teamID || !next.date) {
return
}
await onMove(buildMovePayload(item, next.teamID, next.date))
return
}
const payload = buildResizePayload(item, state.edge, getPointerDateInCell(upEvent, cell))
if (payload) {
await onResize(payload)
}
}
window.addEventListener("pointermove", handlePointerMove)
window.addEventListener("pointerup", handlePointerUp)
}
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>
)
}
return (
<div className="overflow-x-auto rounded-lg border bg-background">
<div className="min-w-[980px]">
<div className="grid grid-cols-[168px_repeat(7,minmax(112px,1fr))] border-b bg-muted/40">
<div className="flex h-14 items-center px-4 text-sm font-medium text-muted-foreground"></div>
{days.map((day, index) => (
<div key={day.toISOString()} className="flex h-14 flex-col justify-center border-l px-3">
<div className="text-sm font-medium">{dayNames[index]}</div>
<div className="text-xs text-muted-foreground">{formatDayTitle(day)}</div>
</div>
))}
</div>
<div className={cn("relative", loading && "opacity-60")}>
{teams.map((team) => (
<div key={team.id} className="grid min-h-28 grid-cols-[168px_repeat(7,minmax(112px,1fr))] border-b last:border-b-0">
<div className="flex min-h-28 items-center px-4">
<div className="min-w-0">
<div className="truncate text-sm font-medium">{team.name}</div>
<div className="text-xs text-muted-foreground">ID{team.id}</div>
</div>
</div>
{days.map((day) => {
const date = formatDate(day)
const daySchedules = schedules.filter((item) => item.teamId === team.id && sliceScheduleForDay(item, day))
return (
<button
key={`${team.id}-${date}`}
type="button"
data-schedule-cell
data-team-id={team.id}
data-date={date}
className="relative min-h-28 border-l bg-background p-2 text-left transition-colors hover:bg-muted/20"
onClick={(event) => {
if (event.target === event.currentTarget) {
handleBlankCellClick(team.id, day)
}
}}
>
{daySchedules.length === 0 ? (
<div className="flex h-full min-h-20 items-center justify-center text-xs text-muted-foreground/70">
<CalendarPlusIcon className="mr-1 size-3.5" />
</div>
) : null}
{daySchedules.map((item, index) => {
const slice = sliceScheduleForDay(item, day)
if (!slice) {
return null
}
const busy = savingId === item.id
return (
<div
key={`${item.id}-${date}`}
role="button"
tabIndex={0}
className={cn(
"absolute top-2 z-10 h-20 cursor-grab overflow-hidden rounded-md border border-primary/20 bg-primary/10 px-2 py-1.5 text-primary shadow-sm outline-none transition active:cursor-grabbing",
busy && "pointer-events-none opacity-60"
)}
style={{
left: `calc(${slice.left}% + 8px)`,
width: `calc(${slice.width}% - 16px)`,
top: `${8 + index * 28}px`,
minWidth: "42px",
}}
onPointerDown={(event) => handlePointerDown(event, item, "move")}
onKeyDown={(event) => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault()
onEdit(item)
}
}}
>
<div
className="absolute left-0 top-0 flex h-full w-2 cursor-ew-resize items-center justify-center bg-primary/15"
onPointerDown={(event) => handlePointerDown(event, item, "resize", "start")}
>
<GripVerticalIcon className="size-3" />
</div>
<div
className="absolute right-0 top-0 flex h-full w-2 cursor-ew-resize items-center justify-center bg-primary/15"
onPointerDown={(event) => handlePointerDown(event, item, "resize", "end")}
>
<GripVerticalIcon className="size-3" />
</div>
<div className="truncate pl-2 pr-2 text-xs font-medium">{item.sourceType}</div>
<div className="truncate pl-2 pr-2 text-xs">
{formatDateTime(item.startAt).slice(11, 16)} - {formatDateTime(item.endAt).slice(11, 16)}
</div>
{item.remark ? (
<div className="truncate pl-2 pr-2 text-[11px] text-primary/80">{item.remark}</div>
) : null}
</div>
)
})}
</button>
)
})}
</div>
))}
</div>
</div>
</div>
)
}
@@ -35,8 +35,10 @@ 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 = [
@@ -75,9 +77,15 @@ function toDateTimeLocal(value?: string) {
return value.replace(" ", "T").slice(0, 16)
}
function buildForm(item: AdminAgentTeamSchedule | null): EditForm {
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),
sourceType: (defaultValues?.sourceType as EditForm["sourceType"] | undefined) ?? emptyForm.sourceType,
remark: defaultValues?.remark ?? emptyForm.remark,
}
}
return {
teamId: String(item.teamId),
@@ -102,8 +110,10 @@ export function EditDialog({
open,
saving,
itemId,
defaultValues,
onOpenChange,
onSubmit,
onDelete,
}: ScheduleEditDialogProps) {
return (
<Dialog open={open} onOpenChange={onOpenChange}>
@@ -111,9 +121,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 +137,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)
@@ -157,7 +171,7 @@ function ScheduleEditDialogBody({
useEffect(() => {
async function loadDetail() {
if (!itemId) {
reset(emptyForm)
reset(buildForm(null, defaultValues))
return
}
setLoading(true)
@@ -171,7 +185,7 @@ function ScheduleEditDialogBody({
}
}
void loadDetail()
}, [itemId, reset])
}, [defaultValues, itemId, reset])
useEffect(() => {
void loadOptions()
@@ -269,6 +283,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>
+299 -131
View File
@@ -1,8 +1,12 @@
"use client"
import { useCallback, useEffect, useState } from "react"
import { useCallback, useEffect, useMemo, useState } from "react"
import {
CalendarClockIcon,
CalendarDaysIcon,
ChevronLeftIcon,
ChevronRightIcon,
ListIcon,
MoreHorizontalIcon,
PlusIcon,
RefreshCwIcon,
@@ -11,19 +15,7 @@ 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 {
@@ -32,8 +24,6 @@ import {
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,
@@ -43,23 +33,87 @@ 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 { ScheduleCalendar } from "./_components/calendar"
import { EditDialog } from "./_components/edit"
type ViewMode = "calendar" | "list"
function startOfDay(date: Date) {
const ret = new Date(date)
ret.setHours(0, 0, 0, 0)
return ret
}
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
}
function addDays(date: Date, days: number) {
const ret = new Date(date)
ret.setDate(ret.getDate() + days)
return ret
}
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 formatWeekRange(weekStart: Date) {
const weekEnd = addDays(weekStart, 6)
return `${weekStart.getFullYear()}-${String(weekStart.getMonth() + 1).padStart(2, "0")}-${String(weekStart.getDate()).padStart(2, "0")}${String(weekEnd.getMonth() + 1).padStart(2, "0")}-${String(weekEnd.getDate()).padStart(2, "0")}`
}
export default function DashboardAgentTeamSchedulesPage() {
const [viewMode, setViewMode] = useState<ViewMode>("calendar")
const [teamFilterInput, setTeamFilterInput] = useState("all")
const [teamFilter, setTeamFilter] = useState("all")
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 [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 +130,47 @@ export default function DashboardAgentTeamSchedulesPage() {
}
}, [limit, page, teamFilter])
const loadCalendarData = useCallback(async () => {
setCalendarLoading(true)
try {
const data = await fetchAgentTeamScheduleCalendar({
startAt: formatDateTimeValue(weekStart),
endAt: formatDateTimeValue(addDays(weekStart, 7)),
teamId: teamFilter === "all" ? undefined : teamFilter,
})
setCalendarItems(data)
} catch (error) {
toast.error(error instanceof Error ? error.message : "加载客服组排班日历失败")
} finally {
setCalendarLoading(false)
}
}, [teamFilter, 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 +188,14 @@ export default function DashboardAgentTeamSchedulesPage() {
setPage(nextPage)
}
function openCreateDialog() {
function openCreateDialog(defaults?: Partial<CreateAdminAgentTeamSchedulePayload>) {
setEditingItem(null)
setDialogDefaults(defaults ?? null)
setDialogOpen(true)
}
function openEditDialog(item: AdminAgentTeamSchedule) {
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,15 @@ export default function DashboardAgentTeamSchedulesPage() {
}
}
async function handleDelete(item: AdminAgentTeamSchedule) {
setActionLoadingId(item.id)
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 +251,201 @@ export default function DashboardAgentTeamSchedulesPage() {
}
}
async function handleDelete(item: AdminAgentTeamSchedule) {
await handleDeleteById(item.id)
}
async function handleCalendarUpdate(payload: UpdateAdminAgentTeamSchedulePayload) {
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)
}
}
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 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 === "calendar" ? "default" : "outline"}
size="sm"
onClick={() => setViewMode("calendar")}
>
<CalendarDaysIcon />
</Button>
<Button
variant={viewMode === "list" ? "default" : "outline"}
size="sm"
onClick={() => setViewMode("list")}
>
<ListIcon />
</Button>
</ButtonGroup>
{viewMode === "calendar" ? (
<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 === "calendar" ? (
<div className="text-sm text-muted-foreground">{formatWeekRange(weekStart)}</div>
) : null}
</div>
<div className="flex flex-col gap-2 sm:flex-row sm:items-center xl:justify-end">
<Select value={teamFilterInput} onValueChange={(value) => setTeamFilterInput(value ?? "all")}>
<SelectTrigger className="w-full sm: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 || calendarLoading}>
<SearchIcon />
</Button>
<Button
variant="outline"
onClick={() => void refreshActiveView()}
disabled={loading || calendarLoading}
>
<RefreshCwIcon className={loading || calendarLoading ? "animate-spin" : ""} />
</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 === "calendar" ? (
<ScheduleCalendar
weekStart={weekStart}
teams={visibleTeams}
schedules={calendarItems}
loading={calendarLoading}
savingId={actionLoadingId}
onCreate={openCreateDialog}
onEdit={openEditDialog}
onMove={handleCalendarUpdate}
onResize={handleCalendarUpdate}
/>
) : (
<div className="space-y-4">
<div className="overflow-hidden rounded-lg 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-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>
<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>
<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}
/>
</>
)
+8
View File
@@ -1092,6 +1092,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}`)
}