83 lines
2.8 KiB
JavaScript
83 lines
2.8 KiB
JavaScript
const db = require("../config/database");
|
|
|
|
class ShoppingListRepository {
|
|
getByHousehold(householdId) {
|
|
return db.prepare(`
|
|
SELECT shopping_lists.*,
|
|
COUNT(shopping_list_items.id) AS item_count,
|
|
COALESCE(SUM(shopping_list_items.checked), 0) AS checked_count
|
|
FROM shopping_lists
|
|
LEFT JOIN shopping_list_items
|
|
ON shopping_list_items.list_id = shopping_lists.id
|
|
WHERE shopping_lists.household_id = ? AND shopping_lists.archived = 0
|
|
GROUP BY shopping_lists.id
|
|
ORDER BY shopping_lists.created_at DESC, shopping_lists.id DESC
|
|
`).all(householdId);
|
|
}
|
|
|
|
findById(id, householdId) {
|
|
return db.prepare(`
|
|
SELECT * FROM shopping_lists
|
|
WHERE id = ? AND household_id = ?
|
|
`).get(id, householdId);
|
|
}
|
|
|
|
getItems(listId, householdId) {
|
|
return db.prepare(`
|
|
SELECT shopping_list_items.*, products.name AS product_name,
|
|
categories.name AS category_name, categories.icon AS category_icon
|
|
FROM shopping_list_items
|
|
JOIN products ON products.id = shopping_list_items.product_id
|
|
LEFT JOIN categories ON categories.id = products.category_id
|
|
WHERE shopping_list_items.list_id = ?
|
|
AND products.household_id = ?
|
|
ORDER BY shopping_list_items.checked ASC,
|
|
categories.name ASC,
|
|
products.name ASC,
|
|
shopping_list_items.sort_order ASC,
|
|
shopping_list_items.created_at ASC
|
|
`).all(listId, householdId);
|
|
}
|
|
|
|
create(householdId, name) {
|
|
return db.prepare(`
|
|
INSERT INTO shopping_lists (household_id, name) VALUES (?, ?)
|
|
`).run(householdId, name);
|
|
}
|
|
|
|
addItem(listId, productId, amount) {
|
|
const nextSortOrder = db.prepare(`
|
|
SELECT COALESCE(MAX(sort_order), -1) + 1 AS value
|
|
FROM shopping_list_items WHERE list_id = ?
|
|
`).get(listId).value;
|
|
return db.prepare(`
|
|
INSERT INTO shopping_list_items (list_id, product_id, amount, sort_order)
|
|
VALUES (?, ?, ?, ?)
|
|
`).run(listId, productId, amount, nextSortOrder);
|
|
}
|
|
|
|
toggleItem(listId, itemId) {
|
|
return db.prepare(`
|
|
UPDATE shopping_list_items
|
|
SET checked = CASE checked WHEN 0 THEN 1 ELSE 0 END
|
|
WHERE id = ? AND list_id = ?
|
|
`).run(itemId, listId);
|
|
}
|
|
|
|
resetItems(listId) {
|
|
return db.prepare(`
|
|
UPDATE shopping_list_items
|
|
SET checked = 0
|
|
WHERE list_id = ?
|
|
`).run(listId);
|
|
}
|
|
|
|
deleteItem(listId, itemId) {
|
|
return db.prepare(`
|
|
DELETE FROM shopping_list_items WHERE id = ? AND list_id = ?
|
|
`).run(itemId, listId);
|
|
}
|
|
}
|
|
|
|
module.exports = new ShoppingListRepository();
|