From 7852838b216168d7128e55631a8b4691d5e2ab34 Mon Sep 17 00:00:00 2001 From: consultoria-as Date: Tue, 30 Jun 2026 18:00:26 +0000 Subject: [PATCH] feat(config): hard-delete branches for admins DELETE /branches/ now removes the row, nullifies FK references, and deletes branch-specific stock/count records. Main branch remains protected. --- pos/blueprints/config_bp.py | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/pos/blueprints/config_bp.py b/pos/blueprints/config_bp.py index c7b8abc..c8ffb72 100644 --- a/pos/blueprints/config_bp.py +++ b/pos/blueprints/config_bp.py @@ -153,7 +153,11 @@ def update_branch(branch_id): @config_bp.route('/branches/', 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()