refactor: replace EditDialog with DashboardCrudFormDialog for companies and quick replies
- Removed the EditDialog component from companies and quick replies. - Integrated DashboardCrudFormDialog to handle form submissions and editing for both entities. - Updated the CompanyPicker to utilize the new form dialog for creating companies. - Introduced DashboardCrudFieldControl for rendering form fields dynamically. - Added utility functions for building form values and normalizing submit values. - Updated tests to cover new form utilities and ensure correct behavior for form submissions.
This commit is contained in:
@@ -1,235 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useMemo, useState } from "react"
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import type { Resolver } from "react-hook-form"
|
||||
import { useForm } from "react-hook-form"
|
||||
import { z } from "zod/v4"
|
||||
|
||||
import { ProjectDialog } from "@/components/project-dialog"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
Field,
|
||||
FieldContent,
|
||||
FieldError,
|
||||
FieldLabel,
|
||||
} from "@/components/ui/field"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Textarea } from "@/components/ui/textarea"
|
||||
import {
|
||||
fetchCompany,
|
||||
type AdminCompany,
|
||||
type CreateAdminCompanyPayload,
|
||||
} from "@/lib/api/company"
|
||||
import { useI18n } from "@/i18n/provider"
|
||||
|
||||
type CompanyEditDialogProps = {
|
||||
open: boolean
|
||||
saving: boolean
|
||||
itemId: number | null
|
||||
initialValues?: Partial<CreateAdminCompanyPayload>
|
||||
onOpenChange: (open: boolean) => void
|
||||
onSubmit: (payload: CreateAdminCompanyPayload) => Promise<void>
|
||||
}
|
||||
|
||||
type EditForm = {
|
||||
name: string
|
||||
code: string
|
||||
remark: string
|
||||
}
|
||||
|
||||
function createSchema(t: (key: string) => string) {
|
||||
return z.object({
|
||||
name: z.string().trim().min(1, t("company.nameRequired")),
|
||||
code: z.string().trim(),
|
||||
remark: z.string().trim(),
|
||||
})
|
||||
}
|
||||
|
||||
const emptyForm: EditForm = {
|
||||
name: "",
|
||||
code: "",
|
||||
remark: "",
|
||||
}
|
||||
|
||||
function buildForm(item: AdminCompany | null): EditForm {
|
||||
if (!item) {
|
||||
return emptyForm
|
||||
}
|
||||
return {
|
||||
name: item.name,
|
||||
code: item.code,
|
||||
remark: item.remark,
|
||||
}
|
||||
}
|
||||
|
||||
function buildPayload(form: EditForm): CreateAdminCompanyPayload {
|
||||
return {
|
||||
name: form.name.trim(),
|
||||
code: form.code.trim(),
|
||||
remark: form.remark.trim(),
|
||||
}
|
||||
}
|
||||
|
||||
function buildInitialForm(initialValues?: Partial<CreateAdminCompanyPayload>): EditForm {
|
||||
return {
|
||||
name: initialValues?.name?.trim() ?? "",
|
||||
code: initialValues?.code?.trim() ?? "",
|
||||
remark: initialValues?.remark?.trim() ?? "",
|
||||
}
|
||||
}
|
||||
|
||||
export function EditDialog({
|
||||
open,
|
||||
saving,
|
||||
itemId,
|
||||
initialValues,
|
||||
onOpenChange,
|
||||
onSubmit,
|
||||
}: CompanyEditDialogProps) {
|
||||
if (!open) {
|
||||
return null
|
||||
}
|
||||
return (
|
||||
<CompanyEditDialogBody
|
||||
key={itemId ? `edit-${itemId}` : "create"}
|
||||
open={open}
|
||||
saving={saving}
|
||||
itemId={itemId}
|
||||
initialValues={initialValues}
|
||||
onOpenChange={onOpenChange}
|
||||
onSubmit={onSubmit}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
type CompanyEditDialogBodyProps = CompanyEditDialogProps
|
||||
|
||||
function CompanyEditDialogBody({
|
||||
open,
|
||||
saving,
|
||||
itemId,
|
||||
initialValues,
|
||||
onOpenChange,
|
||||
onSubmit,
|
||||
}: CompanyEditDialogBodyProps) {
|
||||
const t = useI18n()
|
||||
const formId = "company-edit-form"
|
||||
const [loading, setLoading] = useState(false)
|
||||
const companyFormSchema = useMemo(() => createSchema(t), [t])
|
||||
const editFormResolver = useMemo(
|
||||
() =>
|
||||
zodResolver(companyFormSchema as never) as Resolver<
|
||||
z.input<typeof companyFormSchema>,
|
||||
undefined,
|
||||
z.output<typeof companyFormSchema>
|
||||
>,
|
||||
[companyFormSchema]
|
||||
)
|
||||
const form = useForm<
|
||||
z.input<typeof companyFormSchema>,
|
||||
undefined,
|
||||
z.output<typeof companyFormSchema>
|
||||
>({
|
||||
resolver: editFormResolver,
|
||||
defaultValues: emptyForm,
|
||||
})
|
||||
const {
|
||||
handleSubmit,
|
||||
register,
|
||||
reset,
|
||||
formState: { errors },
|
||||
} = form
|
||||
|
||||
useEffect(() => {
|
||||
async function loadDetail() {
|
||||
if (!itemId) {
|
||||
reset(buildInitialForm(initialValues))
|
||||
return
|
||||
}
|
||||
setLoading(true)
|
||||
try {
|
||||
const data = await fetchCompany(itemId)
|
||||
reset(buildForm(data))
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
void loadDetail()
|
||||
}, [initialValues, itemId, reset])
|
||||
|
||||
async function onFormSubmit(values: EditForm) {
|
||||
await onSubmit(buildPayload(values))
|
||||
}
|
||||
|
||||
return (
|
||||
<ProjectDialog
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
title={itemId ? t("company.editTitle") : t("company.createTitle")}
|
||||
size="md"
|
||||
allowFullscreen
|
||||
footer={
|
||||
<>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => onOpenChange(false)}
|
||||
disabled={saving}
|
||||
>
|
||||
{t("company.cancel")}
|
||||
</Button>
|
||||
<Button type="submit" form={formId} disabled={saving || loading}>
|
||||
{saving ? t("company.saving") : itemId ? t("company.save") : t("company.create")}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{loading ? (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<div className="text-muted-foreground">{t("company.loadingDetail")}</div>
|
||||
</div>
|
||||
) : (
|
||||
<form id={formId} onSubmit={handleSubmit(onFormSubmit)} className="space-y-4">
|
||||
<Field data-invalid={!!errors.name}>
|
||||
<FieldLabel htmlFor="company-name">{t("company.columnName")}</FieldLabel>
|
||||
<FieldContent>
|
||||
<Input
|
||||
id="company-name"
|
||||
placeholder={t("company.namePlaceholder")}
|
||||
aria-invalid={!!errors.name}
|
||||
{...register("name")}
|
||||
/>
|
||||
<FieldError errors={[errors.name]} />
|
||||
</FieldContent>
|
||||
</Field>
|
||||
<Field data-invalid={!!errors.code}>
|
||||
<FieldLabel htmlFor="company-code">{t("company.columnCode")}</FieldLabel>
|
||||
<FieldContent>
|
||||
<Input
|
||||
id="company-code"
|
||||
placeholder={t("company.optional")}
|
||||
aria-invalid={!!errors.code}
|
||||
{...register("code")}
|
||||
/>
|
||||
<FieldError errors={[errors.code]} />
|
||||
</FieldContent>
|
||||
</Field>
|
||||
<Field data-invalid={!!errors.remark}>
|
||||
<FieldLabel htmlFor="company-remark">{t("company.columnRemark")}</FieldLabel>
|
||||
<FieldContent>
|
||||
<Textarea
|
||||
id="company-remark"
|
||||
placeholder={t("company.remarkPlaceholder")}
|
||||
rows={4}
|
||||
aria-invalid={!!errors.remark}
|
||||
{...register("remark")}
|
||||
/>
|
||||
<FieldError errors={[errors.remark]} />
|
||||
</FieldContent>
|
||||
</Field>
|
||||
</form>
|
||||
)}
|
||||
</ProjectDialog>
|
||||
)
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
createCompany,
|
||||
deleteCompany,
|
||||
fetchCompanies,
|
||||
fetchCompany,
|
||||
updateCompany,
|
||||
updateCompanyStatus,
|
||||
type AdminCompany,
|
||||
@@ -18,7 +19,6 @@ import {
|
||||
import { getEnumOptions } from "@/lib/enums"
|
||||
import { Status, StatusLabels } from "@/lib/generated/enums"
|
||||
import { useI18n } from "@/i18n/provider"
|
||||
import { EditDialog } from "./_components/edit"
|
||||
|
||||
function getStatusLabel(status: Status, t: (key: string) => string) {
|
||||
if (status === Status.Disabled) {
|
||||
@@ -132,6 +132,51 @@ export default function DashboardCompaniesPage() {
|
||||
updateItem={(item, payload) => updateCompany({ id: item.id, ...payload })}
|
||||
deleteItem={(item) => deleteCompany(item.id)}
|
||||
canDelete={(item) => item.status !== Status.Deleted}
|
||||
form={{
|
||||
fetchDetail: fetchCompany,
|
||||
fields: [
|
||||
{
|
||||
name: "name",
|
||||
label: t("company.columnName"),
|
||||
placeholder: t("company.namePlaceholder"),
|
||||
required: true,
|
||||
requiredMessage: t("company.nameRequired"),
|
||||
trim: true,
|
||||
},
|
||||
{
|
||||
name: "code",
|
||||
label: t("company.columnCode"),
|
||||
placeholder: t("company.optional"),
|
||||
trim: true,
|
||||
},
|
||||
{
|
||||
name: "remark",
|
||||
label: t("company.columnRemark"),
|
||||
placeholder: t("company.remarkPlaceholder"),
|
||||
type: "textarea",
|
||||
rows: 4,
|
||||
trim: true,
|
||||
},
|
||||
],
|
||||
transformSubmitValues: (values) => ({
|
||||
name: String(values.name ?? ""),
|
||||
code: String(values.code ?? ""),
|
||||
remark: String(values.remark ?? ""),
|
||||
}),
|
||||
labels: {
|
||||
createTitle: t("company.createTitle"),
|
||||
editTitle: t("company.editTitle"),
|
||||
create: t("company.create"),
|
||||
save: t("company.save"),
|
||||
saving: t("company.saving"),
|
||||
cancel: t("company.cancel"),
|
||||
loadingDetail: t("company.loadingDetail"),
|
||||
required: t("company.nameRequired"),
|
||||
invalidNumber: t("company.nameRequired"),
|
||||
minValue: () => t("company.nameRequired"),
|
||||
maxValue: () => t("company.nameRequired"),
|
||||
},
|
||||
}}
|
||||
renderRowActions={({ item, actionLoading, reload, setActionLoadingId }) => (
|
||||
<DropdownMenuItem
|
||||
disabled={item.status === Status.Deleted}
|
||||
@@ -174,15 +219,6 @@ export default function DashboardCompaniesPage() {
|
||||
)}
|
||||
</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"),
|
||||
|
||||
@@ -1,309 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { Controller, Resolver, useForm } from "react-hook-form";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { OptionCombobox } from "@/components/option-combobox";
|
||||
import { ProjectDialog } from "@/components/project-dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Field,
|
||||
FieldContent,
|
||||
FieldError,
|
||||
FieldLabel,
|
||||
} from "@/components/ui/field";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import {
|
||||
type AdminQuickReply,
|
||||
type CreateAdminQuickReplyPayload,
|
||||
fetchQuickReply,
|
||||
} from "@/lib/api/admin";
|
||||
import { getEnumOptions } from "@/lib/enums";
|
||||
import { Status, StatusLabels } from "@/lib/generated/enums";
|
||||
import { useI18n } from "@/i18n/provider";
|
||||
|
||||
type QuickReplyFormDialogProps = {
|
||||
open: boolean;
|
||||
saving: boolean;
|
||||
itemId: number | null;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onSubmit: (payload: CreateAdminQuickReplyPayload) => Promise<void>;
|
||||
};
|
||||
|
||||
const emptyForm: EditForm = {
|
||||
groupName: "",
|
||||
title: "",
|
||||
content: "",
|
||||
status: String(Status.Ok),
|
||||
sortNo: "0",
|
||||
};
|
||||
|
||||
type EditForm = {
|
||||
groupName: string;
|
||||
title: string;
|
||||
content: string;
|
||||
status: string;
|
||||
sortNo: string;
|
||||
};
|
||||
|
||||
function createSchema(t: (key: string) => string) {
|
||||
return z.object({
|
||||
groupName: z.string().trim().min(1, t("quickReply.groupNameRequired")),
|
||||
title: z.string().trim().min(1, t("quickReply.titleRequired")),
|
||||
content: z.string().trim().min(1, t("quickReply.contentRequired")),
|
||||
status: z.enum([String(Status.Ok), String(Status.Disabled)], {
|
||||
message: t("quickReply.statusRequired"),
|
||||
}),
|
||||
sortNo: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1, t("quickReply.sortRequired"))
|
||||
.regex(/^\d+$/, t("quickReply.sortInvalid")),
|
||||
});
|
||||
}
|
||||
|
||||
function getLocalizedStatusLabel(value: string | number, t: (key: string) => string) {
|
||||
const status = Number(value) as Status;
|
||||
if (status === Status.Disabled) {
|
||||
return t("status.disabled");
|
||||
}
|
||||
if (status === Status.Deleted) {
|
||||
return t("status.deleted");
|
||||
}
|
||||
return t("status.ok");
|
||||
}
|
||||
|
||||
function buildForm(item: AdminQuickReply | null): EditForm {
|
||||
if (!item) {
|
||||
return emptyForm;
|
||||
}
|
||||
|
||||
return {
|
||||
groupName: item.groupName,
|
||||
title: item.title,
|
||||
content: item.content,
|
||||
status: String(item.status) as EditForm["status"],
|
||||
sortNo: String(item.sortNo),
|
||||
};
|
||||
}
|
||||
|
||||
function buildPayload(form: EditForm): CreateAdminQuickReplyPayload {
|
||||
return {
|
||||
groupName: form.groupName.trim(),
|
||||
title: form.title.trim(),
|
||||
content: form.content.trim(),
|
||||
status: Number(form.status) as Status,
|
||||
sortNo: Number(form.sortNo),
|
||||
};
|
||||
}
|
||||
|
||||
export function EditDialog({
|
||||
open,
|
||||
saving,
|
||||
itemId,
|
||||
onOpenChange,
|
||||
onSubmit,
|
||||
}: QuickReplyFormDialogProps) {
|
||||
if (!open) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<QuickReplyFormDialogBody
|
||||
key={itemId ? `edit-${itemId}` : "create"}
|
||||
open={open}
|
||||
itemId={itemId}
|
||||
saving={saving}
|
||||
onOpenChange={onOpenChange}
|
||||
onSubmit={onSubmit}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
type QuickReplyFormDialogBodyProps = {
|
||||
open: boolean;
|
||||
saving: boolean;
|
||||
itemId: number | null;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onSubmit: (payload: CreateAdminQuickReplyPayload) => Promise<void>;
|
||||
};
|
||||
|
||||
function QuickReplyFormDialogBody({
|
||||
open,
|
||||
saving,
|
||||
itemId,
|
||||
onOpenChange,
|
||||
onSubmit,
|
||||
}: QuickReplyFormDialogBodyProps) {
|
||||
const t = useI18n();
|
||||
const formId = "quick-reply-edit-form";
|
||||
const [loading, setLoading] = useState(false);
|
||||
const quickReplyFormSchema = useMemo(() => createSchema(t), [t]);
|
||||
const editFormResolver = useMemo(
|
||||
() =>
|
||||
zodResolver(quickReplyFormSchema as never) as Resolver<
|
||||
z.input<typeof quickReplyFormSchema>,
|
||||
undefined,
|
||||
z.output<typeof quickReplyFormSchema>
|
||||
>,
|
||||
[quickReplyFormSchema],
|
||||
);
|
||||
const formStatusOptions = useMemo(
|
||||
() =>
|
||||
getEnumOptions(StatusLabels)
|
||||
.filter((item) => Number(item.value) !== Status.Deleted)
|
||||
.map((item) => ({
|
||||
value: String(item.value),
|
||||
label: getLocalizedStatusLabel(item.value, t),
|
||||
})),
|
||||
[t],
|
||||
);
|
||||
const form = useForm<
|
||||
z.input<typeof quickReplyFormSchema>,
|
||||
undefined,
|
||||
z.output<typeof quickReplyFormSchema>
|
||||
>({
|
||||
resolver: editFormResolver,
|
||||
defaultValues: emptyForm,
|
||||
});
|
||||
const {
|
||||
control,
|
||||
handleSubmit,
|
||||
reset,
|
||||
register,
|
||||
formState: { errors },
|
||||
} = form;
|
||||
|
||||
useEffect(() => {
|
||||
async function loadDetail() {
|
||||
if (!itemId) {
|
||||
reset(emptyForm);
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
try {
|
||||
const data = await fetchQuickReply(itemId);
|
||||
reset(buildForm(data));
|
||||
} catch (error) {
|
||||
console.error("Failed to load quick reply:", error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
void loadDetail();
|
||||
}, [itemId, reset]);
|
||||
|
||||
async function onFormSubmit(values: EditForm) {
|
||||
const payload = buildPayload(values);
|
||||
await onSubmit(payload);
|
||||
}
|
||||
|
||||
return (
|
||||
<ProjectDialog
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
title={itemId ? t("quickReply.editTitle") : t("quickReply.createTitle")}
|
||||
size="md"
|
||||
allowFullscreen
|
||||
footer={
|
||||
<>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => onOpenChange(false)}
|
||||
disabled={saving}
|
||||
>
|
||||
{t("quickReply.cancel")}
|
||||
</Button>
|
||||
<Button type="submit" form={formId} disabled={saving || loading}>
|
||||
{saving ? t("quickReply.saving") : itemId ? t("quickReply.save") : t("quickReply.create")}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{loading ? (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<div className="text-muted-foreground">{t("quickReply.loadingDetail")}</div>
|
||||
</div>
|
||||
) : (
|
||||
<form id={formId} onSubmit={handleSubmit(onFormSubmit)} className="space-y-4">
|
||||
<Field data-invalid={!!errors.groupName}>
|
||||
<FieldLabel htmlFor="quick-reply-group-name">{t("quickReply.groupName")}</FieldLabel>
|
||||
<FieldContent>
|
||||
<Input
|
||||
id="quick-reply-group-name"
|
||||
placeholder={t("quickReply.groupNamePlaceholder")}
|
||||
aria-invalid={!!errors.groupName}
|
||||
{...register("groupName")}
|
||||
/>
|
||||
<FieldError errors={[errors.groupName]} />
|
||||
</FieldContent>
|
||||
</Field>
|
||||
<Field data-invalid={!!errors.title}>
|
||||
<FieldLabel htmlFor="quick-reply-title">{t("quickReply.title")}</FieldLabel>
|
||||
<FieldContent>
|
||||
<Input
|
||||
id="quick-reply-title"
|
||||
placeholder={t("quickReply.titlePlaceholder")}
|
||||
aria-invalid={!!errors.title}
|
||||
{...register("title")}
|
||||
/>
|
||||
<FieldError errors={[errors.title]} />
|
||||
</FieldContent>
|
||||
</Field>
|
||||
<Field data-invalid={!!errors.content}>
|
||||
<FieldLabel htmlFor="quick-reply-content">{t("quickReply.content")}</FieldLabel>
|
||||
<FieldContent>
|
||||
<Textarea
|
||||
id="quick-reply-content"
|
||||
placeholder={t("quickReply.contentPlaceholder")}
|
||||
rows={6}
|
||||
aria-invalid={!!errors.content}
|
||||
{...register("content")}
|
||||
/>
|
||||
<FieldError errors={[errors.content]} />
|
||||
</FieldContent>
|
||||
</Field>
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<Field data-invalid={!!errors.status}>
|
||||
<FieldLabel>{t("quickReply.columnStatus")}</FieldLabel>
|
||||
<FieldContent>
|
||||
<Controller
|
||||
control={control}
|
||||
name="status"
|
||||
render={({ field }) => (
|
||||
<OptionCombobox
|
||||
value={field.value}
|
||||
options={formStatusOptions}
|
||||
placeholder={t("quickReply.statusRequired")}
|
||||
onChange={field.onChange}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<FieldError errors={[errors.status]} />
|
||||
</FieldContent>
|
||||
</Field>
|
||||
<Field data-invalid={!!errors.sortNo}>
|
||||
<FieldLabel htmlFor="quick-reply-sort-no">{t("quickReply.columnSort")}</FieldLabel>
|
||||
<FieldContent>
|
||||
<Input
|
||||
id="quick-reply-sort-no"
|
||||
type="number"
|
||||
min={0}
|
||||
step={1}
|
||||
placeholder={t("quickReply.sortPlaceholder")}
|
||||
aria-invalid={!!errors.sortNo}
|
||||
{...register("sortNo")}
|
||||
/>
|
||||
<FieldError errors={[errors.sortNo]} />
|
||||
</FieldContent>
|
||||
</Field>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
</ProjectDialog>
|
||||
);
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import { DropdownMenuItem } from "@/components/ui/dropdown-menu"
|
||||
import {
|
||||
createQuickReply,
|
||||
deleteQuickReply,
|
||||
fetchQuickReply,
|
||||
fetchQuickReplies,
|
||||
updateQuickReply,
|
||||
type AdminQuickReply,
|
||||
@@ -17,7 +18,6 @@ import {
|
||||
import { getEnumOptions } from "@/lib/enums"
|
||||
import { Status, StatusLabels } from "@/lib/generated/enums"
|
||||
import { useI18n } from "@/i18n/provider"
|
||||
import { EditDialog } from "./_components/edit"
|
||||
|
||||
function getStatusLabel(status: Status, t: (key: string) => string) {
|
||||
if (status === Status.Disabled) {
|
||||
@@ -118,6 +118,81 @@ export default function DashboardQuickRepliesPage() {
|
||||
createItem={createQuickReply}
|
||||
updateItem={(item, payload) => updateQuickReply({ id: item.id, ...payload })}
|
||||
deleteItem={(item) => deleteQuickReply(item.id)}
|
||||
form={{
|
||||
fetchDetail: fetchQuickReply,
|
||||
fields: [
|
||||
{
|
||||
name: "groupName",
|
||||
label: t("quickReply.groupName"),
|
||||
placeholder: t("quickReply.groupNamePlaceholder"),
|
||||
required: true,
|
||||
requiredMessage: t("quickReply.groupNameRequired"),
|
||||
trim: true,
|
||||
},
|
||||
{
|
||||
name: "title",
|
||||
label: t("quickReply.title"),
|
||||
placeholder: t("quickReply.titlePlaceholder"),
|
||||
required: true,
|
||||
requiredMessage: t("quickReply.titleRequired"),
|
||||
trim: true,
|
||||
},
|
||||
{
|
||||
name: "content",
|
||||
label: t("quickReply.content"),
|
||||
placeholder: t("quickReply.contentPlaceholder"),
|
||||
type: "textarea",
|
||||
rows: 6,
|
||||
required: true,
|
||||
requiredMessage: t("quickReply.contentRequired"),
|
||||
trim: true,
|
||||
},
|
||||
{
|
||||
name: "status",
|
||||
label: t("quickReply.columnStatus"),
|
||||
type: "select",
|
||||
defaultValue: String(Status.Ok),
|
||||
valueType: "number",
|
||||
required: true,
|
||||
requiredMessage: t("quickReply.statusRequired"),
|
||||
options: listStatusOptions.filter((item) => item.value !== "all"),
|
||||
valueFromItem: (item) => String(item.status),
|
||||
},
|
||||
{
|
||||
name: "sortNo",
|
||||
label: t("quickReply.columnSort"),
|
||||
placeholder: t("quickReply.sortPlaceholder"),
|
||||
type: "number",
|
||||
defaultValue: "0",
|
||||
min: 0,
|
||||
step: 1,
|
||||
required: true,
|
||||
requiredMessage: t("quickReply.sortRequired"),
|
||||
pattern: /^\d+$/,
|
||||
patternMessage: t("quickReply.sortInvalid"),
|
||||
},
|
||||
],
|
||||
transformSubmitValues: (values) => ({
|
||||
groupName: String(values.groupName ?? ""),
|
||||
title: String(values.title ?? ""),
|
||||
content: String(values.content ?? ""),
|
||||
status: Number(values.status),
|
||||
sortNo: Number(values.sortNo),
|
||||
}),
|
||||
labels: {
|
||||
createTitle: t("quickReply.createTitle"),
|
||||
editTitle: t("quickReply.editTitle"),
|
||||
create: t("quickReply.create"),
|
||||
save: t("quickReply.save"),
|
||||
saving: t("quickReply.saving"),
|
||||
cancel: t("quickReply.cancel"),
|
||||
loadingDetail: t("quickReply.loadingDetail"),
|
||||
required: t("quickReply.titleRequired"),
|
||||
invalidNumber: t("quickReply.sortInvalid"),
|
||||
minValue: () => t("quickReply.sortInvalid"),
|
||||
maxValue: () => t("quickReply.sortInvalid"),
|
||||
},
|
||||
}}
|
||||
renderRowActions={({ item, actionLoading, reload, setActionLoadingId }) => (
|
||||
<DropdownMenuItem
|
||||
onClick={() => {
|
||||
@@ -163,15 +238,6 @@ export default function DashboardQuickRepliesPage() {
|
||||
: 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"),
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useEffect, useMemo, useState } from "react"
|
||||
import { ChevronsUpDownIcon, PlusIcon } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { EditDialog as CompanyEditDialog } from "@/app/dashboard/companies/_components/edit"
|
||||
import { DashboardCrudFormDialog } from "@/components/dashboard/crud"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
Command,
|
||||
@@ -233,11 +233,54 @@ export function CompanyPicker({
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
|
||||
<CompanyEditDialog
|
||||
<DashboardCrudFormDialog<AdminCompany, CreateAdminCompanyPayload>
|
||||
open={createOpen}
|
||||
saving={createSaving}
|
||||
item={null}
|
||||
itemId={null}
|
||||
initialValues={{ name: trimmedKeyword }}
|
||||
fields={[
|
||||
{
|
||||
name: "name",
|
||||
label: t("company.columnName"),
|
||||
placeholder: t("company.namePlaceholder"),
|
||||
defaultValue: trimmedKeyword,
|
||||
required: true,
|
||||
requiredMessage: t("company.nameRequired"),
|
||||
trim: true,
|
||||
},
|
||||
{
|
||||
name: "code",
|
||||
label: t("company.columnCode"),
|
||||
placeholder: t("company.optional"),
|
||||
trim: true,
|
||||
},
|
||||
{
|
||||
name: "remark",
|
||||
label: t("company.columnRemark"),
|
||||
placeholder: t("company.remarkPlaceholder"),
|
||||
type: "textarea",
|
||||
rows: 4,
|
||||
trim: true,
|
||||
},
|
||||
]}
|
||||
transformSubmitValues={(values) => ({
|
||||
name: String(values.name ?? ""),
|
||||
code: String(values.code ?? ""),
|
||||
remark: String(values.remark ?? ""),
|
||||
})}
|
||||
labels={{
|
||||
createTitle: t("company.createTitle"),
|
||||
editTitle: t("company.editTitle"),
|
||||
create: t("company.create"),
|
||||
save: t("company.save"),
|
||||
saving: t("company.saving"),
|
||||
cancel: t("company.cancel"),
|
||||
loadingDetail: t("company.loadingDetail"),
|
||||
required: t("company.nameRequired"),
|
||||
invalidNumber: t("company.nameRequired"),
|
||||
minValue: () => t("company.nameRequired"),
|
||||
maxValue: () => t("company.nameRequired"),
|
||||
}}
|
||||
onOpenChange={setCreateOpen}
|
||||
onSubmit={handleCreateCompany}
|
||||
/>
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
"use client"
|
||||
|
||||
import type { FieldError as HookFormFieldError } from "react-hook-form"
|
||||
import { Controller, type Control, type UseFormRegister } from "react-hook-form"
|
||||
|
||||
import { OptionCombobox } from "@/components/option-combobox"
|
||||
import {
|
||||
Field,
|
||||
FieldContent,
|
||||
FieldError,
|
||||
FieldLabel,
|
||||
} from "@/components/ui/field"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Textarea } from "@/components/ui/textarea"
|
||||
import { cn } from "@/lib/utils"
|
||||
import type { DashboardCrudFormField } from "./dashboard-crud-utils"
|
||||
|
||||
export function DashboardCrudFieldControl<TItem>({
|
||||
field,
|
||||
control,
|
||||
register,
|
||||
error,
|
||||
}: {
|
||||
field: DashboardCrudFormField<TItem>
|
||||
control: Control<Record<string, string>>
|
||||
register: UseFormRegister<Record<string, string>>
|
||||
error?: HookFormFieldError
|
||||
}) {
|
||||
const inputId = `dashboard-crud-field-${field.name}`
|
||||
|
||||
return (
|
||||
<Field
|
||||
data-invalid={!!error}
|
||||
className={cn(
|
||||
(field.colSpan === 2 || field.type === "textarea") && "md:col-span-2"
|
||||
)}
|
||||
>
|
||||
<FieldLabel htmlFor={field.type === "select" ? undefined : inputId}>
|
||||
{field.label}
|
||||
</FieldLabel>
|
||||
<FieldContent>
|
||||
{field.type === "select" ? (
|
||||
<Controller
|
||||
control={control}
|
||||
name={field.name}
|
||||
render={({ field: controllerField }) => (
|
||||
<OptionCombobox
|
||||
value={controllerField.value}
|
||||
options={[...(field.options ?? [])]}
|
||||
placeholder={field.placeholder ?? field.label}
|
||||
onChange={controllerField.onChange}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
) : field.type === "textarea" ? (
|
||||
<Textarea
|
||||
id={inputId}
|
||||
rows={field.rows ?? 4}
|
||||
placeholder={field.placeholder}
|
||||
aria-invalid={!!error}
|
||||
{...register(field.name)}
|
||||
/>
|
||||
) : (
|
||||
<Input
|
||||
id={inputId}
|
||||
type={field.type === "number" ? "number" : "text"}
|
||||
min={field.type === "number" ? field.min : undefined}
|
||||
max={field.type === "number" ? field.max : undefined}
|
||||
step={field.type === "number" ? field.step : undefined}
|
||||
placeholder={field.placeholder}
|
||||
aria-invalid={!!error}
|
||||
{...register(field.name)}
|
||||
/>
|
||||
)}
|
||||
<FieldError errors={error ? [error] : []} />
|
||||
</FieldContent>
|
||||
</Field>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useMemo, useState } from "react"
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import type { Resolver } from "react-hook-form"
|
||||
import { useForm } from "react-hook-form"
|
||||
import { z } from "zod/v4"
|
||||
|
||||
import { ProjectDialog } from "@/components/project-dialog"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
buildDashboardCrudFormValues,
|
||||
normalizeDashboardCrudSubmitValues,
|
||||
type DashboardCrudFormField,
|
||||
} from "./dashboard-crud-utils"
|
||||
import { DashboardCrudFieldControl } from "./dashboard-crud-field-control"
|
||||
|
||||
type DashboardCrudFormDialogProps<TItem, TPayload> = {
|
||||
open: boolean
|
||||
saving: boolean
|
||||
item: TItem | null
|
||||
itemId: number | null
|
||||
fields: DashboardCrudFormField<TItem>[]
|
||||
fetchDetail?: (id: number) => Promise<TItem>
|
||||
transformSubmitValues?: (
|
||||
values: Record<string, string | number>,
|
||||
context: { mode: "create" | "edit"; item: TItem | null }
|
||||
) => TPayload
|
||||
labels: {
|
||||
createTitle: string
|
||||
editTitle: string
|
||||
create: string
|
||||
save: string
|
||||
saving: string
|
||||
cancel: string
|
||||
loadingDetail: string
|
||||
required: string
|
||||
invalidNumber: string
|
||||
minValue: (min: number) => string
|
||||
maxValue: (max: number) => string
|
||||
}
|
||||
onOpenChange: (open: boolean) => void
|
||||
onSubmit: (payload: TPayload) => Promise<void>
|
||||
}
|
||||
|
||||
function createFormSchema<TItem>(
|
||||
fields: ReadonlyArray<DashboardCrudFormField<TItem>>,
|
||||
labels: DashboardCrudFormDialogProps<TItem, unknown>["labels"]
|
||||
) {
|
||||
const shape: Record<string, z.ZodType<string>> = {}
|
||||
|
||||
fields.forEach((field) => {
|
||||
let schema = field.trim ? z.string().trim() : z.string()
|
||||
if (field.required) {
|
||||
schema = schema.min(1, field.requiredMessage ?? labels.required)
|
||||
}
|
||||
if (field.pattern) {
|
||||
schema = schema.regex(field.pattern, field.patternMessage ?? labels.required)
|
||||
}
|
||||
if (field.type === "number") {
|
||||
schema = schema.refine((value) => {
|
||||
if (!value.trim()) return !field.required
|
||||
return Number.isFinite(Number(value))
|
||||
}, labels.invalidNumber)
|
||||
if (field.min !== undefined) {
|
||||
schema = schema.refine((value) => !value.trim() || Number(value) >= field.min!, {
|
||||
message: labels.minValue(field.min),
|
||||
})
|
||||
}
|
||||
if (field.max !== undefined) {
|
||||
schema = schema.refine((value) => !value.trim() || Number(value) <= field.max!, {
|
||||
message: labels.maxValue(field.max),
|
||||
})
|
||||
}
|
||||
}
|
||||
shape[field.name] = schema
|
||||
})
|
||||
|
||||
return z.object(shape)
|
||||
}
|
||||
|
||||
function normalizeFormLayoutFields<TItem>(fields: DashboardCrudFormField<TItem>[]) {
|
||||
return fields.map((field) =>
|
||||
field.type === "textarea" ? { ...field, colSpan: field.colSpan ?? 2 } : field
|
||||
)
|
||||
}
|
||||
|
||||
export function DashboardCrudFormDialog<TItem, TPayload>({
|
||||
open,
|
||||
saving,
|
||||
item,
|
||||
itemId,
|
||||
fields,
|
||||
fetchDetail,
|
||||
transformSubmitValues,
|
||||
labels,
|
||||
onOpenChange,
|
||||
onSubmit,
|
||||
}: DashboardCrudFormDialogProps<TItem, TPayload>) {
|
||||
const layoutFields = useMemo(() => normalizeFormLayoutFields(fields), [fields])
|
||||
const initialValues = useMemo(
|
||||
() => buildDashboardCrudFormValues(fields, item),
|
||||
[fields, item]
|
||||
)
|
||||
const schema = useMemo(() => createFormSchema(fields, labels), [fields, labels])
|
||||
const resolver = useMemo(
|
||||
() =>
|
||||
zodResolver(schema as never) as Resolver<
|
||||
Record<string, string>,
|
||||
undefined,
|
||||
Record<string, string>
|
||||
>,
|
||||
[schema]
|
||||
)
|
||||
const [fetchedDetail, setFetchedDetail] = useState<{
|
||||
id: number
|
||||
item: TItem
|
||||
} | null>(null)
|
||||
const form = useForm<Record<string, string>, undefined, Record<string, string>>({
|
||||
resolver,
|
||||
defaultValues: initialValues,
|
||||
})
|
||||
const {
|
||||
control,
|
||||
handleSubmit,
|
||||
register,
|
||||
reset,
|
||||
formState: { errors },
|
||||
} = form
|
||||
const formId = "dashboard-crud-edit-form"
|
||||
const mode = itemId ? "edit" : "create"
|
||||
const loadingDetail = Boolean(
|
||||
itemId && fetchDetail && fetchedDetail?.id !== itemId
|
||||
)
|
||||
const detailItem =
|
||||
itemId && fetchDetail && fetchedDetail?.id === itemId
|
||||
? fetchedDetail.item
|
||||
: item
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
|
||||
if (!itemId || !fetchDetail) {
|
||||
reset(initialValues)
|
||||
return
|
||||
}
|
||||
|
||||
void fetchDetail(itemId)
|
||||
.then((detail) => {
|
||||
if (cancelled) return
|
||||
setFetchedDetail({ id: itemId, item: detail })
|
||||
reset(buildDashboardCrudFormValues(fields, detail))
|
||||
})
|
||||
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [fetchDetail, fields, initialValues, item, itemId, reset])
|
||||
|
||||
async function submit(values: Record<string, string>) {
|
||||
const normalizedValues = normalizeDashboardCrudSubmitValues(fields, values)
|
||||
const payload = transformSubmitValues
|
||||
? transformSubmitValues(normalizedValues, { mode, item: detailItem })
|
||||
: (normalizedValues as TPayload)
|
||||
await onSubmit(payload)
|
||||
}
|
||||
|
||||
if (!open || fields.length === 0) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<ProjectDialog
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
title={mode === "edit" ? labels.editTitle : labels.createTitle}
|
||||
size="md"
|
||||
allowFullscreen
|
||||
footer={
|
||||
<>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => onOpenChange(false)}
|
||||
disabled={saving}
|
||||
>
|
||||
{labels.cancel}
|
||||
</Button>
|
||||
<Button type="submit" form={formId} disabled={saving || loadingDetail}>
|
||||
{saving ? labels.saving : mode === "edit" ? labels.save : labels.create}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{loadingDetail ? (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<div className="text-muted-foreground">{labels.loadingDetail}</div>
|
||||
</div>
|
||||
) : (
|
||||
<form
|
||||
id={formId}
|
||||
onSubmit={handleSubmit(submit)}
|
||||
className="grid gap-4 md:grid-cols-2"
|
||||
>
|
||||
{layoutFields.map((field) => (
|
||||
<DashboardCrudFieldControl
|
||||
key={field.name}
|
||||
field={field}
|
||||
control={control}
|
||||
register={register}
|
||||
error={errors[field.name]}
|
||||
/>
|
||||
))}
|
||||
</form>
|
||||
)}
|
||||
</ProjectDialog>
|
||||
)
|
||||
}
|
||||
@@ -39,10 +39,12 @@ import {
|
||||
import {
|
||||
buildDashboardCrudQuery,
|
||||
normalizeDashboardCrudPageResult,
|
||||
type DashboardCrudFormField,
|
||||
type DashboardCrudPageResult,
|
||||
type DashboardCrudQueryFilter,
|
||||
type DashboardCrudQueryValue,
|
||||
} from "./dashboard-crud-utils"
|
||||
import { DashboardCrudFormDialog } from "./dashboard-crud-form-dialog"
|
||||
|
||||
type DashboardCrudFilter<TValue extends string | number = string> =
|
||||
DashboardCrudQueryFilter & {
|
||||
@@ -84,7 +86,28 @@ type DashboardCrudPageProps<TItem, TPayload> = {
|
||||
fetchList: (
|
||||
query: Record<string, DashboardCrudQueryValue>
|
||||
) => Promise<DashboardCrudPageResult<TItem>>
|
||||
renderEditDialog: (props: DashboardCrudDialogProps<TItem, TPayload>) => ReactNode
|
||||
renderEditDialog?: (props: DashboardCrudDialogProps<TItem, TPayload>) => ReactNode
|
||||
form?: {
|
||||
fields: DashboardCrudFormField<TItem>[]
|
||||
fetchDetail?: (id: number) => Promise<TItem>
|
||||
transformSubmitValues?: (
|
||||
values: Record<string, string | number>,
|
||||
context: { mode: "create" | "edit"; item: TItem | null }
|
||||
) => TPayload
|
||||
labels: {
|
||||
createTitle: string
|
||||
editTitle: string
|
||||
create: string
|
||||
save: string
|
||||
saving: string
|
||||
cancel: string
|
||||
loadingDetail: string
|
||||
required: string
|
||||
invalidNumber: string
|
||||
minValue: (min: number) => string
|
||||
maxValue: (max: number) => string
|
||||
}
|
||||
}
|
||||
getItemId: (item: TItem) => number
|
||||
createItem: (payload: TPayload) => Promise<unknown>
|
||||
updateItem: (item: TItem, payload: TPayload) => Promise<unknown>
|
||||
@@ -117,6 +140,7 @@ export function DashboardCrudPage<TItem, TPayload>({
|
||||
columns,
|
||||
fetchList,
|
||||
renderEditDialog,
|
||||
form,
|
||||
getItemId,
|
||||
createItem,
|
||||
updateItem,
|
||||
@@ -402,14 +426,29 @@ export function DashboardCrudPage<TItem, TPayload>({
|
||||
</Table>
|
||||
</DashboardTableShell>
|
||||
</DashboardPage>
|
||||
{renderEditDialog({
|
||||
open: dialogOpen,
|
||||
saving,
|
||||
item: editingItem,
|
||||
itemId: editingItem ? getItemId(editingItem) : null,
|
||||
onOpenChange: handleDialogOpenChange,
|
||||
onSubmit: handleSubmit,
|
||||
})}
|
||||
{form ? (
|
||||
<DashboardCrudFormDialog
|
||||
open={dialogOpen}
|
||||
saving={saving}
|
||||
item={editingItem}
|
||||
itemId={editingItem ? getItemId(editingItem) : null}
|
||||
fields={form.fields}
|
||||
fetchDetail={form.fetchDetail}
|
||||
transformSubmitValues={form.transformSubmitValues}
|
||||
labels={form.labels}
|
||||
onOpenChange={handleDialogOpenChange}
|
||||
onSubmit={handleSubmit}
|
||||
/>
|
||||
) : (
|
||||
renderEditDialog?.({
|
||||
open: dialogOpen,
|
||||
saving,
|
||||
item: editingItem,
|
||||
itemId: editingItem ? getItemId(editingItem) : null,
|
||||
onOpenChange: handleDialogOpenChange,
|
||||
onSubmit: handleSubmit,
|
||||
})
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -88,3 +88,58 @@ describe("normalizeDashboardCrudPageResult", () => {
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("buildDashboardCrudFormValues", () => {
|
||||
it("uses defaults for create forms and item values for edit forms", async () => {
|
||||
const { buildDashboardCrudFormValues } = await loadModule()
|
||||
const fields = [
|
||||
{ name: "title", defaultValue: "Untitled" },
|
||||
{ name: "sortNo", type: "number", defaultValue: "0" },
|
||||
{
|
||||
name: "status",
|
||||
defaultValue: "0",
|
||||
valueFromItem: (item) => String(item.status),
|
||||
},
|
||||
]
|
||||
|
||||
assert.deepEqual(plain(buildDashboardCrudFormValues(fields)), {
|
||||
title: "Untitled",
|
||||
sortNo: "0",
|
||||
status: "0",
|
||||
})
|
||||
assert.deepEqual(
|
||||
plain(buildDashboardCrudFormValues(fields, { title: "Hello", sortNo: 7, status: 1 })),
|
||||
{
|
||||
title: "Hello",
|
||||
sortNo: "7",
|
||||
status: "1",
|
||||
}
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe("normalizeDashboardCrudSubmitValues", () => {
|
||||
it("trims strings and converts number fields", async () => {
|
||||
const { normalizeDashboardCrudSubmitValues } = await loadModule()
|
||||
const fields = [
|
||||
{ name: "title", trim: true },
|
||||
{ name: "sortNo", type: "number" },
|
||||
{ name: "status", type: "select", valueType: "number" },
|
||||
]
|
||||
|
||||
assert.deepEqual(
|
||||
plain(
|
||||
normalizeDashboardCrudSubmitValues(fields, {
|
||||
title: " Hello ",
|
||||
sortNo: "12",
|
||||
status: "1",
|
||||
})
|
||||
),
|
||||
{
|
||||
title: "Hello",
|
||||
sortNo: 12,
|
||||
status: 1,
|
||||
}
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -16,6 +16,34 @@ export type DashboardCrudPageResult<T> = {
|
||||
}
|
||||
}
|
||||
|
||||
export type DashboardCrudFormValue = string | number | undefined
|
||||
|
||||
export type DashboardCrudFormOption = {
|
||||
value: string
|
||||
label: string
|
||||
}
|
||||
|
||||
export type DashboardCrudFormField<TItem = unknown> = {
|
||||
name: string
|
||||
label: string
|
||||
type?: "text" | "textarea" | "number" | "select"
|
||||
placeholder?: string
|
||||
defaultValue?: DashboardCrudFormValue
|
||||
required?: boolean
|
||||
requiredMessage?: string
|
||||
trim?: boolean
|
||||
valueType?: "string" | "number"
|
||||
min?: number
|
||||
max?: number
|
||||
step?: number
|
||||
pattern?: RegExp
|
||||
patternMessage?: string
|
||||
options?: ReadonlyArray<DashboardCrudFormOption>
|
||||
colSpan?: 1 | 2
|
||||
rows?: number
|
||||
valueFromItem?: (item: TItem) => DashboardCrudFormValue
|
||||
}
|
||||
|
||||
export function buildDashboardCrudQuery({
|
||||
values,
|
||||
filters,
|
||||
@@ -72,3 +100,42 @@ export function normalizeDashboardCrudPageResult<T>(
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export function buildDashboardCrudFormValues<TItem>(
|
||||
fields: ReadonlyArray<DashboardCrudFormField<TItem>>,
|
||||
item?: TItem | null
|
||||
): Record<string, string> {
|
||||
return Object.fromEntries(
|
||||
fields.map((field) => {
|
||||
let value: unknown = field.defaultValue ?? ""
|
||||
if (item) {
|
||||
if (field.valueFromItem) {
|
||||
value = field.valueFromItem(item)
|
||||
} else if (typeof item === "object" && item && field.name in item) {
|
||||
value = (item as Record<string, unknown>)[field.name]
|
||||
}
|
||||
}
|
||||
return [field.name, value === undefined || value === null ? "" : String(value)]
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
export function normalizeDashboardCrudSubmitValues<TItem>(
|
||||
fields: ReadonlyArray<DashboardCrudFormField<TItem>>,
|
||||
values: Record<string, string>
|
||||
): Record<string, string | number> {
|
||||
const output: Record<string, string | number> = {}
|
||||
|
||||
fields.forEach((field) => {
|
||||
const rawValue = values[field.name] ?? ""
|
||||
const text = field.trim ? rawValue.trim() : rawValue
|
||||
if (field.type === "number" || field.valueType === "number") {
|
||||
const numberValue = Number(text)
|
||||
output[field.name] = Number.isFinite(numberValue) ? numberValue : 0
|
||||
return
|
||||
}
|
||||
output[field.name] = text
|
||||
})
|
||||
|
||||
return output
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
export { DashboardCrudPage } from "./dashboard-crud-page"
|
||||
export { DashboardCrudFormDialog } from "./dashboard-crud-form-dialog"
|
||||
export type {
|
||||
DashboardCrudFormField,
|
||||
DashboardCrudPageResult,
|
||||
DashboardCrudQueryValue,
|
||||
} from "./dashboard-crud-utils"
|
||||
|
||||
Reference in New Issue
Block a user