feat: add multi-tenant client management for admins

- Add tenants API endpoints (list, get, create)
- Add tenant middleware override via X-View-Tenant header
- Add TenantSelector dropdown component in header
- Add tenant view store with persistence
- Add Clientes management page
- Update all navigation layouts with Clientes link for admins

Admins can now:
- View list of all clients
- Create new clients with automatic schema setup
- Switch between viewing different clients' data
- See which client they are currently viewing

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
Consultoria AS
2026-01-22 03:55:44 +00:00
parent 6e3e69005b
commit 0c10c887d2
16 changed files with 768 additions and 6 deletions

View File

@@ -12,6 +12,7 @@ import { alertasRoutes } from './routes/alertas.routes.js';
import { calendarioRoutes } from './routes/calendario.routes.js';
import { reportesRoutes } from './routes/reportes.routes.js';
import { usuariosRoutes } from './routes/usuarios.routes.js';
import { tenantsRoutes } from './routes/tenants.routes.js';
const app = express();
@@ -41,6 +42,7 @@ app.use('/api/alertas', alertasRoutes);
app.use('/api/calendario', calendarioRoutes);
app.use('/api/reportes', reportesRoutes);
app.use('/api/usuarios', usuariosRoutes);
app.use('/api/tenants', tenantsRoutes);
// Error handling
app.use(errorMiddleware);

View File

@@ -0,0 +1,60 @@
import { Request, Response, NextFunction } from 'express';
import * as tenantsService from '../services/tenants.service.js';
import { AppError } from '../utils/errors.js';
export async function getAllTenants(req: Request, res: Response, next: NextFunction) {
try {
// Only admin can list all tenants
if (req.user!.role !== 'admin') {
throw new AppError(403, 'Solo administradores pueden ver todos los clientes');
}
const tenants = await tenantsService.getAllTenants();
res.json(tenants);
} catch (error) {
next(error);
}
}
export async function getTenant(req: Request, res: Response, next: NextFunction) {
try {
if (req.user!.role !== 'admin') {
throw new AppError(403, 'Solo administradores pueden ver detalles de clientes');
}
const tenant = await tenantsService.getTenantById(req.params.id);
if (!tenant) {
throw new AppError(404, 'Cliente no encontrado');
}
res.json(tenant);
} catch (error) {
next(error);
}
}
export async function createTenant(req: Request, res: Response, next: NextFunction) {
try {
if (req.user!.role !== 'admin') {
throw new AppError(403, 'Solo administradores pueden crear clientes');
}
const { nombre, rfc, plan, cfdiLimit, usersLimit } = req.body;
if (!nombre || !rfc) {
throw new AppError(400, 'Nombre y RFC son requeridos');
}
const tenant = await tenantsService.createTenant({
nombre,
rfc,
plan,
cfdiLimit,
usersLimit,
});
res.status(201).json(tenant);
} catch (error) {
next(error);
}
}

View File

@@ -6,6 +6,7 @@ declare global {
namespace Express {
interface Request {
tenantSchema?: string;
viewingTenantId?: string;
}
}
}
@@ -16,8 +17,18 @@ export async function tenantMiddleware(req: Request, res: Response, next: NextFu
}
try {
// Check if admin is viewing a different tenant
const viewTenantId = req.headers['x-view-tenant'] as string | undefined;
let tenantId = req.user.tenantId;
// Only admins can view other tenants
if (viewTenantId && req.user.role === 'admin') {
tenantId = viewTenantId;
req.viewingTenantId = viewTenantId;
}
const tenant = await prisma.tenant.findUnique({
where: { id: req.user.tenantId },
where: { id: tenantId },
select: { schemaName: true, active: true },
});

View File

@@ -0,0 +1,13 @@
import { Router } from 'express';
import { authenticate } from '../middlewares/auth.middleware.js';
import * as tenantsController from '../controllers/tenants.controller.js';
const router = Router();
router.use(authenticate);
router.get('/', tenantsController.getAllTenants);
router.get('/:id', tenantsController.getTenant);
router.post('/', tenantsController.createTenant);
export { router as tenantsRoutes };

View File

@@ -0,0 +1,141 @@
import { prisma } from '../config/database.js';
export async function getAllTenants() {
return prisma.tenant.findMany({
where: { active: true },
select: {
id: true,
nombre: true,
rfc: true,
plan: true,
schemaName: true,
createdAt: true,
_count: {
select: { users: true }
}
},
orderBy: { nombre: 'asc' }
});
}
export async function getTenantById(id: string) {
return prisma.tenant.findUnique({
where: { id },
select: {
id: true,
nombre: true,
rfc: true,
plan: true,
schemaName: true,
cfdiLimit: true,
usersLimit: true,
createdAt: true,
}
});
}
export async function createTenant(data: {
nombre: string;
rfc: string;
plan?: 'starter' | 'business' | 'professional' | 'enterprise';
cfdiLimit?: number;
usersLimit?: number;
}) {
const schemaName = `tenant_${data.rfc.toLowerCase().replace(/[^a-z0-9]/g, '')}`;
// Create tenant record
const tenant = await prisma.tenant.create({
data: {
nombre: data.nombre,
rfc: data.rfc.toUpperCase(),
plan: data.plan || 'starter',
schemaName,
cfdiLimit: data.cfdiLimit || 500,
usersLimit: data.usersLimit || 3,
}
});
// Create schema and tables for the tenant
await prisma.$executeRawUnsafe(`CREATE SCHEMA IF NOT EXISTS "${schemaName}"`);
// Create CFDIs table
await prisma.$executeRawUnsafe(`
CREATE TABLE IF NOT EXISTS "${schemaName}"."cfdis" (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
uuid_fiscal VARCHAR(36) UNIQUE NOT NULL,
tipo VARCHAR(20) NOT NULL,
serie VARCHAR(25),
folio VARCHAR(40),
fecha_emision TIMESTAMP NOT NULL,
fecha_timbrado TIMESTAMP NOT NULL,
rfc_emisor VARCHAR(13) NOT NULL,
nombre_emisor VARCHAR(300) NOT NULL,
rfc_receptor VARCHAR(13) NOT NULL,
nombre_receptor VARCHAR(300) NOT NULL,
subtotal DECIMAL(18,2) NOT NULL,
descuento DECIMAL(18,2) DEFAULT 0,
iva DECIMAL(18,2) DEFAULT 0,
isr_retenido DECIMAL(18,2) DEFAULT 0,
iva_retenido DECIMAL(18,2) DEFAULT 0,
total DECIMAL(18,2) NOT NULL,
moneda VARCHAR(3) DEFAULT 'MXN',
tipo_cambio DECIMAL(10,4) DEFAULT 1,
metodo_pago VARCHAR(3),
forma_pago VARCHAR(2),
uso_cfdi VARCHAR(4),
estado VARCHAR(20) DEFAULT 'vigente',
xml_url TEXT,
pdf_url TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`);
// Create IVA monthly table
await prisma.$executeRawUnsafe(`
CREATE TABLE IF NOT EXISTS "${schemaName}"."iva_mensual" (
id SERIAL PRIMARY KEY,
año INT NOT NULL,
mes INT NOT NULL,
iva_trasladado DECIMAL(18,2) NOT NULL,
iva_acreditable DECIMAL(18,2) NOT NULL,
iva_retenido DECIMAL(18,2) DEFAULT 0,
resultado DECIMAL(18,2) NOT NULL,
acumulado DECIMAL(18,2) NOT NULL,
estado VARCHAR(20) DEFAULT 'pendiente',
fecha_declaracion TIMESTAMP,
UNIQUE(año, mes)
)
`);
// Create alerts table
await prisma.$executeRawUnsafe(`
CREATE TABLE IF NOT EXISTS "${schemaName}"."alertas" (
id SERIAL PRIMARY KEY,
tipo VARCHAR(50) NOT NULL,
titulo VARCHAR(200) NOT NULL,
mensaje TEXT NOT NULL,
prioridad VARCHAR(20) DEFAULT 'media',
fecha_vencimiento TIMESTAMP,
leida BOOLEAN DEFAULT FALSE,
resuelta BOOLEAN DEFAULT FALSE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`);
// Create calendario_fiscal table
await prisma.$executeRawUnsafe(`
CREATE TABLE IF NOT EXISTS "${schemaName}"."calendario_fiscal" (
id SERIAL PRIMARY KEY,
titulo VARCHAR(200) NOT NULL,
descripcion TEXT,
tipo VARCHAR(20) NOT NULL,
fecha_limite TIMESTAMP NOT NULL,
recurrencia VARCHAR(20) DEFAULT 'mensual',
completado BOOLEAN DEFAULT FALSE,
notas TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`);
return tenant;
}