'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 };