// MUST load environment variables BEFORE any other imports require('dotenv').config({ path: require('path').resolve(__dirname, '../.env.local') }); import admin from 'firebase-admin'; import { FieldValue } from 'firebase-admin/firestore'; // Initialize Firebase Admin directly if (!admin.apps.length) { const privateKey = process.env.FIREBASE_PRIVATE_KEY?.replace(/\\n/g, '\n'); if (!process.env.FIREBASE_PROJECT_ID || !process.env.FIREBASE_CLIENT_EMAIL || !privateKey) { throw new Error('Missing Firebase Admin credentials. Check your .env.local file.'); } admin.initializeApp({ credential: admin.credential.cert({ projectId: process.env.FIREBASE_PROJECT_ID, clientEmail: process.env.FIREBASE_CLIENT_EMAIL, privateKey: privateKey, }), }); console.log('āœ… Firebase Admin initialized successfully'); } const adminDb = admin.firestore(); const adminAuth = admin.auth(); async function reassignMigratedData() { console.log('šŸš€ Starting data reassignment...\n'); try { // Get the current user (mark@getacquired.com) console.log('šŸ“‹ Finding current user: mark@getacquired.com'); const currentUser = await adminAuth.getUserByEmail('mark@getacquired.com'); console.log(`āœ… Current user found: ${currentUser.uid}\n`); // Get the migrated user (mark@example.com) console.log('šŸ“‹ Finding migrated user: mark@example.com'); let migratedUser; try { migratedUser = await adminAuth.getUserByEmail('mark@example.com'); console.log(`āœ… Migrated user found: ${migratedUser.uid}\n`); } catch (error) { console.log('āš ļø Migrated user not found, will look for any migrated data by flag\n'); } // Reassign all collections const collections = ['sessions', 'projects', 'clients', 'workCompleted']; for (const collectionName of collections) { console.log(`\nšŸ“‹ Processing ${collectionName}...`); // Query for migrated documents let query = adminDb.collection(collectionName).where('migratedFrom', '==', 'postgresql'); const snapshot = await query.get(); if (snapshot.empty) { console.log(` ā„¹ļø No migrated ${collectionName} found`); continue; } console.log(` Found ${snapshot.size} migrated ${collectionName}`); // Update each document const batch = adminDb.batch(); let count = 0; for (const doc of snapshot.docs) { const data = doc.data(); const updates: any = { updatedAt: FieldValue.serverTimestamp(), }; // Update userId field if (data.userId) { updates.userId = currentUser.uid; } // Update ownerId field (for clients) if (data.ownerId) { updates.ownerId = currentUser.uid; } batch.update(doc.ref, updates); count++; // Commit batch every 500 documents (Firestore limit) if (count % 500 === 0) { await batch.commit(); console.log(` āœ… Committed ${count} updates...`); } } // Commit remaining if (count % 500 !== 0) { await batch.commit(); } console.log(` āœ… Reassigned ${count} ${collectionName} to ${currentUser.email}`); } // Delete the temporary migrated user if it exists if (migratedUser) { console.log('\nšŸ“‹ Cleaning up temporary migrated user account...'); // Delete the user document await adminDb.collection('users').doc(migratedUser.uid).delete(); // Delete the Auth account await adminAuth.deleteUser(migratedUser.uid); console.log('āœ… Temporary user account deleted'); } console.log('\nāœ… Data reassignment completed successfully!'); console.log(`\nšŸŽ‰ All migrated data is now assigned to: ${currentUser.email}`); } catch (error) { console.error('\nāŒ Data reassignment failed:', error); throw error; } } // Run reassignment reassignMigratedData() .then(() => process.exit(0)) .catch((error) => { console.error(error); process.exit(1); });