This commit is contained in:
Ccjcarkbla
2026-06-13 08:03:45 -04:00
parent cfcd6ae11e
commit a2c300678b
121 changed files with 8639 additions and 0 deletions
@@ -0,0 +1,37 @@
'use strict';
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.createTable('Organizations', {
id: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true },
name: { type: Sequelize.STRING, allowNull: false },
slug: { type: Sequelize.STRING, unique: true },
timezone: { type: Sequelize.STRING, defaultValue: 'UTC' },
features: { type: Sequelize.TEXT, defaultValue: '[]' },
isActive: { type: Sequelize.BOOLEAN, defaultValue: true },
licenseOwner: { type: Sequelize.STRING },
licenseEmail: { type: Sequelize.STRING },
createdAt: { type: Sequelize.DATE, allowNull: false },
updatedAt: { type: Sequelize.DATE, allowNull: false },
});
await queryInterface.createTable('Brandings', {
id: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true },
organizationId: { type: Sequelize.INTEGER, allowNull: false, unique: true },
appName: { type: Sequelize.STRING, defaultValue: 'VitFit' },
logoPath: { type: Sequelize.STRING },
primaryColor: { type: Sequelize.STRING, defaultValue: '#00FF88' },
secondaryColor: { type: Sequelize.STRING, defaultValue: '#4488FF' },
workColor: { type: Sequelize.STRING, defaultValue: '#00FF88' },
restColor: { type: Sequelize.STRING, defaultValue: '#4488FF' },
moveColor: { type: Sequelize.STRING, defaultValue: '#FF4444' },
createdAt: { type: Sequelize.DATE, allowNull: false },
updatedAt: { type: Sequelize.DATE, allowNull: false },
});
},
async down(queryInterface) {
await queryInterface.dropTable('Brandings');
await queryInterface.dropTable('Organizations');
},
};
+43
View File
@@ -0,0 +1,43 @@
'use strict';
module.exports = (sequelize, DataTypes) => {
const 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() { try { return JSON.parse(this.getDataValue('features') || '[]'); } catch { return []; } },
set(v) { this.setDataValue('features', JSON.stringify(v)); },
},
isActive: { type: DataTypes.BOOLEAN, defaultValue: true },
licenseOwner: { type: DataTypes.STRING },
licenseEmail: { type: DataTypes.STRING },
});
Organization.beforeCreate(org => {
if (!org.slug) {
org.slug = org.name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
}
});
const 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' },
});
Organization.associate = (models) => {
Organization.hasOne(models.Branding, { foreignKey: 'organizationId' });
};
return { Organization, Branding };
};
+87
View File
@@ -0,0 +1,87 @@
'use strict';
const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const { models } = require('../../core/db');
const { authenticateToken, authenticateRole } = require('../../core/auth');
const { ok, noContent } = require('../../core/respond');
const { AppError } = require('../../core/errors');
const { updateOrg: updateOrgSchema, updateBranding: updateBrandingSchema } = require('../../core/schemas/org');
const svc = require('./service');
const router = express.Router();
router.prefix = 'org';
const OWNERS = ['Owner', 'SystemAdmin'];
const upload = multer({
dest: process.env.UPLOAD_TEMP_DIR || '/tmp/vitfit-uploads',
limits: { fileSize: 5 * 1024 * 1024 }, // 5 MB for logos
});
function validate(schema) {
return (req, res, next) => {
const result = schema.safeParse(req.body);
if (!result.success) {
const e = result.error.errors[0];
return next(new AppError('VALIDATION_FAILED', e.message, 400, e.path[0]));
}
req.body = result.data;
next();
};
}
router.get('/', authenticateToken, async (req, res, next) => {
try {
const org = await svc.getOrg(models, req.user.organizationId);
ok(res, org);
} catch (err) { next(err); }
});
router.patch('/', authenticateToken, authenticateRole(OWNERS), validate(updateOrgSchema), async (req, res, next) => {
try {
const org = await svc.updateOrg(models, req, req.user.organizationId, req.body);
ok(res, org);
} catch (err) { next(err); }
});
router.get('/branding', authenticateToken, async (req, res, next) => {
try {
const branding = await svc.getBranding(models, req.user.organizationId);
ok(res, branding);
} catch (err) { next(err); }
});
router.patch('/branding', authenticateToken, authenticateRole(OWNERS), validate(updateBrandingSchema), async (req, res, next) => {
try {
const branding = await svc.updateBranding(models, req, req.user.organizationId, req.body);
ok(res, branding);
} catch (err) { next(err); }
});
router.post('/logo', authenticateToken, authenticateRole(OWNERS), upload.single('logo'), async (req, res, next) => {
try {
if (!req.file) return next(new AppError('VALIDATION_FAILED', 'No logo file provided.', 400));
const branding = await svc.uploadLogo(models, req, req.user.organizationId, req.file);
ok(res, { logoPath: branding.logoPath });
} catch (err) { next(err); }
});
router.get('/logo', authenticateToken, async (req, res, next) => {
try {
const branding = await svc.getBranding(models, req.user.organizationId);
if (!branding.logoPath) return next(new AppError('NOT_FOUND', 'No custom logo set.', 404));
// Find logo file in uploads dir
const uploadsDir = process.env.UPLOADS_DIR || path.join(__dirname, '..', '..', 'uploads');
const files = fs.readdirSync(uploadsDir).filter(f => f.startsWith(`logo_${req.user.organizationId}_`));
if (!files.length) return next(new AppError('NOT_FOUND', 'Logo file not found.', 404));
const logoFile = files.sort().pop(); // latest
res.sendFile(path.join(uploadsDir, logoFile));
} catch (err) { next(err); }
});
module.exports = router;
+115
View File
@@ -0,0 +1,115 @@
'use strict';
const fs = require('fs');
const path = require('path');
const { AppError } = require('../../core/errors');
const { log: auditLog } = require('../../core/audit');
const UPLOADS_DIR = () => process.env.UPLOADS_DIR || path.join(__dirname, '..', '..', 'uploads');
function contrastRatio(hex, bgHex = '#1a1a1a') {
const toLuminance = (h) => {
const r = parseInt(h.slice(1, 3), 16) / 255;
const g = parseInt(h.slice(3, 5), 16) / 255;
const b = parseInt(h.slice(5, 7), 16) / 255;
const chan = (c) => c <= 0.03928 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);
return 0.2126 * chan(r) + 0.7152 * chan(g) + 0.0722 * chan(b);
};
const L1 = toLuminance(hex);
const L2 = toLuminance(bgHex);
const lighter = Math.max(L1, L2);
const darker = Math.min(L1, L2);
return (lighter + 0.05) / (darker + 0.05);
}
async function getOrg(models, orgId) {
const org = await models.Organization.findByPk(orgId);
if (!org) throw new AppError('NOT_FOUND', 'Organization not found.', 404);
return org;
}
async function updateOrg(models, req, orgId, data) {
if (data.timezone) {
const valid = Intl.supportedValuesOf('timeZone');
if (!valid.includes(data.timezone)) {
throw new AppError('VALIDATION_FAILED', 'Invalid timezone.', 400, 'timezone');
}
}
const org = await getOrg(models, orgId);
await org.update(data);
await auditLog(req, 'org.update', 'organization', orgId, data);
return org;
}
async function getBranding(models, orgId) {
let branding = await models.Branding.findOne({ where: { organizationId: orgId } });
if (!branding) {
branding = await models.Branding.create({ organizationId: orgId });
}
return branding;
}
async function updateBranding(models, req, orgId, data) {
const colorFields = ['primaryColor', 'secondaryColor', 'workColor', 'restColor', 'moveColor'];
const failures = [];
for (const field of colorFields) {
if (data[field]) {
const ratio = contrastRatio(data[field]);
if (ratio < 4.5) {
failures.push({ field, color: data[field], ratio: ratio.toFixed(2) });
}
}
}
if (failures.length > 0) {
throw new AppError('VALIDATION_FAILED', `Colors fail minimum contrast ratio (4.5:1) against display background: ${failures.map(f => `${f.field} (${f.ratio}:1)`).join(', ')}`, 400);
}
const branding = await getBranding(models, orgId);
await branding.update(data);
await auditLog(req, 'branding.update', 'branding', branding.id, data);
return branding;
}
async function uploadLogo(models, req, orgId, file) {
const { fileTypeFromBuffer } = await import('file-type');
const ALLOWED = ['image/png', 'image/jpeg', 'image/gif', 'image/webp'];
const EXT_MAP = { 'image/png': '.png', 'image/jpeg': '.jpg', 'image/gif': '.gif', 'image/webp': '.webp' };
let detectedMime;
try {
const fd = fs.openSync(file.path, 'r');
const buf = Buffer.alloc(12);
fs.readSync(fd, buf, 0, 12, 0);
fs.closeSync(fd);
const result = await fileTypeFromBuffer(buf);
detectedMime = result?.mime;
} finally {
await fs.promises.unlink(file.path).catch(() => {});
}
if (!detectedMime || !ALLOWED.includes(detectedMime)) {
throw new AppError('UPLOAD_TYPE_INVALID', 'Only PNG, JPG, GIF, and WebP images are supported.', 400);
}
const ext = EXT_MAP[detectedMime];
const safeName = `logo_${orgId}_${Date.now()}${ext}`;
const destPath = path.join(UPLOADS_DIR(), safeName);
const branding = await getBranding(models, orgId);
// Delete old logo
if (branding.logoPath) {
const oldFile = path.join(UPLOADS_DIR(), path.basename(branding.logoPath));
await fs.promises.unlink(oldFile).catch(() => {});
}
await fs.promises.rename(file.path, destPath);
await branding.update({ logoPath: `/api/v1/org/logo` });
await auditLog(req, 'logo.upload', 'branding', branding.id, { filename: safeName });
return branding;
}
module.exports = { getOrg, updateOrg, getBranding, updateBranding, uploadLogo, contrastRatio };