diff --git a/server.js b/server.js index cd10fb2..04444c8 100644 --- a/server.js +++ b/server.js @@ -389,7 +389,10 @@ app.get('/api/event-images', async (req, res) => { // GET event images by event ID app.get('/api/event-images/event/:eventId', async (req, res) => { try { - const [rows] = await pool.execute('SELECT * FROM event_images WHERE eventid = ?', [req.params.eventId]); + const [rows] = await pool.execute( + 'SELECT * FROM event_images WHERE eventid = ? ORDER BY sort_order ASC, id ASC', + [req.params.eventId] + ); res.json({ success: true, data: rows @@ -469,6 +472,52 @@ app.post('/api/event-images', async (req, res) => { } }); +// Bulk reorder images +app.put('/api/event-images/reorder', async (req, res) => { + try { + const { images } = req.body; // Array of { id, sort_order } + console.log(`Reorder request received for ${images?.length} images`); + + if (!Array.isArray(images) || images.length === 0) { + return res.status(400).json({ + success: false, + message: 'Images array is required for reordering' + }); + } + + // Using a transaction for bulk update + const connection = await pool.getConnection(); + try { + await connection.beginTransaction(); + + for (const item of images) { + await connection.execute( + 'UPDATE event_images SET sort_order = ? WHERE id = ?', + [item.sort_order, item.id] + ); + } + + await connection.commit(); + res.json({ + success: true, + message: 'Images reordered successfully' + }); + } catch (err) { + console.error('Transaction failed, rolling back:', err); + await connection.rollback(); + throw err; + } finally { + connection.release(); + } + } catch (error) { + console.error('Error reordering images:', error); + res.status(500).json({ + success: false, + message: 'Failed to reorder images' + }); + } +}); + app.post('/api/event-images/bulk', async (req, res) => { try { const { eventid, imageurl } = req.body; diff --git a/setup-db.js b/setup-db.js index 6ef4d3d..fd8bea6 100644 --- a/setup-db.js +++ b/setup-db.js @@ -45,6 +45,7 @@ async function setup() { id INT AUTO_INCREMENT PRIMARY KEY, eventid INT, imageurl TEXT NOT NULL, + sort_order INT DEFAULT 0, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (eventid) REFERENCES events(id) ON DELETE CASCADE )