costco-grocery-list/backend/models/list.model.js
Nico f30474cb5d Fix updating of user roles
Fix adding of items
2025-11-23 01:41:15 -08:00

74 lines
1.6 KiB
JavaScript

const pool = require("../db/pool");
exports.getUnboughtItems = async () => {
const result = await pool.query(
"SELECT * FROM grocery_list WHERE bought = FALSE ORDER BY id ASC"
);
return result.rows;
};
exports.getItemByName = async (itemName) => {
const result = await pool.query(
"SELECT * FROM grocery_list WHERE item_name ILIKE $1",
[itemName]
);
return result.rows[0] || null;
};
exports.addOrUpdateItem = async (itemName, quantity) => {
const result = await pool.query(
"SELECT id, bought FROM grocery_list WHERE item_name ILIKE $1",
[itemName]
);
if (result.rowCount > 0) {
await pool.query(
`UPDATE grocery_list
SET quantity = $1,
bought = FALSE
WHERE id = $2`,
[quantity, result.rows[0].id]
);
return result.rows[0].id;
} else {
const insert = await pool.query(
`INSERT INTO grocery_list
(item_name, quantity)
VALUES ($1, $2) RETURNING id`,
[itemName, quantity]
);
return insert.rows[0].id;
}
};
exports.setBought = async (id) => {
await pool.query("UPDATE grocery_list SET bought = TRUE WHERE id = $1", [id]);
};
exports.addHistoryRecord = async (itemId, quantity) => {
await pool.query(
`INSERT INTO grocery_history (list_item_id, quantity, added_on)
VALUES ($1, $2, NOW())`,
[itemId, quantity]
);
};
exports.getSuggestions = async (query) => {
const result = await pool.query(
`SELECT DISTINCT item_name
FROM grocery_list
WHERE item_name ILIKE $1
LIMIT 10`,
[`%${query}%`]
);
res = result.rows;
return result.rows;
};