Block product deletion if used in food log or recipes
This commit is contained in:
parent
bcb4124be0
commit
b4255ef2d5
2 changed files with 12 additions and 3 deletions
|
|
@ -162,10 +162,13 @@ async function addProduct(p) {
|
|||
return rows[0]?.id;
|
||||
}
|
||||
|
||||
async function getProductRefs(id) {
|
||||
const food = await select("SELECT COUNT(*) as cnt FROM food_log WHERE product_id = ?1", [id]);
|
||||
const recipes = await select("SELECT COUNT(*) as cnt FROM recipe_ingredients WHERE product_id = ?1", [id]);
|
||||
return { food: food[0]?.cnt || 0, recipes: recipes[0]?.cnt || 0 };
|
||||
}
|
||||
|
||||
async function deleteProduct(id) {
|
||||
// Reassign food_log and recipe_ingredients to avoid orphaned references
|
||||
await execute("UPDATE food_log SET product_id = NULL WHERE product_id = ?1", [id]);
|
||||
await execute("UPDATE recipe_ingredients SET product_id = 0 WHERE product_id = ?1", [id]);
|
||||
await execute("DELETE FROM products WHERE id = ?1", [id]);
|
||||
}
|
||||
|
||||
|
|
@ -906,6 +909,7 @@ window.DB.searchProducts = searchProducts;
|
|||
window.DB.getProduct = getProduct;
|
||||
window.DB.addProduct = addProduct;
|
||||
window.DB.deleteProduct = deleteProduct;
|
||||
window.DB.getProductRefs = getProductRefs;
|
||||
window.DB.getFoodForDate = getFoodForDate;
|
||||
window.DB.addFoodManual = addFoodManual;
|
||||
window.DB.addFoodEntry = addFoodEntry;
|
||||
|
|
|
|||
|
|
@ -1326,6 +1326,11 @@ async function renderProducts(container) {
|
|||
btn.onclick = async e => {
|
||||
e.stopPropagation();
|
||||
const pid = parseInt(btn.dataset.pid);
|
||||
const refs = await DB.getProductRefs(pid);
|
||||
if (refs.food > 0 || refs.recipes > 0) {
|
||||
alert(`Нельзя удалить: продукт используется в ${refs.food ? refs.food + " записях еды" : ""}${refs.food && refs.recipes ? " и " : ""}${refs.recipes ? refs.recipes + " рецептах" : ""}`);
|
||||
return;
|
||||
}
|
||||
await DB.deleteProduct(pid);
|
||||
doSearch(false);
|
||||
};
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue