Merge pull request #83 from beatz174-bit/codex/extend-product-validation-in-manageproductsscreen

Validate product name uniqueness
This commit is contained in:
beatz174-bit
2025-11-24 07:35:57 +10:00
committed by GitHub
3 changed files with 149 additions and 12 deletions
+21 -10
View File
@@ -50,16 +50,16 @@ export const ProductRow = ({ product, categories, onSave, onDelete }: ProductRow
const [isEditing, setIsEditing] = useState(false);
const [formState, setFormState] = useState<ProductFormState>(() => getInitialFormState(product));
const [isScannerOpen, setIsScannerOpen] = useState(false);
const [saveError, setSaveError] = useState('');
const [fieldErrors, setFieldErrors] = useState<{ name?: string; barcode?: string }>({});
useEffect(() => {
setFormState(getInitialFormState(product));
setSaveError('');
setFieldErrors({});
}, [product]);
const handleChange = (field: keyof ProductFormState) => (event: ChangeEvent<HTMLInputElement>) => {
setFormState((prev) => ({ ...prev, [field]: event.target.value }));
setSaveError('');
setFieldErrors((prev) => ({ ...prev, [field]: undefined }));
};
const handleSave = async () => {
@@ -71,10 +71,14 @@ export const ProductRow = ({ product, categories, onSave, onDelete }: ProductRow
barcode: formState.barcode || undefined,
});
setIsEditing(false);
setSaveError('');
setFieldErrors({});
} catch (error) {
if (error instanceof Error && error.name === 'DuplicateNameError') {
setFieldErrors({ name: 'A product with this name already exists.' });
return;
}
if (error instanceof Error && error.name === 'DuplicateBarcodeError') {
setSaveError('This barcode is already assigned to another product.');
setFieldErrors({ barcode: 'This barcode is already assigned to another product.' });
return;
}
throw error;
@@ -84,7 +88,7 @@ export const ProductRow = ({ product, categories, onSave, onDelete }: ProductRow
const handleCancel = () => {
setIsEditing(false);
setFormState(getInitialFormState(product));
setSaveError('');
setFieldErrors({});
};
return (
@@ -92,7 +96,14 @@ export const ProductRow = ({ product, categories, onSave, onDelete }: ProductRow
<CardContent sx={{ p: 1.25, '&:last-child': { pb: 1.25 } }}>
{isEditing ? (
<Stack spacing={1}>
<TextField label="Name" value={formState.name} onChange={handleChange('name')} size="small" />
<TextField
label="Name"
value={formState.name}
onChange={handleChange('name')}
size="small"
error={Boolean(fieldErrors.name)}
helperText={fieldErrors.name || undefined}
/>
<TextField
select
label="Category"
@@ -112,15 +123,15 @@ export const ProductRow = ({ product, categories, onSave, onDelete }: ProductRow
value={formState.barcode}
onChange={handleChange('barcode')}
size="small"
error={Boolean(saveError)}
helperText={saveError || undefined}
error={Boolean(fieldErrors.barcode)}
helperText={fieldErrors.barcode || undefined}
InputProps={{
endAdornment: (
<Button
size="small"
onClick={() => {
setFormState((prev) => ({ ...prev, barcode: '' }));
setSaveError('');
setFieldErrors((prev) => ({ ...prev, barcode: undefined }));
}}
>
Clear
+78
View File
@@ -165,6 +165,35 @@ describe('ManageProductsScreen barcode lookup', () => {
expect(mockDb.products.add).not.toHaveBeenCalled();
});
it('prevents adding a product with a duplicate name (case-insensitive)', async () => {
mockUseProducts.mockReturnValue([
{
id: 'prod-1',
name: 'Existing Product',
category: 'Snacks',
barcode: undefined,
unit_type: 'unit',
bulk_name: 'pack',
archived: false,
created_at: 0,
updated_at: 0,
},
]);
const user = userEvent.setup();
render(
<MemoryRouter>
<ManageProductsScreen />
</MemoryRouter>,
);
await user.type(screen.getByLabelText(/name/i), 'existing product');
await user.click(screen.getByRole('button', { name: /save product/i }));
expect(await screen.findByText(/product with this name already exists/i)).toBeVisible();
expect(mockDb.products.add).not.toHaveBeenCalled();
});
it('informs the user when barcode lookup happens offline', async () => {
const originalNavigator = navigator;
Object.defineProperty(globalThis, 'navigator', {
@@ -237,6 +266,55 @@ describe('ManageProductsScreen barcode lookup', () => {
});
expect(mockDb.products.update).not.toHaveBeenCalled();
});
it('prevents updating a product to use an existing name', async () => {
mockUseProducts.mockReturnValue([
{
id: 'prod-1',
name: 'Existing Product',
category: 'Snacks',
barcode: '123456',
unit_type: 'unit',
bulk_name: 'pack',
archived: false,
created_at: 0,
updated_at: 0,
},
{
id: 'prod-2',
name: 'Another Product',
category: 'Snacks',
barcode: '654321',
unit_type: 'unit',
bulk_name: 'pack',
archived: false,
created_at: 0,
updated_at: 0,
},
]);
const user = userEvent.setup();
render(
<MemoryRouter>
<ManageProductsScreen />
</MemoryRouter>,
);
await user.click(screen.getByLabelText(/edit another product/i));
const nameField = screen
.getAllByLabelText(/name/i)
.find((input) => (input as HTMLInputElement).value === 'Another Product');
expect(nameField).toBeDefined();
fireEvent.change(nameField as Element, { target: { value: 'Existing Product' } });
expect(nameField).toHaveValue('Existing Product');
await user.click(screen.getByLabelText(/save product/i));
await waitFor(() => {
expect(nameField).toHaveAccessibleDescription('A product with this name already exists.');
expect(nameField).toHaveAttribute('aria-invalid', 'true');
});
expect(mockDb.products.update).not.toHaveBeenCalled();
});
});
describe('ManageProductsScreen auto-adding products to pick lists', () => {
+50 -2
View File
@@ -34,6 +34,7 @@ export const ManageProductsScreen = () => {
const [category, setCategory] = useState('');
const [barcode, setBarcode] = useState('');
const [barcodeError, setBarcodeError] = useState('');
const [nameError, setNameError] = useState('');
const [scannerOpen, setScannerOpen] = useState(false);
const [lookupStatus, setLookupStatus] = useState<'idle' | 'loading' | 'found' | 'notfound' | 'offline'>(
'idle',
@@ -79,6 +80,19 @@ export const ManageProductsScreen = () => {
[products],
);
const findNameConflict = useCallback(
(value?: string, productId?: string) => {
if (!value) return undefined;
const normalizedValue = value.trim().toLowerCase();
return products.find(
(product) => product.id !== productId && product.name.trim().toLowerCase() === normalizedValue,
);
},
[products],
);
const assertUniqueBarcode = useCallback(
async (value?: string, productId?: string) => {
if (!value) return;
@@ -95,6 +109,22 @@ export const ManageProductsScreen = () => {
[db.products, findBarcodeConflict],
);
const assertUniqueName = useCallback(
async (value: string, productId?: string) => {
const normalized = value.trim().toLowerCase();
if (!normalized) return;
const conflict = findNameConflict(value, productId);
if (conflict) {
const error = new Error('A product with this name already exists.');
error.name = 'DuplicateNameError';
throw error;
}
},
[findNameConflict],
);
const addProductToAutoLists = useCallback(
async (product: Product, timestamp: number) => {
const pickLists = await db.pickLists.toArray();
@@ -183,8 +213,13 @@ export const ManageProductsScreen = () => {
if (!name || !category) return;
try {
await assertUniqueName(name);
await assertUniqueBarcode(barcode || undefined);
} catch (error) {
if (error instanceof Error && error.name === 'DuplicateNameError') {
setNameError(error.message);
return;
}
if (error instanceof Error && error.name === 'DuplicateBarcodeError') {
setBarcodeError(error.message);
return;
@@ -211,6 +246,7 @@ export const ManageProductsScreen = () => {
});
setName('');
setBarcode('');
setNameError('');
setFeedback({ text: 'Product added.', severity: 'success' });
};
@@ -222,6 +258,7 @@ export const ManageProductsScreen = () => {
barcode?: string;
},
) => {
await assertUniqueName(updates.name, productId);
await assertUniqueBarcode(updates.barcode, productId);
await db.products.update(productId, {
@@ -284,12 +321,23 @@ export const ManageProductsScreen = () => {
<TextField
label="Name"
value={name}
onChange={(event) => setName(event.target.value)}
onChange={(event) => {
setName(event.target.value);
setNameError('');
}}
error={Boolean(nameError)}
helperText={nameError || undefined}
InputProps={
name
? {
endAdornment: (
<Button onClick={() => setName('')} size="small">
<Button
onClick={() => {
setName('');
setNameError('');
}}
size="small"
>
Clear
</Button>
),