Deduplicate prefilled pick list products
This commit is contained in:
@@ -0,0 +1,168 @@
|
||||
import { MemoryRouter } from 'react-router-dom';
|
||||
import { render, screen, waitFor } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { StartPickListScreen } from './StartPickListScreen';
|
||||
|
||||
const navigateMock = vi.fn();
|
||||
|
||||
vi.mock('react-router-dom', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('react-router-dom')>();
|
||||
return {
|
||||
...actual,
|
||||
useNavigate: () => navigateMock,
|
||||
};
|
||||
});
|
||||
|
||||
const areasMock = [{ id: 'area-1', name: 'Front Counter', created_at: 0, updated_at: 0 }];
|
||||
const categoriesMock = [
|
||||
{ id: 'cat-1', name: 'Drinks', created_at: 0, updated_at: 0 },
|
||||
{ id: 'cat-2', name: 'Snacks', created_at: 0, updated_at: 0 },
|
||||
];
|
||||
|
||||
const productsMock = [
|
||||
{
|
||||
id: 'prod-1',
|
||||
name: 'Soda',
|
||||
category: 'Drinks',
|
||||
unit_type: 'unit',
|
||||
bulk_name: 'box',
|
||||
archived: false,
|
||||
created_at: 0,
|
||||
updated_at: 0,
|
||||
},
|
||||
{
|
||||
id: 'prod-2',
|
||||
name: 'Chips',
|
||||
category: 'Snacks',
|
||||
unit_type: 'unit',
|
||||
bulk_name: 'box',
|
||||
archived: false,
|
||||
created_at: 0,
|
||||
updated_at: 0,
|
||||
},
|
||||
{
|
||||
id: 'prod-3',
|
||||
name: 'Old Soda',
|
||||
category: 'Drinks',
|
||||
unit_type: 'unit',
|
||||
bulk_name: 'box',
|
||||
archived: true,
|
||||
created_at: 0,
|
||||
updated_at: 0,
|
||||
},
|
||||
];
|
||||
|
||||
const pickListAddMock = vi.fn();
|
||||
const pickItemsBulkAddMock = vi.fn();
|
||||
const transactionMock = vi.fn();
|
||||
const productsToArrayMock = vi.fn();
|
||||
|
||||
vi.mock('../hooks/dataHooks', () => ({
|
||||
useAreas: () => areasMock,
|
||||
useCategories: () => categoriesMock,
|
||||
}));
|
||||
|
||||
vi.mock('../context/DBProvider', () => ({
|
||||
useDatabase: () => ({
|
||||
pickLists: { add: pickListAddMock },
|
||||
pickItems: { bulkAdd: pickItemsBulkAddMock },
|
||||
products: { toArray: productsToArrayMock },
|
||||
transaction: transactionMock,
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('uuid', () => ({
|
||||
v4: () => 'generated-id',
|
||||
}));
|
||||
|
||||
beforeEach(() => {
|
||||
navigateMock.mockReset();
|
||||
pickListAddMock.mockReset();
|
||||
pickItemsBulkAddMock.mockReset();
|
||||
transactionMock.mockReset();
|
||||
productsToArrayMock.mockReset();
|
||||
productsToArrayMock.mockResolvedValue(productsMock);
|
||||
transactionMock.mockImplementation(async (_mode: string, ...args: unknown[]) => {
|
||||
const callback = args[args.length - 1] as () => Promise<void>;
|
||||
await callback();
|
||||
});
|
||||
});
|
||||
|
||||
describe('StartPickListScreen', () => {
|
||||
it('shows category selection controls', () => {
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<StartPickListScreen />
|
||||
</MemoryRouter>,
|
||||
);
|
||||
|
||||
categoriesMock.forEach((category) => {
|
||||
expect(screen.getByRole('checkbox', { name: category.name })).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('prefills a new pick list with products from selected categories', async () => {
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<StartPickListScreen />
|
||||
</MemoryRouter>,
|
||||
);
|
||||
|
||||
await user.click(screen.getByLabelText(/area/i));
|
||||
await user.click(screen.getByRole('option', { name: /front counter/i }));
|
||||
|
||||
await user.click(screen.getByRole('checkbox', { name: /drinks/i }));
|
||||
await user.click(screen.getByRole('checkbox', { name: /snacks/i }));
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /save pick list/i }));
|
||||
|
||||
await waitFor(() => expect(pickListAddMock).toHaveBeenCalled());
|
||||
await waitFor(() => expect(pickItemsBulkAddMock).toHaveBeenCalled());
|
||||
|
||||
const pickItems = pickItemsBulkAddMock.mock.calls[0][0];
|
||||
|
||||
expect(pickItems).toHaveLength(2);
|
||||
expect(pickItems.map((item: any) => item.product_id).sort()).toEqual(['prod-1', 'prod-2']);
|
||||
pickItems.forEach((item: any) => {
|
||||
expect(item.pick_list_id).toBe('generated-id');
|
||||
expect(item.is_carton).toBe(false);
|
||||
expect(item.quantity).toBe(1);
|
||||
expect(item.status).toBe('pending');
|
||||
});
|
||||
});
|
||||
|
||||
it('deduplicates products when selected categories include overlaps', async () => {
|
||||
const user = userEvent.setup();
|
||||
productsToArrayMock.mockResolvedValue([
|
||||
...productsMock,
|
||||
{ ...productsMock[0] },
|
||||
{ ...productsMock[1], id: 'prod-2-duplicate' },
|
||||
]);
|
||||
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<StartPickListScreen />
|
||||
</MemoryRouter>,
|
||||
);
|
||||
|
||||
await user.click(screen.getByLabelText(/area/i));
|
||||
await user.click(screen.getByRole('option', { name: /front counter/i }));
|
||||
|
||||
await user.click(screen.getByRole('checkbox', { name: /drinks/i }));
|
||||
await user.click(screen.getByRole('checkbox', { name: /snacks/i }));
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /save pick list/i }));
|
||||
|
||||
await waitFor(() => expect(pickItemsBulkAddMock).toHaveBeenCalled());
|
||||
|
||||
const pickItems = pickItemsBulkAddMock.mock.calls[0][0];
|
||||
const uniqueProductIds = new Set(pickItems.map((item: any) => item.product_id));
|
||||
|
||||
expect(pickItems).toHaveLength(2);
|
||||
expect(uniqueProductIds.size).toBe(2);
|
||||
expect(uniqueProductIds).toEqual(new Set(['prod-1', 'prod-2']));
|
||||
});
|
||||
});
|
||||
@@ -1,25 +1,98 @@
|
||||
import { Button, Container, MenuItem, Stack, TextField, Typography } from '@mui/material';
|
||||
import { useState } from 'react';
|
||||
import {
|
||||
Button,
|
||||
Checkbox,
|
||||
Container,
|
||||
FormControlLabel,
|
||||
FormGroup,
|
||||
MenuItem,
|
||||
Stack,
|
||||
TextField,
|
||||
Typography,
|
||||
} from '@mui/material';
|
||||
import { useMemo, useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
import { useAreas } from '../hooks/dataHooks';
|
||||
import { useAreas, useCategories } from '../hooks/dataHooks';
|
||||
import { useDatabase } from '../context/DBProvider';
|
||||
|
||||
export const StartPickListScreen = () => {
|
||||
const areas = useAreas();
|
||||
const categories = useCategories();
|
||||
const db = useDatabase();
|
||||
const navigate = useNavigate();
|
||||
const [areaId, setAreaId] = useState('');
|
||||
const [notes, setNotes] = useState('');
|
||||
const [selectedCategories, setSelectedCategories] = useState<string[]>([]);
|
||||
|
||||
const sortedCategories = useMemo(
|
||||
() =>
|
||||
[...categories].sort((a, b) =>
|
||||
a.name.localeCompare(b.name, undefined, { sensitivity: 'base' }),
|
||||
),
|
||||
[categories],
|
||||
);
|
||||
|
||||
const handleToggleCategory = (categoryId: string) => {
|
||||
setSelectedCategories((current) =>
|
||||
current.includes(categoryId)
|
||||
? current.filter((id) => id !== categoryId)
|
||||
: [...current, categoryId],
|
||||
);
|
||||
};
|
||||
|
||||
const start = async () => {
|
||||
if (!areaId) return;
|
||||
const pickListId = uuidv4();
|
||||
await db.pickLists.add({
|
||||
id: pickListId,
|
||||
area_id: areaId,
|
||||
created_at: Date.now(),
|
||||
notes: notes.trim() || undefined,
|
||||
const timestamp = Date.now();
|
||||
|
||||
const selectedCategoryNames = categories
|
||||
.filter((category) => selectedCategories.includes(category.id))
|
||||
.map((category) => category.name);
|
||||
|
||||
await db.transaction('rw', db.pickLists, db.pickItems, db.products, async () => {
|
||||
await db.pickLists.add({
|
||||
id: pickListId,
|
||||
area_id: areaId,
|
||||
created_at: timestamp,
|
||||
notes: notes.trim() || undefined,
|
||||
});
|
||||
|
||||
if (selectedCategoryNames.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const products = await db.products.toArray();
|
||||
const productsInCategories = products.filter(
|
||||
(product) => selectedCategoryNames.includes(product.category) && !product.archived,
|
||||
);
|
||||
|
||||
const uniqueProducts: typeof productsInCategories = [];
|
||||
const seenNames = new Set<string>();
|
||||
|
||||
productsInCategories.forEach((product) => {
|
||||
const nameKey = product.name.toLowerCase();
|
||||
if (!seenNames.has(nameKey)) {
|
||||
seenNames.add(nameKey);
|
||||
uniqueProducts.push(product);
|
||||
}
|
||||
});
|
||||
|
||||
if (productsInCategories.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
await db.pickItems.bulkAdd(
|
||||
uniqueProducts.map((product) => ({
|
||||
id: uuidv4(),
|
||||
pick_list_id: pickListId,
|
||||
product_id: product.id,
|
||||
quantity: 1,
|
||||
is_carton: false,
|
||||
status: 'pending',
|
||||
created_at: timestamp,
|
||||
updated_at: timestamp,
|
||||
})),
|
||||
);
|
||||
});
|
||||
navigate(`/pick-lists/${pickListId}`);
|
||||
};
|
||||
@@ -47,12 +120,30 @@ export const StartPickListScreen = () => {
|
||||
))}
|
||||
</TextField>
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Notes (optional)"
|
||||
value={notes}
|
||||
onChange={(event) => setNotes(event.target.value)}
|
||||
multiline
|
||||
minRows={2}
|
||||
/>
|
||||
<Stack spacing={1}>
|
||||
<Typography variant="subtitle2">Add categories to prefill products</Typography>
|
||||
<FormGroup>
|
||||
{sortedCategories.map((category) => (
|
||||
<FormControlLabel
|
||||
key={category.id}
|
||||
control={
|
||||
<Checkbox
|
||||
checked={selectedCategories.includes(category.id)}
|
||||
onChange={() => handleToggleCategory(category.id)}
|
||||
/>
|
||||
}
|
||||
label={category.name}
|
||||
/>
|
||||
))}
|
||||
</FormGroup>
|
||||
</Stack>
|
||||
<Button variant="contained" disabled={!areaId} onClick={start}>
|
||||
Save Pick List
|
||||
</Button>
|
||||
|
||||
Reference in New Issue
Block a user