refactor(erp): integração direta com banco ERP — schema sar
Revoga ADR 0006 (BD-por-workspace separado). O SAR agora conecta ao banco PostgreSQL do ERP (módulo SIG) e usa o schema `sar` para tudo. PRISMA - Remove: Client, Product, Order, OrderItem, OrderStatusHistory, RepTarget, RepDiscountLimit, PushSubscription (modelos isolados) - Adiciona: Pedido, PedidoItem, HistoricoPedido, AlcadaDesconto, MetaRepresentante, PushSubscription (mapeados para sar.*) - IDs: id_cliente/cod_vendedor/id_empresa são INTEGER (ERP) - situa: Int (1=Pendente 2=Aprovado 3=Cancelado 4=Faturado) - JWT: workspace_id:string → id_empresa:number - URL: inclui ?schema=sar para Prisma rotear ao schema ERP SERVICES - ClientsService: $queryRawUnsafe contra sar.vw_clientes + sar.pedidos - CatalogService: $queryRawUnsafe contra sar.vw_produtos + sar.vw_estoque - OrdersService: Prisma models Pedido/PedidoItem/HistoricoPedido/AlcadaDesconto - DashboardService: MetaRepresentante + queries raw para inativos - NotificationsService: PushSubscription com codVendedor + idEmpresa CONTRATOS (api-interface) - client.contract: campos ERP (idCliente, nome, cgcpf, cod_vendedor…) - order.contract: PedidoSummary/PedidoDetail/CreatePedido + SITUA_LABEL - product.contract: ProdutoSummary/ProdutoDetail (vw_produtos) - auth.contract: workspaceId:string → idEmpresa:number WEB - Todos os cockpits e queries atualizados para os novos tipos Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -1,6 +1,5 @@
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { ClsService } from 'nestjs-cls';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import type {
|
||||
ClientDetail,
|
||||
ClientListQuery,
|
||||
@@ -10,123 +9,187 @@ import type {
|
||||
} from '@sar/api-interface';
|
||||
import type { WorkspaceClsStore } from '../workspace/workspace.types';
|
||||
|
||||
// Thresholds de atividade (FR-2.3). Configuráveis por workspace futuramente.
|
||||
// Thresholds de atividade (FR-2.3). Configuráveis por empresa futuramente.
|
||||
const ALERT_DAYS = 30;
|
||||
const INACTIVE_DAYS = 60;
|
||||
|
||||
function activityStatus(lastOrderAt: Date | null): ActivityStatus {
|
||||
if (!lastOrderAt) return 'inactive';
|
||||
const days = Math.floor((Date.now() - lastOrderAt.getTime()) / 86_400_000);
|
||||
function activityStatus(dtUltimaCompra: Date | null): ActivityStatus {
|
||||
if (!dtUltimaCompra) return 'inactive';
|
||||
const days = Math.floor((Date.now() - dtUltimaCompra.getTime()) / 86_400_000);
|
||||
if (days >= INACTIVE_DAYS) return 'inactive';
|
||||
if (days >= ALERT_DAYS) return 'alert';
|
||||
return 'active';
|
||||
}
|
||||
|
||||
function decimalToString(v: Prisma.Decimal | null): string | null {
|
||||
return v ? v.toString() : null;
|
||||
function escSql(s: string): string {
|
||||
return s.replace(/'/g, "''");
|
||||
}
|
||||
|
||||
// Row bruta do $queryRawUnsafe
|
||||
interface ClientRow {
|
||||
id_cliente: number;
|
||||
id_empresa: number;
|
||||
nome: string;
|
||||
razao: string | null;
|
||||
cgcpf: string | null;
|
||||
email: string | null;
|
||||
telefone: string | null;
|
||||
cod_vendedor: number;
|
||||
limite_credito: string | null;
|
||||
dt_ultima_compra: Date | null;
|
||||
ativo: number;
|
||||
pessoa: number | null;
|
||||
inscricao_estadual: string | null;
|
||||
endereco: string | null;
|
||||
num_endereco: string | null;
|
||||
bairro: string | null;
|
||||
cep: string | null;
|
||||
ddd: string | null;
|
||||
obs: string | null;
|
||||
cod_pauta: number | null;
|
||||
dt_cadastro: string | null;
|
||||
dt_atual: string | null;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class ClientsService {
|
||||
constructor(private readonly cls: ClsService<WorkspaceClsStore>) {}
|
||||
|
||||
async list(query: ClientListQuery, userId: string, role: string): Promise<ClientListResponse> {
|
||||
async list(query: ClientListQuery): Promise<ClientListResponse> {
|
||||
const prisma = this.cls.get('prisma');
|
||||
if (!prisma) throw new Error('prisma não disponível no CLS');
|
||||
const idEmpresa = this.cls.get('idEmpresa');
|
||||
const role = this.cls.get('role');
|
||||
const userId = this.cls.get('userId');
|
||||
const codVendedor = userId ? parseInt(userId, 10) : 0;
|
||||
|
||||
const { q, status, financialStatus, page, limit } = query;
|
||||
const skip = (page - 1) * limit;
|
||||
const { q, status, page, limit } = query;
|
||||
const offset = (page - 1) * limit;
|
||||
|
||||
// Rep vê apenas sua carteira; supervisor/manager/admin vê tudo (FR-2.1).
|
||||
const repFilter: Prisma.ClientWhereInput = role === 'rep' ? { repId: userId } : {};
|
||||
// Rep vê apenas sua carteira (cod_vendedor = seu código)
|
||||
const vendedorFilter = role === 'rep' ? `AND c.cod_vendedor = ${codVendedor}` : '';
|
||||
const searchFilter = q
|
||||
? `AND (c.nome ILIKE '%${escSql(q)}%' OR c.cgcpf LIKE '%${escSql(q)}%')`
|
||||
: '';
|
||||
|
||||
const searchFilter: Prisma.ClientWhereInput = q
|
||||
? {
|
||||
OR: [
|
||||
{ name: { contains: q, mode: 'insensitive' } },
|
||||
{ tradeName: { contains: q, mode: 'insensitive' } },
|
||||
{ taxId: { contains: q } },
|
||||
],
|
||||
}
|
||||
: {};
|
||||
const rows = await prisma.$queryRawUnsafe<ClientRow[]>(`
|
||||
SELECT
|
||||
c.id_cliente,
|
||||
c.id_empresa,
|
||||
c.nome,
|
||||
c.razao,
|
||||
c.cgcpf,
|
||||
c.email,
|
||||
c.telefone,
|
||||
c.cod_vendedor,
|
||||
c.limite_credito::text,
|
||||
c.ativo,
|
||||
c.pessoa,
|
||||
c.inscricao_estadual,
|
||||
c.endereco,
|
||||
c.num_endereco,
|
||||
c.bairro,
|
||||
c.cep,
|
||||
c.ddd,
|
||||
c.obs,
|
||||
c.cod_pauta,
|
||||
c.dt_cadastro::text,
|
||||
c.dt_atual::text,
|
||||
MAX(p.dt_pedido) AS dt_ultima_compra
|
||||
FROM vw_clientes c
|
||||
LEFT JOIN pedidos p ON p.id_cliente = c.id_cliente AND p.id_empresa = c.id_empresa AND p.situa != 3
|
||||
WHERE c.id_empresa = ${idEmpresa}
|
||||
AND c.ativo = 1
|
||||
${vendedorFilter}
|
||||
${searchFilter}
|
||||
GROUP BY
|
||||
c.id_cliente, c.id_empresa, c.nome, c.razao, c.cgcpf, c.email,
|
||||
c.telefone, c.cod_vendedor, c.limite_credito, c.ativo, c.pessoa,
|
||||
c.inscricao_estadual, c.endereco, c.num_endereco, c.bairro, c.cep,
|
||||
c.ddd, c.obs, c.cod_pauta, c.dt_cadastro, c.dt_atual
|
||||
ORDER BY c.nome
|
||||
LIMIT ${limit} OFFSET ${offset}
|
||||
`);
|
||||
|
||||
const financialFilter: Prisma.ClientWhereInput = financialStatus ? { financialStatus } : {};
|
||||
const totalRows = await prisma.$queryRawUnsafe<[{ count: string }]>(`
|
||||
SELECT COUNT(*)::text AS count
|
||||
FROM vw_clientes c
|
||||
WHERE c.id_empresa = ${idEmpresa}
|
||||
AND c.ativo = 1
|
||||
${vendedorFilter}
|
||||
${searchFilter}
|
||||
`);
|
||||
const total = parseInt(totalRows[0]?.count ?? '0', 10);
|
||||
|
||||
const where: Prisma.ClientWhereInput = {
|
||||
deletedAt: null,
|
||||
...repFilter,
|
||||
...searchFilter,
|
||||
...financialFilter,
|
||||
};
|
||||
|
||||
const [rows, total] = await Promise.all([
|
||||
prisma.client.findMany({
|
||||
where,
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
tradeName: true,
|
||||
taxId: true,
|
||||
financialStatus: true,
|
||||
lastOrderAt: true,
|
||||
lastOrderValue: true,
|
||||
openOrdersCount: true,
|
||||
},
|
||||
skip,
|
||||
take: limit,
|
||||
orderBy: { name: 'asc' },
|
||||
}),
|
||||
prisma.client.count({ where }),
|
||||
]);
|
||||
|
||||
// Filtra por activityStatus depois do fetch (computed field — não persiste no DB).
|
||||
const mapped: ClientSummary[] = rows.map((r) => ({
|
||||
id: r.id,
|
||||
name: r.name,
|
||||
tradeName: r.tradeName,
|
||||
taxId: r.taxId,
|
||||
financialStatus: r.financialStatus,
|
||||
activityStatus: activityStatus(r.lastOrderAt),
|
||||
lastOrderAt: r.lastOrderAt?.toISOString() ?? null,
|
||||
lastOrderValue: decimalToString(r.lastOrderValue),
|
||||
openOrdersCount: r.openOrdersCount,
|
||||
let mapped: ClientSummary[] = rows.map((r) => ({
|
||||
idCliente: Number(r.id_cliente),
|
||||
idEmpresa: Number(r.id_empresa),
|
||||
nome: r.nome,
|
||||
razao: r.razao,
|
||||
cgcpf: r.cgcpf,
|
||||
email: r.email,
|
||||
telefone: r.telefone,
|
||||
codVendedor: Number(r.cod_vendedor),
|
||||
limiteCreditoStr: r.limite_credito,
|
||||
activityStatus: activityStatus(r.dt_ultima_compra),
|
||||
dtUltimaCompra: r.dt_ultima_compra?.toISOString() ?? null,
|
||||
}));
|
||||
|
||||
const filtered = status ? mapped.filter((c) => c.activityStatus === status) : mapped;
|
||||
if (status) mapped = mapped.filter((c) => c.activityStatus === status);
|
||||
|
||||
return { data: filtered, total, page, limit };
|
||||
return { data: mapped, total, page, limit };
|
||||
}
|
||||
|
||||
async findOne(id: string, userId: string, role: string): Promise<ClientDetail> {
|
||||
async findOne(idCliente: number): Promise<ClientDetail> {
|
||||
const prisma = this.cls.get('prisma');
|
||||
if (!prisma) throw new Error('prisma não disponível no CLS');
|
||||
const idEmpresa = this.cls.get('idEmpresa');
|
||||
|
||||
const repFilter: Prisma.ClientWhereInput = role === 'rep' ? { repId: userId } : {};
|
||||
const rows = await prisma.$queryRawUnsafe<ClientRow[]>(`
|
||||
SELECT
|
||||
c.id_cliente, c.id_empresa, c.nome, c.razao, c.cgcpf, c.email,
|
||||
c.telefone, c.cod_vendedor, c.limite_credito::text,
|
||||
c.ativo, c.pessoa, c.inscricao_estadual, c.endereco, c.num_endereco,
|
||||
c.bairro, c.cep, c.ddd, c.obs, c.cod_pauta,
|
||||
c.dt_cadastro::text, c.dt_atual::text,
|
||||
MAX(p.dt_pedido) AS dt_ultima_compra
|
||||
FROM vw_clientes c
|
||||
LEFT JOIN pedidos p ON p.id_cliente = c.id_cliente AND p.id_empresa = c.id_empresa AND p.situa != 3
|
||||
WHERE c.id_empresa = ${idEmpresa} AND c.id_cliente = ${idCliente}
|
||||
GROUP BY c.id_cliente, c.id_empresa, c.nome, c.razao, c.cgcpf, c.email,
|
||||
c.telefone, c.cod_vendedor, c.limite_credito, c.ativo, c.pessoa,
|
||||
c.inscricao_estadual, c.endereco, c.num_endereco, c.bairro, c.cep,
|
||||
c.ddd, c.obs, c.cod_pauta, c.dt_cadastro, c.dt_atual
|
||||
LIMIT 1
|
||||
`);
|
||||
|
||||
const client = await prisma.client.findFirst({
|
||||
where: { id, deletedAt: null, ...repFilter },
|
||||
});
|
||||
|
||||
if (!client) throw new NotFoundException(`Cliente ${id} não encontrado`);
|
||||
const r = rows[0];
|
||||
if (!r) throw new NotFoundException(`Cliente ${idCliente} não encontrado`);
|
||||
|
||||
return {
|
||||
id: client.id,
|
||||
name: client.name,
|
||||
tradeName: client.tradeName,
|
||||
taxId: client.taxId,
|
||||
email: client.email,
|
||||
phone: client.phone,
|
||||
address: client.address as ClientDetail['address'],
|
||||
financialStatus: client.financialStatus,
|
||||
activityStatus: activityStatus(client.lastOrderAt),
|
||||
creditLimit: decimalToString(client.creditLimit),
|
||||
lastOrderAt: client.lastOrderAt?.toISOString() ?? null,
|
||||
lastOrderValue: decimalToString(client.lastOrderValue),
|
||||
openOrdersCount: client.openOrdersCount,
|
||||
erpCode: client.erpCode,
|
||||
syncedAt: client.syncedAt?.toISOString() ?? null,
|
||||
createdAt: client.createdAt.toISOString(),
|
||||
updatedAt: client.updatedAt.toISOString(),
|
||||
idCliente: Number(r.id_cliente),
|
||||
idEmpresa: Number(r.id_empresa),
|
||||
nome: r.nome,
|
||||
razao: r.razao,
|
||||
cgcpf: r.cgcpf,
|
||||
email: r.email,
|
||||
telefone: r.telefone,
|
||||
codVendedor: Number(r.cod_vendedor),
|
||||
limiteCreditoStr: r.limite_credito,
|
||||
activityStatus: activityStatus(r.dt_ultima_compra),
|
||||
dtUltimaCompra: r.dt_ultima_compra?.toISOString() ?? null,
|
||||
ativo: Number(r.ativo),
|
||||
pessoa: r.pessoa !== null ? Number(r.pessoa) : null,
|
||||
inscricaoEstadual: r.inscricao_estadual,
|
||||
endereco: r.endereco,
|
||||
numEndereco: r.num_endereco,
|
||||
bairro: r.bairro,
|
||||
cep: r.cep,
|
||||
ddd: r.ddd,
|
||||
obs: r.obs,
|
||||
codPauta: r.cod_pauta !== null ? Number(r.cod_pauta) : null,
|
||||
dtCadastro: r.dt_cadastro,
|
||||
dtAtual: r.dt_atual,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user