diff --git a/V2/app/modules/org/migrations/020-add-missing-updatedAt.js b/V2/app/modules/org/migrations/020-add-missing-updatedAt.js new file mode 100644 index 0000000..a3c862a --- /dev/null +++ b/V2/app/modules/org/migrations/020-add-missing-updatedAt.js @@ -0,0 +1,28 @@ +'use strict'; + +// Workouts, CrossfitWorkouts, and Timers were raw SQL tables in V1 — no updatedAt. +// Sequelize requires updatedAt by default; without this column any write to these +// tables fails. Backfill with createdAt so existing rows have a valid timestamp. +module.exports = { + async up(queryInterface, Sequelize) { + for (const table of ['Workouts', 'CrossfitWorkouts', 'Timers']) { + const cols = await queryInterface.describeTable(table).catch(() => null); + if (!cols || cols['updatedAt']) continue; + + await queryInterface.addColumn(table, 'updatedAt', { + type: Sequelize.DATE, + allowNull: true, + }); + + await queryInterface.sequelize.query( + `UPDATE "${table}" SET "updatedAt" = "createdAt"` + ); + } + }, + + async down(queryInterface) { + for (const table of ['Workouts', 'CrossfitWorkouts', 'Timers']) { + await queryInterface.removeColumn(table, 'updatedAt').catch(() => {}); + } + }, +}; diff --git a/V2/app/package.json b/V2/app/package.json index 45287a0..9c664cc 100644 --- a/V2/app/package.json +++ b/V2/app/package.json @@ -8,6 +8,7 @@ "dev": "node --watch app.js", "setup": "node scripts/setup.js", "migrate": "node scripts/migrate.js", + "migrate:v1": "node scripts/migrate-v1-to-v2.js", "test": "node --experimental-vm-modules node_modules/.bin/jest --runInBand", "test:unit": "jest tests/unit --runInBand", "test:integration": "jest tests/integration --runInBand", diff --git a/V2/app/scripts/migrate-v1-to-v2.js b/V2/app/scripts/migrate-v1-to-v2.js new file mode 100644 index 0000000..cde2e34 --- /dev/null +++ b/V2/app/scripts/migrate-v1-to-v2.js @@ -0,0 +1,227 @@ +#!/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); +});