diff --git a/backend/src/routes/properties.js b/backend/src/routes/properties.js index 5e1f168..b0fa6d2 100644 --- a/backend/src/routes/properties.js +++ b/backend/src/routes/properties.js @@ -308,7 +308,7 @@ router.delete('/:id', validateParams(idParamSchema), async (req, res, next) => { throw new AppError('Property not found', 404); } - // Check for active applications + // Check for active applications (planned/in_progress) linked to any sections on this property const activeApps = await pool.query( `SELECT COUNT(*) as count FROM application_plans ap @@ -322,6 +322,18 @@ router.delete('/:id', validateParams(idParamSchema), async (req, res, next) => { throw new AppError('Cannot delete property with active applications', 400); } + // Prevent deletion if there are historical application logs referencing sections on this property + const histLogs = await pool.query( + `SELECT COUNT(*) as count + FROM application_logs al + JOIN lawn_sections ls ON al.lawn_section_id = ls.id + WHERE ls.property_id = $1`, + [propertyId] + ); + if (parseInt(histLogs.rows[0].count) > 0) { + throw new AppError('Cannot delete property with historical application logs; delete logs first or archive data', 400); + } + await pool.query('DELETE FROM properties WHERE id = $1', [propertyId]); res.json({ @@ -505,7 +517,7 @@ router.delete('/:propertyId/sections/:sectionId', async (req, res, next) => { throw new AppError('Lawn section not found', 404); } - // Check for active applications + // Check for active applications that include this section const activeApps = await pool.query( `SELECT COUNT(*) as count FROM application_plans ap @@ -518,6 +530,15 @@ router.delete('/:propertyId/sections/:sectionId', async (req, res, next) => { throw new AppError('Cannot delete section with active applications', 400); } + // Prevent deletion if there are historical logs tied to this section + const logs = await pool.query( + `SELECT COUNT(*) as count FROM application_logs WHERE lawn_section_id = $1`, + [sectionId] + ); + if (parseInt(logs.rows[0].count) > 0) { + throw new AppError('Cannot delete section with historical application logs; delete logs first', 400); + } + await pool.query('DELETE FROM lawn_sections WHERE id = $1', [sectionId]); res.json({