modified: src/screens/ManageProductsScreen.tsx
This commit is contained in:
1 parent
f61d078900
commit
0465683018
1 file changed
+95
-23
@@ -93,7 +93,7 @@ export const ManageProductsScreen = () => {
|
|||||||
[findNameConflict],
|
[findNameConflict],
|
||||||
);
|
);
|
||||||
|
|
||||||
const addProductToAutoLists = useCallback(
|
const addProductToAutoLists = useCallback(
|
||||||
async (product: Product, timestamp: number) => {
|
async (product: Product, timestamp: number) => {
|
||||||
const pickLists = await db.pickLists.toArray();
|
const pickLists = await db.pickLists.toArray();
|
||||||
const categoriesAll = await db.categories.toArray();
|
const categoriesAll = await db.categories.toArray();
|
||||||
@@ -133,8 +133,7 @@ const addProductToAutoLists = useCallback(
|
|||||||
);
|
);
|
||||||
},
|
},
|
||||||
[db.pickItems, db.pickLists, db.categories],
|
[db.pickItems, db.pickLists, db.categories],
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (categoryOptions.length === 0) return;
|
if (categoryOptions.length === 0) return;
|
||||||
@@ -204,26 +203,47 @@ const addProductToAutoLists = useCallback(
|
|||||||
}
|
}
|
||||||
|
|
||||||
const addProduct = async () => {
|
const addProduct = async () => {
|
||||||
// Resolve selected category name -> id if possible, otherwise create
|
// clear previous field-level errors
|
||||||
let categoryIdToSave: string;
|
setNameError('');
|
||||||
let chosenCategoryObj = categories.find((c) => c.name === category);
|
setBarcodeError('');
|
||||||
|
|
||||||
if (chosenCategoryObj) {
|
// Basic guard (button is disabled when not provided but extra safety)
|
||||||
categoryIdToSave = chosenCategoryObj.id;
|
if (!name || !category) {
|
||||||
} else {
|
setFeedback({ text: 'Name and category are required.', severity: 'error' });
|
||||||
// create a category automatically (or you can prompt the user if you prefer)
|
return;
|
||||||
const now = Date.now();
|
|
||||||
const newCatId = uuidv4();
|
|
||||||
await db.categories.add({ id: newCatId, name: category, created_at: now, updated_at: now });
|
|
||||||
categoryIdToSave = newCatId;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const timestamp = Date.now();
|
const timestamp = Date.now();
|
||||||
const productId = uuidv4();
|
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 = {
|
const newProduct: Product = {
|
||||||
id: productId,
|
id: productId,
|
||||||
name,
|
name: name.trim(),
|
||||||
category: categoryIdToSave,
|
category: categoryIdToSave,
|
||||||
unit_type: DEFAULT_UNIT_TYPE,
|
unit_type: DEFAULT_UNIT_TYPE,
|
||||||
bulk_name: DEFAULT_BULK_NAME,
|
bulk_name: DEFAULT_BULK_NAME,
|
||||||
@@ -233,14 +253,35 @@ const addProductToAutoLists = useCallback(
|
|||||||
updated_at: timestamp,
|
updated_at: timestamp,
|
||||||
};
|
};
|
||||||
|
|
||||||
await db.transaction('rw', db.products, db.pickLists, db.pickItems, async () => {
|
|
||||||
await db.products.add(newProduct);
|
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);
|
await addProductToAutoLists(newProduct, timestamp);
|
||||||
});
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
// Clear inputs & show success feedback
|
||||||
setName('');
|
setName('');
|
||||||
setBarcode('');
|
setBarcode('');
|
||||||
setNameError('');
|
setNameError('');
|
||||||
|
setBarcodeError('');
|
||||||
setFeedback({ text: 'Product added.', severity: 'success' });
|
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 (
|
const updateProduct = async (
|
||||||
@@ -251,31 +292,46 @@ const addProductToAutoLists = useCallback(
|
|||||||
barcode?: string;
|
barcode?: string;
|
||||||
},
|
},
|
||||||
) => {
|
) => {
|
||||||
|
// Clear previous errors
|
||||||
|
setNameError('');
|
||||||
|
setBarcodeError('');
|
||||||
|
|
||||||
|
try {
|
||||||
await assertUniqueName(updates.name, productId);
|
await assertUniqueName(updates.name, productId);
|
||||||
await assertUniqueBarcode(updates.barcode, productId);
|
await assertUniqueBarcode(updates.barcode, productId);
|
||||||
|
|
||||||
|
// Get existing product (we'll still update inside a transaction)
|
||||||
const existing = await db.products.get(productId);
|
const existing = await db.products.get(productId);
|
||||||
if (!existing) return;
|
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
|
// Map the provided category name back to the id (if it exists), or create one
|
||||||
let categoryIdToSave = updates.category;
|
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) {
|
if (matchingCategory) {
|
||||||
categoryIdToSave = matchingCategory.id;
|
categoryIdToSave = matchingCategory.id;
|
||||||
} else {
|
} else {
|
||||||
// If updates.category already looks like an id, keep it. Otherwise create a new category
|
// If updates.category already looks like an id, check it exists
|
||||||
const isExistingId = categories.some((c) => c.id === updates.category);
|
const isExistingId = await db.categories.get(updates.category);
|
||||||
if (!isExistingId) {
|
if (!isExistingId) {
|
||||||
const newCatId = uuidv4();
|
const newCatId = uuidv4();
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
await db.categories.add({ id: newCatId, name: updates.category, created_at: now, updated_at: now });
|
await db.categories.add({ id: newCatId, name: updates.category, created_at: now, updated_at: now });
|
||||||
categoryIdToSave = newCatId;
|
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 = {
|
const updatedProduct: Product = {
|
||||||
...existing,
|
...existing,
|
||||||
...updates,
|
...updates,
|
||||||
@@ -287,10 +343,26 @@ const addProductToAutoLists = useCallback(
|
|||||||
};
|
};
|
||||||
|
|
||||||
await db.products.put(updatedProduct);
|
await db.products.put(updatedProduct);
|
||||||
|
// Remove duplicates that used to have the same old name
|
||||||
await db.products
|
await db.products
|
||||||
.filter((product) => product.id !== productId && product.name.trim().toLowerCase() === oldNameKey)
|
.filter((product) => product.id !== productId && product.name.trim().toLowerCase() === oldNameKey)
|
||||||
.delete();
|
.delete();
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
setFeedback({ text: 'Product updated.', severity: 'success' });
|
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) => {
|
const deleteProduct = async (productId: string) => {
|
||||||
|
|||||||
Reference in new issue
Block a user