costco-grocery-list/backend/models/list.model.js
2025-11-21 18:09:33 -08:00

47 lines
1.1 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.addOrUpdateItem = async (item_name, quantity) => {
const result = await pool.query(
"SELECT id, bought FROM grocery_list WHERE item_name = $1",
[item_name]
);
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",
[item_name, 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]
);
};