Files
vitfit-r2/V2/structure/DATABASE_SCHEMA.md
T
2026-06-11 10:52:07 -04:00

427 lines
16 KiB
Markdown

# VitFit V2 — Database Schema
Sequelize model definitions. Every model is defined in its module's `model.js` file
and registered via `core/db.js`. Primary keys, `createdAt`, `updatedAt` are generated
by Sequelize unless noted. `timestamps: false` is only used on AuditLog (no `updatedAt`).
---
## Associations Summary
```
Organization hasOne Branding (via organizationId)
Organization hasMany User (via organizationId)
Organization hasMany Video (via organizationId)
Organization hasMany Category (via organizationId)
Organization hasMany Workout (via organizationId)
Organization hasMany Timer (via organizationId)
Organization hasMany CrossfitWorkout (via organizationId)
Organization hasMany CoachClientLink (via organizationId)
Organization hasMany ClientWorkout (via organizationId)
Organization hasMany CalendarSession (via organizationId)
User hasMany DeviceToken (via userId)
User hasMany CoachClientLink (as coach, via coachId)
User hasMany CoachClientLink (as client, via clientId)
User hasMany ClientWorkout (as coach, via coachId)
User hasMany ClientWorkout (as client, via clientId)
User hasMany CalendarSession (as coach, via coachId)
User hasMany CalendarSession (as client, via clientId)
Workout belongsTo Video (as VideoOne, via video1)
Workout belongsTo Video (as VideoTwo, via video2)
Workout belongsTo Video (as VideoThree, via video3)
Workout belongsTo Video (as VideoFour, via video4)
ClientWorkout belongsTo CalendarSession (via linkedWorkoutId, optional)
```
AuditLog has no enforced FK associations (see DATA_MODEL.md rationale).
---
## Organizations
```js
// modules/org/model.js
Organization = sequelize.define('Organization', {
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
name: { type: DataTypes.STRING, allowNull: false },
slug: { type: DataTypes.STRING, unique: true },
timezone: { type: DataTypes.STRING, defaultValue: 'UTC' },
features: { type: DataTypes.TEXT, defaultValue: '[]',
get() { return JSON.parse(this.getDataValue('features') || '[]'); },
set(v) { this.setDataValue('features', JSON.stringify(v)); } },
isActive: { type: DataTypes.BOOLEAN, defaultValue: true },
licenseOwner: { type: DataTypes.STRING },
licenseEmail: { type: DataTypes.STRING },
});
```
Hooks:
```js
Organization.beforeCreate(org => {
if (!org.slug) {
org.slug = org.name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
}
});
```
---
## Brandings
```js
// modules/org/model.js
Branding = sequelize.define('Branding', {
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
organizationId: { type: DataTypes.INTEGER, allowNull: false, unique: true },
appName: { type: DataTypes.STRING, defaultValue: 'VitFit' },
logoPath: { type: DataTypes.STRING },
primaryColor: { type: DataTypes.STRING, defaultValue: '#00FF88' },
secondaryColor: { type: DataTypes.STRING, defaultValue: '#4488FF' },
workColor: { type: DataTypes.STRING, defaultValue: '#00FF88' },
restColor: { type: DataTypes.STRING, defaultValue: '#4488FF' },
moveColor: { type: DataTypes.STRING, defaultValue: '#FF4444' },
});
```
---
## Users
```js
// modules/users/model.js
User = sequelize.define('User', {
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
organizationId: { type: DataTypes.INTEGER }, // nullable for SystemAdmin
username: { type: DataTypes.STRING, allowNull: false, unique: true },
email: { type: DataTypes.STRING, unique: true },
password: { type: DataTypes.STRING, allowNull: false },
role: { type: DataTypes.ENUM('SystemAdmin', 'Owner', 'Coach', 'Client'),
allowNull: false, defaultValue: 'Coach' },
firstName: { type: DataTypes.STRING },
lastName: { type: DataTypes.STRING },
isActive: { type: DataTypes.BOOLEAN, defaultValue: true },
lastLoginAt: { type: DataTypes.DATE },
passwordChangedAt: { type: DataTypes.DATE }, // set on every password change/reset; null for new accounts
});
```
Instance method:
```js
User.prototype.toPublic = function() {
const { password, ...rest } = this.toJSON();
return rest; // password never sent in responses
};
```
Default scope (always applied):
```js
User.addScope('defaultScope', { attributes: { exclude: ['password', 'passwordChangedAt'] } });
```
Both `password` and `passwordChangedAt` are excluded from all normal queries.
`authenticateToken` and `changeOwnPassword` explicitly select these fields when needed.
---
## DeviceTokens
```js
// modules/auth/model.js
DeviceToken = sequelize.define('DeviceToken', {
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
userId: { type: DataTypes.INTEGER, allowNull: false },
organizationId: { type: DataTypes.INTEGER, allowNull: false },
token: { type: DataTypes.STRING, allowNull: false, unique: true }, // SHA-256 hash
deviceName: { type: DataTypes.STRING },
deviceType: { type: DataTypes.ENUM('kiosk', 'personal'), defaultValue: 'personal' },
lastUsedAt: { type: DataTypes.DATE },
expiresAt: { type: DataTypes.DATE, allowNull: false },
isRevoked: { type: DataTypes.BOOLEAN, defaultValue: false },
});
```
Index:
```js
DeviceToken.addIndex(['token']); // lookup by hash
DeviceToken.addIndex(['userId', 'isRevoked']); // list user's active tokens
```
---
## Videos
```js
// modules/videos/model.js
Video = sequelize.define('Video', {
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
organizationId: { type: DataTypes.INTEGER, allowNull: false },
filename: { type: DataTypes.STRING, allowNull: false },
description: { type: DataTypes.STRING },
category: { type: DataTypes.STRING },
mimeType: { type: DataTypes.STRING },
fileSizeBytes: { type: DataTypes.INTEGER },
});
```
Virtual field appended in service layer (not stored):
```js
// In service.getVideos() — appended after DB query:
video.streamUrl = `/api/v1/videos/stream/${video.filename}`;
```
---
## Categories
```js
// modules/videos/model.js
Category = sequelize.define('Category', {
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
organizationId: { type: DataTypes.INTEGER, allowNull: false },
name: { type: DataTypes.STRING, allowNull: false },
});
Category.addIndex(['organizationId', 'name'], { unique: true });
```
---
## Workouts
```js
// modules/workouts/model.js
Workout = sequelize.define('Workout', {
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
organizationId: { type: DataTypes.INTEGER, allowNull: false },
name: { type: DataTypes.STRING },
workoutDate: { type: DataTypes.DATE },
video1: { type: DataTypes.INTEGER },
video2: { type: DataTypes.INTEGER },
video3: { type: DataTypes.INTEGER },
video4: { type: DataTypes.INTEGER },
number1: { type: DataTypes.INTEGER },
number2: { type: DataTypes.INTEGER },
number3: { type: DataTypes.INTEGER },
number4: { type: DataTypes.INTEGER },
createdByUserId: { type: DataTypes.INTEGER },
});
// Associations (using aliases to resolve 4x FK to same table)
Workout.belongsTo(Video, { foreignKey: 'video1', as: 'VideoOne', constraints: false });
Workout.belongsTo(Video, { foreignKey: 'video2', as: 'VideoTwo', constraints: false });
Workout.belongsTo(Video, { foreignKey: 'video3', as: 'VideoThree', constraints: false });
Workout.belongsTo(Video, { foreignKey: 'video4', as: 'VideoFour', constraints: false });
// constraints: false — allows hard-deleted videos without FK violation
```
Index:
```js
Workout.addIndex(['organizationId', 'workoutDate']); // used by today-workouts query
```
---
## Timers
```js
// modules/timers/model.js
Timer = sequelize.define('Timer', {
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
organizationId: { type: DataTypes.INTEGER, allowNull: false },
name: { type: DataTypes.STRING, allowNull: false },
totalTime: { type: DataTypes.INTEGER, allowNull: false },
setTime: { type: DataTypes.INTEGER, allowNull: false },
restTime: { type: DataTypes.INTEGER, defaultValue: 0 },
moveTime: { type: DataTypes.INTEGER, defaultValue: 0 },
setCount: { type: DataTypes.INTEGER, allowNull: false },
exerciseCount: { type: DataTypes.INTEGER, allowNull: false },
lapCount: { type: DataTypes.INTEGER, defaultValue: 1 },
createdByUserId: { type: DataTypes.INTEGER },
});
```
---
## CrossfitWorkouts
```js
// modules/crossfit/model.js
CrossfitWorkout = sequelize.define('CrossfitWorkout', {
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
organizationId: { type: DataTypes.INTEGER, allowNull: false },
name: { type: DataTypes.STRING },
workoutDate: { type: DataTypes.DATE },
workoutItems: {
type: DataTypes.TEXT,
get() { return JSON.parse(this.getDataValue('workoutItems') || '[]'); },
set(v) { this.setDataValue('workoutItems', JSON.stringify(v)); },
},
createdByUserId: { type: DataTypes.INTEGER },
});
```
---
## CoachClientLinks
```js
// modules/clients/model.js
CoachClientLink = sequelize.define('CoachClientLink', {
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
organizationId: { type: DataTypes.INTEGER, allowNull: false },
coachId: { type: DataTypes.INTEGER, allowNull: false },
clientId: { type: DataTypes.INTEGER, allowNull: false },
isActive: { type: DataTypes.BOOLEAN, defaultValue: true },
assignedAt: { type: DataTypes.DATE, defaultValue: DataTypes.NOW },
assignedByUserId:{ type: DataTypes.INTEGER },
});
CoachClientLink.addIndex(['coachId', 'clientId', 'isActive']);
CoachClientLink.addIndex(['clientId', 'isActive']); // find active coach for a client
```
---
## ClientWorkouts
```js
// modules/clients/model.js
ClientWorkout = sequelize.define('ClientWorkout', {
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
organizationId: { type: DataTypes.INTEGER, allowNull: false },
clientId: { type: DataTypes.INTEGER, allowNull: false },
coachId: { type: DataTypes.INTEGER, allowNull: false },
name: { type: DataTypes.STRING },
scheduledDate: { type: DataTypes.DATE },
notes: { type: DataTypes.TEXT },
items: {
type: DataTypes.TEXT,
get() { return JSON.parse(this.getDataValue('items') || '[]'); },
set(v) { this.setDataValue('items', JSON.stringify(v)); },
},
completedAt: { type: DataTypes.DATE },
deletedAt: { type: DataTypes.DATE }, // soft delete
});
ClientWorkout.addScope('active', { where: { deletedAt: null } });
// All queries use: ClientWorkout.scope('active').findAll(...)
```
Index:
```js
ClientWorkout.addIndex(['clientId', 'deletedAt', 'scheduledDate']);
```
---
## CalendarSessions
```js
// modules/clients/model.js
CalendarSession = sequelize.define('CalendarSession', {
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
organizationId: { type: DataTypes.INTEGER, allowNull: false },
coachId: { type: DataTypes.INTEGER, allowNull: false },
clientId: { type: DataTypes.INTEGER }, // nullable = group session
title: { type: DataTypes.STRING },
sessionType: { type: DataTypes.ENUM('personal', 'group', 'assessment', 'other'),
defaultValue: 'personal' },
startAt: { type: DataTypes.DATE, allowNull: false },
endAt: { type: DataTypes.DATE, allowNull: false },
locationNotes: { type: DataTypes.STRING },
coachNotes: { type: DataTypes.TEXT },
sharedNotes: { type: DataTypes.TEXT },
status: { type: DataTypes.ENUM('scheduled', 'completed', 'cancelled', 'no-show'),
defaultValue: 'scheduled' },
linkedWorkoutId: { type: DataTypes.INTEGER },
});
```
Index:
```js
CalendarSession.addIndex(['coachId', 'startAt']);
CalendarSession.addIndex(['clientId', 'startAt']);
```
---
## AuditLogs
```js
// modules/audit/model.js
AuditLog = sequelize.define('AuditLog', {
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
organizationId: { type: DataTypes.INTEGER }, // no FK constraint — intentional
userId: { type: DataTypes.INTEGER }, // no FK constraint — intentional
userRole: { type: DataTypes.STRING },
action: { type: DataTypes.STRING, allowNull: false },
entityType: { type: DataTypes.STRING },
entityId: { type: DataTypes.INTEGER },
details: {
type: DataTypes.TEXT,
get() { try { return JSON.parse(this.getDataValue('details') || '{}'); } catch { return {}; } },
set(v) { this.setDataValue('details', JSON.stringify(v)); },
},
ipAddress: { type: DataTypes.STRING },
userAgent: { type: DataTypes.STRING },
}, {
updatedAt: false, // audit logs have no updatedAt
createdAt: 'createdAt',
});
```
Indexes:
```js
AuditLog.addIndex(['organizationId', 'createdAt']); // paginate by org
AuditLog.addIndex(['userId']); // filter by user
AuditLog.addIndex(['action']); // filter by action type
AuditLog.addIndex(['entityType', 'entityId']); // find all logs for a specific record
```
---
## Migration Numbering
```
modules/*/migrations/
├── 001-baseline.js V1 tables (idempotent — skips if tables exist)
├── 002-organizations.js Create Organizations, Brandings tables; seed one org + branding
├── 003-users-v2.js Add organizationId, email, firstName, lastName, isActive, lastLoginAt to Users
├── 004-videos-v2.js Add organizationId, mimeType, fileSizeBytes to Videos
├── 005-categories-v2.js Add organizationId to Categories
├── 006-workouts-v2.js Add organizationId, createdByUserId to Workouts
├── 007-timers-v2.js Add organizationId, name, createdByUserId to Timers
├── 008-crossfit-v2.js Add organizationId, createdByUserId to CrossfitWorkouts
├── 009-device-tokens.js Create DeviceTokens table
├── 010-coach-client-links.js Create CoachClientLinks table
├── 011-client-workouts.js Create ClientWorkouts table (with deletedAt)
├── 012-calendar-sessions.js Create CalendarSessions table
├── 013-audit-logs.js Create AuditLogs table
└── 014-users-password-changed-at.js Add passwordChangedAt column to Users (nullable, no default)
```
Migration 001 checks table existence before creating — safe to run against the populated V1 database.
Migrations 002+ are additive only (addColumn, createTable) — no data destroyed.
---
## Soft Delete vs. Hard Delete Reference
| Entity | Delete behavior | Restorable? | Notes |
|---|---|---|---|
| User | Soft — `isActive = false` | Yes (Owner can reactivate) | Record preserved; history intact |
| Organization | Soft — `isActive = false` | Yes (SystemAdmin only) | |
| CoachClientLink | Soft — `isActive = false` | Yes (reassign flow) | Old link deactivated, new link created |
| ClientWorkout | Soft — `deletedAt` timestamp | Yes (no UI, but data recoverable by DB) | `scope('active')` hides it |
| CalendarSession | Soft — `status = 'cancelled'` | No (status change, not hidden) | Remains in history |
| Video | Hard — DB record + file removed | No | File on disk is deleted immediately |
| Workout | Hard — DB record removed | No | Video FKs use `constraints: false` so video deletion doesn't cascade |
| Timer | Hard — DB record removed | No | In-memory sessions already gone if server restarted |
| CrossfitWorkout | Hard — DB record removed | No | |
| Category | Hard — blocked if videos exist in it | N/A (blocked, not deleted) | Returns `CONFLICT` |
| DeviceToken | Hard — DB record removed | No (user must re-login to get new token) | |
| AuditLog | Never deleted | N/A | Append-only; no delete endpoint |
| Branding | Never deleted | N/A | Updated in-place; one per org |