refactor: support i18n

This commit is contained in:
mlogclub
2026-05-25 12:06:15 +08:00
parent 309ac1fe9e
commit 988f55c80d
179 changed files with 10968 additions and 3763 deletions
@@ -2,6 +2,7 @@
import { toast } from "sonner"
import { useI18n } from "@/i18n/provider"
import { createTicketFromConversation } from "@/lib/api/ticket"
import { EditDialog } from "./edit"
@@ -26,6 +27,7 @@ export function CreateTicketFromConversationDialog({
onOpenChange,
onSuccess,
}: CreateTicketFromConversationDialogProps) {
const t = useI18n()
const initialValues = conversation
? {
title: conversation.customerName || "",
@@ -43,11 +45,11 @@ export function CreateTicketFromConversationDialog({
fixedConversationId={conversation?.id}
fixedCustomerId={conversation?.customerId}
initialValues={initialValues}
titleOverride="会话转工单"
descriptionOverride="从当前会话上下文创建正式工单"
titleOverride={t("ticket.conversationToTicket")}
descriptionOverride={t("ticket.conversationToTicketDescription")}
onSubmit={async (payload) => {
if (!conversation?.id) {
throw new Error("会话不存在")
throw new Error(t("ticket.conversationMissing"))
}
await createTicketFromConversation({
conversationId: conversation.id,
@@ -56,7 +58,7 @@ export function CreateTicketFromConversationDialog({
currentAssigneeId: payload.currentAssigneeId,
tagIds: payload.tagIds,
})
toast.success("工单创建成功")
toast.success(t("ticket.createSuccess"))
onSuccess?.()
}}
/>
+43 -35
View File
@@ -42,6 +42,9 @@ import {
type TicketItem,
type UpdateTicketPayload,
} from "@/lib/api/ticket"
import { useI18n } from "@/i18n/provider"
type TFunction = (key: string, values?: Record<string, string | number>) => string
type EditDialogProps = {
open: boolean
@@ -56,20 +59,21 @@ type EditDialogProps = {
onSubmit: (payload: CreateTicketPayload | UpdateTicketPayload) => Promise<void>
}
const schema = z.object({
title: z.string().trim().min(1, "请输入工单标题"),
description: z.string().refine((value) => !isRichTextEmpty(value), "请输入问题描述"),
function createSchema(t: TFunction) {
return z.object({
title: z.string().trim().min(1, t("ticket.titleRequired")),
description: z.string().refine((value) => !isRichTextEmpty(value), t("ticket.descriptionRequired")),
currentAssigneeId: z.coerce.number().int().min(0).optional(),
tagIds: z.array(z.number().int().positive()).default([]),
})
})
}
type EditForm = z.infer<typeof schema>
const editFormResolver = zodResolver(schema as never) as Resolver<
z.input<typeof schema>,
undefined,
z.output<typeof schema>
>
type EditForm = {
title: string
description: string
currentAssigneeId?: number
tagIds: number[]
}
const emptyForm: EditForm = {
title: "",
@@ -130,9 +134,10 @@ type TicketTagSelectorProps = {
value?: number[]
onChange: (value: number[]) => void
availableTags: TagTree[]
t: TFunction
}
function TicketTagSelector({ value, onChange, availableTags }: TicketTagSelectorProps) {
function TicketTagSelector({ value, onChange, availableTags, t }: TicketTagSelectorProps) {
const selectedValues = useMemo(() => value ?? [], [value])
const flatTags = useMemo(() => flattenTagTree(availableTags), [availableTags])
const selectedTagIDs = useMemo(() => new Set(selectedValues), [selectedValues])
@@ -158,14 +163,14 @@ function TicketTagSelector({ value, onChange, availableTags }: TicketTagSelector
}
>
<TagIcon className="size-4" />
{selectedTags.length > 0 ? `已选择 ${selectedTags.length} 个标签` : "请选择工单标签"}
{selectedTags.length > 0 ? t("ticket.selectedTags", { count: selectedTags.length }) : t("ticket.selectTags")}
</PopoverTrigger>
<PopoverContent align="start" className="w-[320px] p-0">
<Command>
<CommandInput placeholder="搜索标签" />
<CommandInput placeholder={t("ticket.searchTags")} />
<CommandList>
<CommandEmpty></CommandEmpty>
<CommandGroup heading="标签">
<CommandEmpty>{t("ticket.emptyTags")}</CommandEmpty>
<CommandGroup heading={t("ticket.tags")}>
{flatTags.map((tag) => {
const checked = selectedTagIDs.has(tag.id)
return (
@@ -245,15 +250,17 @@ function TicketEditDialogBody({
onOpenChange,
onSubmit,
}: TicketEditDialogBodyProps) {
const t = useI18n()
const formId = "ticket-edit-form"
const [loading, setLoading] = useState(false)
const [tags, setTags] = useState<TagTree[]>([])
const [agents, setAgents] = useState<AdminAgentProfile[]>([])
const form = useForm<
z.input<typeof schema>,
undefined,
z.output<typeof schema>
>({
const schema = useMemo(() => createSchema(t), [t])
const editFormResolver = useMemo(
() => zodResolver(schema) as Resolver<EditForm>,
[schema],
)
const form = useForm<EditForm>({
resolver: editFormResolver,
defaultValues: emptyForm,
})
@@ -296,14 +303,14 @@ function TicketEditDialogBody({
})()
}, [open])
const agentOptions = [{ value: "0", label: "不指定处理人" }].concat(
const agentOptions = [{ value: "0", label: t("ticket.noAssignee") }].concat(
agents.map((agent) => ({
value: String(agent.userId),
label:
agent.displayName ||
agent.nickname ||
agent.username ||
`客服#${agent.userId}`,
t("ticket.agentFallback", { id: agent.userId }),
})),
)
@@ -328,8 +335,8 @@ function TicketEditDialogBody({
<ProjectDialog
open={open}
onOpenChange={onOpenChange}
title={titleOverride || (itemId ? "编辑工单" : "新建工单")}
description={descriptionOverride || "填写工单基础信息"}
title={titleOverride || (itemId ? t("ticket.editTitle") : t("ticket.createTitle"))}
description={descriptionOverride || t("ticket.dialogDescription")}
size="lg"
allowFullscreen
footer={
@@ -340,27 +347,27 @@ function TicketEditDialogBody({
onClick={() => onOpenChange(false)}
disabled={saving}
>
{t("ticket.cancel")}
</Button>
<Button type="submit" form={formId} disabled={saving || loading}>
{saving ? "保存中..." : itemId ? "保存" : "创建"}
{saving ? t("ticket.saving") : itemId ? t("ticket.save") : t("ticket.create")}
</Button>
</>
}
>
{loading ? (
<div className="flex items-center justify-center py-12">
<div className="text-muted-foreground">...</div>
<div className="text-muted-foreground">{t("ticket.loading")}</div>
</div>
) : (
<form id={formId} onSubmit={handleSubmit(onFormSubmit)} className="space-y-4">
<FieldGroup>
<Field data-invalid={!!errors.title}>
<FieldLabel htmlFor="ticket-title"></FieldLabel>
<FieldLabel htmlFor="ticket-title">{t("ticket.title")}</FieldLabel>
<FieldContent>
<Input
id="ticket-title"
placeholder="请输入工单标题"
placeholder={t("ticket.titlePlaceholder")}
aria-invalid={!!errors.title}
{...register("title")}
/>
@@ -369,7 +376,7 @@ function TicketEditDialogBody({
</Field>
<Field data-invalid={!!errors.description}>
<FieldLabel></FieldLabel>
<FieldLabel>{t("ticket.description")}</FieldLabel>
<FieldContent>
<Controller
control={control}
@@ -378,7 +385,7 @@ function TicketEditDialogBody({
<ContentEditor
value={{ mode: "html", raw: field.value ?? "" }}
onChange={(next) => field.onChange(next.raw)}
placeholder="请输入问题描述"
placeholder={t("ticket.descriptionRequired")}
disabled={saving || loading}
allowedModes={["html"]}
height={260}
@@ -390,7 +397,7 @@ function TicketEditDialogBody({
</Field>
<Field>
<FieldLabel></FieldLabel>
<FieldLabel>{t("ticket.assignee")}</FieldLabel>
<FieldContent>
<Controller
control={control}
@@ -399,7 +406,7 @@ function TicketEditDialogBody({
<OptionCombobox
value={String(field.value ?? 0)}
onChange={(value) => field.onChange(Number(value))}
placeholder="请选择处理人"
placeholder={t("ticket.selectAssignee")}
options={agentOptions}
/>
)}
@@ -408,7 +415,7 @@ function TicketEditDialogBody({
</Field>
<Field>
<FieldLabel></FieldLabel>
<FieldLabel>{t("ticket.ticketTags")}</FieldLabel>
<FieldContent>
<Controller
control={control}
@@ -418,6 +425,7 @@ function TicketEditDialogBody({
value={field.value}
onChange={field.onChange}
availableTags={tags}
t={t}
/>
)}
/>
@@ -1,8 +1,8 @@
"use client"
import { useEffect, useRef, useState } from "react"
import { useEffect, useMemo, useRef, useState } from "react"
import { zodResolver } from "@hookform/resolvers/zod"
import { Controller, Resolver, useForm } from "react-hook-form"
import { Controller, type Resolver, useForm } from "react-hook-form"
import { toast } from "sonner"
import { z } from "zod/v4"
@@ -21,20 +21,22 @@ import {
fetchAgentProfilesAll,
type AdminAgentProfile,
} from "@/lib/api/admin"
import { useI18n } from "@/i18n/provider"
import { assignTicket } from "@/lib/api/ticket"
const schema = z.object({
toUserId: z.string().trim().min(1, "请选择处理人"),
type TFunction = (key: string, values?: Record<string, string | number>) => string
function createSchema(t: TFunction) {
return z.object({
toUserId: z.string().trim().min(1, t("ticket.assigneeRequired")),
reason: z.string().trim(),
})
})
}
type FormValues = z.infer<typeof schema>
const resolver = zodResolver(schema as never) as Resolver<
z.input<typeof schema>,
undefined,
z.output<typeof schema>
>
type FormValues = {
toUserId: string
reason: string
}
const emptyForm: FormValues = {
toUserId: "",
@@ -77,16 +79,18 @@ function TicketAssignDialogBody({
onOpenChange,
onSuccess,
}: Omit<TicketAssignDialogProps, "open">) {
const t = useI18n()
const [saving, setSaving] = useState(false)
const [loading, setLoading] = useState(false)
const [agents, setAgents] = useState<AdminAgentProfile[]>([])
const activeRef = useRef(false)
const form = useForm<
z.input<typeof schema>,
undefined,
z.output<typeof schema>
>({
const schema = useMemo(() => createSchema(t), [t])
const resolver = useMemo(
() => zodResolver(schema) as Resolver<FormValues>,
[schema],
)
const form = useForm<FormValues>({
resolver,
defaultValues: emptyForm,
})
@@ -126,18 +130,18 @@ function TicketAssignDialogBody({
if (!activeRef.current) {
return
}
toast.error(error instanceof Error ? error.message : "加载处理人失败")
toast.error(error instanceof Error ? error.message : t("ticket.loadAssigneesFailed"))
})
.finally(() => {
if (activeRef.current) {
setLoading(false)
}
})
}, [])
}, [t])
async function onFormSubmit(values: FormValues) {
if (!ticketId) {
toast.error("请选择工单")
toast.error(t("ticket.selectTicket"))
return
}
setSaving(true)
@@ -150,7 +154,7 @@ function TicketAssignDialogBody({
if (!activeRef.current) {
return
}
toast.success("处理人已更新")
toast.success(t("ticket.assigneeUpdated"))
if (!activeRef.current) {
return
}
@@ -160,7 +164,7 @@ function TicketAssignDialogBody({
if (!activeRef.current) {
return
}
toast.error(error instanceof Error ? error.message : "指派工单失败")
toast.error(error instanceof Error ? error.message : t("ticket.assignFailed"))
} finally {
if (activeRef.current) {
setSaving(false)
@@ -171,12 +175,12 @@ function TicketAssignDialogBody({
return (
<DialogContent className="max-w-lg gap-0 p-0 sm:max-w-lg">
<DialogHeader className="px-6 pt-6">
<DialogTitle></DialogTitle>
<DialogTitle>{t("ticket.assignTitle")}</DialogTitle>
</DialogHeader>
<form onSubmit={handleSubmit(onFormSubmit)}>
<div className="space-y-4 p-6">
<Field data-invalid={!!errors.toUserId}>
<FieldLabel></FieldLabel>
<FieldLabel>{t("ticket.assignee")}</FieldLabel>
<FieldContent>
<Controller
control={control}
@@ -185,14 +189,14 @@ function TicketAssignDialogBody({
<OptionCombobox
value={field.value}
onChange={field.onChange}
placeholder={loading ? "加载中..." : "选择处理人"}
placeholder={loading ? t("ticket.loading") : t("ticket.selectHandler")}
options={agents.map((agent) => ({
value: String(agent.userId),
label:
agent.displayName ||
agent.nickname ||
agent.username ||
`客服#${agent.userId}`,
t("ticket.agentFallback", { id: agent.userId }),
}))}
/>
)}
@@ -201,19 +205,19 @@ function TicketAssignDialogBody({
</FieldContent>
</Field>
<Field data-invalid={!!errors.reason}>
<FieldLabel></FieldLabel>
<FieldLabel>{t("ticket.assignReason")}</FieldLabel>
<FieldContent>
<Textarea rows={4} placeholder="填写指派说明" {...register("reason")} />
<Textarea rows={4} placeholder={t("ticket.assignReasonPlaceholder")} {...register("reason")} />
<FieldError errors={[errors.reason]} />
</FieldContent>
</Field>
</div>
<DialogFooter className="mx-0 mb-0 px-6 py-4">
<Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
{t("ticket.cancel")}
</Button>
<Button type="submit" disabled={saving}>
{saving ? "提交中..." : "确认指派"}
{saving ? t("ticket.submitting") : t("ticket.confirmAssign")}
</Button>
</DialogFooter>
</form>
@@ -31,6 +31,7 @@ import {
type UpdateTicketPayload,
updateTicket,
} from "@/lib/api/ticket"
import { useI18n } from "@/i18n/provider"
import { cn, formatDateTime } from "@/lib/utils"
import { EditDialog } from "./edit"
import { TicketAssignDialog } from "./ticket-assign-dialog"
@@ -43,18 +44,22 @@ type TicketDetailDialogProps = {
onChanged: () => void
}
const statusOptions: Array<{ value: TicketStatus; label: string }> = [
{ value: "pending", label: "待处理" },
{ value: "in_progress", label: "处理中" },
{ value: "done", label: "已处理" },
]
type TFunction = (key: string, values?: Record<string, string | number>) => string
function sourceLabel(source: string) {
function getStatusOptions(t: TFunction): Array<{ value: TicketStatus; label: string }> {
return [
{ value: "pending", label: t("ticket.statusPending") },
{ value: "in_progress", label: t("ticket.statusInProgress") },
{ value: "done", label: t("ticket.statusDone") },
]
}
function sourceLabel(source: string, t: TFunction) {
switch (source) {
case "manual":
return "手动创建"
return t("ticket.manualCreated")
case "conversation":
return "会话生成"
return t("ticket.conversationGenerated")
default:
return source || "-"
}
@@ -77,6 +82,7 @@ export function TicketDetailDialog({
onOpenChange,
onChanged,
}: TicketDetailDialogProps) {
const t = useI18n()
const [detail, setDetail] = useState<TicketDetail | null>(null)
const [loading, setLoading] = useState(false)
const [statusSaving, setStatusSaving] = useState<TicketStatus | null>(null)
@@ -120,13 +126,13 @@ export function TicketDetailDialog({
if (loadSeqRef.current !== seq || !isCurrentOperation(targetTicketId, dialogSeq)) {
return
}
toast.error(error instanceof Error ? error.message : "加载工单详情失败")
toast.error(error instanceof Error ? error.message : t("ticket.loadDetailFailed"))
} finally {
if (loadSeqRef.current === seq) {
setLoading(false)
}
}
}, [open, ticketId])
}, [open, t, ticketId])
useEffect(() => {
dialogSeqRef.current += 1
@@ -160,7 +166,7 @@ export function TicketDetailDialog({
if (!isCurrentOperation(activeTicketId, activeDialogSeq)) {
return
}
toast.success("工单状态已更新")
toast.success(t("ticket.statusUpdated"))
await loadDetail(activeTicketId, activeDialogSeq)
if (!isCurrentOperation(activeTicketId, activeDialogSeq)) {
return
@@ -170,7 +176,7 @@ export function TicketDetailDialog({
if (!isCurrentOperation(activeTicketId, activeDialogSeq)) {
return
}
toast.error(error instanceof Error ? error.message : "更新工单状态失败")
toast.error(error instanceof Error ? error.message : t("ticket.statusUpdateFailed"))
} finally {
if (isCurrentOperation(activeTicketId, activeDialogSeq)) {
setStatusSaving(null)
@@ -186,7 +192,7 @@ export function TicketDetailDialog({
const activeDialogSeq = dialogSeqRef.current
const content = progressContent.trim()
if (isRichTextEmpty(content)) {
toast.error("请填写处理进展")
toast.error(t("ticket.progressRequired"))
return
}
setProgressSaving(true)
@@ -198,7 +204,7 @@ export function TicketDetailDialog({
if (!isCurrentOperation(activeTicketId, activeDialogSeq)) {
return
}
toast.success("处理进展已记录")
toast.success(t("ticket.progressRecorded"))
setProgressContent("")
setProgressOpen(false)
await loadDetail(activeTicketId, activeDialogSeq)
@@ -210,7 +216,7 @@ export function TicketDetailDialog({
if (!isCurrentOperation(activeTicketId, activeDialogSeq)) {
return
}
toast.error(error instanceof Error ? error.message : "记录处理进展失败")
toast.error(error instanceof Error ? error.message : t("ticket.progressCreateFailed"))
} finally {
if (isCurrentOperation(activeTicketId, activeDialogSeq)) {
setProgressSaving(false)
@@ -233,7 +239,7 @@ export function TicketDetailDialog({
async function handleUpdateTicket(payload: CreateTicketPayload | UpdateTicketPayload) {
if (!("ticketId" in payload) || payload.ticketId <= 0) {
toast.error("请选择工单")
toast.error(t("ticket.selectTicket"))
return
}
const activeDialogSeq = dialogSeqRef.current
@@ -243,7 +249,7 @@ export function TicketDetailDialog({
if (!isCurrentOperation(payload.ticketId, activeDialogSeq)) {
return
}
toast.success("工单已更新")
toast.success(t("ticket.updated"))
setEditOpen(false)
await loadDetail(payload.ticketId, activeDialogSeq)
if (!isCurrentOperation(payload.ticketId, activeDialogSeq)) {
@@ -254,7 +260,7 @@ export function TicketDetailDialog({
if (!isCurrentOperation(payload.ticketId, activeDialogSeq)) {
return
}
toast.error(error instanceof Error ? error.message : "更新工单失败")
toast.error(error instanceof Error ? error.message : t("ticket.updateFailed"))
} finally {
if (isCurrentOperation(payload.ticketId, activeDialogSeq)) {
setEditSaving(false)
@@ -265,7 +271,7 @@ export function TicketDetailDialog({
async function handleUpdateCustomer(payload: CustomerFormSavePayload) {
const activeCustomerId = getTicketCustomerId(ticket)
if (!ticket?.id || activeCustomerId <= 0) {
toast.error("当前工单未关联客户")
toast.error(t("ticket.noLinkedCustomer"))
return
}
if (customerEditSaving) {
@@ -279,7 +285,7 @@ export function TicketDetailDialog({
if (!isCurrentOperation(activeTicketId, activeDialogSeq)) {
return
}
toast.success("已保存")
toast.success(t("ticket.saved"))
setCustomerEditOpen(false)
await loadDetail(activeTicketId, activeDialogSeq)
if (!isCurrentOperation(activeTicketId, activeDialogSeq)) {
@@ -290,7 +296,7 @@ export function TicketDetailDialog({
if (!isCurrentOperation(activeTicketId, activeDialogSeq)) {
return
}
toast.error(error instanceof Error ? error.message : "保存失败")
toast.error(error instanceof Error ? error.message : t("ticket.saveFailed"))
} finally {
if (isCurrentOperation(activeTicketId, activeDialogSeq)) {
setCustomerEditSaving(false)
@@ -313,6 +319,7 @@ export function TicketDetailDialog({
const ticket = detail?.ticket
const customerId = getTicketCustomerId(ticket)
const statusOptions = getStatusOptions(t)
return (
<>
@@ -321,7 +328,7 @@ export function TicketDetailDialog({
onOpenChange={onOpenChange}
title={
<div className="flex min-w-0 items-center gap-2 pr-16 text-base">
<span className="truncate">{ticket?.title ?? "工单详情"}</span>
<span className="truncate">{ticket?.title ?? t("ticket.detailTitle")}</span>
{ticket ? <TicketStatusBadge status={ticket.status} /> : null}
</div>
}
@@ -329,8 +336,8 @@ export function TicketDetailDialog({
ticket ? (
<span className="flex flex-wrap items-center gap-2 text-sm">
<span className="font-mono">{ticket.ticketNo}</span>
<span>{sourceLabel(ticket.source)}</span>
<span>{metadataValue(ticket.createdByName || ticket.createdBy)}</span>
<span>{sourceLabel(ticket.source, t)}</span>
<span>{t("ticket.creator", { name: metadataValue(ticket.createdByName || ticket.createdBy) })}</span>
</span>
) : undefined
}
@@ -342,21 +349,21 @@ export function TicketDetailDialog({
{loading && !ticket ? (
<div className="flex h-130 items-center justify-center gap-2 text-sm text-muted-foreground">
<RefreshCcwIcon className="size-4 animate-spin" />
...
{t("ticket.loading")}
</div>
) : ticket ? (
<div className="grid w-full h-full grid-cols-1 overflow-hidden lg:grid-cols-[minmax(0,1fr)_380px] border-t">
<div className="min-h-0 space-y-5 overflow-y-auto border-b p-6 lg:border-r lg:border-b-0">
<section className="space-y-2">
<div className="text-sm font-medium text-muted-foreground"></div>
<div className="text-sm font-medium text-muted-foreground">{t("ticket.description")}</div>
<div className="rounded-md border bg-muted/30 px-3 py-2">
<SafeRichHTML html={ticket.description} fallback="暂无描述" />
<SafeRichHTML html={ticket.description} fallback={t("ticket.noDescription")} />
</div>
</section>
<section className="grid gap-4 md:grid-cols-[minmax(0,1fr)_220px]">
<div className="space-y-2">
<div className="text-sm font-medium text-muted-foreground"></div>
<div className="text-sm font-medium text-muted-foreground">{t("ticket.columnStatus")}</div>
<div className="flex flex-wrap gap-2">
{statusOptions.map((option) => (
<Button
@@ -367,20 +374,20 @@ export function TicketDetailDialog({
disabled={!!statusSaving}
onClick={() => void handleStatusChange(option.value)}
>
{statusSaving === option.value ? "更新中..." : option.label}
{statusSaving === option.value ? t("ticket.updating") : option.label}
</Button>
))}
</div>
</div>
<div className="space-y-2">
<div className="text-sm font-medium text-muted-foreground"></div>
<div className="text-sm font-medium text-muted-foreground">{t("ticket.columnAssignee")}</div>
<div className="flex items-center justify-between gap-2 rounded-md border px-3 py-2">
<div className="flex min-w-0 items-center gap-2 text-sm">
<UserRoundIcon className="size-4 shrink-0 text-muted-foreground" />
<span className="truncate">{ticket.currentAssigneeName || "未分配"}</span>
<span className="truncate">{ticket.currentAssigneeName || t("ticket.unassigned")}</span>
</div>
<Button type="button" size="sm" variant="outline" onClick={() => setAssignOpen(true)}>
{t("ticket.assign")}
</Button>
</div>
</div>
@@ -388,9 +395,9 @@ export function TicketDetailDialog({
<section className="space-y-2">
<div className="flex items-center justify-between gap-2">
<div className="text-sm font-medium text-muted-foreground"></div>
<div className="text-sm font-medium text-muted-foreground">{t("ticket.tags")}</div>
<Button type="button" size="sm" variant="outline" onClick={() => setEditOpen(true)}>
{t("ticket.edit")}
</Button>
</div>
{ticket.tags && ticket.tags.length > 0 ? (
@@ -402,13 +409,13 @@ export function TicketDetailDialog({
))}
</div>
) : (
<div className="text-sm text-muted-foreground"></div>
<div className="text-sm text-muted-foreground">{t("ticket.emptyTags")}</div>
)}
</section>
<section className="space-y-3 rounded-md border p-3 text-sm">
<div className="flex items-center justify-between gap-2">
<div className="font-medium text-muted-foreground"></div>
<div className="font-medium text-muted-foreground">{t("ticket.customerInfo")}</div>
<Button
type="button"
variant="ghost"
@@ -423,22 +430,22 @@ export function TicketDetailDialog({
}}
>
<PencilIcon className="size-3.5" />
{customerId > 0 ? "编辑" : "关联或创建"}
{customerId > 0 ? t("ticket.edit") : t("ticket.linkOrCreate")}
</Button>
</div>
<div className="grid gap-3 sm:grid-cols-2">
<MetadataItem label="客户" value={ticket.customer?.name || ticket.customerId} />
<MetadataItem label="联系方式" value={ticket.customer?.primaryMobile || ticket.customer?.primaryEmail} />
<MetadataItem label={t("ticket.customer")} value={ticket.customer?.name || ticket.customerId} />
<MetadataItem label={t("ticket.contact")} value={ticket.customer?.primaryMobile || ticket.customer?.primaryEmail} />
</div>
</section>
<section className="space-y-3 rounded-md border p-3 text-sm">
<div className="font-medium text-muted-foreground"></div>
<div className="font-medium text-muted-foreground">{t("ticket.ticketInfo")}</div>
<div className="grid gap-3 sm:grid-cols-2">
<MetadataItem label="来源" value={sourceLabel(ticket.source)} />
<MetadataItem label="渠道" value={ticket.channel} />
<MetadataItem label="会话 ID" value={ticket.conversationId || undefined} />
<MetadataItem label="最后更新" value={ticket.updatedAt ? formatDateTime(ticket.updatedAt) : undefined} />
<MetadataItem label={t("ticket.source")} value={sourceLabel(ticket.source, t)} />
<MetadataItem label={t("ticket.channel")} value={ticket.channel} />
<MetadataItem label={t("ticket.conversationId")} value={ticket.conversationId || undefined} />
<MetadataItem label={t("ticket.columnUpdated")} value={ticket.updatedAt ? formatDateTime(ticket.updatedAt) : undefined} />
</div>
</section>
</div>
@@ -447,11 +454,11 @@ export function TicketDetailDialog({
<div className="flex items-center justify-between gap-2 px-4 py-2">
<div className="flex items-center gap-2 text-sm font-medium">
<MessageSquareTextIcon className="size-4 text-muted-foreground" />
{t("ticket.progress")}
</div>
<Button type="button" size="sm" onClick={() => setProgressOpen(true)}>
<PlusIcon className="size-3.5" />
{t("ticket.addProgress")}
</Button>
</div>
<Separator />
@@ -471,7 +478,7 @@ export function TicketDetailDialog({
</div>
<div className="min-w-0 flex-1 pb-3">
<div className="flex flex-wrap items-center gap-2 text-sm text-muted-foreground">
<span>{progress.authorName || `用户#${progress.authorId}`}</span>
<span>{progress.authorName || t("ticket.userFallback", { id: progress.authorId })}</span>
<span>{progress.createdAt ? formatDateTime(progress.createdAt) : "-"}</span>
</div>
<SafeRichHTML html={progress.content} className="mt-1" />
@@ -481,14 +488,14 @@ export function TicketDetailDialog({
</div>
) : (
<div className="rounded-md border border-dashed px-3 py-6 text-center text-sm text-muted-foreground">
{t("ticket.noProgress")}
</div>
)}
</div>
</aside>
</div>
) : (
<div className="flex h-[360px] items-center justify-center text-sm text-muted-foreground"></div>
<div className="flex h-[360px] items-center justify-center text-sm text-muted-foreground">{t("ticket.chooseTicket")}</div>
)}
</ProjectDialog>
@@ -533,13 +540,13 @@ export function TicketDetailDialog({
>
<DialogContent className="max-w-2xl gap-0 p-0 sm:max-w-3xl">
<DialogHeader className="px-6 pt-6">
<DialogTitle></DialogTitle>
<DialogTitle>{t("ticket.addProgress")}</DialogTitle>
</DialogHeader>
<div className="px-6 py-4">
<ContentEditor
value={{ mode: "html", raw: progressContent }}
onChange={(next) => setProgressContent(next.raw)}
placeholder="记录本次处理进展"
placeholder={t("ticket.progressPlaceholder")}
disabled={progressSaving}
allowedModes={["html"]}
height={260}
@@ -555,11 +562,11 @@ export function TicketDetailDialog({
setProgressContent("")
}}
>
{t("ticket.cancel")}
</Button>
<Button type="button" disabled={progressSaving} onClick={() => void handleCreateProgress()}>
<SendIcon className="size-3.5" />
{progressSaving ? "提交中..." : "提交"}
{progressSaving ? t("ticket.submitting") : t("ticket.submit")}
</Button>
</DialogFooter>
</DialogContent>
@@ -1,24 +1,26 @@
"use client"
import { Badge } from "@/components/ui/badge"
import { useI18n } from "@/i18n/provider"
import type { TicketStatus } from "@/lib/api/ticket"
const statusMap = {
pending: { label: "待处理", className: "border-amber-200 bg-amber-50 text-amber-700" },
in_progress: { label: "处理中", className: "border-blue-200 bg-blue-50 text-blue-700" },
done: { label: "已处理", className: "border-emerald-200 bg-emerald-50 text-emerald-700" },
pending: { labelKey: "ticket.statusPending", className: "border-amber-200 bg-amber-50 text-amber-700" },
in_progress: { labelKey: "ticket.statusInProgress", className: "border-blue-200 bg-blue-50 text-blue-700" },
done: { labelKey: "ticket.statusDone", className: "border-emerald-200 bg-emerald-50 text-emerald-700" },
} as const
export function ticketStatusLabel(status: string) {
return statusMap[status as TicketStatus]?.label ?? status
return status
}
export function TicketStatusBadge({ status }: { status: string }) {
const t = useI18n()
const option = statusMap[status as TicketStatus]
return (
<Badge variant="outline" className={option?.className ?? "border-border bg-muted text-muted-foreground"}>
{option?.label ?? status}
{option ? t(option.labelKey) : status}
</Badge>
)
}
+65 -50
View File
@@ -39,6 +39,7 @@ import {
type TicketStatus,
type TicketSummary,
} from "@/lib/api/ticket"
import { useI18n } from "@/i18n/provider"
import { cn, formatDateTime } from "@/lib/utils"
import { EditDialog } from "./_components/edit"
import { TicketDetailDialog } from "./_components/ticket-detail-dialog"
@@ -63,13 +64,23 @@ const emptySummary: TicketSummary = {
stale: 0,
}
const assigneeAllOption: ComboboxOption = { value: "0", label: "全部负责人" }
const tagAllOption: ComboboxOption = { value: "0", label: "全部标签" }
const staleHourOptions: ComboboxOption[] = [
{ value: "24", label: "24 小时" },
{ value: "48", label: "48 小时" },
{ value: "168", label: "168 小时" },
]
type TFunction = (key: string, values?: Record<string, string | number>) => string
function getAssigneeAllOption(t: TFunction): ComboboxOption {
return { value: "0", label: t("ticket.allAssignees") }
}
function getTagAllOption(t: TFunction): ComboboxOption {
return { value: "0", label: t("ticket.allTags") }
}
function getStaleHourOptions(t: TFunction): ComboboxOption[] {
return [
{ value: "24", label: t("ticket.hours", { hours: 24 }) },
{ value: "48", label: t("ticket.hours", { hours: 48 }) },
{ value: "168", label: t("ticket.hours", { hours: 168 }) },
]
}
function buildTagOptions(nodes: TagTree[], parentPath = ""): ComboboxOption[] {
const result: ComboboxOption[] = []
@@ -86,28 +97,29 @@ function buildTagOptions(nodes: TagTree[], parentPath = ""): ComboboxOption[] {
return result
}
function sourceLabel(source: string) {
function sourceLabel(source: string, t: TFunction) {
switch (source) {
case "manual":
return "手动"
return t("ticket.manual")
case "conversation":
return "会话"
return t("ticket.conversation")
default:
return source || "-"
}
}
function assigneeLabel(ticket: TicketItem) {
function assigneeLabel(ticket: TicketItem, t: TFunction) {
if (ticket.currentAssigneeName) {
return ticket.currentAssigneeName
}
if (ticket.currentAssigneeId > 0) {
return `客服#${ticket.currentAssigneeId}`
return t("ticket.agentFallback", { id: ticket.currentAssigneeId })
}
return "未分配"
return t("ticket.unassigned")
}
export default function TicketsPage() {
const t = useI18n()
const searchParams = useSearchParams()
const [tickets, setTickets] = useState<TicketItem[]>([])
const [summary, setSummary] = useState<TicketSummary>(emptySummary)
@@ -116,8 +128,8 @@ export default function TicketsPage() {
const [assigneeId, setAssigneeId] = useState("0")
const [tagId, setTagId] = useState("0")
const [staleHours, setStaleHours] = useState("24")
const [assigneeOptions, setAssigneeOptions] = useState<ComboboxOption[]>([assigneeAllOption])
const [tagOptions, setTagOptions] = useState<ComboboxOption[]>([tagAllOption])
const [assigneeOptions, setAssigneeOptions] = useState<ComboboxOption[]>([])
const [tagOptions, setTagOptions] = useState<ComboboxOption[]>([])
const [loading, setLoading] = useState(false)
const [selectedTicketId, setSelectedTicketId] = useState<number | null>(null)
const [detailOpen, setDetailOpen] = useState(false)
@@ -128,16 +140,19 @@ export default function TicketsPage() {
const quickViews = useMemo(
() =>
[
{ key: "all", label: "全部工单", count: summary.all },
{ key: "pending", label: "待处理", count: summary.pending },
{ key: "in_progress", label: "处理中", count: summary.inProgress },
{ key: "done", label: "已处理", count: summary.done },
{ key: "unassigned", label: "待分配", count: summary.unassigned },
{ key: "mine", label: "我的工单", count: summary.mine },
{ key: "stale", label: "长时间未更新", count: summary.stale },
{ key: "all", label: t("ticket.quickAll"), count: summary.all },
{ key: "pending", label: t("ticket.quickPending"), count: summary.pending },
{ key: "in_progress", label: t("ticket.quickInProgress"), count: summary.inProgress },
{ key: "done", label: t("ticket.quickDone"), count: summary.done },
{ key: "unassigned", label: t("ticket.quickUnassigned"), count: summary.unassigned },
{ key: "mine", label: t("ticket.quickMine"), count: summary.mine },
{ key: "stale", label: t("ticket.quickStale"), count: summary.stale },
] satisfies Array<{ key: QuickViewKey; label: string; count: number }>,
[summary],
[summary, t],
)
const assigneeAllOption = useMemo(() => getAssigneeAllOption(t), [t])
const tagAllOption = useMemo(() => getTagAllOption(t), [t])
const staleHourOptions = useMemo(() => getStaleHourOptions(t), [t])
const loadData = useCallback(async () => {
const seq = loadSeqRef.current + 1
@@ -179,13 +194,13 @@ export default function TicketsPage() {
if (loadSeqRef.current !== seq) {
return
}
toast.error(error instanceof Error ? error.message : "加载工单失败")
toast.error(error instanceof Error ? error.message : t("ticket.loadFailed"))
} finally {
if (loadSeqRef.current === seq) {
setLoading(false)
}
}
}, [assigneeId, keyword, quickView, staleHours, tagId])
}, [assigneeId, keyword, quickView, staleHours, tagId, t])
useEffect(() => {
void loadData()
@@ -214,18 +229,18 @@ export default function TicketsPage() {
agent.displayName ||
agent.nickname ||
agent.username ||
`客服#${agent.userId}`,
t("ticket.agentFallback", { id: agent.userId }),
})),
])
setTagOptions([tagAllOption, ...buildTagOptions(Array.isArray(tags) ? tags : [])])
})
.catch((error) => {
toast.error(error instanceof Error ? error.message : "加载筛选项失败")
toast.error(error instanceof Error ? error.message : t("ticket.loadFiltersFailed"))
})
return () => {
active = false
}
}, [])
}, [assigneeAllOption, tagAllOption, t])
function resetFilters() {
setQuickView("all")
@@ -239,11 +254,11 @@ export default function TicketsPage() {
setSavingCreate(true)
try {
await createTicket(payload)
toast.success("工单已创建")
toast.success(t("ticket.created"))
setCreateOpen(false)
await loadData()
} catch (error) {
toast.error(error instanceof Error ? error.message : "创建工单失败")
toast.error(error instanceof Error ? error.message : t("ticket.createFailed"))
} finally {
setSavingCreate(false)
}
@@ -282,18 +297,18 @@ export default function TicketsPage() {
<>
<Button type="button" variant="outline" onClick={() => void loadData()} disabled={loading}>
<RefreshCcwIcon className={cn("size-4", loading ? "animate-spin" : "")} />
{t("ticket.refresh")}
</Button>
<Button type="button" onClick={() => setCreateOpen(true)}>
<PlusIcon className="size-4" />
{t("ticket.newTicket")}
</Button>
</>
}
>
<Input
className="w-full sm:w-72"
placeholder="搜索编号、标题或描述"
placeholder={t("ticket.searchPlaceholder")}
value={keyword}
onChange={(event) => setKeyword(event.target.value)}
onKeyDown={(event) => {
@@ -306,7 +321,7 @@ export default function TicketsPage() {
<OptionCombobox
value={assigneeId}
onChange={setAssigneeId}
placeholder="全部负责人"
placeholder={t("ticket.allAssignees")}
options={assigneeOptions}
/>
</div>
@@ -314,7 +329,7 @@ export default function TicketsPage() {
<OptionCombobox
value={tagId}
onChange={setTagId}
placeholder="全部标签"
placeholder={t("ticket.allTags")}
options={tagOptions}
/>
</div>
@@ -322,21 +337,21 @@ export default function TicketsPage() {
<OptionCombobox
value={staleHours}
onChange={setStaleHours}
placeholder="未更新阈值"
placeholder={t("ticket.staleThreshold")}
options={staleHourOptions}
/>
</div>
<Button type="button" variant="outline" onClick={resetFilters}>
<SearchXIcon className="size-4" />
{t("ticket.reset")}
</Button>
<Button type="button" variant="outline" onClick={() => void loadData()} disabled={loading}>
<RefreshCcwIcon className={cn("size-4", loading ? "animate-spin" : "")} />
{t("ticket.refresh")}
</Button>
<Button type="button" onClick={() => void loadData()} disabled={loading}>
<SearchIcon className="size-4" />
{t("ticket.query")}
</Button>
</DashboardToolbar>
@@ -344,11 +359,11 @@ export default function TicketsPage() {
<Table>
<TableHeader>
<TableRow>
<TableHead></TableHead>
<TableHead className="w-28"></TableHead>
<TableHead className="w-36"></TableHead>
<TableHead className="w-40"></TableHead>
<TableHead className="w-24 text-right"></TableHead>
<TableHead>{t("ticket.columnTicket")}</TableHead>
<TableHead className="w-28">{t("ticket.columnStatus")}</TableHead>
<TableHead className="w-36">{t("ticket.columnAssignee")}</TableHead>
<TableHead className="w-40">{t("ticket.columnUpdated")}</TableHead>
<TableHead className="w-24 text-right">{t("ticket.columnActions")}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
@@ -356,8 +371,8 @@ export default function TicketsPage() {
<DashboardTableStateRow
colSpan={5}
loading={loading}
loadingText="正在加载工单..."
emptyText="暂无工单"
loadingText={t("ticket.loadingRows")}
emptyText={t("ticket.emptyRows")}
/>
) : (
tickets.map((ticket) => (
@@ -367,8 +382,8 @@ export default function TicketsPage() {
<div className="truncate text-sm font-medium">{ticket.title}</div>
<div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
<span className="font-mono">{ticket.ticketNo}</span>
<span>{ticket.customer?.name || (ticket.customerId ? `客户#${ticket.customerId}` : "无客户")}</span>
<span>{sourceLabel(ticket.source)}</span>
<span>{ticket.customer?.name || (ticket.customerId ? t("ticket.customerFallback", { id: ticket.customerId }) : t("ticket.noCustomer"))}</span>
<span>{sourceLabel(ticket.source, t)}</span>
{ticket.channel ? <span>{ticket.channel}</span> : null}
</div>
{ticket.tags && ticket.tags.length > 0 ? (
@@ -391,7 +406,7 @@ export default function TicketsPage() {
<TicketStatusBadge status={ticket.status} />
</TableCell>
<TableCell className="max-w-36 truncate text-sm text-muted-foreground">
{assigneeLabel(ticket)}
{assigneeLabel(ticket, t)}
</TableCell>
<TableCell className="text-sm text-muted-foreground">
{ticket.updatedAt ? formatDateTime(ticket.updatedAt) : "-"}
@@ -406,7 +421,7 @@ export default function TicketsPage() {
setDetailOpen(true)
}}
>
{t("ticket.detail")}
</Button>
</TableCell>
</TableRow>