diff --git a/backend/src/routes/cart.js b/backend/src/routes/cart.js index e2605c6..df4b570 100644 --- a/backend/src/routes/cart.js +++ b/backend/src/routes/cart.js @@ -742,7 +742,7 @@ module.exports = (pool, query, authMiddleware) => { } }); - // New endpoint: Complete checkout after successful payment + // Complete checkout after successful payment router.post('/complete-checkout', async (req, res, next) => { try { const { userId, orderId, sessionId } = req.body; @@ -800,6 +800,36 @@ module.exports = (pool, query, authMiddleware) => { 'UPDATE products SET stock_quantity = stock_quantity - $1 WHERE id = $2', [item.quantity, item.product_id] ); + + // Process low stock notifications within the transaction + const productWithNotification = await client.query( + `SELECT stock_quantity, stock_notification + FROM products + WHERE id = $1 AND stock_notification IS NOT NULL`, + [item.product_id] + ); + + if (productWithNotification.rows.length > 0) { + const product = productWithNotification.rows[0]; + + // Check if notification is enabled and stock is below threshold + if (product.stock_notification && + typeof product.stock_notification === 'object' && + product.stock_notification.enabled === true && + product.stock_notification.threshold && + product.stock_quantity <= product.stock_notification.threshold) { + + // Log the notification - using the current order ID (not NULL) + await client.query( + `INSERT INTO notification_logs + (order_id, notification_type, sent_at, status) + VALUES ($1, $2, NOW(), $3)`, + [orderId, 'low_stock_alert', 'pending'] + ); + + console.log(`Low stock notification queued for product ${item.product_id}`); + } + } } // Clear cart @@ -811,36 +841,6 @@ module.exports = (pool, query, authMiddleware) => { await client.query('COMMIT'); - for (const item of cartItemsResult.rows) { - // Get product details including notification settings - const productWithNotification = await client.query( - `SELECT stock_quantity, stock_notification - FROM products - WHERE id = $1 AND stock_notification IS NOT NULL`, - [item.product_id] - ); - - if (productWithNotification.rows.length > 0) { - const product = productWithNotification.rows[0]; - - // Check if notification is enabled and stock is below threshold - if (product.stock_notification && - product.stock_notification.enabled === true && - product.stock_notification.threshold && - product.stock_quantity <= product.stock_notification.threshold) { - - // Log the notification - it will be picked up by the notification service - await client.query( - `INSERT INTO notification_logs - (order_id, notification_type, sent_at, status) - VALUES ($1, $2, NOW(), $3)`, - [orderId, 'low_stock_alert', 'pending'] - ); - - console.log(`Low stock notification queued for product ${item.product_id}`); - } - } - } res.status(200).json({ success: true, message: 'Order completed successfully',