// Resolve the active company for the request from the X-Company-Id header. The company must be one // the user may access (see companies.companiesForUser); otherwise we fall back to their first // accessible company so the app always has a valid, permitted company context. Mount after requireAuth. // Required lazily to avoid a load-time cycle (companies -> roles -> ...). function resolveCompany(req, res, next) { const { companyIdsForUser } = require('../services/companies'); const accessible = companyIdsForUser(req.user); const requested = Number(req.headers['x-company-id']); req.companyId = accessible.includes(requested) ? requested : (accessible[0] || null); return next(); } module.exports = { resolveCompany };