165 lines
7.5 KiB
JavaScript
165 lines
7.5 KiB
JavaScript
'use strict';
|
|
|
|
/**
|
|
* One-time migration: site/database.sqlite → V2/app/vitfit.sqlite
|
|
*
|
|
* Run from V2/app/: node migrate_v1.js
|
|
* Safe to re-run — uses INSERT OR IGNORE so duplicates are skipped.
|
|
*/
|
|
|
|
const sqlite3 = require('sqlite3').verbose();
|
|
const path = require('path');
|
|
const fs = require('fs');
|
|
|
|
const OLD_DB = path.resolve(__dirname, '../../site/database.sqlite');
|
|
const NEW_DB = path.resolve(__dirname, './vitfit.sqlite');
|
|
const OLD_UPL = path.resolve(__dirname, '../../site/public/uploads');
|
|
const NEW_UPL = path.resolve(__dirname, './uploads');
|
|
const ORG_ID = 1; // VitalityFitness org already exists
|
|
const OWNER_ID = 1; // Tyler (Owner) used as createdByUserId
|
|
|
|
function db(filePath, flags = sqlite3.OPEN_READWRITE) {
|
|
return new sqlite3.Database(filePath, flags);
|
|
}
|
|
const run = (d, sql, p = []) => new Promise((ok, fail) => d.run(sql, p, function(e) { e ? fail(e) : ok(this); }));
|
|
const all = (d, sql, p = []) => new Promise((ok, fail) => d.all(sql, p, (e, r) => e ? fail(e) : ok(r)));
|
|
const get = (d, sql, p = []) => new Promise((ok, fail) => d.get(sql, p, (e, r) => e ? fail(e) : ok(r)));
|
|
|
|
async function bumpSeq(d, table, minVal) {
|
|
const row = await get(d, 'SELECT seq FROM sqlite_sequence WHERE name = ?', [table]);
|
|
if (!row) {
|
|
await run(d, 'INSERT INTO sqlite_sequence (name, seq) VALUES (?, ?)', [table, minVal]);
|
|
} else if (row.seq < minVal) {
|
|
await run(d, 'UPDATE sqlite_sequence SET seq = ? WHERE name = ?', [minVal, table]);
|
|
}
|
|
}
|
|
|
|
function mimeFromFilename(name) {
|
|
const ext = path.extname(name).toLowerCase();
|
|
return { '.mp4': 'video/mp4', '.mov': 'video/quicktime', '.avi': 'video/x-msvideo',
|
|
'.mkv': 'video/x-matroska', '.webm': 'video/webm' }[ext] || 'video/mp4';
|
|
}
|
|
|
|
function mapRole(oldRole) {
|
|
if (oldRole === 'Coach') return 'Coach';
|
|
return 'Owner'; // Admin → Owner
|
|
}
|
|
|
|
async function migrate() {
|
|
const old = db(OLD_DB, sqlite3.OPEN_READONLY);
|
|
const nw = db(NEW_DB);
|
|
|
|
console.log('Starting migration...\n');
|
|
|
|
// ── 1. Categories ────────────────────────────────────────────────────────────
|
|
const oldCats = await all(old, 'SELECT * FROM Categories');
|
|
await run(nw, 'BEGIN');
|
|
let catCount = 0;
|
|
for (const c of oldCats) {
|
|
const result = await run(nw,
|
|
'INSERT OR IGNORE INTO Categories (organizationId, name, createdAt, updatedAt) VALUES (?,?,?,?)',
|
|
[ORG_ID, c.name, c.createdAt, c.updatedAt || c.createdAt]);
|
|
if (result.changes) catCount++;
|
|
}
|
|
await run(nw, 'COMMIT');
|
|
console.log(`✓ Categories: ${catCount}/${oldCats.length} inserted`);
|
|
|
|
// ── 2. Videos (keep original IDs so workout references stay valid) ───────────
|
|
const oldVideos = await all(old, 'SELECT * FROM Videos ORDER BY id');
|
|
await run(nw, 'BEGIN');
|
|
let vidCount = 0;
|
|
for (const v of oldVideos) {
|
|
const result = await run(nw,
|
|
`INSERT OR IGNORE INTO Videos
|
|
(id, organizationId, filename, description, category, mimeType, fileSizeBytes, createdAt, updatedAt)
|
|
VALUES (?,?,?,?,?,?,?,?,?)`,
|
|
[v.id, ORG_ID, v.filename, v.description, v.category,
|
|
mimeFromFilename(v.filename), null, v.createdAt, v.updatedAt || v.createdAt]);
|
|
if (result.changes) vidCount++;
|
|
}
|
|
// Advance the sequence past the highest inserted ID
|
|
const maxVidId = oldVideos.reduce((m, v) => Math.max(m, v.id), 0);
|
|
await bumpSeq(nw, 'Videos', maxVidId);
|
|
await run(nw, 'COMMIT');
|
|
console.log(`✓ Videos: ${vidCount}/${oldVideos.length} inserted (IDs preserved)`);
|
|
|
|
// ── 3. Workouts ──────────────────────────────────────────────────────────────
|
|
const oldWorkouts = await all(old, 'SELECT * FROM Workouts ORDER BY id');
|
|
await run(nw, 'BEGIN');
|
|
let wkCount = 0;
|
|
for (const w of oldWorkouts) {
|
|
const result = await run(nw,
|
|
`INSERT OR IGNORE INTO Workouts
|
|
(id, organizationId, name, workoutDate, video1, video2, video3, video4,
|
|
number1, number2, number3, number4, createdByUserId, createdAt, updatedAt)
|
|
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
|
|
[w.id, ORG_ID, w.name, w.workoutDate,
|
|
w.video1, w.video2, w.video3, w.video4,
|
|
w.number1, w.number2, w.number3, w.number4,
|
|
OWNER_ID, w.createdAt, w.createdAt]);
|
|
if (result.changes) wkCount++;
|
|
}
|
|
const maxWkId = oldWorkouts.reduce((m, w) => Math.max(m, w.id), 0);
|
|
await bumpSeq(nw, 'Workouts', maxWkId);
|
|
await run(nw, 'COMMIT');
|
|
console.log(`✓ Workouts: ${wkCount}/${oldWorkouts.length} inserted`);
|
|
|
|
// ── 4. Timers ────────────────────────────────────────────────────────────────
|
|
const oldTimers = await all(old, 'SELECT * FROM Timers');
|
|
await run(nw, 'BEGIN');
|
|
let timCount = 0;
|
|
for (const t of oldTimers) {
|
|
const result = await run(nw,
|
|
`INSERT OR IGNORE INTO Timers
|
|
(organizationId, name, totalTime, setTime, restTime, moveTime,
|
|
setCount, exerciseCount, lapCount, createdByUserId, createdAt, updatedAt)
|
|
VALUES (?,?,?,?,?,?,?,?,?,?,?,?)`,
|
|
[ORG_ID, 'Imported Timer', t.totalTime, t.setTime, t.restTime, t.moveTime,
|
|
t.setCount, t.exerciseCount, t.lapCount, OWNER_ID, t.createdAt, t.createdAt]);
|
|
if (result.changes) timCount++;
|
|
}
|
|
await run(nw, 'COMMIT');
|
|
console.log(`✓ Timers: ${timCount}/${oldTimers.length} inserted`);
|
|
|
|
// ── 5. Users (old IDs may conflict → assign new sequential IDs) ──────────────
|
|
const oldUsers = await all(old, 'SELECT * FROM Users ORDER BY id');
|
|
await run(nw, 'BEGIN');
|
|
let usrCount = 0;
|
|
for (const u of oldUsers) {
|
|
// Skip if username already exists in new DB
|
|
const existing = await get(nw, 'SELECT id FROM Users WHERE username = ?', [u.username]);
|
|
if (existing) { console.log(` ↳ skipped existing user: ${u.username}`); continue; }
|
|
const result = await run(nw,
|
|
`INSERT INTO Users
|
|
(organizationId, username, email, password, role, isActive, createdAt, updatedAt)
|
|
VALUES (?,?,?,?,?,1,?,?)`,
|
|
[ORG_ID, u.username, null, u.password, mapRole(u.role),
|
|
u.createdAt, u.updatedAt || u.createdAt]);
|
|
if (result.changes) usrCount++;
|
|
}
|
|
await run(nw, 'COMMIT');
|
|
console.log(`✓ Users: ${usrCount}/${oldUsers.length} inserted (Admin→Owner, Coach→Coach)`);
|
|
|
|
// ── 6. Copy existing video files ─────────────────────────────────────────────
|
|
if (!fs.existsSync(NEW_UPL)) fs.mkdirSync(NEW_UPL, { recursive: true });
|
|
let copied = 0, missing = 0;
|
|
const oldFiles = fs.existsSync(OLD_UPL) ? fs.readdirSync(OLD_UPL) : [];
|
|
for (const file of oldFiles) {
|
|
const src = path.join(OLD_UPL, file);
|
|
const dest = path.join(NEW_UPL, file);
|
|
if (!fs.existsSync(dest)) { fs.copyFileSync(src, dest); copied++; }
|
|
}
|
|
missing = oldVideos.length - oldFiles.length;
|
|
console.log(`✓ Video files: ${copied} copied to uploads/`);
|
|
if (missing > 0) {
|
|
console.log(` ⚠ ${missing} video files not found locally — copy them from`);
|
|
console.log(` wherever the old uploads folder lives into: ${NEW_UPL}`);
|
|
}
|
|
|
|
old.close();
|
|
nw.close();
|
|
console.log('\nMigration complete.');
|
|
}
|
|
|
|
migrate().catch(err => { console.error('Migration failed:', err.message); process.exit(1); });
|