feat(config): hard-delete branches for admins
DELETE /branches/<id> now removes the row, nullifies FK references, and deletes branch-specific stock/count records. Main branch remains protected.
This commit is contained in:
@@ -153,7 +153,11 @@ def update_branch(branch_id):
|
||||
@config_bp.route('/branches/<int:branch_id>', methods=['DELETE'])
|
||||
@require_auth('config.edit')
|
||||
def delete_branch(branch_id):
|
||||
"""Soft-delete a branch. Only owner/admin can delete; main branch cannot be deleted."""
|
||||
"""Hard-delete a branch. Only owner/admin can delete; main branch cannot be deleted.
|
||||
|
||||
Related records keep their data but lose the branch reference; stock and count
|
||||
rows tied exclusively to the branch are removed.
|
||||
"""
|
||||
if g.employee_role not in ('owner', 'admin'):
|
||||
return jsonify({'error': 'Solo administradores pueden eliminar sucursales'}), 403
|
||||
|
||||
@@ -170,7 +174,26 @@ def delete_branch(branch_id):
|
||||
cur.close(); conn.close()
|
||||
return jsonify({'error': 'No se puede eliminar la sucursal principal'}), 403
|
||||
|
||||
cur.execute("UPDATE branches SET is_active = false WHERE id = %s", (branch_id,))
|
||||
# Remove branch-specific stock and count rows first.
|
||||
cur.execute("DELETE FROM inventory_stock WHERE branch_id = %s", (branch_id,))
|
||||
cur.execute("DELETE FROM inventory_stock_summary WHERE branch_id = %s", (branch_id,))
|
||||
cur.execute("DELETE FROM physical_counts WHERE branch_id = %s", (branch_id,))
|
||||
|
||||
# Nullify every other FK reference back to branches.
|
||||
cur.execute("""
|
||||
SELECT c.relname::text AS tbl, a.attname::text AS col
|
||||
FROM pg_constraint con
|
||||
JOIN pg_class c ON c.oid = con.conrelid
|
||||
JOIN pg_attribute a ON a.attrelid = con.conrelid AND a.attnum = ANY(con.conkey)
|
||||
WHERE con.confrelid = 'public.branches'::regclass
|
||||
AND con.contype = 'f'
|
||||
""")
|
||||
for tbl, col in cur.fetchall():
|
||||
if tbl in ('inventory_stock', 'inventory_stock_summary', 'physical_counts'):
|
||||
continue
|
||||
cur.execute(f'UPDATE "{tbl}" SET "{col}" = NULL WHERE "{col}" = %s', (branch_id,))
|
||||
|
||||
cur.execute("DELETE FROM branches WHERE id = %s", (branch_id,))
|
||||
conn.commit()
|
||||
cur.close()
|
||||
conn.close()
|
||||
|
||||
Reference in New Issue
Block a user