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"
|
"use client"
|
||||||
|
|
||||||
import { useCallback, useEffect, useState } from "react"
|
|
||||||
import {
|
import {
|
||||||
Building2Icon,
|
Building2Icon,
|
||||||
MessagesSquareIcon,
|
MessagesSquareIcon,
|
||||||
MessageSquareMoreIcon,
|
MessageSquareMoreIcon,
|
||||||
MoreHorizontalIcon,
|
|
||||||
PlusIcon,
|
|
||||||
RefreshCwIcon,
|
|
||||||
SearchIcon,
|
|
||||||
Trash2Icon,
|
|
||||||
} from "lucide-react"
|
} from "lucide-react"
|
||||||
import { toast } from "sonner"
|
import { toast } from "sonner"
|
||||||
|
|
||||||
|
import { DashboardCrudPage } from "@/components/dashboard/crud"
|
||||||
|
import { Badge } from "@/components/ui/badge"
|
||||||
|
import { Switch } from "@/components/ui/switch"
|
||||||
import {
|
import {
|
||||||
createChannel,
|
createChannel,
|
||||||
deleteChannel,
|
deleteChannel,
|
||||||
@@ -21,39 +18,11 @@ import {
|
|||||||
updateChannelStatus,
|
updateChannelStatus,
|
||||||
type AdminChannel,
|
type AdminChannel,
|
||||||
type CreateAdminChannelPayload,
|
type CreateAdminChannelPayload,
|
||||||
type PageResult,
|
|
||||||
} from "@/lib/api/admin"
|
} 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 { getEnumOptions } from "@/lib/enums"
|
||||||
import { ButtonGroup } from "@/components/ui/button-group"
|
import { Status, StatusLabels } from "@/lib/generated/enums"
|
||||||
import { Switch } from "@/components/ui/switch"
|
|
||||||
import { useI18n } from "@/i18n/provider"
|
import { useI18n } from "@/i18n/provider"
|
||||||
|
import { EditDialog } from "./_components/edit"
|
||||||
|
|
||||||
function getChannelTypeLabel(channelType: string, t: (key: string) => string) {
|
function getChannelTypeLabel(channelType: string, t: (key: string) => string) {
|
||||||
if (channelType === "wechat_mp") {
|
if (channelType === "wechat_mp") {
|
||||||
@@ -87,45 +56,6 @@ function ChannelIcon({ channelType }: { channelType: string }) {
|
|||||||
|
|
||||||
export default function DashboardChannelsPage() {
|
export default function DashboardChannelsPage() {
|
||||||
const t = useI18n()
|
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 = [
|
const statusOptions = [
|
||||||
{ value: "all", label: t("status.all") },
|
{ value: "all", label: t("status.all") },
|
||||||
...getEnumOptions(StatusLabels).map((option) => ({
|
...getEnumOptions(StatusLabels).map((option) => ({
|
||||||
@@ -133,7 +63,6 @@ export default function DashboardChannelsPage() {
|
|||||||
label: getStatusLabel(option.value as Status, t),
|
label: getStatusLabel(option.value as Status, t),
|
||||||
})),
|
})),
|
||||||
]
|
]
|
||||||
|
|
||||||
const channelTypeOptions = [
|
const channelTypeOptions = [
|
||||||
{ value: "all", label: t("channel.allTypes") },
|
{ value: "all", label: t("channel.allTypes") },
|
||||||
{ value: "web", label: t("channel.typeWeb") },
|
{ value: "web", label: t("channel.typeWeb") },
|
||||||
@@ -141,251 +70,159 @@ export default function DashboardChannelsPage() {
|
|||||||
{ value: "wxwork_kf", label: t("channel.typeWxworkKf") },
|
{ 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 (
|
return (
|
||||||
<>
|
<DashboardCrudPage<AdminChannel, CreateAdminChannelPayload>
|
||||||
<DashboardPage>
|
filters={[
|
||||||
<DashboardToolbar
|
{
|
||||||
actions={
|
name: "name",
|
||||||
<>
|
label: t("channel.filterName"),
|
||||||
<Button variant="outline" onClick={() => void loadData()} disabled={loading}>
|
placeholder: t("channel.filterName"),
|
||||||
<RefreshCwIcon className={loading ? "animate-spin" : ""} />
|
defaultValue: "",
|
||||||
{t("channel.refresh")}
|
trim: true,
|
||||||
</Button>
|
className: "w-full sm:w-56",
|
||||||
<Button onClick={openCreateDialog}>
|
},
|
||||||
<PlusIcon />
|
{
|
||||||
{t("channel.new")}
|
name: "channelId",
|
||||||
</Button>
|
label: t("channel.filterChannelId"),
|
||||||
</>
|
placeholder: t("channel.filterChannelId"),
|
||||||
}
|
defaultValue: "",
|
||||||
>
|
trim: true,
|
||||||
<Input
|
className: "w-full sm:w-72",
|
||||||
value={nameInput}
|
},
|
||||||
onChange={(event) => setNameInput(event.target.value)}
|
{
|
||||||
onKeyDown={handleFilterKeyDown}
|
name: "channelType",
|
||||||
placeholder={t("channel.filterName")}
|
label: t("channel.allTypes"),
|
||||||
className="w-full sm:w-56"
|
type: "select",
|
||||||
/>
|
defaultValue: "all",
|
||||||
<div className="relative w-full sm:w-72">
|
allValue: "all",
|
||||||
<SearchIcon className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground" />
|
options: channelTypeOptions,
|
||||||
<Input
|
className: "w-full sm:w-40",
|
||||||
value={channelIdInput}
|
},
|
||||||
onChange={(event) => setChannelIdInput(event.target.value)}
|
{
|
||||||
onKeyDown={handleFilterKeyDown}
|
name: "status",
|
||||||
placeholder={t("channel.filterChannelId")}
|
label: t("status.all"),
|
||||||
className="pl-9"
|
type: "select",
|
||||||
/>
|
defaultValue: "all",
|
||||||
</div>
|
allValue: "all",
|
||||||
<div className="w-full sm:w-40">
|
options: statusOptions,
|
||||||
<OptionCombobox
|
className: "w-full sm:w-36",
|
||||||
value={channelTypeInput}
|
},
|
||||||
options={[...channelTypeOptions]}
|
]}
|
||||||
placeholder={t("channel.allTypes")}
|
columns={[
|
||||||
searchPlaceholder={t("channel.searchType")}
|
{
|
||||||
emptyText={t("channel.emptyType")}
|
key: "channel",
|
||||||
onChange={setChannelTypeInput}
|
label: t("channel.columnChannel"),
|
||||||
/>
|
render: (item) => (
|
||||||
</div>
|
<div className="flex items-center gap-3">
|
||||||
<div className="w-full sm:w-36">
|
<div className="flex size-10 items-center justify-center rounded-2xl bg-muted">
|
||||||
<OptionCombobox
|
<ChannelIcon channelType={item.channelType} />
|
||||||
value={statusInput}
|
</div>
|
||||||
options={[...statusOptions]}
|
<div>
|
||||||
placeholder={t("status.all")}
|
<div className="font-medium">{item.name}</div>
|
||||||
searchPlaceholder={t("channel.searchStatus")}
|
<div className="text-xs text-muted-foreground">
|
||||||
emptyText={t("channel.emptyStatus")}
|
{getChannelTypeLabel(item.channelType, t)}
|
||||||
onChange={setStatusInput}
|
</div>
|
||||||
/>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<Button variant="outline" onClick={applyFilters} disabled={loading}>
|
),
|
||||||
<SearchIcon />
|
},
|
||||||
{t("channel.query")}
|
{
|
||||||
</Button>
|
key: "type",
|
||||||
</DashboardToolbar>
|
label: t("channel.columnType"),
|
||||||
|
render: (item) => (
|
||||||
<DashboardTableShell
|
<Badge variant="outline">
|
||||||
pagination={
|
{getChannelTypeLabel(item.channelType, t)}
|
||||||
<ListPagination
|
</Badge>
|
||||||
page={result.page.page}
|
),
|
||||||
limit={result.page.limit}
|
},
|
||||||
total={result.page.total}
|
{
|
||||||
loading={loading}
|
key: "channelId",
|
||||||
onPageChange={(nextPage) => setPage(nextPage)}
|
label: "ChannelID",
|
||||||
onLimitChange={(nextLimit) => {
|
render: (item) => (
|
||||||
setLimit(nextLimit)
|
<span className="font-mono text-xs">{item.channelId || "-"}</span>
|
||||||
setPage(1)
|
),
|
||||||
}}
|
},
|
||||||
/>
|
{
|
||||||
}
|
key: "agent",
|
||||||
>
|
label: t("channel.columnAgent"),
|
||||||
<Table>
|
render: (item) => item.aiAgentName || "-",
|
||||||
<TableHeader>
|
},
|
||||||
<TableRow>
|
{
|
||||||
<TableHead>{t("channel.columnChannel")}</TableHead>
|
key: "status",
|
||||||
<TableHead>{t("channel.columnType")}</TableHead>
|
label: t("channel.columnStatus"),
|
||||||
<TableHead>ChannelID</TableHead>
|
render: (item, { actionLoading, reload, setActionLoadingId }) => (
|
||||||
<TableHead>{t("channel.columnAgent")}</TableHead>
|
<div className="flex items-center gap-3">
|
||||||
<TableHead>{t("channel.columnStatus")}</TableHead>
|
<Switch
|
||||||
<TableHead className="w-[88px] text-right">{t("channel.columnActions")}</TableHead>
|
checked={item.status === Status.Ok}
|
||||||
</TableRow>
|
disabled={actionLoading}
|
||||||
</TableHeader>
|
onCheckedChange={() => {
|
||||||
<TableBody>
|
void (async () => {
|
||||||
{loading || result.results.length === 0 ? (
|
setActionLoadingId(item.id)
|
||||||
<DashboardTableStateRow
|
try {
|
||||||
colSpan={6}
|
const nextStatus =
|
||||||
loading={loading}
|
item.status === Status.Ok ? Status.Disabled : Status.Ok
|
||||||
loadingText={t("channel.loading")}
|
await updateChannelStatus(item.id, nextStatus)
|
||||||
emptyText={t("channel.empty")}
|
toast.success(
|
||||||
/>
|
t(
|
||||||
) : null}
|
nextStatus === Status.Ok
|
||||||
{result.results.map((item) => (
|
? "channel.statusEnabled"
|
||||||
<TableRow key={item.id}>
|
: "channel.statusDisabled",
|
||||||
<TableCell>
|
{ name: item.name }
|
||||||
<div className="flex items-center gap-3">
|
)
|
||||||
<div className="flex size-10 items-center justify-center rounded-2xl bg-muted">
|
)
|
||||||
<ChannelIcon channelType={item.channelType} />
|
await reload()
|
||||||
</div>
|
} catch (error) {
|
||||||
<div>
|
toast.error(
|
||||||
<div className="font-medium">{item.name}</div>
|
error instanceof Error
|
||||||
<div className="text-xs text-muted-foreground">{getChannelTypeLabel(item.channelType, t)}</div>
|
? error.message
|
||||||
</div>
|
: t("channel.statusUpdateFailed")
|
||||||
</div>
|
)
|
||||||
</TableCell>
|
} finally {
|
||||||
<TableCell>
|
setActionLoadingId(null)
|
||||||
<Badge variant="outline">{getChannelTypeLabel(item.channelType, t)}</Badge>
|
}
|
||||||
</TableCell>
|
})()
|
||||||
<TableCell className="font-mono text-xs">{item.channelId || "-"}</TableCell>
|
}}
|
||||||
<TableCell>{item.aiAgentName || "-"}</TableCell>
|
aria-label={t("channel.toggleStatus", { name: item.name })}
|
||||||
<TableCell>
|
/>
|
||||||
<div className="flex items-center gap-3">
|
<Badge variant={item.status === Status.Ok ? "default" : "outline"}>
|
||||||
<Switch
|
{getStatusLabel(item.status as Status, t)}
|
||||||
checked={item.status === Status.Ok}
|
</Badge>
|
||||||
disabled={actionLoadingId === item.id}
|
</div>
|
||||||
onCheckedChange={() => void handleToggleStatus(item)}
|
),
|
||||||
aria-label={t("channel.toggleStatus", { name: item.name })}
|
},
|
||||||
/>
|
]}
|
||||||
<Badge variant={item.status === Status.Ok ? "default" : "outline"}>
|
fetchList={fetchChannels}
|
||||||
{getStatusLabel(item.status as Status, t)}
|
getItemId={(item) => item.id}
|
||||||
</Badge>
|
createItem={createChannel}
|
||||||
</div>
|
updateItem={(item, payload) => updateChannel({ id: item.id, ...payload })}
|
||||||
</TableCell>
|
deleteItem={(item) => deleteChannel(item.id)}
|
||||||
<TableCell className="text-right">
|
renderEditDialog={({ open, saving, itemId, onOpenChange, onSubmit }) => (
|
||||||
<ButtonGroup className="ml-auto">
|
<EditDialog
|
||||||
<Button variant="outline" size="sm" onClick={() => openEditDialog(item)}>
|
open={open}
|
||||||
{t("channel.edit")}
|
saving={saving}
|
||||||
</Button>
|
itemId={itemId}
|
||||||
<DropdownMenu>
|
onOpenChange={onOpenChange}
|
||||||
<DropdownMenuTrigger
|
onSubmit={onSubmit}
|
||||||
render={<Button variant="outline" size="icon-sm" className="ml-auto" />}
|
/>
|
||||||
aria-label={t("channel.moreActions", { name: item.name })}
|
)}
|
||||||
>
|
labels={{
|
||||||
<MoreHorizontalIcon />
|
refresh: t("channel.refresh"),
|
||||||
</DropdownMenuTrigger>
|
create: t("channel.new"),
|
||||||
<DropdownMenuContent align="end">
|
query: t("channel.query"),
|
||||||
<DropdownMenuItem
|
loading: t("channel.loading"),
|
||||||
className="text-destructive"
|
empty: t("channel.empty"),
|
||||||
disabled={actionLoadingId === item.id}
|
actions: t("channel.columnActions"),
|
||||||
onClick={() => void handleDelete(item)}
|
edit: t("channel.edit"),
|
||||||
>
|
delete: t("channel.delete"),
|
||||||
<Trash2Icon className="size-4" />
|
processing: t("channel.processing"),
|
||||||
{t("channel.delete")}
|
moreActions: (item) => t("channel.moreActions", { name: item.name }),
|
||||||
</DropdownMenuItem>
|
loadFailed: t("channel.loadFailed"),
|
||||||
</DropdownMenuContent>
|
saveFailed: t("channel.saveFailed"),
|
||||||
</DropdownMenu>
|
deleteFailed: t("channel.deleteFailed"),
|
||||||
</ButtonGroup>
|
created: (payload) => t("channel.created", { name: payload.name }),
|
||||||
</TableCell>
|
updated: (_item, payload) => t("channel.updated", { name: payload.name }),
|
||||||
</TableRow>
|
deleted: (item) => t("channel.deleted", { name: item.name }),
|
||||||
))}
|
}}
|
||||||
</TableBody>
|
/>
|
||||||
</Table>
|
|
||||||
</DashboardTableShell>
|
|
||||||
</DashboardPage>
|
|
||||||
|
|
||||||
<EditDialog
|
|
||||||
open={dialogOpen}
|
|
||||||
saving={saving}
|
|
||||||
itemId={editingItem?.id ?? null}
|
|
||||||
onOpenChange={setDialogOpen}
|
|
||||||
onSubmit={handleSubmit}
|
|
||||||
/>
|
|
||||||
</>
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,44 +1,11 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
import {
|
import { BanIcon, CheckCircle2Icon } from "lucide-react"
|
||||||
BanIcon,
|
|
||||||
CheckCircle2Icon,
|
|
||||||
MoreHorizontalIcon,
|
|
||||||
PlusIcon,
|
|
||||||
RefreshCwIcon,
|
|
||||||
SearchIcon,
|
|
||||||
Trash2Icon,
|
|
||||||
} from "lucide-react"
|
|
||||||
import { useCallback, useEffect, useState } from "react"
|
|
||||||
import { toast } from "sonner"
|
import { toast } from "sonner"
|
||||||
|
|
||||||
import {
|
import { DashboardCrudPage } from "@/components/dashboard/crud"
|
||||||
DashboardPage,
|
|
||||||
DashboardTableShell,
|
|
||||||
DashboardTableStateRow,
|
|
||||||
DashboardToolbar,
|
|
||||||
} from "@/components/dashboard-page"
|
|
||||||
import { ListPagination } from "@/components/list-pagination"
|
|
||||||
import { OptionCombobox } from "@/components/option-combobox"
|
|
||||||
import { Badge } from "@/components/ui/badge"
|
import { Badge } from "@/components/ui/badge"
|
||||||
import { Button } from "@/components/ui/button"
|
import { DropdownMenuItem } from "@/components/ui/dropdown-menu"
|
||||||
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 {
|
import {
|
||||||
createCompany,
|
createCompany,
|
||||||
deleteCompany,
|
deleteCompany,
|
||||||
@@ -65,42 +32,6 @@ function getStatusLabel(status: Status, t: (key: string) => string) {
|
|||||||
|
|
||||||
export default function DashboardCompaniesPage() {
|
export default function DashboardCompaniesPage() {
|
||||||
const t = useI18n()
|
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 = [
|
const listStatusOptions = [
|
||||||
{ value: "all", label: t("status.all") },
|
{ value: "all", label: t("status.all") },
|
||||||
...getEnumOptions(StatusLabels)
|
...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 (
|
return (
|
||||||
<>
|
<DashboardCrudPage<AdminCompany, CreateAdminCompanyPayload>
|
||||||
<DashboardPage>
|
filters={[
|
||||||
<DashboardToolbar
|
{
|
||||||
actions={
|
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}>
|
<BanIcon />
|
||||||
<RefreshCwIcon className={loading ? "animate-spin" : ""} />
|
{t("company.disable")}
|
||||||
{t("company.refresh")}
|
|
||||||
</Button>
|
|
||||||
<Button onClick={openCreateDialog}>
|
|
||||||
<PlusIcon />
|
|
||||||
{t("company.new")}
|
|
||||||
</Button>
|
|
||||||
</>
|
</>
|
||||||
}
|
) : (
|
||||||
>
|
<>
|
||||||
<div className="relative w-full sm:w-72">
|
<CheckCircle2Icon />
|
||||||
<SearchIcon className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground" />
|
{t("company.enable")}
|
||||||
<Input
|
</>
|
||||||
value={nameInput}
|
)}
|
||||||
onChange={(event) => setNameInput(event.target.value)}
|
</DropdownMenuItem>
|
||||||
onKeyDown={handleFilterKeyDown}
|
)}
|
||||||
placeholder={t("company.filterName")}
|
renderEditDialog={({ open, saving, itemId, onOpenChange, onSubmit }) => (
|
||||||
className="pl-9"
|
<EditDialog
|
||||||
/>
|
open={open}
|
||||||
</div>
|
saving={saving}
|
||||||
<Input
|
itemId={itemId}
|
||||||
value={codeInput}
|
onOpenChange={onOpenChange}
|
||||||
onChange={(event) => setCodeInput(event.target.value)}
|
onSubmit={onSubmit}
|
||||||
onKeyDown={handleFilterKeyDown}
|
/>
|
||||||
placeholder={t("company.filterCode")}
|
)}
|
||||||
className="w-full sm:w-44"
|
labels={{
|
||||||
/>
|
refresh: t("company.refresh"),
|
||||||
<div className="w-full sm:w-36">
|
create: t("company.new"),
|
||||||
<OptionCombobox
|
query: t("company.query"),
|
||||||
value={statusFilterInput}
|
loading: t("company.loading"),
|
||||||
onChange={setStatusFilterInput}
|
empty: t("company.empty"),
|
||||||
placeholder={t("status.all")}
|
actions: t("company.columnActions"),
|
||||||
options={[...listStatusOptions]}
|
edit: t("company.edit"),
|
||||||
/>
|
delete: t("company.delete"),
|
||||||
</div>
|
processing: t("company.processing"),
|
||||||
<Button variant="outline" onClick={applyFilters} disabled={loading}>
|
moreActions: (item) => t("company.moreActions", { name: item.name }),
|
||||||
<SearchIcon />
|
loadFailed: t("company.loadFailed"),
|
||||||
{t("company.query")}
|
saveFailed: t("company.saveFailed"),
|
||||||
</Button>
|
deleteFailed: t("company.deleteFailed"),
|
||||||
</DashboardToolbar>
|
created: (payload) => t("company.created", { name: payload.name }),
|
||||||
|
updated: (item) => t("company.updated", { name: item.name }),
|
||||||
<DashboardTableShell
|
deleted: (item) => t("company.deleted", { name: item.name }),
|
||||||
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}
|
|
||||||
/>
|
|
||||||
</>
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,42 +1,11 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
import { useCallback, useEffect, useState } from "react"
|
import { FileTextIcon, RefreshCwIcon } from "lucide-react"
|
||||||
import {
|
|
||||||
FileTextIcon,
|
|
||||||
MoreHorizontalIcon,
|
|
||||||
PlusIcon,
|
|
||||||
RefreshCwIcon,
|
|
||||||
SearchIcon,
|
|
||||||
Trash2Icon,
|
|
||||||
} from "lucide-react"
|
|
||||||
import { toast } from "sonner"
|
import { toast } from "sonner"
|
||||||
|
|
||||||
import {
|
import { DashboardCrudPage } from "@/components/dashboard/crud"
|
||||||
DashboardPage,
|
|
||||||
DashboardTableShell,
|
|
||||||
DashboardTableStateRow,
|
|
||||||
DashboardToolbar,
|
|
||||||
} from "@/components/dashboard-page"
|
|
||||||
import { ListPagination } from "@/components/list-pagination"
|
|
||||||
import { OptionCombobox } from "@/components/option-combobox"
|
|
||||||
import { Badge } from "@/components/ui/badge"
|
import { Badge } from "@/components/ui/badge"
|
||||||
import { Button } from "@/components/ui/button"
|
import { DropdownMenuItem } from "@/components/ui/dropdown-menu"
|
||||||
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 {
|
import {
|
||||||
createQuickReply,
|
createQuickReply,
|
||||||
deleteQuickReply,
|
deleteQuickReply,
|
||||||
@@ -44,7 +13,6 @@ import {
|
|||||||
updateQuickReply,
|
updateQuickReply,
|
||||||
type AdminQuickReply,
|
type AdminQuickReply,
|
||||||
type CreateAdminQuickReplyPayload,
|
type CreateAdminQuickReplyPayload,
|
||||||
type PageResult,
|
|
||||||
} from "@/lib/api/admin"
|
} from "@/lib/api/admin"
|
||||||
import { getEnumOptions } from "@/lib/enums"
|
import { getEnumOptions } from "@/lib/enums"
|
||||||
import { Status, StatusLabels } from "@/lib/generated/enums"
|
import { Status, StatusLabels } from "@/lib/generated/enums"
|
||||||
@@ -63,42 +31,6 @@ function getStatusLabel(status: Status, t: (key: string) => string) {
|
|||||||
|
|
||||||
export default function DashboardQuickRepliesPage() {
|
export default function DashboardQuickRepliesPage() {
|
||||||
const t = useI18n()
|
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 = [
|
const listStatusOptions = [
|
||||||
{ value: "all", label: t("status.all") },
|
{ value: "all", label: t("status.all") },
|
||||||
...getEnumOptions(StatusLabels)
|
...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 (
|
return (
|
||||||
<>
|
<DashboardCrudPage<AdminQuickReply, CreateAdminQuickReplyPayload>
|
||||||
<DashboardPage>
|
filters={[
|
||||||
<DashboardToolbar
|
{
|
||||||
actions={
|
name: "title",
|
||||||
<>
|
label: t("quickReply.filterTitle"),
|
||||||
<Button variant="outline" onClick={() => void loadData()} disabled={loading}>
|
placeholder: t("quickReply.filterTitle"),
|
||||||
<RefreshCwIcon className={loading ? "animate-spin" : undefined} />
|
defaultValue: "",
|
||||||
{t("quickReply.refresh")}
|
trim: true,
|
||||||
</Button>
|
className: "w-full sm:w-72",
|
||||||
<Button onClick={openCreateDialog}>
|
},
|
||||||
<PlusIcon />
|
{
|
||||||
{t("quickReply.new")}
|
name: "groupName",
|
||||||
</Button>
|
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">
|
<RefreshCwIcon />
|
||||||
<SearchIcon className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground" />
|
{actionLoading
|
||||||
<Input
|
? t("quickReply.processing")
|
||||||
value={keywordInput}
|
: item.status === Status.Ok
|
||||||
onChange={(event) => setKeywordInput(event.target.value)}
|
? t("quickReply.disable")
|
||||||
onKeyDown={handleFilterKeyDown}
|
: t("quickReply.enable")}
|
||||||
placeholder={t("quickReply.filterTitle")}
|
</DropdownMenuItem>
|
||||||
className="pl-9"
|
)}
|
||||||
/>
|
renderEditDialog={({ open, saving, itemId, onOpenChange, onSubmit }) => (
|
||||||
</div>
|
<EditDialog
|
||||||
<Input
|
open={open}
|
||||||
value={groupNameInput}
|
saving={saving}
|
||||||
onChange={(event) => setGroupNameInput(event.target.value)}
|
itemId={itemId}
|
||||||
onKeyDown={handleFilterKeyDown}
|
onOpenChange={onOpenChange}
|
||||||
placeholder={t("quickReply.filterGroup")}
|
onSubmit={onSubmit}
|
||||||
className="w-full sm:w-44"
|
/>
|
||||||
/>
|
)}
|
||||||
<div className="w-full sm:w-36">
|
labels={{
|
||||||
<OptionCombobox
|
refresh: t("quickReply.refresh"),
|
||||||
value={statusFilterInput}
|
create: t("quickReply.new"),
|
||||||
onChange={setStatusFilterInput}
|
query: t("quickReply.query"),
|
||||||
placeholder={t("status.all")}
|
loading: t("quickReply.loading"),
|
||||||
options={[...listStatusOptions]}
|
empty: t("quickReply.empty"),
|
||||||
/>
|
actions: t("quickReply.columnActions"),
|
||||||
</div>
|
edit: t("quickReply.edit"),
|
||||||
<Button variant="outline" onClick={applyFilters} disabled={loading}>
|
delete: t("quickReply.delete"),
|
||||||
<SearchIcon />
|
processing: t("quickReply.processing"),
|
||||||
{t("quickReply.query")}
|
moreActions: (item) =>
|
||||||
</Button>
|
t("quickReply.moreActions", { title: item.title }),
|
||||||
</DashboardToolbar>
|
loadFailed: t("quickReply.loadFailed"),
|
||||||
<DashboardTableShell
|
saveFailed: t("quickReply.saveFailed"),
|
||||||
pagination={
|
deleteFailed: t("quickReply.deleteFailed"),
|
||||||
<ListPagination
|
created: (payload) => t("quickReply.created", { title: payload.title }),
|
||||||
page={result.page.page}
|
updated: (item) => t("quickReply.updated", { title: item.title }),
|
||||||
total={result.page.total}
|
deleted: (item) => t("quickReply.deleted", { title: item.title }),
|
||||||
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}
|
|
||||||
/>
|
|
||||||
</>
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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