feat(infra): conecta ao banco ERP libreplast e fixa rep 29 como usuário dev
- sar-erp-schema.sql: corrige grupo.nome (era descricao), tp_pauta inexistente
em pauxpro, COALESCE(id_empresa,1) em vw_clientes para bancos single-tenant,
e nome do cliente via COALESCE(NULLIF(TRIM(nome),''), TRIM(razao))
- WorkspacePrismaPool: PrismaPg({ schema: 'sar' }) + options search_path=sar
para ORM e queries raw funcionarem no schema correto
- JwtAuthGuard: força DEV_REP_CODE/DEV_EMPRESA_ID em não-prod — filtro
global sem tocar em nenhum service
- env.schema: adiciona DEV_REP_CODE e DEV_EMPRESA_ID com defaults 29 e 1
Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -18,6 +18,9 @@ import { IS_PUBLIC_KEY } from './public.decorator';
|
||||
@Injectable()
|
||||
export class JwtAuthGuard implements CanActivate {
|
||||
private readonly secret: Uint8Array;
|
||||
private readonly isProd: boolean;
|
||||
private readonly devRepCode: string;
|
||||
private readonly devEmpresaId: number;
|
||||
|
||||
constructor(
|
||||
private readonly reflector: Reflector,
|
||||
@@ -26,6 +29,9 @@ export class JwtAuthGuard implements CanActivate {
|
||||
config: ConfigService<Env, true>,
|
||||
) {
|
||||
this.secret = new TextEncoder().encode(config.get('MASTER_LOGIN_JWT_SECRET', { infer: true }));
|
||||
this.isProd = config.get('NODE_ENV', { infer: true }) === 'production';
|
||||
this.devRepCode = String(config.get('DEV_REP_CODE', { infer: true }));
|
||||
this.devEmpresaId = config.get('DEV_EMPRESA_ID', { infer: true });
|
||||
}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
@@ -45,18 +51,18 @@ export class JwtAuthGuard implements CanActivate {
|
||||
|
||||
(req as Request & { user: JwtPayload }).user = payload as JwtPayload;
|
||||
|
||||
// Sobrescreve CLS com idEmpresa real do JWT (corre depois do middleware).
|
||||
const idEmpresa = payload.id_empresa;
|
||||
// Em dev: força representante fixo (DEV_REP_CODE / DEV_EMPRESA_ID) ignorando o JWT.
|
||||
// Em prod: usa os valores reais do JWT.
|
||||
const idEmpresa = this.isProd ? payload.id_empresa : this.devEmpresaId;
|
||||
const userId = this.isProd ? payload.sub : this.devRepCode;
|
||||
this.cls.set('idEmpresa', idEmpresa);
|
||||
this.cls.set('userId', payload.sub);
|
||||
this.cls.set('userId', userId);
|
||||
this.cls.set('role', payload.role);
|
||||
|
||||
// URL inclui ?schema=sar para o Prisma rotear ao schema correto no ERP
|
||||
const baseUrl =
|
||||
process.env['DATABASE_URL'] ??
|
||||
'postgresql://sar:sar_dev_password@localhost:5432/sar_workspace_dev';
|
||||
const dbUrl = baseUrl.includes('?') ? `${baseUrl}&schema=sar` : `${baseUrl}?schema=sar`;
|
||||
this.cls.set('prisma', this.pool.getOrCreate(idEmpresa, dbUrl));
|
||||
this.cls.set('prisma', this.pool.getOrCreate(idEmpresa, baseUrl));
|
||||
|
||||
return true;
|
||||
} catch {
|
||||
|
||||
@@ -41,6 +41,10 @@ export const EnvSchema = z
|
||||
// Multi-tenancy — workspace de dev (até master-login real entrar)
|
||||
DEFAULT_WORKSPACE_ID: z.string().min(1).default('dev-workspace'),
|
||||
|
||||
// Representante fixo de dev — forçado no guard enquanto não há login real
|
||||
DEV_REP_CODE: z.coerce.number().int().positive().default(29),
|
||||
DEV_EMPRESA_ID: z.coerce.number().int().positive().default(1),
|
||||
|
||||
// Postgres (Prisma virá depois)
|
||||
DATABASE_URL: z.string().optional(),
|
||||
MIGRATION_DATABASE_URL: z.string().optional(),
|
||||
|
||||
@@ -37,8 +37,12 @@ export class WorkspacePrismaPool implements OnModuleDestroy {
|
||||
this.evictOldest();
|
||||
}
|
||||
|
||||
const pgPool = new pg.Pool({ connectionString: dbUrl, max: PG_POOL_SIZE });
|
||||
const adapter = new PrismaPg(pgPool);
|
||||
const pgPool = new pg.Pool({
|
||||
connectionString: dbUrl,
|
||||
max: PG_POOL_SIZE,
|
||||
options: '-c search_path=sar',
|
||||
});
|
||||
const adapter = new PrismaPg(pgPool, { schema: 'sar' });
|
||||
const client = new PrismaClient({ adapter });
|
||||
this.cache.set(key, { client, pgPool });
|
||||
this.logger.log(`pool criado: idEmpresa=${idEmpresa} total=${this.cache.size}`);
|
||||
|
||||
Reference in New Issue
Block a user