From 32abe60d9861ce969ec7225f08544a8ca55adc6d Mon Sep 17 00:00:00 2001 From: Theis Gaedigk Date: Mon, 29 Sep 2025 10:44:51 +0200 Subject: [PATCH] fixed api route for setting the return and take date --- backend/routes/apiV2.js | 2 +- backend/services/database.js | 38 ++++++++++++++++++++++++++++++++++-- 2 files changed, 37 insertions(+), 3 deletions(-) diff --git a/backend/routes/apiV2.js b/backend/routes/apiV2.js index 1d32c54..5f1098b 100644 --- a/backend/routes/apiV2.js +++ b/backend/routes/apiV2.js @@ -3,8 +3,8 @@ import dotenv from "dotenv"; import { getItemsFromDatabaseV2, changeInSafeStateV2, - setReturnDateV2, setTakeDateV2, + setReturnDateV2, getLoanByCodeV2, getAllLoansV2, getAPIkey, diff --git a/backend/services/database.js b/backend/services/database.js index 5ddcc9c..dacc1d1 100644 --- a/backend/services/database.js +++ b/backend/services/database.js @@ -51,22 +51,56 @@ export const changeInSafeStateV2 = async (itemId) => { }; export const setReturnDateV2 = async (loanCode) => { + const [items] = await pool.query( + "SELECT loaned_items_id FROM loans WHERE loan_code = ?", + [loanCode] + ); + + if (items.length === 0) return { success: false }; + + const itemIds = Array.isArray(items[0].loaned_items_id) + ? items[0].loaned_items_id + : JSON.parse(items[0].loaned_items_id || "[]"); + + const [setItemStates] = await pool.query( + "UPDATE items SET inSafe = 1 WHERE id IN (?)", + [itemIds] + ); + const [result] = await pool.query( "UPDATE loans SET returned_date = NOW() WHERE loan_code = ?", [loanCode] ); - if (result.affectedRows > 0) { + + if (result.affectedRows > 0 && setItemStates.affectedRows > 0) { return { success: true }; } return { success: false }; }; export const setTakeDateV2 = async (loanCode) => { + const [items] = await pool.query( + "SELECT loaned_items_id FROM loans WHERE loan_code = ?", + [loanCode] + ); + + if (items.length === 0) return { success: false }; + + const itemIds = Array.isArray(items[0].loaned_items_id) + ? items[0].loaned_items_id + : JSON.parse(items[0].loaned_items_id || "[]"); + + const [setItemStates] = await pool.query( + "UPDATE items SET inSafe = 0 WHERE id IN (?)", + [itemIds] + ); + const [result] = await pool.query( "UPDATE loans SET take_date = NOW() WHERE loan_code = ?", [loanCode] ); - if (result.affectedRows > 0) { + + if (result.affectedRows > 0 && setItemStates.affectedRows > 0) { return { success: true }; } return { success: false };