diff --git a/server/db/database.js b/server/db/database.js index 30ea4ab..693f083 100644 --- a/server/db/database.js +++ b/server/db/database.js @@ -5,10 +5,14 @@ export const DB_USER_ERROR = 'USER'; let currentDate = (new Date()).toISOString().slice(0, 10); -export async function getCurrentDate() { +export function getCurrentDate() { return currentDate; } +function Random_Increase() { + return Math.floor(Math.random() * 5) + 1; +} + export async function setCurrentDate(newDate) { currentDate = newDate; console.log(`📅 Date changed to: ${currentDate}`); @@ -62,6 +66,24 @@ export default class DBAdapter { console.log("DISCONNECT"); } + async stock(){ + try { + const products = await this.#dbClient.query('SELECT id FROM products'); + for (const product of products) { + const increment = Random_Increase(); + await this.#dbClient.query('UPDATE products SET quantity = quantity + ? WHERE id = ?', [ + increment, + product.id + ]); + } + } catch (err){ + return Promise.reject({ + type: err + } + ); + } + } + async getProducts() { try { const products = await this.#dbClient.query('SELECT * FROM products ORDER BY name'); diff --git a/server/server.js b/server/server.js index 6f71759..00c82c9 100644 --- a/server/server.js +++ b/server/server.js @@ -16,7 +16,7 @@ const { PASSWORD } = process.env; -const appPort = Number(PORT) || 3000; +const appPort = 3000; const app = express(); app.use(express.json()); @@ -35,12 +35,8 @@ function AddDays(dateString, days) { return date.toISOString().slice(0, 10); } -function Random_Increase() { - return Math.floor(Math.random() * 5) + 1; -} - app.get('/api/current-date', async (req, res) => { - let currentDate = await getCurrentDate(); + let currentDate = getCurrentDate(); res.json({ currentDate }); }); @@ -70,13 +66,15 @@ app.get('/api/products', async(req, res) => { }); app.post('/api/current-date/advance', async (req, res) => { - let currentDate = await getCurrentDate(); + let currentDate = getCurrentDate(); try { const raw_ids = await adapter.getOrdersByDate(currentDate); - const ids = raw_ids.map(item => item.id); - await adapter.clearOrders(ids); - + if (raw_ids && raw_ids.length > 0) { + const ids = raw_ids.map(item => item.id); + await adapter.clearOrders(ids); + } let nextDate = AddDays(currentDate, 1); + await adapter.stock(); await setCurrentDate(nextDate); res.json({ currentDate: nextDate }); } catch (err){ @@ -84,7 +82,7 @@ app.post('/api/current-date/advance', async (req, res) => { res.message = "WHOOPS"; res.json({ timeStamp: new Date().toISOString(), - statusCode: 500, + statusCode: res.statusCode, error : `${err}` }) }