mirror of
https://github.com/Sea-Haven-Industries/proposal-system.git
synced 2026-10-07 09:19:04 +00:00
refactor(web): pricing library on domain layer + react-hook-form
This commit is contained in:
parent
e0261f0cee
commit
b7c6386aca
1 changed files with 162 additions and 202 deletions
|
|
@ -1,5 +1,6 @@
|
|||
import { useState } from 'react';
|
||||
import { useQuery, useMutation } from '@tanstack/react-query';
|
||||
import { Controller, useForm, type DefaultValues } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import {
|
||||
Box,
|
||||
Typography,
|
||||
|
|
@ -29,17 +30,18 @@ import AddIcon from '@mui/icons-material/Add';
|
|||
import EditIcon from '@mui/icons-material/Edit';
|
||||
import DeleteIcon from '@mui/icons-material/Delete';
|
||||
import ErrorOutlineIcon from '@mui/icons-material/ErrorOutlined';
|
||||
import { toast } from 'react-toastify';
|
||||
import {
|
||||
pricingLibraryApi,
|
||||
type PricingLibraryItem,
|
||||
type PagedPricingLibraryResponse,
|
||||
type CreatePricingLibraryItemRequest,
|
||||
type UpdatePricingLibraryItemRequest,
|
||||
} from '../../../lib/api/pricingLibrary';
|
||||
import type { ServiceCategory } from '@proposal-system/api-contracts';
|
||||
import { queryClient } from '../../../lib/queryClient';
|
||||
import { QUERY_KEYS } from '../../../constants/queryKeys';
|
||||
usePricingLibraryList,
|
||||
useCreatePricingLibraryItem,
|
||||
useUpdatePricingLibraryItem,
|
||||
useDeletePricingLibraryItem,
|
||||
} from '../../../domain/pricingLibrary/use-cases';
|
||||
import type { PricingLibraryItem } from '../../../domain/pricingLibrary/types';
|
||||
import {
|
||||
pricingLibraryItemFormSchema,
|
||||
toPricingLibraryItemRequest,
|
||||
type PricingLibraryItemFormValues,
|
||||
} from '../../../domain/pricingLibrary/schemas';
|
||||
import { DEFAULT_PAGE, DEFAULT_PAGE_SIZE, SERVICE_CATEGORIES } from '../../../constants';
|
||||
import { useDocumentTitle } from '../../../hooks/useDocumentTitle';
|
||||
|
||||
|
|
@ -55,18 +57,12 @@ const CATEGORY_CHIP_STYLES: Record<string, { bgcolor: string; color: string; bor
|
|||
Other: { bgcolor: '#F1F5F9', color: '#475569', border: '1px solid #CBD5E1' },
|
||||
};
|
||||
|
||||
interface ItemFormState {
|
||||
title: string;
|
||||
serviceCategory: ServiceCategory | '';
|
||||
unit: string;
|
||||
unitPrice: string;
|
||||
keywords: string;
|
||||
description: string;
|
||||
}
|
||||
|
||||
const EMPTY_FORM: ItemFormState = {
|
||||
/**
|
||||
* serviceCategory stays union-typed (ServiceCategory) in the form schema, so the
|
||||
* create defaults leave it unset rather than using an out-of-union '' sentinel.
|
||||
*/
|
||||
const EMPTY_FORM_VALUES: DefaultValues<PricingLibraryItemFormValues> = {
|
||||
title: '',
|
||||
serviceCategory: '',
|
||||
unit: '',
|
||||
unitPrice: '',
|
||||
keywords: '',
|
||||
|
|
@ -86,15 +82,7 @@ export default function PricingLibraryPage() {
|
|||
const [page, setPage] = useState(DEFAULT_PAGE);
|
||||
const [pageSize, setPageSize] = useState(DEFAULT_PAGE_SIZE);
|
||||
|
||||
const {
|
||||
data,
|
||||
isLoading,
|
||||
isError,
|
||||
refetch,
|
||||
} = useQuery<PagedPricingLibraryResponse>({
|
||||
queryKey: [QUERY_KEYS.pricingLibraryList, page, pageSize],
|
||||
queryFn: () => pricingLibraryApi.list({ page, pageSize }),
|
||||
});
|
||||
const { data, isLoading, isError, refetch } = usePricingLibraryList({ page, pageSize });
|
||||
|
||||
const rows = data?.items ?? [];
|
||||
const totalCount = data?.totalCount ?? 0;
|
||||
|
|
@ -102,21 +90,28 @@ export default function PricingLibraryPage() {
|
|||
// --- Create/Edit dialog state ---
|
||||
const [dialogOpen, setDialogOpen] = useState(false);
|
||||
const [editingItem, setEditingItem] = useState<PricingLibraryItem | null>(null);
|
||||
const [form, setForm] = useState<ItemFormState>(EMPTY_FORM);
|
||||
const [formErrors, setFormErrors] = useState<Partial<Record<keyof ItemFormState, string>>>({});
|
||||
|
||||
const isEditing = editingItem !== null;
|
||||
|
||||
const {
|
||||
control,
|
||||
handleSubmit,
|
||||
reset,
|
||||
formState: { errors },
|
||||
} = useForm<PricingLibraryItemFormValues>({
|
||||
resolver: zodResolver(pricingLibraryItemFormSchema),
|
||||
defaultValues: EMPTY_FORM_VALUES,
|
||||
});
|
||||
|
||||
const openCreateDialog = () => {
|
||||
setEditingItem(null);
|
||||
setForm(EMPTY_FORM);
|
||||
setFormErrors({});
|
||||
reset(EMPTY_FORM_VALUES);
|
||||
setDialogOpen(true);
|
||||
};
|
||||
|
||||
const openEditDialog = (item: PricingLibraryItem) => {
|
||||
setEditingItem(item);
|
||||
setForm({
|
||||
reset({
|
||||
title: item.title,
|
||||
serviceCategory: item.serviceCategory,
|
||||
unit: item.unit ?? '',
|
||||
|
|
@ -124,40 +119,13 @@ export default function PricingLibraryPage() {
|
|||
keywords: item.keywords ?? '',
|
||||
description: item.description ?? '',
|
||||
});
|
||||
setFormErrors({});
|
||||
setDialogOpen(true);
|
||||
};
|
||||
|
||||
const closeDialog = () => {
|
||||
setDialogOpen(false);
|
||||
setEditingItem(null);
|
||||
setForm(EMPTY_FORM);
|
||||
setFormErrors({});
|
||||
};
|
||||
|
||||
const validateForm = (): boolean => {
|
||||
const errors: Partial<Record<keyof ItemFormState, string>> = {};
|
||||
if (!form.title.trim()) errors.title = 'Title is required';
|
||||
if (!form.serviceCategory) errors.serviceCategory = 'Service category is required';
|
||||
if (form.unitPrice.trim() !== '') {
|
||||
const parsed = parseFloat(form.unitPrice);
|
||||
if (isNaN(parsed) || parsed < 0) {
|
||||
errors.unitPrice = 'Must be a number >= 0';
|
||||
}
|
||||
}
|
||||
setFormErrors(errors);
|
||||
return Object.keys(errors).length === 0;
|
||||
};
|
||||
|
||||
const handleFieldChange = (field: keyof ItemFormState, value: string) => {
|
||||
setForm((prev) => ({ ...prev, [field]: value }));
|
||||
if (formErrors[field]) {
|
||||
setFormErrors((prev) => {
|
||||
const next = { ...prev };
|
||||
delete next[field];
|
||||
return next;
|
||||
});
|
||||
}
|
||||
reset(EMPTY_FORM_VALUES);
|
||||
};
|
||||
|
||||
// --- Delete confirm dialog state ---
|
||||
|
|
@ -171,67 +139,26 @@ export default function PricingLibraryPage() {
|
|||
setDeleteTarget(null);
|
||||
};
|
||||
|
||||
// --- Mutations ---
|
||||
const createMutation = useMutation({
|
||||
mutationFn: (data: CreatePricingLibraryItemRequest) => pricingLibraryApi.create(data),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: [QUERY_KEYS.pricingLibraryList] });
|
||||
closeDialog();
|
||||
toast.success('Pricing item created');
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
toast.error(`Failed to create item: ${error.message}`);
|
||||
},
|
||||
});
|
||||
// --- Mutations (domain hooks own invalidation + toasts; dialog close stays here) ---
|
||||
const createMutation = useCreatePricingLibraryItem();
|
||||
const updateMutation = useUpdatePricingLibraryItem();
|
||||
const deleteMutation = useDeletePricingLibraryItem();
|
||||
|
||||
const updateMutation = useMutation({
|
||||
mutationFn: ({ id, data }: { id: string; data: UpdatePricingLibraryItemRequest }) =>
|
||||
pricingLibraryApi.update(id, data),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: [QUERY_KEYS.pricingLibraryList] });
|
||||
closeDialog();
|
||||
toast.success('Pricing item updated');
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
toast.error(`Failed to update item: ${error.message}`);
|
||||
},
|
||||
});
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: (id: string) => pricingLibraryApi.remove(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: [QUERY_KEYS.pricingLibraryList] });
|
||||
closeDeleteDialog();
|
||||
toast.success('Pricing item deleted');
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
toast.error(`Failed to delete item: ${error.message}`);
|
||||
},
|
||||
});
|
||||
|
||||
const handleSubmit = () => {
|
||||
if (!validateForm()) return;
|
||||
if (!form.serviceCategory) return; // validateForm guarantees this; narrows '' out of the union
|
||||
|
||||
const payload = {
|
||||
title: form.title.trim(),
|
||||
serviceCategory: form.serviceCategory,
|
||||
...(form.unit.trim() ? { unit: form.unit.trim() } : {}),
|
||||
unitPrice: form.unitPrice.trim() !== '' ? parseFloat(form.unitPrice) : null,
|
||||
...(form.keywords.trim() ? { keywords: form.keywords.trim() } : {}),
|
||||
...(form.description.trim() ? { description: form.description.trim() } : {}),
|
||||
};
|
||||
|
||||
if (isEditing) {
|
||||
updateMutation.mutate({ id: editingItem.id, data: payload });
|
||||
const onSubmit = handleSubmit((values) => {
|
||||
const payload = toPricingLibraryItemRequest(values);
|
||||
if (editingItem) {
|
||||
updateMutation.mutate(
|
||||
{ id: editingItem.id, data: payload },
|
||||
{ onSuccess: () => closeDialog() }
|
||||
);
|
||||
} else {
|
||||
createMutation.mutate(payload);
|
||||
createMutation.mutate(payload, { onSuccess: () => closeDialog() });
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
const handleDeleteConfirm = () => {
|
||||
if (deleteTarget) {
|
||||
deleteMutation.mutate(deleteTarget.id);
|
||||
deleteMutation.mutate(deleteTarget.id, { onSuccess: () => closeDeleteDialog() });
|
||||
}
|
||||
};
|
||||
|
||||
|
|
@ -368,90 +295,123 @@ export default function PricingLibraryPage() {
|
|||
{/* Create / Edit Dialog */}
|
||||
<Dialog open={dialogOpen} onClose={closeDialog} maxWidth="sm" fullWidth>
|
||||
<DialogTitle>{isEditing ? 'Edit Pricing Item' : 'New Pricing Item'}</DialogTitle>
|
||||
<DialogContent>
|
||||
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 2, mt: 1 }}>
|
||||
<TextField
|
||||
label="Title"
|
||||
value={form.title}
|
||||
onChange={(e) => handleFieldChange('title', e.target.value)}
|
||||
error={!!formErrors.title}
|
||||
helperText={formErrors.title}
|
||||
size="small"
|
||||
required
|
||||
fullWidth
|
||||
autoFocus
|
||||
/>
|
||||
<TextField
|
||||
label="Service Category"
|
||||
value={form.serviceCategory}
|
||||
onChange={(e) => handleFieldChange('serviceCategory', e.target.value)}
|
||||
error={!!formErrors.serviceCategory}
|
||||
helperText={formErrors.serviceCategory}
|
||||
size="small"
|
||||
required
|
||||
fullWidth
|
||||
select
|
||||
<form onSubmit={onSubmit} noValidate>
|
||||
<DialogContent>
|
||||
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 2, mt: 1 }}>
|
||||
<Controller
|
||||
name="title"
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<TextField
|
||||
{...field}
|
||||
label="Title"
|
||||
error={!!errors.title}
|
||||
helperText={errors.title?.message}
|
||||
size="small"
|
||||
required
|
||||
fullWidth
|
||||
autoFocus
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<Controller
|
||||
name="serviceCategory"
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<TextField
|
||||
{...field}
|
||||
value={field.value ?? ''}
|
||||
label="Service Category"
|
||||
error={!!errors.serviceCategory}
|
||||
helperText={errors.serviceCategory ? 'Service category is required' : undefined}
|
||||
size="small"
|
||||
required
|
||||
fullWidth
|
||||
select
|
||||
>
|
||||
{SERVICE_CATEGORIES.map((cat) => (
|
||||
<MenuItem key={cat} value={cat}>
|
||||
{cat}
|
||||
</MenuItem>
|
||||
))}
|
||||
</TextField>
|
||||
)}
|
||||
/>
|
||||
<Controller
|
||||
name="unit"
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<TextField
|
||||
{...field}
|
||||
label="Unit"
|
||||
helperText="e.g., each, hour, sq ft"
|
||||
size="small"
|
||||
fullWidth
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<Controller
|
||||
name="unitPrice"
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<TextField
|
||||
{...field}
|
||||
label="Unit Price"
|
||||
type="number"
|
||||
error={!!errors.unitPrice}
|
||||
helperText={errors.unitPrice?.message || 'Optional. Leave blank if price varies.'}
|
||||
size="small"
|
||||
fullWidth
|
||||
slotProps={{
|
||||
htmlInput: { min: 0, step: '0.01' },
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<Controller
|
||||
name="keywords"
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<TextField
|
||||
{...field}
|
||||
label="Keywords"
|
||||
helperText="Comma-separated keywords for AI matching."
|
||||
size="small"
|
||||
fullWidth
|
||||
multiline
|
||||
minRows={2}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<Controller
|
||||
name="description"
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<TextField
|
||||
{...field}
|
||||
label="Description"
|
||||
size="small"
|
||||
fullWidth
|
||||
multiline
|
||||
minRows={2}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</Box>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={closeDialog} disabled={isSaving}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
variant="contained"
|
||||
disabled={isSaving}
|
||||
>
|
||||
{SERVICE_CATEGORIES.map((cat) => (
|
||||
<MenuItem key={cat} value={cat}>
|
||||
{cat}
|
||||
</MenuItem>
|
||||
))}
|
||||
</TextField>
|
||||
<TextField
|
||||
label="Unit"
|
||||
value={form.unit}
|
||||
onChange={(e) => handleFieldChange('unit', e.target.value)}
|
||||
helperText="e.g., each, hour, sq ft"
|
||||
size="small"
|
||||
fullWidth
|
||||
/>
|
||||
<TextField
|
||||
label="Unit Price"
|
||||
type="number"
|
||||
value={form.unitPrice}
|
||||
onChange={(e) => handleFieldChange('unitPrice', e.target.value)}
|
||||
error={!!formErrors.unitPrice}
|
||||
helperText={formErrors.unitPrice || 'Optional. Leave blank if price varies.'}
|
||||
size="small"
|
||||
fullWidth
|
||||
slotProps={{
|
||||
htmlInput: { min: 0, step: '0.01' },
|
||||
}}
|
||||
/>
|
||||
<TextField
|
||||
label="Keywords"
|
||||
value={form.keywords}
|
||||
onChange={(e) => handleFieldChange('keywords', e.target.value)}
|
||||
helperText="Comma-separated keywords for AI matching."
|
||||
size="small"
|
||||
fullWidth
|
||||
multiline
|
||||
minRows={2}
|
||||
/>
|
||||
<TextField
|
||||
label="Description"
|
||||
value={form.description}
|
||||
onChange={(e) => handleFieldChange('description', e.target.value)}
|
||||
size="small"
|
||||
fullWidth
|
||||
multiline
|
||||
minRows={2}
|
||||
/>
|
||||
</Box>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={closeDialog} disabled={isSaving}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
variant="contained"
|
||||
onClick={handleSubmit}
|
||||
disabled={isSaving}
|
||||
>
|
||||
{isSaving ? (isEditing ? 'Saving...' : 'Creating...') : isEditing ? 'Save Changes' : 'Create Item'}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
{isSaving ? (isEditing ? 'Saving...' : 'Creating...') : isEditing ? 'Save Changes' : 'Create Item'}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</form>
|
||||
</Dialog>
|
||||
|
||||
{/* Delete Confirm Dialog */}
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue