#!/usr/bin/env node 'use strict'; /** * VitFit V1 → V2 data migration * * Run ONCE after placing the V1 database.sqlite in the V2 app directory, * BEFORE starting the app for the first time. * * What it does: * 1. Runs all Umzug schema migrations (adds missing columns / tables) * 2. Creates the Organization and Branding records * 3. Backfills organizationId on every existing data table * 4. Sets isActive = true on all existing users * 5. Promotes one existing user to Owner * 6. Creates a new SystemAdmin account * * Safe to inspect what will happen — it asks for confirmation before writing. * Idempotent: exits cleanly if an Organization already exists. */ require('dotenv').config({ path: require('path').join(__dirname, '..', '.env') }); const readline = require('readline'); const bcrypt = require('bcryptjs'); const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); const ask = (q) => new Promise(resolve => rl.question(q, resolve)); async function main() { console.log('\n╔══════════════════════════════════════════╗'); console.log('║ VitFit V1 → V2 Data Migration ║'); console.log('╚══════════════════════════════════════════╝\n'); const { initDb, runMigrations, models } = require('../core/db'); const { sequelize } = require('../core/db'); // ── Step 1: schema migrations ──────────────────────────────────────────── console.log('Step 1/5 Running schema migrations...'); await initDb(); await runMigrations(); console.log(' Schema migrations complete.\n'); // ── Idempotency guard ──────────────────────────────────────────────────── const orgCount = await models.Organization.count(); if (orgCount > 0) { console.log('An Organization already exists — migration was already applied.'); console.log('Nothing to do. Exiting.\n'); process.exit(0); } // ── Step 2: inspect V1 data ────────────────────────────────────────────── const [userRows] = await sequelize.query( 'SELECT id, username, role, createdAt FROM Users ORDER BY id' ); if (userRows.length === 0) { console.log('No V1 users found. Use scripts/setup.js for a fresh install.'); process.exit(1); } const [videoCount] = await sequelize.query('SELECT COUNT(*) AS c FROM Videos'); const [catCount] = await sequelize.query('SELECT COUNT(*) AS c FROM Categories'); const [workoutCount] = await sequelize.query('SELECT COUNT(*) AS c FROM Workouts'); const [cfCount] = await sequelize.query('SELECT COUNT(*) AS c FROM CrossfitWorkouts'); const [timerCount] = await sequelize.query('SELECT COUNT(*) AS c FROM Timers'); console.log('Step 2/5 V1 data detected:'); console.log(` Users: ${userRows.length}`); console.log(` Videos: ${videoCount[0].c}`); console.log(` Categories: ${catCount[0].c}`); console.log(` Workouts: ${workoutCount[0].c}`); console.log(` CrossfitWorkouts: ${cfCount[0].c}`); console.log(` Timers: ${timerCount[0].c}`); console.log(''); console.log(' Existing users:'); userRows.forEach((u, i) => { console.log(` [${i + 1}] id=${u.id} username=${u.username} role=${u.role || 'Coach'}`); }); console.log(''); // ── Step 3: gather inputs ──────────────────────────────────────────────── console.log('Step 3/5 Configuration\n'); const orgName = await ask(' Organization name (e.g. CrossFit Downtown): '); const timezone = await ask(' Timezone (e.g. America/New_York) [UTC]: ') || 'UTC'; console.log(''); const ownerIdxStr = await ask( ` Which existing user should become Owner? [1-${userRows.length}]: ` ); const ownerIdx = parseInt(ownerIdxStr, 10) - 1; if (isNaN(ownerIdx) || ownerIdx < 0 || ownerIdx >= userRows.length) { console.error(' Invalid selection. Exiting.'); process.exit(1); } const ownerUser = userRows[ownerIdx]; console.log(''); console.log(' A SystemAdmin account is required (org-independent super-admin).'); const saUser = await ask(' SystemAdmin username: '); const saPass = await ask(' SystemAdmin password (min 8 chars): '); if (!orgName.trim()) { console.error(' Organization name cannot be blank.'); process.exit(1); } if (saPass.length < 8) { console.error(' SystemAdmin password must be at least 8 characters.'); process.exit(1); } if (userRows.some(u => u.username === saUser)) { console.error(` Username "${saUser}" already exists in V1 data. Choose a different one.`); process.exit(1); } // ── Confirmation ────────────────────────────────────────────────────────── console.log('\n──────────────────────────────────────────────'); console.log(' About to apply the following changes:\n'); console.log(` • Create Organization: "${orgName}" (tz: ${timezone})`); console.log(` • Create Branding record for the organization`); console.log(` • Assign all ${userRows.length} existing users to this organization`); console.log(` • Set isActive = true on all existing users`); console.log(` • Promote "${ownerUser.username}" to Owner`); console.log(` • Set organizationId on all Videos, Categories, Workouts, CrossfitWorkouts, Timers`); console.log(` • Create SystemAdmin user: "${saUser}"`); console.log('──────────────────────────────────────────────\n'); const confirm = await ask(' Proceed? [yes/no]: '); if (confirm.trim().toLowerCase() !== 'yes') { console.log(' Aborted. No changes made.'); process.exit(0); } // ── Step 4: apply data migration ───────────────────────────────────────── console.log('\nStep 4/5 Applying data migration...\n'); const transaction = await sequelize.transaction(); try { const now = new Date(); // Create organization const org = await models.Organization.create( { name: orgName.trim(), timezone, isActive: true, createdAt: now, updatedAt: now }, { transaction } ); console.log(` ✓ Organization created (id=${org.id})`); // Create branding await models.Branding.create( { organizationId: org.id, createdAt: now, updatedAt: now }, { transaction } ); console.log(' ✓ Branding record created'); // Update all existing users: set organizationId + isActive, normalize role const validRoles = new Set(['SystemAdmin', 'Owner', 'Coach', 'Client']); for (const u of userRows) { const currentRole = u.role || 'Coach'; const newRole = u.id === ownerUser.id ? 'Owner' : (validRoles.has(currentRole) ? currentRole : 'Coach'); await sequelize.query( `UPDATE Users SET organizationId = ?, isActive = 1, role = ?, updatedAt = ? WHERE id = ?`, { replacements: [org.id, newRole, now.toISOString(), u.id], transaction } ); } console.log(` ✓ ${userRows.length} users updated (organizationId, isActive, roles normalized)`); console.log(` ✓ "${ownerUser.username}" promoted to Owner`); // Backfill organizationId on data tables for (const table of ['Videos', 'Categories', 'Workouts', 'CrossfitWorkouts', 'Timers']) { const [result] = await sequelize.query( `UPDATE "${table}" SET organizationId = ? WHERE organizationId IS NULL`, { replacements: [org.id], transaction } ); const changed = result?.changes ?? '?'; console.log(` ✓ ${table}: organizationId backfilled (${changed} rows)`); } // Set createdByUserId = ownerUser.id where null on owned tables for (const table of ['Workouts', 'CrossfitWorkouts', 'Timers']) { await sequelize.query( `UPDATE "${table}" SET createdByUserId = ? WHERE createdByUserId IS NULL`, { replacements: [ownerUser.id], transaction } ); } console.log(` ✓ Workouts/CrossfitWorkouts/Timers: createdByUserId set to owner`); // Create SystemAdmin const saHash = await bcrypt.hash(saPass, 12); await models.User.create({ organizationId: null, username: saUser, password: saHash, role: 'SystemAdmin', isActive: true, createdAt: now, updatedAt: now, }, { transaction }); console.log(` ✓ SystemAdmin "${saUser}" created`); await transaction.commit(); console.log('\nStep 5/5 Migration committed successfully.\n'); } catch (err) { await transaction.rollback(); console.error('\n ERROR — transaction rolled back. No data was changed.'); console.error(' Details:', err.message); process.exit(1); } console.log('╔══════════════════════════════════════════╗'); console.log('║ Migration complete. ║'); console.log('║ Start the app with: npm start ║'); console.log('╚══════════════════════════════════════════╝\n'); rl.close(); process.exit(0); } main().catch(err => { console.error('\nFatal error:', err); process.exit(1); });