Fix user deletion to preserve data integrity

Updates the `deleteUser` method to handle foreign key constraints by transferring user-created records to an admin user before deletion, ensuring data integrity and preventing errors.

Replit-Commit-Author: Agent
Replit-Commit-Session-Id: a8a78c07-e900-425c-a577-5b4c5894379d
Replit-Commit-Checkpoint-Type: full_checkpoint
Replit-Commit-Screenshot-Url: https://storage.googleapis.com/screenshot-production-us-central1/1957c339-2757-4d1f-8e92-e9f71a1ce58e/a8a78c07-e900-425c-a577-5b4c5894379d/vetH0Gp
This commit is contained in:
michaelschal committed 2025-08-11 17:50:38 +00:00
1 parent 70839e4c22
commit 2cb363c0b4
3 files changed
+27 -3

No files matched your search

Binary file not shown.

After

Width:  |  Height:  |  Size: 231 KiB

+15 -1
View File
@@ -75,4 +75,18 @@ Preferred communication style: Simple, everyday language.
- **Development Server**: Vite dev server
### Other Integrations
- **NocoDB Integration**: Configurable for invoice verification and data synchronization.
- **NocoDB Integration**: Configurable for invoice verification and data synchronization.
## Recent Changes
### August 11, 2025 - User Deletion Fix
- **Issue**: Foreign key constraint errors when deleting users who created customer orders or other records
- **Root Cause**: User records were referenced by multiple tables (customer_orders, deliveries, DLC products, etc.)
- **Solution Implemented**:
- Enhanced deleteUser method with database transaction for atomicity
- Dynamic admin user lookup instead of hardcoded fallback user
- Ownership transfer of all user-created records to existing admin before deletion
- Comprehensive handling of all foreign key relationships
- Graceful error handling when no admin user exists
- **Tables Handled**: customer_orders, orders, deliveries, publicities, dlcProducts, tasks, nocodbConfig, userGroups, userRoles
- **Result**: Safe user deletion while preserving business data integrity
+12 -2
View File
@@ -356,8 +356,18 @@ export class DatabaseStorage implements IStorage {
async deleteUser(id: string): Promise<void> {
// Use a transaction to ensure atomicity
await db.transaction(async (tx: typeof db) => {
// Transfer ownership of all records created by this user to admin_dev
const adminUserId = "admin_dev";
// Find an existing admin user to transfer ownership to
const adminUser = await tx
.select({ id: users.id })
.from(users)
.where(eq(users.role, "admin"))
.limit(1);
if (adminUser.length === 0) {
throw new Error("Cannot delete user: No admin user found to transfer ownership to");
}
const adminUserId = adminUser[0].id;
// Update customer orders
await tx