feat: refactor quick replies page to use DashboardCrudPage component
- Removed redundant state management and effects from DashboardQuickRepliesPage. - Integrated DashboardCrudPage for handling CRUD operations and filtering. - Created a new DashboardCrudPage component to encapsulate common CRUD logic. - Added utility functions for building and normalizing dashboard CRUD queries. - Implemented tests for the new utility functions to ensure correctness.
This commit is contained in:
+158
-321
@@ -1,18 +1,15 @@
|
||||
"use client"
|
||||
|
||||
import { useCallback, useEffect, useState } from "react"
|
||||
import {
|
||||
Building2Icon,
|
||||
MessagesSquareIcon,
|
||||
MessageSquareMoreIcon,
|
||||
MoreHorizontalIcon,
|
||||
PlusIcon,
|
||||
RefreshCwIcon,
|
||||
SearchIcon,
|
||||
Trash2Icon,
|
||||
} from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { DashboardCrudPage } from "@/components/dashboard/crud"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Switch } from "@/components/ui/switch"
|
||||
import {
|
||||
createChannel,
|
||||
deleteChannel,
|
||||
@@ -21,39 +18,11 @@ import {
|
||||
updateChannelStatus,
|
||||
type AdminChannel,
|
||||
type CreateAdminChannelPayload,
|
||||
type PageResult,
|
||||
} from "@/lib/api/admin"
|
||||
import {
|
||||
DashboardPage,
|
||||
DashboardTableShell,
|
||||
DashboardTableStateRow,
|
||||
DashboardToolbar,
|
||||
} from "@/components/dashboard-page"
|
||||
import { OptionCombobox } from "@/components/option-combobox"
|
||||
import { EditDialog } from "./_components/edit"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { ListPagination } from "@/components/list-pagination"
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table"
|
||||
import { Status, StatusLabels } from "@/lib/generated/enums"
|
||||
import { getEnumOptions } from "@/lib/enums"
|
||||
import { ButtonGroup } from "@/components/ui/button-group"
|
||||
import { Switch } from "@/components/ui/switch"
|
||||
import { Status, StatusLabels } from "@/lib/generated/enums"
|
||||
import { useI18n } from "@/i18n/provider"
|
||||
import { EditDialog } from "./_components/edit"
|
||||
|
||||
function getChannelTypeLabel(channelType: string, t: (key: string) => string) {
|
||||
if (channelType === "wechat_mp") {
|
||||
@@ -87,45 +56,6 @@ function ChannelIcon({ channelType }: { channelType: string }) {
|
||||
|
||||
export default function DashboardChannelsPage() {
|
||||
const t = useI18n()
|
||||
const [nameInput, setNameInput] = useState("")
|
||||
const [channelIdInput, setChannelIdInput] = useState("")
|
||||
const [channelTypeInput, setChannelTypeInput] = useState("all")
|
||||
const [statusInput, setStatusInput] = useState("all")
|
||||
const [name, setName] = useState("")
|
||||
const [channelId, setChannelId] = useState("")
|
||||
const [channelType, setChannelType] = useState("all")
|
||||
const [status, setStatus] = useState("all")
|
||||
const [page, setPage] = useState(1)
|
||||
const [limit, setLimit] = useState(20)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [actionLoadingId, setActionLoadingId] = useState<number | null>(null)
|
||||
const [dialogOpen, setDialogOpen] = useState(false)
|
||||
const [editingItem, setEditingItem] = useState<AdminChannel | null>(null)
|
||||
const [result, setResult] = useState<PageResult<AdminChannel>>({
|
||||
results: [],
|
||||
page: { page: 1, limit: 20, total: 0 },
|
||||
})
|
||||
|
||||
const loadData = useCallback(async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const data = await fetchChannels({
|
||||
name: name.trim() || undefined,
|
||||
channelId: channelId.trim() || undefined,
|
||||
channelType: channelType === "all" ? undefined : channelType,
|
||||
status: status === "all" ? undefined : status,
|
||||
page,
|
||||
limit,
|
||||
})
|
||||
setResult(data)
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : t("channel.loadFailed"))
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [channelId, channelType, limit, name, page, status, t])
|
||||
|
||||
const statusOptions = [
|
||||
{ value: "all", label: t("status.all") },
|
||||
...getEnumOptions(StatusLabels).map((option) => ({
|
||||
@@ -133,7 +63,6 @@ export default function DashboardChannelsPage() {
|
||||
label: getStatusLabel(option.value as Status, t),
|
||||
})),
|
||||
]
|
||||
|
||||
const channelTypeOptions = [
|
||||
{ value: "all", label: t("channel.allTypes") },
|
||||
{ value: "web", label: t("channel.typeWeb") },
|
||||
@@ -141,251 +70,159 @@ export default function DashboardChannelsPage() {
|
||||
{ value: "wxwork_kf", label: t("channel.typeWxworkKf") },
|
||||
]
|
||||
|
||||
useEffect(() => {
|
||||
void loadData()
|
||||
}, [loadData])
|
||||
|
||||
function applyFilters() {
|
||||
setName(nameInput)
|
||||
setChannelId(channelIdInput)
|
||||
setChannelType(channelTypeInput)
|
||||
setStatus(statusInput)
|
||||
setPage(1)
|
||||
}
|
||||
|
||||
function handleFilterKeyDown(event: React.KeyboardEvent<HTMLInputElement>) {
|
||||
if (event.key !== "Enter") {
|
||||
return
|
||||
}
|
||||
event.preventDefault()
|
||||
applyFilters()
|
||||
}
|
||||
|
||||
function openCreateDialog() {
|
||||
setEditingItem(null)
|
||||
setDialogOpen(true)
|
||||
}
|
||||
|
||||
function openEditDialog(item: AdminChannel) {
|
||||
setEditingItem(item)
|
||||
setDialogOpen(true)
|
||||
}
|
||||
|
||||
async function handleSubmit(payload: CreateAdminChannelPayload) {
|
||||
if (saving) {
|
||||
return
|
||||
}
|
||||
setSaving(true)
|
||||
try {
|
||||
if (editingItem) {
|
||||
await updateChannel({ id: editingItem.id, ...payload })
|
||||
toast.success(t("channel.updated", { name: payload.name }))
|
||||
} else {
|
||||
const created = await createChannel(payload)
|
||||
toast.success(t("channel.created", { name: created.name }))
|
||||
}
|
||||
setDialogOpen(false)
|
||||
setEditingItem(null)
|
||||
await loadData()
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : t("channel.saveFailed"))
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function handleToggleStatus(item: AdminChannel) {
|
||||
setActionLoadingId(item.id)
|
||||
try {
|
||||
const nextStatus = item.status === Status.Ok ? Status.Disabled : Status.Ok
|
||||
await updateChannelStatus(item.id, nextStatus)
|
||||
toast.success(t(nextStatus === Status.Ok ? "channel.statusEnabled" : "channel.statusDisabled", { name: item.name }))
|
||||
await loadData()
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : t("channel.statusUpdateFailed"))
|
||||
} finally {
|
||||
setActionLoadingId(null)
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDelete(item: AdminChannel) {
|
||||
setActionLoadingId(item.id)
|
||||
try {
|
||||
await deleteChannel(item.id)
|
||||
toast.success(t("channel.deleted", { name: item.name }))
|
||||
await loadData()
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : t("channel.deleteFailed"))
|
||||
} finally {
|
||||
setActionLoadingId(null)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<DashboardPage>
|
||||
<DashboardToolbar
|
||||
actions={
|
||||
<>
|
||||
<Button variant="outline" onClick={() => void loadData()} disabled={loading}>
|
||||
<RefreshCwIcon className={loading ? "animate-spin" : ""} />
|
||||
{t("channel.refresh")}
|
||||
</Button>
|
||||
<Button onClick={openCreateDialog}>
|
||||
<PlusIcon />
|
||||
{t("channel.new")}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<Input
|
||||
value={nameInput}
|
||||
onChange={(event) => setNameInput(event.target.value)}
|
||||
onKeyDown={handleFilterKeyDown}
|
||||
placeholder={t("channel.filterName")}
|
||||
className="w-full sm:w-56"
|
||||
/>
|
||||
<div className="relative w-full sm:w-72">
|
||||
<SearchIcon className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
value={channelIdInput}
|
||||
onChange={(event) => setChannelIdInput(event.target.value)}
|
||||
onKeyDown={handleFilterKeyDown}
|
||||
placeholder={t("channel.filterChannelId")}
|
||||
className="pl-9"
|
||||
/>
|
||||
</div>
|
||||
<div className="w-full sm:w-40">
|
||||
<OptionCombobox
|
||||
value={channelTypeInput}
|
||||
options={[...channelTypeOptions]}
|
||||
placeholder={t("channel.allTypes")}
|
||||
searchPlaceholder={t("channel.searchType")}
|
||||
emptyText={t("channel.emptyType")}
|
||||
onChange={setChannelTypeInput}
|
||||
/>
|
||||
</div>
|
||||
<div className="w-full sm:w-36">
|
||||
<OptionCombobox
|
||||
value={statusInput}
|
||||
options={[...statusOptions]}
|
||||
placeholder={t("status.all")}
|
||||
searchPlaceholder={t("channel.searchStatus")}
|
||||
emptyText={t("channel.emptyStatus")}
|
||||
onChange={setStatusInput}
|
||||
/>
|
||||
</div>
|
||||
<Button variant="outline" onClick={applyFilters} disabled={loading}>
|
||||
<SearchIcon />
|
||||
{t("channel.query")}
|
||||
</Button>
|
||||
</DashboardToolbar>
|
||||
|
||||
<DashboardTableShell
|
||||
pagination={
|
||||
<ListPagination
|
||||
page={result.page.page}
|
||||
limit={result.page.limit}
|
||||
total={result.page.total}
|
||||
loading={loading}
|
||||
onPageChange={(nextPage) => setPage(nextPage)}
|
||||
onLimitChange={(nextLimit) => {
|
||||
setLimit(nextLimit)
|
||||
setPage(1)
|
||||
}}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>{t("channel.columnChannel")}</TableHead>
|
||||
<TableHead>{t("channel.columnType")}</TableHead>
|
||||
<TableHead>ChannelID</TableHead>
|
||||
<TableHead>{t("channel.columnAgent")}</TableHead>
|
||||
<TableHead>{t("channel.columnStatus")}</TableHead>
|
||||
<TableHead className="w-[88px] text-right">{t("channel.columnActions")}</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{loading || result.results.length === 0 ? (
|
||||
<DashboardTableStateRow
|
||||
colSpan={6}
|
||||
loading={loading}
|
||||
loadingText={t("channel.loading")}
|
||||
emptyText={t("channel.empty")}
|
||||
/>
|
||||
) : null}
|
||||
{result.results.map((item) => (
|
||||
<TableRow key={item.id}>
|
||||
<TableCell>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex size-10 items-center justify-center rounded-2xl bg-muted">
|
||||
<ChannelIcon channelType={item.channelType} />
|
||||
</div>
|
||||
<div>
|
||||
<div className="font-medium">{item.name}</div>
|
||||
<div className="text-xs text-muted-foreground">{getChannelTypeLabel(item.channelType, t)}</div>
|
||||
</div>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant="outline">{getChannelTypeLabel(item.channelType, t)}</Badge>
|
||||
</TableCell>
|
||||
<TableCell className="font-mono text-xs">{item.channelId || "-"}</TableCell>
|
||||
<TableCell>{item.aiAgentName || "-"}</TableCell>
|
||||
<TableCell>
|
||||
<div className="flex items-center gap-3">
|
||||
<Switch
|
||||
checked={item.status === Status.Ok}
|
||||
disabled={actionLoadingId === item.id}
|
||||
onCheckedChange={() => void handleToggleStatus(item)}
|
||||
aria-label={t("channel.toggleStatus", { name: item.name })}
|
||||
/>
|
||||
<Badge variant={item.status === Status.Ok ? "default" : "outline"}>
|
||||
{getStatusLabel(item.status as Status, t)}
|
||||
</Badge>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="text-right">
|
||||
<ButtonGroup className="ml-auto">
|
||||
<Button variant="outline" size="sm" onClick={() => openEditDialog(item)}>
|
||||
{t("channel.edit")}
|
||||
</Button>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger
|
||||
render={<Button variant="outline" size="icon-sm" className="ml-auto" />}
|
||||
aria-label={t("channel.moreActions", { name: item.name })}
|
||||
>
|
||||
<MoreHorizontalIcon />
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem
|
||||
className="text-destructive"
|
||||
disabled={actionLoadingId === item.id}
|
||||
onClick={() => void handleDelete(item)}
|
||||
>
|
||||
<Trash2Icon className="size-4" />
|
||||
{t("channel.delete")}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</ButtonGroup>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</DashboardTableShell>
|
||||
</DashboardPage>
|
||||
|
||||
<EditDialog
|
||||
open={dialogOpen}
|
||||
saving={saving}
|
||||
itemId={editingItem?.id ?? null}
|
||||
onOpenChange={setDialogOpen}
|
||||
onSubmit={handleSubmit}
|
||||
/>
|
||||
</>
|
||||
<DashboardCrudPage<AdminChannel, CreateAdminChannelPayload>
|
||||
filters={[
|
||||
{
|
||||
name: "name",
|
||||
label: t("channel.filterName"),
|
||||
placeholder: t("channel.filterName"),
|
||||
defaultValue: "",
|
||||
trim: true,
|
||||
className: "w-full sm:w-56",
|
||||
},
|
||||
{
|
||||
name: "channelId",
|
||||
label: t("channel.filterChannelId"),
|
||||
placeholder: t("channel.filterChannelId"),
|
||||
defaultValue: "",
|
||||
trim: true,
|
||||
className: "w-full sm:w-72",
|
||||
},
|
||||
{
|
||||
name: "channelType",
|
||||
label: t("channel.allTypes"),
|
||||
type: "select",
|
||||
defaultValue: "all",
|
||||
allValue: "all",
|
||||
options: channelTypeOptions,
|
||||
className: "w-full sm:w-40",
|
||||
},
|
||||
{
|
||||
name: "status",
|
||||
label: t("status.all"),
|
||||
type: "select",
|
||||
defaultValue: "all",
|
||||
allValue: "all",
|
||||
options: statusOptions,
|
||||
className: "w-full sm:w-36",
|
||||
},
|
||||
]}
|
||||
columns={[
|
||||
{
|
||||
key: "channel",
|
||||
label: t("channel.columnChannel"),
|
||||
render: (item) => (
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex size-10 items-center justify-center rounded-2xl bg-muted">
|
||||
<ChannelIcon channelType={item.channelType} />
|
||||
</div>
|
||||
<div>
|
||||
<div className="font-medium">{item.name}</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{getChannelTypeLabel(item.channelType, t)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: "type",
|
||||
label: t("channel.columnType"),
|
||||
render: (item) => (
|
||||
<Badge variant="outline">
|
||||
{getChannelTypeLabel(item.channelType, t)}
|
||||
</Badge>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: "channelId",
|
||||
label: "ChannelID",
|
||||
render: (item) => (
|
||||
<span className="font-mono text-xs">{item.channelId || "-"}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: "agent",
|
||||
label: t("channel.columnAgent"),
|
||||
render: (item) => item.aiAgentName || "-",
|
||||
},
|
||||
{
|
||||
key: "status",
|
||||
label: t("channel.columnStatus"),
|
||||
render: (item, { actionLoading, reload, setActionLoadingId }) => (
|
||||
<div className="flex items-center gap-3">
|
||||
<Switch
|
||||
checked={item.status === Status.Ok}
|
||||
disabled={actionLoading}
|
||||
onCheckedChange={() => {
|
||||
void (async () => {
|
||||
setActionLoadingId(item.id)
|
||||
try {
|
||||
const nextStatus =
|
||||
item.status === Status.Ok ? Status.Disabled : Status.Ok
|
||||
await updateChannelStatus(item.id, nextStatus)
|
||||
toast.success(
|
||||
t(
|
||||
nextStatus === Status.Ok
|
||||
? "channel.statusEnabled"
|
||||
: "channel.statusDisabled",
|
||||
{ name: item.name }
|
||||
)
|
||||
)
|
||||
await reload()
|
||||
} catch (error) {
|
||||
toast.error(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: t("channel.statusUpdateFailed")
|
||||
)
|
||||
} finally {
|
||||
setActionLoadingId(null)
|
||||
}
|
||||
})()
|
||||
}}
|
||||
aria-label={t("channel.toggleStatus", { name: item.name })}
|
||||
/>
|
||||
<Badge variant={item.status === Status.Ok ? "default" : "outline"}>
|
||||
{getStatusLabel(item.status as Status, t)}
|
||||
</Badge>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
]}
|
||||
fetchList={fetchChannels}
|
||||
getItemId={(item) => item.id}
|
||||
createItem={createChannel}
|
||||
updateItem={(item, payload) => updateChannel({ id: item.id, ...payload })}
|
||||
deleteItem={(item) => deleteChannel(item.id)}
|
||||
renderEditDialog={({ open, saving, itemId, onOpenChange, onSubmit }) => (
|
||||
<EditDialog
|
||||
open={open}
|
||||
saving={saving}
|
||||
itemId={itemId}
|
||||
onOpenChange={onOpenChange}
|
||||
onSubmit={onSubmit}
|
||||
/>
|
||||
)}
|
||||
labels={{
|
||||
refresh: t("channel.refresh"),
|
||||
create: t("channel.new"),
|
||||
query: t("channel.query"),
|
||||
loading: t("channel.loading"),
|
||||
empty: t("channel.empty"),
|
||||
actions: t("channel.columnActions"),
|
||||
edit: t("channel.edit"),
|
||||
delete: t("channel.delete"),
|
||||
processing: t("channel.processing"),
|
||||
moreActions: (item) => t("channel.moreActions", { name: item.name }),
|
||||
loadFailed: t("channel.loadFailed"),
|
||||
saveFailed: t("channel.saveFailed"),
|
||||
deleteFailed: t("channel.deleteFailed"),
|
||||
created: (payload) => t("channel.created", { name: payload.name }),
|
||||
updated: (_item, payload) => t("channel.updated", { name: payload.name }),
|
||||
deleted: (item) => t("channel.deleted", { name: item.name }),
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,44 +1,11 @@
|
||||
"use client"
|
||||
|
||||
import {
|
||||
BanIcon,
|
||||
CheckCircle2Icon,
|
||||
MoreHorizontalIcon,
|
||||
PlusIcon,
|
||||
RefreshCwIcon,
|
||||
SearchIcon,
|
||||
Trash2Icon,
|
||||
} from "lucide-react"
|
||||
import { useCallback, useEffect, useState } from "react"
|
||||
import { BanIcon, CheckCircle2Icon } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import {
|
||||
DashboardPage,
|
||||
DashboardTableShell,
|
||||
DashboardTableStateRow,
|
||||
DashboardToolbar,
|
||||
} from "@/components/dashboard-page"
|
||||
import { ListPagination } from "@/components/list-pagination"
|
||||
import { OptionCombobox } from "@/components/option-combobox"
|
||||
import { DashboardCrudPage } from "@/components/dashboard/crud"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { ButtonGroup } from "@/components/ui/button-group"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table"
|
||||
import { type PageResult } from "@/lib/api/admin"
|
||||
import { DropdownMenuItem } from "@/components/ui/dropdown-menu"
|
||||
import {
|
||||
createCompany,
|
||||
deleteCompany,
|
||||
@@ -65,42 +32,6 @@ function getStatusLabel(status: Status, t: (key: string) => string) {
|
||||
|
||||
export default function DashboardCompaniesPage() {
|
||||
const t = useI18n()
|
||||
const [nameInput, setNameInput] = useState("")
|
||||
const [codeInput, setCodeInput] = useState("")
|
||||
const [statusFilterInput, setStatusFilterInput] = useState("all")
|
||||
const [name, setName] = useState("")
|
||||
const [code, setCode] = useState("")
|
||||
const [statusFilter, setStatusFilter] = useState("all")
|
||||
const [page, setPage] = useState(1)
|
||||
const [limit, setLimit] = useState(20)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [actionLoadingId, setActionLoadingId] = useState<number | null>(null)
|
||||
const [dialogOpen, setDialogOpen] = useState(false)
|
||||
const [editingItem, setEditingItem] = useState<AdminCompany | null>(null)
|
||||
const [result, setResult] = useState<PageResult<AdminCompany>>({
|
||||
results: [],
|
||||
page: { page: 1, limit: 20, total: 0 },
|
||||
})
|
||||
|
||||
const loadData = useCallback(async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const data = await fetchCompanies({
|
||||
name: name.trim() || undefined,
|
||||
code: code.trim() || undefined,
|
||||
status: statusFilter === "all" ? undefined : statusFilter,
|
||||
page,
|
||||
limit,
|
||||
})
|
||||
setResult(data)
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : t("company.loadFailed"))
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [code, limit, name, page, statusFilter, t])
|
||||
|
||||
const listStatusOptions = [
|
||||
{ value: "all", label: t("status.all") },
|
||||
...getEnumOptions(StatusLabels)
|
||||
@@ -111,261 +42,165 @@ export default function DashboardCompaniesPage() {
|
||||
})),
|
||||
]
|
||||
|
||||
useEffect(() => {
|
||||
void loadData()
|
||||
}, [loadData])
|
||||
|
||||
function applyFilters() {
|
||||
setName(nameInput)
|
||||
setCode(codeInput)
|
||||
setStatusFilter(statusFilterInput)
|
||||
setPage(1)
|
||||
}
|
||||
|
||||
function handleFilterKeyDown(event: React.KeyboardEvent<HTMLInputElement>) {
|
||||
if (event.key !== "Enter") return
|
||||
event.preventDefault()
|
||||
applyFilters()
|
||||
}
|
||||
|
||||
function handlePageChange(nextPage: number) {
|
||||
if (nextPage < 1 || nextPage === page) return
|
||||
setPage(nextPage)
|
||||
}
|
||||
|
||||
function openCreateDialog() {
|
||||
setEditingItem(null)
|
||||
setDialogOpen(true)
|
||||
}
|
||||
|
||||
function openEditDialog(item: AdminCompany) {
|
||||
setEditingItem(item)
|
||||
setDialogOpen(true)
|
||||
}
|
||||
|
||||
function handleDialogOpenChange(open: boolean) {
|
||||
if (saving) return
|
||||
if (!open) setEditingItem(null)
|
||||
setDialogOpen(open)
|
||||
}
|
||||
|
||||
async function handleSubmit(payload: CreateAdminCompanyPayload) {
|
||||
if (saving) return
|
||||
setSaving(true)
|
||||
try {
|
||||
if (editingItem) {
|
||||
await updateCompany({ id: editingItem.id, ...payload })
|
||||
toast.success(t("company.updated", { name: editingItem.name }))
|
||||
} else {
|
||||
await createCompany(payload)
|
||||
toast.success(t("company.created", { name: payload.name }))
|
||||
}
|
||||
setDialogOpen(false)
|
||||
setEditingItem(null)
|
||||
await loadData()
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : t("company.saveFailed"))
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function handleToggleStatus(item: AdminCompany) {
|
||||
setActionLoadingId(item.id)
|
||||
try {
|
||||
const nextStatus = item.status === 0 ? 1 : 0
|
||||
await updateCompanyStatus(item.id, nextStatus)
|
||||
toast.success(t(nextStatus === 0 ? "company.enabled" : "company.disabled", { name: item.name }))
|
||||
await loadData()
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : t("company.statusUpdateFailed"))
|
||||
} finally {
|
||||
setActionLoadingId(null)
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDelete(item: AdminCompany) {
|
||||
setActionLoadingId(item.id)
|
||||
try {
|
||||
await deleteCompany(item.id)
|
||||
toast.success(t("company.deleted", { name: item.name }))
|
||||
await loadData()
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : t("company.deleteFailed"))
|
||||
} finally {
|
||||
setActionLoadingId(null)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<DashboardPage>
|
||||
<DashboardToolbar
|
||||
actions={
|
||||
<DashboardCrudPage<AdminCompany, CreateAdminCompanyPayload>
|
||||
filters={[
|
||||
{
|
||||
name: "name",
|
||||
label: t("company.filterName"),
|
||||
placeholder: t("company.filterName"),
|
||||
defaultValue: "",
|
||||
trim: true,
|
||||
className: "w-full sm:w-72",
|
||||
},
|
||||
{
|
||||
name: "code",
|
||||
label: t("company.filterCode"),
|
||||
placeholder: t("company.filterCode"),
|
||||
defaultValue: "",
|
||||
trim: true,
|
||||
className: "w-full sm:w-44",
|
||||
},
|
||||
{
|
||||
name: "status",
|
||||
label: t("status.all"),
|
||||
type: "select",
|
||||
defaultValue: "all",
|
||||
allValue: "all",
|
||||
options: listStatusOptions,
|
||||
className: "w-full sm:w-36",
|
||||
},
|
||||
]}
|
||||
columns={[
|
||||
{
|
||||
key: "id",
|
||||
label: "ID",
|
||||
className: "w-20",
|
||||
render: (item) => item.id,
|
||||
},
|
||||
{
|
||||
key: "name",
|
||||
label: t("company.columnName"),
|
||||
render: (item) => <span className="font-medium">{item.name}</span>,
|
||||
},
|
||||
{
|
||||
key: "code",
|
||||
label: t("company.columnCode"),
|
||||
render: (item) => (
|
||||
<span className="text-muted-foreground">{item.code || "-"}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: "customerCount",
|
||||
label: t("company.columnCustomerCount"),
|
||||
className: "w-28",
|
||||
render: (item) => item.customerCount,
|
||||
},
|
||||
{
|
||||
key: "status",
|
||||
label: t("company.columnStatus"),
|
||||
className: "w-24",
|
||||
render: (item) => (
|
||||
<Badge
|
||||
variant={
|
||||
item.status === Status.Ok
|
||||
? "default"
|
||||
: item.status === Status.Deleted
|
||||
? "outline"
|
||||
: "secondary"
|
||||
}
|
||||
>
|
||||
{StatusLabels[item.status as Status]
|
||||
? getStatusLabel(item.status as Status, t)
|
||||
: t("company.unknownStatus")}
|
||||
</Badge>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: "remark",
|
||||
label: t("company.columnRemark"),
|
||||
render: (item) => (
|
||||
<div className="line-clamp-2 max-w-[320px] text-muted-foreground">
|
||||
{item.remark || "-"}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
]}
|
||||
fetchList={fetchCompanies}
|
||||
getItemId={(item) => item.id}
|
||||
createItem={createCompany}
|
||||
updateItem={(item, payload) => updateCompany({ id: item.id, ...payload })}
|
||||
deleteItem={(item) => deleteCompany(item.id)}
|
||||
canDelete={(item) => item.status !== Status.Deleted}
|
||||
renderRowActions={({ item, actionLoading, reload, setActionLoadingId }) => (
|
||||
<DropdownMenuItem
|
||||
disabled={item.status === Status.Deleted}
|
||||
onClick={() => {
|
||||
void (async () => {
|
||||
setActionLoadingId(item.id)
|
||||
try {
|
||||
const nextStatus = item.status === Status.Ok ? Status.Disabled : Status.Ok
|
||||
await updateCompanyStatus(item.id, nextStatus)
|
||||
toast.success(
|
||||
t(nextStatus === Status.Ok ? "company.enabled" : "company.disabled", {
|
||||
name: item.name,
|
||||
})
|
||||
)
|
||||
await reload()
|
||||
} catch (error) {
|
||||
toast.error(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: t("company.statusUpdateFailed")
|
||||
)
|
||||
} finally {
|
||||
setActionLoadingId(null)
|
||||
}
|
||||
})()
|
||||
}}
|
||||
>
|
||||
{actionLoading ? (
|
||||
t("company.processing")
|
||||
) : item.status === Status.Ok ? (
|
||||
<>
|
||||
<Button variant="outline" onClick={() => void loadData()} disabled={loading}>
|
||||
<RefreshCwIcon className={loading ? "animate-spin" : ""} />
|
||||
{t("company.refresh")}
|
||||
</Button>
|
||||
<Button onClick={openCreateDialog}>
|
||||
<PlusIcon />
|
||||
{t("company.new")}
|
||||
</Button>
|
||||
<BanIcon />
|
||||
{t("company.disable")}
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="relative w-full sm:w-72">
|
||||
<SearchIcon className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
value={nameInput}
|
||||
onChange={(event) => setNameInput(event.target.value)}
|
||||
onKeyDown={handleFilterKeyDown}
|
||||
placeholder={t("company.filterName")}
|
||||
className="pl-9"
|
||||
/>
|
||||
</div>
|
||||
<Input
|
||||
value={codeInput}
|
||||
onChange={(event) => setCodeInput(event.target.value)}
|
||||
onKeyDown={handleFilterKeyDown}
|
||||
placeholder={t("company.filterCode")}
|
||||
className="w-full sm:w-44"
|
||||
/>
|
||||
<div className="w-full sm:w-36">
|
||||
<OptionCombobox
|
||||
value={statusFilterInput}
|
||||
onChange={setStatusFilterInput}
|
||||
placeholder={t("status.all")}
|
||||
options={[...listStatusOptions]}
|
||||
/>
|
||||
</div>
|
||||
<Button variant="outline" onClick={applyFilters} disabled={loading}>
|
||||
<SearchIcon />
|
||||
{t("company.query")}
|
||||
</Button>
|
||||
</DashboardToolbar>
|
||||
|
||||
<DashboardTableShell
|
||||
pagination={
|
||||
<ListPagination
|
||||
page={result.page.page}
|
||||
total={result.page.total}
|
||||
limit={result.page.limit}
|
||||
loading={loading}
|
||||
onPageChange={handlePageChange}
|
||||
onLimitChange={(nextLimit) => {
|
||||
setLimit(nextLimit)
|
||||
setPage(1)
|
||||
}}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead className="w-20">ID</TableHead>
|
||||
<TableHead>{t("company.columnName")}</TableHead>
|
||||
<TableHead>{t("company.columnCode")}</TableHead>
|
||||
<TableHead className="w-28">{t("company.columnCustomerCount")}</TableHead>
|
||||
<TableHead className="w-24">{t("company.columnStatus")}</TableHead>
|
||||
<TableHead>{t("company.columnRemark")}</TableHead>
|
||||
<TableHead className="w-40">{t("company.columnActions")}</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{loading || result.results.length === 0 ? (
|
||||
<DashboardTableStateRow
|
||||
colSpan={7}
|
||||
loading={loading}
|
||||
loadingText={t("company.loading")}
|
||||
emptyText={t("company.empty")}
|
||||
/>
|
||||
) : (
|
||||
result.results.map((item) => {
|
||||
const actionLoading = actionLoadingId === item.id
|
||||
return (
|
||||
<TableRow key={item.id}>
|
||||
<TableCell>{item.id}</TableCell>
|
||||
<TableCell className="font-medium">{item.name}</TableCell>
|
||||
<TableCell className="text-muted-foreground">{item.code || "-"}</TableCell>
|
||||
<TableCell>{item.customerCount}</TableCell>
|
||||
<TableCell>
|
||||
<Badge
|
||||
variant={
|
||||
item.status === Status.Ok
|
||||
? "default"
|
||||
: item.status === Status.Deleted
|
||||
? "outline"
|
||||
: "secondary"
|
||||
}
|
||||
>
|
||||
{StatusLabels[item.status as Status] ? getStatusLabel(item.status as Status, t) : t("company.unknownStatus")}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell className="max-w-[320px]">
|
||||
<div className="line-clamp-2 text-muted-foreground">{item.remark || "-"}</div>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<ButtonGroup className="w-full justify-end">
|
||||
<Button variant="outline" size="sm" onClick={() => openEditDialog(item)}>
|
||||
{t("company.edit")}
|
||||
</Button>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger
|
||||
render={
|
||||
<Button variant="outline" size="sm" disabled={actionLoading} />
|
||||
}
|
||||
aria-label={t("company.moreActions", { name: item.name })}
|
||||
>
|
||||
<MoreHorizontalIcon />
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-40 min-w-40">
|
||||
<DropdownMenuItem
|
||||
disabled={item.status === Status.Deleted}
|
||||
onClick={() => void handleToggleStatus(item)}
|
||||
>
|
||||
{actionLoading ? (
|
||||
t("company.processing")
|
||||
) : item.status === Status.Ok ? (
|
||||
<>
|
||||
<BanIcon />
|
||||
{t("company.disable")}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<CheckCircle2Icon />
|
||||
{t("company.enable")}
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
variant="destructive"
|
||||
disabled={item.status === Status.Deleted}
|
||||
onClick={() => void handleDelete(item)}
|
||||
>
|
||||
<Trash2Icon />
|
||||
{t("company.delete")}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</ButtonGroup>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)
|
||||
})
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</DashboardTableShell>
|
||||
</DashboardPage>
|
||||
|
||||
<EditDialog
|
||||
open={dialogOpen}
|
||||
saving={saving}
|
||||
itemId={editingItem?.id ?? null}
|
||||
onOpenChange={handleDialogOpenChange}
|
||||
onSubmit={handleSubmit}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<CheckCircle2Icon />
|
||||
{t("company.enable")}
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
renderEditDialog={({ open, saving, itemId, onOpenChange, onSubmit }) => (
|
||||
<EditDialog
|
||||
open={open}
|
||||
saving={saving}
|
||||
itemId={itemId}
|
||||
onOpenChange={onOpenChange}
|
||||
onSubmit={onSubmit}
|
||||
/>
|
||||
)}
|
||||
labels={{
|
||||
refresh: t("company.refresh"),
|
||||
create: t("company.new"),
|
||||
query: t("company.query"),
|
||||
loading: t("company.loading"),
|
||||
empty: t("company.empty"),
|
||||
actions: t("company.columnActions"),
|
||||
edit: t("company.edit"),
|
||||
delete: t("company.delete"),
|
||||
processing: t("company.processing"),
|
||||
moreActions: (item) => t("company.moreActions", { name: item.name }),
|
||||
loadFailed: t("company.loadFailed"),
|
||||
saveFailed: t("company.saveFailed"),
|
||||
deleteFailed: t("company.deleteFailed"),
|
||||
created: (payload) => t("company.created", { name: payload.name }),
|
||||
updated: (item) => t("company.updated", { name: item.name }),
|
||||
deleted: (item) => t("company.deleted", { name: item.name }),
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,42 +1,11 @@
|
||||
"use client"
|
||||
|
||||
import { useCallback, useEffect, useState } from "react"
|
||||
import {
|
||||
FileTextIcon,
|
||||
MoreHorizontalIcon,
|
||||
PlusIcon,
|
||||
RefreshCwIcon,
|
||||
SearchIcon,
|
||||
Trash2Icon,
|
||||
} from "lucide-react"
|
||||
import { FileTextIcon, RefreshCwIcon } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import {
|
||||
DashboardPage,
|
||||
DashboardTableShell,
|
||||
DashboardTableStateRow,
|
||||
DashboardToolbar,
|
||||
} from "@/components/dashboard-page"
|
||||
import { ListPagination } from "@/components/list-pagination"
|
||||
import { OptionCombobox } from "@/components/option-combobox"
|
||||
import { DashboardCrudPage } from "@/components/dashboard/crud"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { ButtonGroup } from "@/components/ui/button-group"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table"
|
||||
import { DropdownMenuItem } from "@/components/ui/dropdown-menu"
|
||||
import {
|
||||
createQuickReply,
|
||||
deleteQuickReply,
|
||||
@@ -44,7 +13,6 @@ import {
|
||||
updateQuickReply,
|
||||
type AdminQuickReply,
|
||||
type CreateAdminQuickReplyPayload,
|
||||
type PageResult,
|
||||
} from "@/lib/api/admin"
|
||||
import { getEnumOptions } from "@/lib/enums"
|
||||
import { Status, StatusLabels } from "@/lib/generated/enums"
|
||||
@@ -63,42 +31,6 @@ function getStatusLabel(status: Status, t: (key: string) => string) {
|
||||
|
||||
export default function DashboardQuickRepliesPage() {
|
||||
const t = useI18n()
|
||||
const [keywordInput, setKeywordInput] = useState("")
|
||||
const [groupNameInput, setGroupNameInput] = useState("")
|
||||
const [statusFilterInput, setStatusFilterInput] = useState("all")
|
||||
const [keyword, setKeyword] = useState("")
|
||||
const [groupName, setGroupName] = useState("")
|
||||
const [statusFilter, setStatusFilter] = useState("all")
|
||||
const [page, setPage] = useState(1)
|
||||
const [limit, setLimit] = useState(20)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [actionLoadingId, setActionLoadingId] = useState<number | null>(null)
|
||||
const [dialogOpen, setDialogOpen] = useState(false)
|
||||
const [editingItem, setEditingItem] = useState<AdminQuickReply | null>(null)
|
||||
const [result, setResult] = useState<PageResult<AdminQuickReply>>({
|
||||
results: [],
|
||||
page: { page: 1, limit: 20, total: 0 },
|
||||
})
|
||||
|
||||
const loadData = useCallback(async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const data = await fetchQuickReplies({
|
||||
title: keyword.trim() || undefined,
|
||||
groupName: groupName.trim() || undefined,
|
||||
status: statusFilter === "all" ? undefined : statusFilter,
|
||||
page,
|
||||
limit,
|
||||
})
|
||||
setResult(data)
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : t("quickReply.loadFailed"))
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [groupName, keyword, limit, page, statusFilter, t])
|
||||
|
||||
const listStatusOptions = [
|
||||
{ value: "all", label: t("status.all") },
|
||||
...getEnumOptions(StatusLabels)
|
||||
@@ -109,277 +41,156 @@ export default function DashboardQuickRepliesPage() {
|
||||
})),
|
||||
]
|
||||
|
||||
useEffect(() => {
|
||||
void loadData()
|
||||
}, [loadData])
|
||||
|
||||
function applyFilters() {
|
||||
setKeyword(keywordInput)
|
||||
setGroupName(groupNameInput)
|
||||
setStatusFilter(statusFilterInput)
|
||||
setPage(1)
|
||||
}
|
||||
|
||||
function handleFilterKeyDown(event: React.KeyboardEvent<HTMLInputElement>) {
|
||||
if (event.key !== "Enter") {
|
||||
return
|
||||
}
|
||||
|
||||
event.preventDefault()
|
||||
applyFilters()
|
||||
}
|
||||
|
||||
function handlePageChange(nextPage: number) {
|
||||
if (nextPage < 1 || nextPage === page) {
|
||||
return
|
||||
}
|
||||
setPage(nextPage)
|
||||
}
|
||||
|
||||
function openCreateDialog() {
|
||||
setEditingItem(null)
|
||||
setDialogOpen(true)
|
||||
}
|
||||
|
||||
function openEditDialog(item: AdminQuickReply) {
|
||||
setEditingItem(item)
|
||||
setDialogOpen(true)
|
||||
}
|
||||
|
||||
function handleDialogOpenChange(open: boolean) {
|
||||
if (saving) {
|
||||
return
|
||||
}
|
||||
if (!open) {
|
||||
setEditingItem(null)
|
||||
}
|
||||
setDialogOpen(open)
|
||||
}
|
||||
|
||||
async function handleSubmit(payload: CreateAdminQuickReplyPayload) {
|
||||
if (saving) {
|
||||
return
|
||||
}
|
||||
|
||||
setSaving(true)
|
||||
try {
|
||||
if (editingItem) {
|
||||
await updateQuickReply({
|
||||
id: editingItem.id,
|
||||
...payload,
|
||||
})
|
||||
toast.success(t("quickReply.updated", { title: editingItem.title }))
|
||||
} else {
|
||||
await createQuickReply(payload)
|
||||
toast.success(t("quickReply.created", { title: payload.title }))
|
||||
}
|
||||
setDialogOpen(false)
|
||||
setEditingItem(null)
|
||||
await loadData()
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : t("quickReply.saveFailed"))
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function handleToggleStatus(item: AdminQuickReply) {
|
||||
setActionLoadingId(item.id)
|
||||
try {
|
||||
const nextStatus =
|
||||
item.status === Status.Ok ? Status.Disabled : Status.Ok
|
||||
await updateQuickReply({
|
||||
id: item.id,
|
||||
groupName: item.groupName,
|
||||
title: item.title,
|
||||
content: item.content,
|
||||
sortNo: item.sortNo,
|
||||
status: nextStatus,
|
||||
})
|
||||
toast.success(
|
||||
t(nextStatus === Status.Ok ? "quickReply.enabled" : "quickReply.disabled", { title: item.title })
|
||||
)
|
||||
await loadData()
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : t("quickReply.statusUpdateFailed"))
|
||||
} finally {
|
||||
setActionLoadingId(null)
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDelete(item: AdminQuickReply) {
|
||||
setActionLoadingId(item.id)
|
||||
try {
|
||||
await deleteQuickReply(item.id)
|
||||
toast.success(t("quickReply.deleted", { title: item.title }))
|
||||
await loadData()
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : t("quickReply.deleteFailed"))
|
||||
} finally {
|
||||
setActionLoadingId(null)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<DashboardPage>
|
||||
<DashboardToolbar
|
||||
actions={
|
||||
<>
|
||||
<Button variant="outline" onClick={() => void loadData()} disabled={loading}>
|
||||
<RefreshCwIcon className={loading ? "animate-spin" : undefined} />
|
||||
{t("quickReply.refresh")}
|
||||
</Button>
|
||||
<Button onClick={openCreateDialog}>
|
||||
<PlusIcon />
|
||||
{t("quickReply.new")}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
<DashboardCrudPage<AdminQuickReply, CreateAdminQuickReplyPayload>
|
||||
filters={[
|
||||
{
|
||||
name: "title",
|
||||
label: t("quickReply.filterTitle"),
|
||||
placeholder: t("quickReply.filterTitle"),
|
||||
defaultValue: "",
|
||||
trim: true,
|
||||
className: "w-full sm:w-72",
|
||||
},
|
||||
{
|
||||
name: "groupName",
|
||||
label: t("quickReply.filterGroup"),
|
||||
placeholder: t("quickReply.filterGroup"),
|
||||
defaultValue: "",
|
||||
trim: true,
|
||||
className: "w-full sm:w-44",
|
||||
},
|
||||
{
|
||||
name: "status",
|
||||
label: t("status.all"),
|
||||
type: "select",
|
||||
defaultValue: "all",
|
||||
allValue: "all",
|
||||
options: listStatusOptions,
|
||||
className: "w-full sm:w-36",
|
||||
},
|
||||
]}
|
||||
columns={[
|
||||
{
|
||||
key: "quickReply",
|
||||
label: t("quickReply.columnQuickReply"),
|
||||
render: (item) => (
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="mt-0.5 flex size-8 items-center justify-center rounded-md bg-muted text-muted-foreground">
|
||||
<FileTextIcon className="size-4" />
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<div className="font-medium">{item.title}</div>
|
||||
<div className="mt-1 line-clamp-2 text-sm text-muted-foreground">
|
||||
{item.content}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: "groupName",
|
||||
label: t("quickReply.columnGroup"),
|
||||
render: (item) => <Badge variant="outline">{item.groupName}</Badge>,
|
||||
},
|
||||
{
|
||||
key: "status",
|
||||
label: t("quickReply.columnStatus"),
|
||||
render: (item) => (
|
||||
<Badge variant={item.status === Status.Ok ? "default" : "outline"}>
|
||||
{getStatusLabel(item.status as Status, t)}
|
||||
</Badge>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: "sortNo",
|
||||
label: t("quickReply.columnSort"),
|
||||
render: (item) => item.sortNo,
|
||||
},
|
||||
{
|
||||
key: "createdBy",
|
||||
label: t("quickReply.columnCreator"),
|
||||
render: (item) => item.createdBy || "-",
|
||||
},
|
||||
]}
|
||||
fetchList={fetchQuickReplies}
|
||||
getItemId={(item) => item.id}
|
||||
createItem={createQuickReply}
|
||||
updateItem={(item, payload) => updateQuickReply({ id: item.id, ...payload })}
|
||||
deleteItem={(item) => deleteQuickReply(item.id)}
|
||||
renderRowActions={({ item, actionLoading, reload, setActionLoadingId }) => (
|
||||
<DropdownMenuItem
|
||||
onClick={() => {
|
||||
void (async () => {
|
||||
setActionLoadingId(item.id)
|
||||
try {
|
||||
const nextStatus =
|
||||
item.status === Status.Ok ? Status.Disabled : Status.Ok
|
||||
await updateQuickReply({
|
||||
id: item.id,
|
||||
groupName: item.groupName,
|
||||
title: item.title,
|
||||
content: item.content,
|
||||
sortNo: item.sortNo,
|
||||
status: nextStatus,
|
||||
})
|
||||
toast.success(
|
||||
t(
|
||||
nextStatus === Status.Ok
|
||||
? "quickReply.enabled"
|
||||
: "quickReply.disabled",
|
||||
{ title: item.title }
|
||||
)
|
||||
)
|
||||
await reload()
|
||||
} catch (error) {
|
||||
toast.error(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: t("quickReply.statusUpdateFailed")
|
||||
)
|
||||
} finally {
|
||||
setActionLoadingId(null)
|
||||
}
|
||||
})()
|
||||
}}
|
||||
>
|
||||
<div className="relative w-full sm:w-72">
|
||||
<SearchIcon className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
value={keywordInput}
|
||||
onChange={(event) => setKeywordInput(event.target.value)}
|
||||
onKeyDown={handleFilterKeyDown}
|
||||
placeholder={t("quickReply.filterTitle")}
|
||||
className="pl-9"
|
||||
/>
|
||||
</div>
|
||||
<Input
|
||||
value={groupNameInput}
|
||||
onChange={(event) => setGroupNameInput(event.target.value)}
|
||||
onKeyDown={handleFilterKeyDown}
|
||||
placeholder={t("quickReply.filterGroup")}
|
||||
className="w-full sm:w-44"
|
||||
/>
|
||||
<div className="w-full sm:w-36">
|
||||
<OptionCombobox
|
||||
value={statusFilterInput}
|
||||
onChange={setStatusFilterInput}
|
||||
placeholder={t("status.all")}
|
||||
options={[...listStatusOptions]}
|
||||
/>
|
||||
</div>
|
||||
<Button variant="outline" onClick={applyFilters} disabled={loading}>
|
||||
<SearchIcon />
|
||||
{t("quickReply.query")}
|
||||
</Button>
|
||||
</DashboardToolbar>
|
||||
<DashboardTableShell
|
||||
pagination={
|
||||
<ListPagination
|
||||
page={result.page.page}
|
||||
total={result.page.total}
|
||||
limit={limit}
|
||||
loading={loading}
|
||||
onPageChange={handlePageChange}
|
||||
onLimitChange={(nextLimit) => {
|
||||
setLimit(nextLimit)
|
||||
setPage(1)
|
||||
}}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<Table>
|
||||
<TableHeader className="bg-muted/40">
|
||||
<TableRow>
|
||||
<TableHead>{t("quickReply.columnQuickReply")}</TableHead>
|
||||
<TableHead>{t("quickReply.columnGroup")}</TableHead>
|
||||
<TableHead>{t("quickReply.columnStatus")}</TableHead>
|
||||
<TableHead>{t("quickReply.columnSort")}</TableHead>
|
||||
<TableHead>{t("quickReply.columnCreator")}</TableHead>
|
||||
<TableHead className="w-[92px] text-right">{t("quickReply.columnActions")}</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-8 items-center justify-center rounded-md bg-muted text-muted-foreground">
|
||||
<FileTextIcon className="size-4" />
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<div className="font-medium">{item.title}</div>
|
||||
<div className="mt-1 line-clamp-2 text-sm text-muted-foreground">
|
||||
{item.content}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant="outline">{item.groupName}</Badge>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Badge
|
||||
variant={
|
||||
item.status === Status.Ok ? "default" : "outline"
|
||||
}
|
||||
>
|
||||
{getStatusLabel(item.status as Status, t)}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell>{item.sortNo}</TableCell>
|
||||
<TableCell>{item.createdBy || "-"}</TableCell>
|
||||
<TableCell className="text-right">
|
||||
<ButtonGroup className="ml-auto">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => openEditDialog(item)}
|
||||
>
|
||||
{t("quickReply.edit")}
|
||||
</Button>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger
|
||||
render={<Button variant="outline" size="icon-sm" />}
|
||||
aria-label={t("quickReply.moreActions", { title: item.title })}
|
||||
>
|
||||
<MoreHorizontalIcon />
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-40 min-w-40">
|
||||
<DropdownMenuItem onClick={() => void handleToggleStatus(item)}>
|
||||
<RefreshCwIcon />
|
||||
{actionLoadingId === item.id
|
||||
? t("quickReply.processing")
|
||||
: item.status === Status.Ok
|
||||
? t("quickReply.disable")
|
||||
: t("quickReply.enable")}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => void handleDelete(item)}
|
||||
className="text-destructive focus:text-destructive"
|
||||
>
|
||||
<Trash2Icon />
|
||||
{actionLoadingId === item.id ? t("quickReply.deleting") : t("quickReply.delete")}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</ButtonGroup>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
{loading || result.results.length === 0 ? (
|
||||
<DashboardTableStateRow
|
||||
colSpan={6}
|
||||
loading={loading}
|
||||
loadingText={t("quickReply.loading")}
|
||||
emptyText={t("quickReply.empty")}
|
||||
/>
|
||||
) : null}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</DashboardTableShell>
|
||||
</DashboardPage>
|
||||
<EditDialog
|
||||
open={dialogOpen}
|
||||
saving={saving}
|
||||
itemId={editingItem?.id ?? null}
|
||||
onOpenChange={handleDialogOpenChange}
|
||||
onSubmit={handleSubmit}
|
||||
/>
|
||||
</>
|
||||
<RefreshCwIcon />
|
||||
{actionLoading
|
||||
? t("quickReply.processing")
|
||||
: item.status === Status.Ok
|
||||
? t("quickReply.disable")
|
||||
: t("quickReply.enable")}
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
renderEditDialog={({ open, saving, itemId, onOpenChange, onSubmit }) => (
|
||||
<EditDialog
|
||||
open={open}
|
||||
saving={saving}
|
||||
itemId={itemId}
|
||||
onOpenChange={onOpenChange}
|
||||
onSubmit={onSubmit}
|
||||
/>
|
||||
)}
|
||||
labels={{
|
||||
refresh: t("quickReply.refresh"),
|
||||
create: t("quickReply.new"),
|
||||
query: t("quickReply.query"),
|
||||
loading: t("quickReply.loading"),
|
||||
empty: t("quickReply.empty"),
|
||||
actions: t("quickReply.columnActions"),
|
||||
edit: t("quickReply.edit"),
|
||||
delete: t("quickReply.delete"),
|
||||
processing: t("quickReply.processing"),
|
||||
moreActions: (item) =>
|
||||
t("quickReply.moreActions", { title: item.title }),
|
||||
loadFailed: t("quickReply.loadFailed"),
|
||||
saveFailed: t("quickReply.saveFailed"),
|
||||
deleteFailed: t("quickReply.deleteFailed"),
|
||||
created: (payload) => t("quickReply.created", { title: payload.title }),
|
||||
updated: (item) => t("quickReply.updated", { title: item.title }),
|
||||
deleted: (item) => t("quickReply.deleted", { title: item.title }),
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,415 @@
|
||||
"use client"
|
||||
|
||||
import type { ReactNode } from "react"
|
||||
import { useCallback, useEffect, useMemo, useState } from "react"
|
||||
import {
|
||||
MoreHorizontalIcon,
|
||||
PlusIcon,
|
||||
RefreshCwIcon,
|
||||
SearchIcon,
|
||||
Trash2Icon,
|
||||
} from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import {
|
||||
DashboardPage,
|
||||
DashboardTableShell,
|
||||
DashboardTableStateRow,
|
||||
DashboardToolbar,
|
||||
} from "@/components/dashboard-page"
|
||||
import { ListPagination } from "@/components/list-pagination"
|
||||
import { OptionCombobox } from "@/components/option-combobox"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { ButtonGroup } from "@/components/ui/button-group"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table"
|
||||
import {
|
||||
buildDashboardCrudQuery,
|
||||
normalizeDashboardCrudPageResult,
|
||||
type DashboardCrudPageResult,
|
||||
type DashboardCrudQueryFilter,
|
||||
type DashboardCrudQueryValue,
|
||||
} from "./dashboard-crud-utils"
|
||||
|
||||
type DashboardCrudFilter<TValue extends string | number = string> =
|
||||
DashboardCrudQueryFilter & {
|
||||
label: string
|
||||
placeholder?: string
|
||||
defaultValue: TValue
|
||||
type?: "text" | "select"
|
||||
className?: string
|
||||
options?: ReadonlyArray<{ value: string; label: string }>
|
||||
}
|
||||
|
||||
type DashboardCrudColumn<TItem> = {
|
||||
key: string
|
||||
label: ReactNode
|
||||
className?: string
|
||||
render: (item: TItem, context: DashboardCrudRowActionContext<TItem>) => ReactNode
|
||||
}
|
||||
|
||||
type DashboardCrudDialogProps<TItem, TPayload> = {
|
||||
open: boolean
|
||||
saving: boolean
|
||||
item: TItem | null
|
||||
itemId: number | null
|
||||
onOpenChange: (open: boolean) => void
|
||||
onSubmit: (payload: TPayload) => Promise<void>
|
||||
}
|
||||
|
||||
type DashboardCrudRowActionContext<TItem> = {
|
||||
item: TItem
|
||||
actionLoading: boolean
|
||||
actionLoadingId: number | null
|
||||
reload: () => Promise<void>
|
||||
setActionLoadingId: (id: number | null) => void
|
||||
}
|
||||
|
||||
type DashboardCrudPageProps<TItem, TPayload> = {
|
||||
filters: DashboardCrudFilter[]
|
||||
columns: DashboardCrudColumn<TItem>[]
|
||||
fetchList: (
|
||||
query: Record<string, DashboardCrudQueryValue>
|
||||
) => Promise<DashboardCrudPageResult<TItem>>
|
||||
renderEditDialog: (props: DashboardCrudDialogProps<TItem, TPayload>) => ReactNode
|
||||
getItemId: (item: TItem) => number
|
||||
createItem: (payload: TPayload) => Promise<unknown>
|
||||
updateItem: (item: TItem, payload: TPayload) => Promise<unknown>
|
||||
deleteItem?: (item: TItem) => Promise<unknown>
|
||||
canDelete?: (item: TItem) => boolean
|
||||
renderRowActions?: (context: DashboardCrudRowActionContext<TItem>) => ReactNode
|
||||
pageSize?: number
|
||||
labels: {
|
||||
refresh: string
|
||||
create: string
|
||||
query: string
|
||||
loading: string
|
||||
empty: string
|
||||
actions: string
|
||||
edit: string
|
||||
delete: string
|
||||
processing: string
|
||||
moreActions: (item: TItem) => string
|
||||
loadFailed: string
|
||||
saveFailed: string
|
||||
deleteFailed: string
|
||||
created: (item: TPayload) => string
|
||||
updated: (item: TItem, payload: TPayload) => string
|
||||
deleted?: (item: TItem) => string
|
||||
}
|
||||
}
|
||||
|
||||
export function DashboardCrudPage<TItem, TPayload>({
|
||||
filters,
|
||||
columns,
|
||||
fetchList,
|
||||
renderEditDialog,
|
||||
getItemId,
|
||||
createItem,
|
||||
updateItem,
|
||||
deleteItem,
|
||||
canDelete,
|
||||
renderRowActions,
|
||||
pageSize = 20,
|
||||
labels,
|
||||
}: DashboardCrudPageProps<TItem, TPayload>) {
|
||||
const initialFilters = useMemo(
|
||||
() =>
|
||||
Object.fromEntries(
|
||||
filters.map((filter) => [filter.name, filter.defaultValue])
|
||||
) as Record<string, string | number | undefined>,
|
||||
[filters]
|
||||
)
|
||||
const [draftFilters, setDraftFilters] = useState(initialFilters)
|
||||
const [appliedFilters, setAppliedFilters] = useState(initialFilters)
|
||||
const [page, setPage] = useState(1)
|
||||
const [limit, setLimit] = useState(pageSize)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [actionLoadingId, setActionLoadingId] = useState<number | null>(null)
|
||||
const [dialogOpen, setDialogOpen] = useState(false)
|
||||
const [editingItem, setEditingItem] = useState<TItem | null>(null)
|
||||
const [result, setResult] = useState<DashboardCrudPageResult<TItem>>({
|
||||
results: [],
|
||||
page: { page: 1, limit: pageSize, total: 0 },
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
setDraftFilters(initialFilters)
|
||||
setAppliedFilters(initialFilters)
|
||||
}, [initialFilters])
|
||||
|
||||
const loadData = useCallback(async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const data = await fetchList(
|
||||
buildDashboardCrudQuery({
|
||||
values: appliedFilters,
|
||||
filters,
|
||||
page,
|
||||
limit,
|
||||
})
|
||||
)
|
||||
setResult(normalizeDashboardCrudPageResult(data, page, limit))
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : labels.loadFailed)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [appliedFilters, fetchList, filters, labels.loadFailed, limit, page])
|
||||
|
||||
useEffect(() => {
|
||||
void loadData()
|
||||
}, [loadData])
|
||||
|
||||
function applyFilters() {
|
||||
setAppliedFilters(draftFilters)
|
||||
setPage(1)
|
||||
}
|
||||
|
||||
function handleFilterKeyDown(event: React.KeyboardEvent<HTMLInputElement>) {
|
||||
if (event.key !== "Enter") return
|
||||
event.preventDefault()
|
||||
applyFilters()
|
||||
}
|
||||
|
||||
function openCreateDialog() {
|
||||
setEditingItem(null)
|
||||
setDialogOpen(true)
|
||||
}
|
||||
|
||||
function openEditDialog(item: TItem) {
|
||||
setEditingItem(item)
|
||||
setDialogOpen(true)
|
||||
}
|
||||
|
||||
function handleDialogOpenChange(open: boolean) {
|
||||
if (saving) return
|
||||
if (!open) setEditingItem(null)
|
||||
setDialogOpen(open)
|
||||
}
|
||||
|
||||
async function handleSubmit(payload: TPayload) {
|
||||
if (saving) return
|
||||
setSaving(true)
|
||||
try {
|
||||
if (editingItem) {
|
||||
await updateItem(editingItem, payload)
|
||||
toast.success(labels.updated(editingItem, payload))
|
||||
} else {
|
||||
await createItem(payload)
|
||||
toast.success(labels.created(payload))
|
||||
}
|
||||
setDialogOpen(false)
|
||||
setEditingItem(null)
|
||||
await loadData()
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : labels.saveFailed)
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDelete(item: TItem) {
|
||||
if (!deleteItem) return
|
||||
const id = getItemId(item)
|
||||
setActionLoadingId(id)
|
||||
try {
|
||||
await deleteItem(item)
|
||||
toast.success(labels.deleted?.(item) ?? labels.delete)
|
||||
await loadData()
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : labels.deleteFailed)
|
||||
} finally {
|
||||
setActionLoadingId(null)
|
||||
}
|
||||
}
|
||||
|
||||
const colSpan = columns.length + 1
|
||||
|
||||
return (
|
||||
<>
|
||||
<DashboardPage>
|
||||
<DashboardToolbar
|
||||
actions={
|
||||
<>
|
||||
<Button variant="outline" onClick={() => void loadData()} disabled={loading}>
|
||||
<RefreshCwIcon className={loading ? "animate-spin" : undefined} />
|
||||
{labels.refresh}
|
||||
</Button>
|
||||
<Button onClick={openCreateDialog}>
|
||||
<PlusIcon />
|
||||
{labels.create}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{filters.map((filter) => {
|
||||
const value = draftFilters[filter.name]
|
||||
if (filter.type === "select") {
|
||||
return (
|
||||
<div key={filter.name} className={filter.className ?? "w-full sm:w-40"}>
|
||||
<OptionCombobox
|
||||
value={String(value ?? "")}
|
||||
onChange={(nextValue) =>
|
||||
setDraftFilters((current) => ({
|
||||
...current,
|
||||
[filter.name]: nextValue,
|
||||
}))
|
||||
}
|
||||
placeholder={filter.placeholder ?? filter.label}
|
||||
options={[...(filter.options ?? [])]}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div key={filter.name} className={filter.className ?? "w-full sm:w-64"}>
|
||||
<Input
|
||||
value={String(value ?? "")}
|
||||
onChange={(event) =>
|
||||
setDraftFilters((current) => ({
|
||||
...current,
|
||||
[filter.name]: event.target.value,
|
||||
}))
|
||||
}
|
||||
onKeyDown={handleFilterKeyDown}
|
||||
placeholder={filter.placeholder ?? filter.label}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
<Button variant="outline" onClick={applyFilters} disabled={loading}>
|
||||
<SearchIcon />
|
||||
{labels.query}
|
||||
</Button>
|
||||
</DashboardToolbar>
|
||||
|
||||
<DashboardTableShell
|
||||
pagination={
|
||||
<ListPagination
|
||||
page={result.page.page}
|
||||
total={result.page.total}
|
||||
limit={limit}
|
||||
loading={loading}
|
||||
onPageChange={(nextPage) => {
|
||||
if (nextPage < 1 || nextPage === page) return
|
||||
setPage(nextPage)
|
||||
}}
|
||||
onLimitChange={(nextLimit) => {
|
||||
setLimit(nextLimit)
|
||||
setPage(1)
|
||||
}}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<Table>
|
||||
<TableHeader className="bg-muted/40">
|
||||
<TableRow>
|
||||
{columns.map((column) => (
|
||||
<TableHead key={column.key} className={column.className}>
|
||||
{column.label}
|
||||
</TableHead>
|
||||
))}
|
||||
<TableHead className="w-[92px] text-right">
|
||||
{labels.actions}
|
||||
</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{result.results.map((item) => {
|
||||
const id = getItemId(item)
|
||||
const actionLoading = actionLoadingId === id
|
||||
return (
|
||||
<TableRow key={id}>
|
||||
{columns.map((column) => (
|
||||
<TableCell key={column.key} className={column.className}>
|
||||
{column.render(item, {
|
||||
item,
|
||||
actionLoading,
|
||||
actionLoadingId,
|
||||
reload: loadData,
|
||||
setActionLoadingId,
|
||||
})}
|
||||
</TableCell>
|
||||
))}
|
||||
<TableCell className="text-right">
|
||||
<ButtonGroup className="ml-auto">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => openEditDialog(item)}
|
||||
>
|
||||
{labels.edit}
|
||||
</Button>
|
||||
{renderRowActions || deleteItem ? (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger
|
||||
render={<Button variant="outline" size="icon-sm" />}
|
||||
aria-label={labels.moreActions(item)}
|
||||
>
|
||||
<MoreHorizontalIcon />
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-40 min-w-40">
|
||||
{renderRowActions?.({
|
||||
item,
|
||||
actionLoading,
|
||||
actionLoadingId,
|
||||
reload: loadData,
|
||||
setActionLoadingId,
|
||||
})}
|
||||
{deleteItem ? (
|
||||
<DropdownMenuItem
|
||||
onClick={() => void handleDelete(item)}
|
||||
disabled={canDelete ? !canDelete(item) : false}
|
||||
className="text-destructive focus:text-destructive"
|
||||
>
|
||||
<Trash2Icon />
|
||||
{actionLoading ? labels.processing : labels.delete}
|
||||
</DropdownMenuItem>
|
||||
) : null}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
) : null}
|
||||
</ButtonGroup>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)
|
||||
})}
|
||||
{loading || result.results.length === 0 ? (
|
||||
<DashboardTableStateRow
|
||||
colSpan={colSpan}
|
||||
loading={loading}
|
||||
loadingText={labels.loading}
|
||||
emptyText={labels.empty}
|
||||
/>
|
||||
) : null}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</DashboardTableShell>
|
||||
</DashboardPage>
|
||||
{renderEditDialog({
|
||||
open: dialogOpen,
|
||||
saving,
|
||||
item: editingItem,
|
||||
itemId: editingItem ? getItemId(editingItem) : null,
|
||||
onOpenChange: handleDialogOpenChange,
|
||||
onSubmit: handleSubmit,
|
||||
})}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { describe, it } from "node:test"
|
||||
import ts from "typescript"
|
||||
import { readFile } from "node:fs/promises"
|
||||
import vm from "node:vm"
|
||||
|
||||
function plain(value) {
|
||||
return JSON.parse(JSON.stringify(value))
|
||||
}
|
||||
|
||||
async function loadModule() {
|
||||
const source = await readFile(
|
||||
new URL("./dashboard-crud-utils.ts", import.meta.url),
|
||||
"utf8"
|
||||
)
|
||||
const compiled = ts.transpileModule(source, {
|
||||
compilerOptions: {
|
||||
target: ts.ScriptTarget.ES2017,
|
||||
module: ts.ModuleKind.CommonJS,
|
||||
},
|
||||
fileName: "dashboard-crud-utils.ts",
|
||||
})
|
||||
const sandbox = {
|
||||
exports: {},
|
||||
module: { exports: {} },
|
||||
}
|
||||
sandbox.exports = sandbox.module.exports
|
||||
vm.runInNewContext(compiled.outputText, sandbox)
|
||||
return sandbox.module.exports
|
||||
}
|
||||
|
||||
describe("buildDashboardCrudQuery", () => {
|
||||
it("trims text filters and omits empty values", async () => {
|
||||
const { buildDashboardCrudQuery } = await loadModule()
|
||||
const query = buildDashboardCrudQuery({
|
||||
values: {
|
||||
title: " hello ",
|
||||
groupName: " ",
|
||||
},
|
||||
filters: [
|
||||
{ name: "title", trim: true },
|
||||
{ name: "groupName", trim: true },
|
||||
],
|
||||
page: 2,
|
||||
limit: 50,
|
||||
})
|
||||
|
||||
assert.deepEqual(plain(query), {
|
||||
title: "hello",
|
||||
page: 2,
|
||||
limit: 50,
|
||||
})
|
||||
})
|
||||
|
||||
it("omits configured all values and parses numbers", async () => {
|
||||
const { buildDashboardCrudQuery } = await loadModule()
|
||||
const query = buildDashboardCrudQuery({
|
||||
values: {
|
||||
status: "all",
|
||||
companyId: "42",
|
||||
},
|
||||
filters: [
|
||||
{ name: "status", allValue: "all" },
|
||||
{ name: "companyId", allValue: "0", valueType: "number" },
|
||||
],
|
||||
page: 1,
|
||||
limit: 20,
|
||||
})
|
||||
|
||||
assert.deepEqual(plain(query), {
|
||||
companyId: 42,
|
||||
page: 1,
|
||||
limit: 20,
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("normalizeDashboardCrudPageResult", () => {
|
||||
it("returns a stable empty page when the API result is missing", async () => {
|
||||
const { normalizeDashboardCrudPageResult } = await loadModule()
|
||||
assert.deepEqual(plain(normalizeDashboardCrudPageResult(null, 3, 10)), {
|
||||
results: [],
|
||||
page: {
|
||||
page: 3,
|
||||
limit: 10,
|
||||
total: 0,
|
||||
},
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,74 @@
|
||||
export type DashboardCrudQueryValue = string | number | undefined
|
||||
|
||||
export type DashboardCrudQueryFilter = {
|
||||
name: string
|
||||
trim?: boolean
|
||||
allValue?: string | number
|
||||
valueType?: "string" | "number"
|
||||
}
|
||||
|
||||
export type DashboardCrudPageResult<T> = {
|
||||
results: T[]
|
||||
page: {
|
||||
page: number
|
||||
limit: number
|
||||
total: number
|
||||
}
|
||||
}
|
||||
|
||||
export function buildDashboardCrudQuery({
|
||||
values,
|
||||
filters,
|
||||
page,
|
||||
limit,
|
||||
}: {
|
||||
values: Record<string, string | number | undefined>
|
||||
filters: DashboardCrudQueryFilter[]
|
||||
page: number
|
||||
limit: number
|
||||
}): Record<string, DashboardCrudQueryValue> {
|
||||
const query: Record<string, DashboardCrudQueryValue> = {}
|
||||
|
||||
filters.forEach((filter) => {
|
||||
const rawValue = values[filter.name]
|
||||
const value =
|
||||
filter.trim && typeof rawValue === "string" ? rawValue.trim() : rawValue
|
||||
|
||||
if (
|
||||
value === undefined ||
|
||||
value === "" ||
|
||||
(filter.allValue !== undefined && String(value) === String(filter.allValue))
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
if (filter.valueType === "number") {
|
||||
const numberValue = Number(value)
|
||||
if (Number.isFinite(numberValue)) {
|
||||
query[filter.name] = numberValue
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
query[filter.name] = value
|
||||
})
|
||||
|
||||
query.page = page
|
||||
query.limit = limit
|
||||
return query
|
||||
}
|
||||
|
||||
export function normalizeDashboardCrudPageResult<T>(
|
||||
result: Partial<DashboardCrudPageResult<T>> | null | undefined,
|
||||
page: number,
|
||||
limit: number
|
||||
): DashboardCrudPageResult<T> {
|
||||
return {
|
||||
results: Array.isArray(result?.results) ? result.results : [],
|
||||
page: {
|
||||
page: result?.page?.page ?? page,
|
||||
limit: result?.page?.limit ?? limit,
|
||||
total: result?.page?.total ?? 0,
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
export { DashboardCrudPage } from "./dashboard-crud-page"
|
||||
export type {
|
||||
DashboardCrudPageResult,
|
||||
DashboardCrudQueryValue,
|
||||
} from "./dashboard-crud-utils"
|
||||
Reference in New Issue
Block a user