chore: import clean Agent Desk snapshot (6/7)

This commit is contained in:
2026-10-16 12:02:48 +00:00
parent d215bf6303
commit 756ae33d05
278 changed files with 53808 additions and 0 deletions

View File

@@ -0,0 +1,547 @@
"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 { useI18n } from "@/i18n/provider"
import { cn } from "@/lib/utils"
type BatchScheduleDialogProps = {
open: boolean
onOpenChange: (open: boolean) => void
onSuccess: (created: number) => void | Promise<void>
}
type TFunction = (key: string, values?: Record<string, string | number>) => string
const weekdayKeys = [
"weekdayMon",
"weekdayTue",
"weekdayWed",
"weekdayThu",
"weekdayFri",
"weekdaySat",
"weekdaySun",
] as const
function getWeekdayOptions(t: TFunction) {
return weekdayKeys.map((key, index) => ({
value: index + 1,
label: t(`agentTeamSchedule.${key}`),
}))
}
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, t: TFunction) {
const weekdayOptions = getWeekdayOptions(t)
return weekdayOptions.find((option) => option.value === value)?.label ?? String(value)
}
function validateForm(form: BatchFormState, t: TFunction) {
const today = todayDateValue()
if (form.selectedTeamIds.length === 0) {
return t("agentTeamSchedule.selectAtLeastOneTeam")
}
if (!form.startDate || !form.endDate) {
return t("agentTeamSchedule.selectDateRange")
}
if (form.startDate < today) {
return t("agentTeamSchedule.startBeforeToday")
}
if (form.endDate < form.startDate) {
return t("agentTeamSchedule.endBeforeStart")
}
if (form.weekdays.length === 0) {
return t("agentTeamSchedule.selectAtLeastOneWeekday")
}
if (!form.startTime || !form.endTime) {
return t("agentTeamSchedule.selectStartEndTime")
}
if (form.endTime <= form.startTime) {
return t("agentTeamSchedule.endAfterStart")
}
return ""
}
export function BatchScheduleDialog({
open,
onOpenChange,
onSuccess,
}: BatchScheduleDialogProps) {
const t = useI18n()
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 weekdayOptions = useMemo(() => getWeekdayOptions(t), [t])
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 : t("agentTeamSchedule.loadTeamsFailed"))
}
} finally {
if (!ignore) {
setLoadingTeams(false)
}
}
}
void loadTeams()
return () => {
ignore = true
}
}, [open, t])
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, t)
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 : t("agentTeamSchedule.previewFailed"))
}
} finally {
if (openRef.current && previewRequestIdRef.current === requestId) {
setPreviewing(false)
}
}
}
async function handleSubmit() {
if (!preview || !previewPayload) {
toast.error(t("agentTeamSchedule.previewFirst"))
return
}
if (preview.conflict) {
toast.error(t("agentTeamSchedule.conflictCannotSubmit"))
return
}
const payload = previewPayload
setSubmitting(true)
try {
const data = await generateAgentTeamScheduleBatch(payload)
toast.success(t("agentTeamSchedule.batchCreated", { count: data.created }))
setPreview(null)
setPreviewPayload(null)
onOpenChange(false)
try {
await onSuccess(data.created)
} catch (error) {
toast.error(error instanceof Error ? t("agentTeamSchedule.batchRefreshFailed", { message: error.message }) : t("agentTeamSchedule.batchRefreshFailedFallback"))
}
} catch (error) {
toast.error(error instanceof Error ? error.message : t("agentTeamSchedule.generateFailed"))
} 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>{t("agentTeamSchedule.batch")}</DialogTitle>
<DialogDescription>
{t("agentTeamSchedule.batchDescription")}
</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>{t("agentTeamSchedule.team")}</Label>
<div className="flex gap-2">
<div className="min-w-0 flex-1">
<OptionCombobox
value=""
options={teamOptions}
placeholder={loadingTeams ? t("agentTeamSchedule.loadingTeams") : t("agentTeamSchedule.addTeam")}
searchPlaceholder={t("agentTeamSchedule.searchTeam")}
emptyText={teams.length === 0 ? t("agentTeamSchedule.noTeams") : t("agentTeamSchedule.allTeamsSelected")}
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={t("agentTeamSchedule.removeTeam", { name: team.name })}
>
<XIcon className="size-3" />
</Button>
</Badge>
))}
</div>
) : (
<div className="text-sm text-muted-foreground">{t("agentTeamSchedule.noSelectedTeams")}</div>
)}
</div>
<div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-2">
<Label htmlFor="batch-schedule-start-date">{t("agentTeamSchedule.startDate")}</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">{t("agentTeamSchedule.endDate")}</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>{t("agentTeamSchedule.weekday")}</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">{t("agentTeamSchedule.startTime")}</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">{t("agentTeamSchedule.endTime")}</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">{t("agentTeamSchedule.remark")}</Label>
<Textarea
id="batch-schedule-remark"
rows={4}
placeholder={t("agentTeamSchedule.remarkPlaceholder")}
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">
{hasConflict
? t("agentTeamSchedule.previewSummaryConflict", { total: preview?.total ?? 0 })
: t("agentTeamSchedule.previewSummaryReady", { total: preview?.total ?? 0 })}
</div>
{hasConflict ? (
<Badge variant="destructive">{t("agentTeamSchedule.hasConflict")}</Badge>
) : (
<Badge variant="secondary">{t("agentTeamSchedule.noConflict")}</Badge>
)}
</div>
<div className="overflow-x-auto rounded-lg border">
<div className="min-w-[760px]">
<Table>
<TableHeader className="bg-muted/40">
<TableRow>
<TableHead>{t("agentTeamSchedule.team")}</TableHead>
<TableHead>{t("agentTeamSchedule.date")}</TableHead>
<TableHead>{t("agentTeamSchedule.weekday")}</TableHead>
<TableHead>{t("agentTeamSchedule.time")}</TableHead>
<TableHead>{t("agentTeamSchedule.remark")}</TableHead>
<TableHead>{t("agentTeamSchedule.status")}</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 || t("agentTeamSchedule.teamFallback", { id: item.teamId })}</div>
<div className="text-xs text-muted-foreground">{t("agentTeamSchedule.teamId", { id: item.teamId })}</div>
</TableCell>
<TableCell>{item.date}</TableCell>
<TableCell>{getWeekdayLabel(item.weekday, t)}</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 || t("agentTeamSchedule.conflictFallback")}
</span>
) : (
<span className="text-muted-foreground">{t("agentTeamSchedule.canGenerate")}</span>
)}
</TableCell>
</TableRow>
))}
{preview && preview.items.length === 0 ? (
<TableRow>
<TableCell colSpan={6} className="py-10 text-center text-muted-foreground">
{t("agentTeamSchedule.emptyPreview")}
</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 />
{t("agentTeamSchedule.backToEdit")}
</Button>
) : null}
<Button
type="button"
variant="outline"
onClick={() => handleOpenChange(false)}
disabled={busy}
>
{t("agentTeamSchedule.cancel")}
</Button>
{step === "form" ? (
<Button type="button" onClick={() => void handlePreview()} disabled={busy}>
{previewing ? <Loader2Icon className="animate-spin" /> : <CheckIcon />}
{t("agentTeamSchedule.preview")}
</Button>
) : (
<Button
type="button"
onClick={() => void handleSubmit()}
disabled={submitting || hasConflict || !preview || !previewPayload || preview.items.length === 0}
>
{submitting ? <Loader2Icon className="animate-spin" /> : <CheckIcon />}
{t("agentTeamSchedule.generate")}
</Button>
)}
</DialogFooter>
</DialogContent>
</Dialog>
)
}

View File

@@ -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)
})

View File

@@ -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))}`
}

View File

@@ -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",
})
})

View File

@@ -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,
}
}

View File

@@ -0,0 +1,603 @@
"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"
type TFunction = (key: string, values?: Record<string, string | number>) => string
const weekDayKeys = [
"weekdayShortMon",
"weekdayShortTue",
"weekdayShortWed",
"weekdayShortThu",
"weekdayShortFri",
"weekdayShortSat",
"weekdayShortSun",
] as const
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>
t: TFunction
}
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,
t,
}: 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: t("agentTeamSchedule.dropInsideCalendar"),
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: t("agentTeamSchedule.historyReadonly"),
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, t("agentTeamSchedule.cannotMoveHere"))
}
const payload = buildResizePayload(state.item, state.edge, getPointerDateInCell(pointerEvent, cell))
return buildPreviewFromPayload(state.item.id, date, payload, point, t("agentTeamSchedule.resizeInvalid"))
}
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">
{t("agentTeamSchedule.noTeamsCalendar")}
</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">
{t("agentTeamSchedule.today")}
</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 || t("agentTeamSchedule.teamFallback", { id: 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">{t("agentTeamSchedule.moreItems", { count: 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>{t(`agentTeamSchedule.${weekDayKeys[dayIndex] ?? "weekdayShortMon"}`)}</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">
{weekDayKeys.map((key) => (
<div key={key} className="flex h-10 items-center justify-center border-l first:border-l-0 text-sm font-medium">
{t(`agentTeamSchedule.${key}`)}
</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>
)
}

View File

@@ -0,0 +1,321 @@
"use client"
import { zodResolver } from "@hookform/resolvers/zod"
import { useCallback, useEffect, useMemo, useState } from "react"
import { Controller, type Resolver, useForm } from "react-hook-form"
import { toast } from "sonner"
import { z } from "zod/v4"
import { Button } from "@/components/ui/button"
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog"
import {
Field,
FieldContent,
FieldError,
FieldLabel,
} from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import { OptionCombobox } from "@/components/option-combobox"
import { Textarea } from "@/components/ui/textarea"
import {
type AdminAgentTeam,
type AdminAgentTeamSchedule,
type CreateAdminAgentTeamSchedulePayload,
fetchAgentTeamSchedule,
fetchAgentTeamsAll,
} from "@/lib/api/admin"
import { useI18n } from "@/i18n/provider"
type TFunction = (key: string, values?: Record<string, string | number>) => string
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 emptyForm: EditForm = {
teamId: "",
startAt: "",
endAt: "",
remark: "",
}
type EditForm = {
teamId: string
startAt: string
endAt: string
remark: string
}
function createEditFormSchema(t: TFunction) {
return z.object({
teamId: z.string().trim().regex(/^\d+$/, t("agentTeamSchedule.teamRequired")),
startAt: z.string().trim().min(1, t("agentTeamSchedule.startRequired")),
endAt: z.string().trim().min(1, t("agentTeamSchedule.endRequired")),
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: t("agentTeamSchedule.endAfterStart"),
})
return
}
if (!isSameLocalDay(startAt, endAt)) {
ctx.addIssue({
code: "custom",
path: ["endAt"],
message: t("agentTeamSchedule.singleDayOnly"),
})
}
if (startAt < startOfLocalDay(new Date())) {
ctx.addIssue({
code: "custom",
path: ["startAt"],
message: t("agentTeamSchedule.historyReadonly"),
})
}
})
}
function toDateTimeLocal(value?: string) {
if (!value) {
return ""
}
return value.replace(" ", "T").slice(0, 16)
}
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 {
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),
remark: item.remark || "",
}
}
function buildPayload(form: EditForm): CreateAdminAgentTeamSchedulePayload {
return {
teamId: Number(form.teamId),
startAt: form.startAt.trim(),
endAt: form.endAt.trim(),
remark: form.remark.trim(),
}
}
export function EditDialog({
open,
saving,
itemId,
defaultValues,
onOpenChange,
onSubmit,
onDelete,
}: ScheduleEditDialogProps) {
return (
<Dialog open={open} onOpenChange={onOpenChange}>
{open ? (
<ScheduleEditDialogBody
key={itemId ? `edit-${itemId}` : "create"}
itemId={itemId}
defaultValues={defaultValues}
saving={saving}
onOpenChange={onOpenChange}
onSubmit={onSubmit}
onDelete={onDelete}
/>
) : null}
</Dialog>
)
}
type ScheduleEditDialogBodyProps = Omit<ScheduleEditDialogProps, "open">
function ScheduleEditDialogBody({
saving,
itemId,
defaultValues,
onOpenChange,
onSubmit,
onDelete,
}: ScheduleEditDialogBodyProps) {
const t = useI18n()
const [teams, setTeams] = useState<AdminAgentTeam[]>([])
const [loading, setLoading] = useState(false)
const loadOptions = useCallback(async () => {
try {
const teamsData = await fetchAgentTeamsAll()
setTeams(teamsData)
} catch (error) {
toast.error(error instanceof Error ? error.message : t("agentTeamSchedule.loadOptionsFailed"))
}
}, [t])
const editFormSchema = useMemo(() => createEditFormSchema(t), [t])
const editFormResolver = useMemo(
() => zodResolver(editFormSchema) as Resolver<EditForm>,
[editFormSchema],
)
const form = useForm<EditForm>({
resolver: editFormResolver,
defaultValues: emptyForm,
})
const {
control,
handleSubmit,
reset,
register,
formState: { errors },
} = form
const minDateTime = todayDateTimeLocalMin()
useEffect(() => {
async function loadDetail() {
if (!itemId) {
reset(buildForm(null, defaultValues))
return
}
setLoading(true)
try {
const data = await fetchAgentTeamSchedule(itemId)
reset(buildForm(data))
} catch (error) {
toast.error(error instanceof Error ? error.message : t("agentTeamSchedule.loadDetailFailed"))
} finally {
setLoading(false)
}
}
void loadDetail()
}, [defaultValues, itemId, reset, t])
useEffect(() => {
void loadOptions()
}, [loadOptions])
async function onFormSubmit(values: EditForm) {
await onSubmit(buildPayload(values))
}
return (
<DialogContent className="max-w-xl gap-0 p-0 sm:max-w-xl">
<DialogHeader className="px-6 pt-6">
<DialogTitle>{itemId ? t("agentTeamSchedule.editTitle") : t("agentTeamSchedule.createTitle")}</DialogTitle>
</DialogHeader>
{loading ? (
<div className="flex items-center justify-center py-12">
<div className="text-muted-foreground">{t("agentTeamSchedule.loading")}</div>
</div>
) : (
<form onSubmit={handleSubmit(onFormSubmit)}>
<div className="space-y-4 p-6">
<div className="grid grid-cols-1 gap-4">
<Field data-invalid={!!errors.teamId}>
<FieldLabel>{t("agentTeamSchedule.team")}</FieldLabel>
<FieldContent>
<Controller
control={control}
name="teamId"
render={({ field }) => (
<OptionCombobox
value={field.value}
options={teams.map((team) => ({
value: String(team.id),
label: team.name,
}))}
placeholder={t("agentTeamSchedule.teamRequired")}
searchPlaceholder={t("agentTeamSchedule.searchTeam")}
emptyText={t("agentTeamSchedule.emptyTeam")}
onChange={field.onChange}
/>
)}
/>
<FieldError errors={[errors.teamId]} />
</FieldContent>
</Field>
</div>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<Field data-invalid={!!errors.startAt}>
<FieldLabel htmlFor="agent-team-schedule-start-at">{t("agentTeamSchedule.startTime")}</FieldLabel>
<FieldContent>
<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">{t("agentTeamSchedule.endTime")}</FieldLabel>
<FieldContent>
<Input id="agent-team-schedule-end-at" type="datetime-local" min={minDateTime} {...register("endAt")} />
<FieldError errors={[errors.endAt]} />
</FieldContent>
</Field>
</div>
<Field>
<FieldLabel htmlFor="agent-team-schedule-remark">{t("agentTeamSchedule.remark")}</FieldLabel>
<FieldContent>
<Textarea id="agent-team-schedule-remark" rows={4} placeholder={t("agentTeamSchedule.remarkPlaceholder")} {...register("remark")} />
</FieldContent>
</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}>
{t("agentTeamSchedule.delete")}
</Button>
) : null}
<Button type="button" variant="outline" onClick={() => onOpenChange(false)} disabled={saving}>
{t("agentTeamSchedule.cancel")}
</Button>
<Button type="submit" disabled={saving || loading}>
{saving ? t("agentTeamSchedule.saving") : t("agentTeamSchedule.save")}
</Button>
</DialogFooter>
</form>
)}
</DialogContent>
)
}