modified: src/screens/ManageProductsScreen.tsx

This commit is contained in:
beatzaplenty committed 2025-11-25 13:46:04 +10:00
1 parent f61d078900
commit 0465683018
1 file changed
+95 -23
+95 -23
View File
@@ -93,7 +93,7 @@ export const ManageProductsScreen = () => {
[findNameConflict],
);
const addProductToAutoLists = useCallback(
const addProductToAutoLists = useCallback(
async (product: Product, timestamp: number) => {
const pickLists = await db.pickLists.toArray();
const categoriesAll = await db.categories.toArray();
@@ -133,8 +133,7 @@ const addProductToAutoLists = useCallback(
);
},
[db.pickItems, db.pickLists, db.categories],
);
);
useEffect(() => {
if (categoryOptions.length === 0) return;
@@ -204,26 +203,47 @@ const addProductToAutoLists = useCallback(
}
const addProduct = async () => {
// Resolve selected category name -> id if possible, otherwise create
let categoryIdToSave: string;
let chosenCategoryObj = categories.find((c) => c.name === category);
// clear previous field-level errors
setNameError('');
setBarcodeError('');
if (chosenCategoryObj) {
categoryIdToSave = chosenCategoryObj.id;
} else {
// create a category automatically (or you can prompt the user if you prefer)
const now = Date.now();
const newCatId = uuidv4();
await db.categories.add({ id: newCatId, name: category, created_at: now, updated_at: now });
categoryIdToSave = newCatId;
// Basic guard (button is disabled when not provided but extra safety)
if (!name || !category) {
setFeedback({ text: 'Name and category are required.', severity: 'error' });
return;
}
const timestamp = Date.now();
const productId = uuidv4();
try {
// Run uniqueness checks inside the try so we can handle the errors
await assertUniqueName(name);
await assertUniqueBarcode(barcode);
// Use a transaction that includes categories too, and make category creation atomic
await db.transaction(
'rw',
db.categories,
db.products,
db.pickLists,
db.pickItems,
async () => {
// Determine or create the category within the transaction
let categoryIdToSave: string;
const existingCategory = await db.categories.where('name').equals(category).first();
if (existingCategory) {
categoryIdToSave = existingCategory.id;
} else {
const newCatId = uuidv4();
const now = Date.now();
await db.categories.add({ id: newCatId, name: category, created_at: now, updated_at: now });
categoryIdToSave = newCatId;
}
const newProduct: Product = {
id: productId,
name,
name: name.trim(),
category: categoryIdToSave,
unit_type: DEFAULT_UNIT_TYPE,
bulk_name: DEFAULT_BULK_NAME,
@@ -233,14 +253,35 @@ const addProductToAutoLists = useCallback(
updated_at: timestamp,
};
await db.transaction('rw', db.products, db.pickLists, db.pickItems, async () => {
await db.products.add(newProduct);
// add product to auto-add pick lists (this uses db.* but will execute within the same transaction)
await addProductToAutoLists(newProduct, timestamp);
});
},
);
// Clear inputs & show success feedback
setName('');
setBarcode('');
setNameError('');
setBarcodeError('');
setFeedback({ text: 'Product added.', severity: 'success' });
} catch (err: any) {
console.error('Failed to add product', err);
// Provide field-level errors for duplicates
if (err?.name === 'DuplicateNameError') {
setNameError(err.message || 'A product with this name already exists.');
return;
}
if (err?.name === 'DuplicateBarcodeError') {
setBarcodeError(err.message || 'This barcode is already assigned to another product.');
return;
}
// Generic DB failure
setFeedback({ text: `Failed to add product: ${err?.message ?? String(err)}`, severity: 'error' });
}
};
const updateProduct = async (
@@ -251,31 +292,46 @@ const addProductToAutoLists = useCallback(
barcode?: string;
},
) => {
// Clear previous errors
setNameError('');
setBarcodeError('');
try {
await assertUniqueName(updates.name, productId);
await assertUniqueBarcode(updates.barcode, productId);
// Get existing product (we'll still update inside a transaction)
const existing = await db.products.get(productId);
if (!existing) return;
const normalizedName = updates.name.trim();
const oldNameKey = existing.name.trim().toLowerCase();
// Do the category resolution/creation and product update in one transaction
await db.transaction(
'rw',
db.categories,
db.products,
async () => {
// Map the provided category name back to the id (if it exists), or create one
let categoryIdToSave = updates.category;
const matchingCategory = categories.find((c) => c.name === updates.category);
const matchingCategory = await db.categories.where('name').equals(updates.category).first();
if (matchingCategory) {
categoryIdToSave = matchingCategory.id;
} else {
// If updates.category already looks like an id, keep it. Otherwise create a new category
const isExistingId = categories.some((c) => c.id === updates.category);
// If updates.category already looks like an id, check it exists
const isExistingId = await db.categories.get(updates.category);
if (!isExistingId) {
const newCatId = uuidv4();
const now = Date.now();
await db.categories.add({ id: newCatId, name: updates.category, created_at: now, updated_at: now });
categoryIdToSave = newCatId;
} else {
// updates.category was an id and exists — no change
categoryIdToSave = updates.category;
}
}
const normalizedName = updates.name.trim();
const oldNameKey = existing.name.trim().toLowerCase();
const updatedProduct: Product = {
...existing,
...updates,
@@ -287,10 +343,26 @@ const addProductToAutoLists = useCallback(
};
await db.products.put(updatedProduct);
// Remove duplicates that used to have the same old name
await db.products
.filter((product) => product.id !== productId && product.name.trim().toLowerCase() === oldNameKey)
.delete();
},
);
setFeedback({ text: 'Product updated.', severity: 'success' });
} catch (err: any) {
console.error('Failed to update product', err);
if (err?.name === 'DuplicateNameError') {
setNameError(err.message || 'A product with this name already exists.');
return;
}
if (err?.name === 'DuplicateBarcodeError') {
setBarcodeError(err.message || 'This barcode is already assigned to another product.');
return;
}
setFeedback({ text: `Failed to update product: ${err?.message ?? String(err)}`, severity: 'error' });
}
};
const deleteProduct = async (productId: string) => {