refactor(api,web): remove fila de aprovacao e consolida painel do supervisor
Alcada agora e bloqueio duro no pedido (sem fluxo de aprovar/recusar): remove ApprovalQueuePage, CarteirePage e rota /aprovacoes, absorvendo carteira e acompanhamento de pedidos dentro do SupervisorPainel. Colunas de desempenho por representante extraidas para componente compartilhado (rep-performance-columns) entre gerente e supervisor. Ajusta dashboard e orders (controller/service/contract) para o novo fluxo. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,9 +1,19 @@
|
||||
import { Body, Controller, ForbiddenException, Get, HttpCode, Put, Query } from '@nestjs/common';
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
ForbiddenException,
|
||||
Get,
|
||||
HttpCode,
|
||||
ParseIntPipe,
|
||||
Put,
|
||||
Query,
|
||||
} from '@nestjs/common';
|
||||
import { ClsService } from 'nestjs-cls';
|
||||
import { createZodDto } from 'nestjs-zod';
|
||||
import {
|
||||
SaveMetaPositivacaoBodySchema,
|
||||
type RepDashboard,
|
||||
type RepInativosDetail,
|
||||
type SupervisorDashboard,
|
||||
type ManagerDashboard,
|
||||
type SaveMetaPositivacaoBody,
|
||||
@@ -40,6 +50,14 @@ export class DashboardController {
|
||||
return this.dashboard.supervisorDashboard();
|
||||
}
|
||||
|
||||
@Get('supervisor/inativos')
|
||||
supervisorInativos(
|
||||
@Query('codVendedor', ParseIntPipe) codVendedor: number,
|
||||
): Promise<RepInativosDetail> {
|
||||
this.assertGestor();
|
||||
return this.dashboard.supervisorInativos(codVendedor);
|
||||
}
|
||||
|
||||
@Put('manager/meta-positivacao-dia')
|
||||
@HttpCode(204)
|
||||
saveMetaPositivacaoDia(@Body() body: SaveMetaPositivacaoDto): Promise<void> {
|
||||
|
||||
@@ -2,6 +2,7 @@ import { ForbiddenException, Injectable } from '@nestjs/common';
|
||||
import { ClsService } from 'nestjs-cls';
|
||||
import type {
|
||||
RepDashboard,
|
||||
RepInativosDetail,
|
||||
SupervisorDashboard,
|
||||
ManagerDashboard,
|
||||
RankingRep,
|
||||
@@ -11,8 +12,6 @@ import type { WorkspaceClsStore } from '../workspace/workspace.types';
|
||||
import { getTeamCodes } from '../workspace/team-scope.util';
|
||||
|
||||
// Situa ERP: 2=Liberado, 4=Faturado, 5=Cancelado
|
||||
// Situa SAR (pedidos novos): 1=Pendente, 2=Aprovado, 3=Cancelado, 4=Faturado
|
||||
const SITUA_PENDENTE = 1;
|
||||
|
||||
// vw_metas.tipo (gestao.metavenda): GL = meta global, GR = meta por grupo.
|
||||
const TIPO_META_GLOBAL = 'GL';
|
||||
@@ -744,17 +743,6 @@ export class DashboardService {
|
||||
role === 'supervisor' ? await getTeamCodes(prisma, userId ? parseInt(userId, 10) : 0) : null;
|
||||
const teamSqlFilter = (col: string) => (team ? `AND ${col} IN (${team.join(',')})` : '');
|
||||
|
||||
// Fila de aprovações — pedidos SAR pendentes (novos, ainda não integrados ao ERP)
|
||||
const approvalQueue = await prisma.pedido.findMany({
|
||||
where: {
|
||||
idEmpresa,
|
||||
situa: SITUA_PENDENTE,
|
||||
...(team ? { codVendedor: { in: team } } : {}),
|
||||
},
|
||||
orderBy: { dtPedido: 'asc' },
|
||||
take: 50,
|
||||
});
|
||||
|
||||
// Pedidos do dia — lê do ERP (situa != 5=Cancelado)
|
||||
const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate());
|
||||
const todayStr = todayStart.toISOString().slice(0, 10);
|
||||
@@ -785,7 +773,152 @@ export class DashboardService {
|
||||
`),
|
||||
]);
|
||||
|
||||
// Top 3 reps com mais clientes inativos (>30 dias sem compra no ERP)
|
||||
// Métricas do mês corrente da equipe — mesmas contas do painel gerencial,
|
||||
// escopadas pelos códigos da equipe (gerente/admin sem filtro = empresa toda).
|
||||
const idEmpresaMatriz = matrizEmpresa(idEmpresa);
|
||||
const year = now.getFullYear();
|
||||
const month = now.getMonth() + 1;
|
||||
const monthStartStr = new Date(year, month - 1, 1).toISOString().slice(0, 10);
|
||||
const monthEndStr = new Date(year, month, 0).toISOString().slice(0, 10);
|
||||
|
||||
interface RankingRow {
|
||||
cod_vendedor: number;
|
||||
nome: string | null;
|
||||
pedidos: string;
|
||||
clientes_atendidos: string;
|
||||
faturamento: string;
|
||||
meta_valor: string | null;
|
||||
}
|
||||
interface MetaTotalRow {
|
||||
meta_total: string;
|
||||
}
|
||||
interface PositivacaoRow {
|
||||
cod_vendedor: number;
|
||||
nome_vendedor: string | null;
|
||||
total_clientes: string;
|
||||
clientes_positivados: string;
|
||||
}
|
||||
interface NovosClientesRow {
|
||||
cod_vendedor: number;
|
||||
novos: string;
|
||||
}
|
||||
|
||||
const [mesRows, rankingRows, metaTotalRows, positivacaoRows, novosClientesRows] =
|
||||
await Promise.all([
|
||||
prisma.$queryRawUnsafe<DayRow[]>(`
|
||||
SELECT COUNT(*)::text AS count, COALESCE(SUM(total), 0)::text AS total
|
||||
FROM vw_pedidos_erp
|
||||
WHERE id_empresa = ${idEmpresa}
|
||||
AND situa NOT IN (1, 5)
|
||||
AND dt_pedido >= '${monthStartStr}'
|
||||
AND dt_pedido <= '${monthEndStr}'
|
||||
${teamSqlFilter('cod_vendedor')}
|
||||
`),
|
||||
prisma.$queryRawUnsafe<RankingRow[]>(`
|
||||
SELECT p.cod_vendedor,
|
||||
(SELECT r.nome FROM vw_representantes r
|
||||
WHERE r.codigo = p.cod_vendedor LIMIT 1) AS nome,
|
||||
COUNT(*)::text AS pedidos,
|
||||
COUNT(DISTINCT p.id_cliente)::text AS clientes_atendidos,
|
||||
COALESCE(SUM(p.total), 0)::text AS faturamento,
|
||||
(SELECT SUM(m.valor)::text FROM sar.vw_metas m
|
||||
WHERE m.id_empresa = ${idEmpresaMatriz}
|
||||
AND m.cod_vendedor = p.cod_vendedor
|
||||
AND m.ano = ${year}
|
||||
AND m.mes = ${month}
|
||||
AND TRIM(m.tipo) = '${TIPO_META_GRUPO}') AS meta_valor
|
||||
FROM vw_pedidos_erp p
|
||||
WHERE p.id_empresa = ${idEmpresa}
|
||||
AND p.situa NOT IN (1, 5)
|
||||
AND p.dt_pedido >= '${monthStartStr}'
|
||||
AND p.dt_pedido <= '${monthEndStr}'
|
||||
${teamSqlFilter('p.cod_vendedor')}
|
||||
GROUP BY p.cod_vendedor
|
||||
ORDER BY SUM(p.total) DESC
|
||||
LIMIT 10
|
||||
`),
|
||||
prisma.$queryRawUnsafe<MetaTotalRow[]>(`
|
||||
SELECT COALESCE(SUM(valor), 0)::text AS meta_total
|
||||
FROM sar.vw_metas
|
||||
WHERE id_empresa = ${idEmpresaMatriz}
|
||||
AND ano = ${year}
|
||||
AND mes = ${month}
|
||||
AND TRIM(tipo) = '${TIPO_META_GRUPO}'
|
||||
${teamSqlFilter('cod_vendedor')}
|
||||
`),
|
||||
prisma.$queryRawUnsafe<PositivacaoRow[]>(`
|
||||
SELECT
|
||||
c.cod_vendedor,
|
||||
(SELECT r.nome FROM vw_representantes r WHERE r.codigo = c.cod_vendedor LIMIT 1) AS nome_vendedor,
|
||||
COUNT(DISTINCT c.id_cliente)::text AS total_clientes,
|
||||
COUNT(DISTINCT CASE WHEN ped.id_cliente IS NOT NULL THEN c.id_cliente END)::text AS clientes_positivados
|
||||
FROM vw_clientes c
|
||||
LEFT JOIN (
|
||||
SELECT DISTINCT id_cliente, cod_vendedor
|
||||
FROM vw_pedidos_erp
|
||||
WHERE id_empresa = ${idEmpresa}
|
||||
AND situa NOT IN (1, 5)
|
||||
AND dt_pedido >= '${monthStartStr}'
|
||||
AND dt_pedido <= '${monthEndStr}'
|
||||
) ped ON ped.id_cliente = c.id_cliente AND ped.cod_vendedor = c.cod_vendedor
|
||||
WHERE c.cod_vendedor > 0
|
||||
${teamSqlFilter('c.cod_vendedor')}
|
||||
GROUP BY c.cod_vendedor
|
||||
HAVING COUNT(DISTINCT c.id_cliente) > 0
|
||||
ORDER BY COUNT(DISTINCT CASE WHEN ped.id_cliente IS NOT NULL THEN c.id_cliente END) DESC
|
||||
`),
|
||||
prisma.$queryRawUnsafe<NovosClientesRow[]>(`
|
||||
SELECT c.cod_vendedor, COUNT(*)::text AS novos
|
||||
FROM (
|
||||
SELECT id_cliente, MIN(dt_pedido) AS primeira_compra
|
||||
FROM vw_pedidos_erp
|
||||
WHERE id_empresa = ${idEmpresa}
|
||||
AND situa NOT IN (1, 5)
|
||||
GROUP BY id_cliente
|
||||
) f
|
||||
JOIN (SELECT DISTINCT id_cliente, cod_vendedor FROM vw_clientes) c
|
||||
ON c.id_cliente = f.id_cliente
|
||||
WHERE f.primeira_compra >= '${monthStartStr}'
|
||||
AND f.primeira_compra <= '${monthEndStr}'
|
||||
${teamSqlFilter('c.cod_vendedor')}
|
||||
GROUP BY c.cod_vendedor
|
||||
`),
|
||||
]);
|
||||
|
||||
const pedidosMes = Number(mesRows[0]?.count ?? 0);
|
||||
const faturamentoMes = Number(mesRows[0]?.total ?? 0);
|
||||
const metaTotal = Number(metaTotalRows[0]?.meta_total ?? 0);
|
||||
|
||||
const rankingReps: RankingRep[] = rankingRows.map((r) => {
|
||||
const fat = Number(r.faturamento);
|
||||
const meta = r.meta_valor ? Number(r.meta_valor) : 0;
|
||||
return {
|
||||
codVendedor: Number(r.cod_vendedor),
|
||||
nomeVendedor: r.nome ?? null,
|
||||
pedidos: Number(r.pedidos),
|
||||
clientesAtendidos: Number(r.clientes_atendidos),
|
||||
faturamento: fat,
|
||||
pctMeta: meta > 0 ? Math.round((fat / meta) * 100) : 0,
|
||||
};
|
||||
});
|
||||
|
||||
const novosMap = new Map(
|
||||
novosClientesRows.map((n) => [Number(n.cod_vendedor), Number(n.novos)]),
|
||||
);
|
||||
const positivacaoReps: PositivacaoRep[] = positivacaoRows.map((r) => {
|
||||
const total = Number(r.total_clientes);
|
||||
const positivados = Number(r.clientes_positivados);
|
||||
return {
|
||||
codVendedor: Number(r.cod_vendedor),
|
||||
nomeVendedor: r.nome_vendedor ?? null,
|
||||
totalClientes: total,
|
||||
clientesPositivados: positivados,
|
||||
pctPositivacao: total > 0 ? Math.round((positivados / total) * 100) : 0,
|
||||
novosClientes: novosMap.get(Number(r.cod_vendedor)) ?? 0,
|
||||
};
|
||||
});
|
||||
|
||||
// Reps com mais clientes inativos (>30 dias sem compra no ERP)
|
||||
const thirtyDaysAgo = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
|
||||
const inativosPorRep = await prisma.$queryRawUnsafe<InativosPorRepRow[]>(`
|
||||
SELECT inativos.cod_vendedor,
|
||||
@@ -808,50 +941,10 @@ export class DashboardService {
|
||||
) inativos
|
||||
GROUP BY inativos.cod_vendedor
|
||||
ORDER BY COUNT(*) DESC
|
||||
LIMIT 3
|
||||
LIMIT 10
|
||||
`);
|
||||
|
||||
// Resolve nomes de cliente e representante da fila (pedidos SAR só têm os códigos)
|
||||
const repCods = [...new Set(approvalQueue.map((p) => p.codVendedor))];
|
||||
const cliIds = [...new Set(approvalQueue.map((p) => p.idCliente))];
|
||||
const [repNameRows, cliNameRows] = await Promise.all([
|
||||
repCods.length
|
||||
? prisma.$queryRawUnsafe<{ codigo: number; nome: string | null }[]>(
|
||||
`SELECT codigo, nome FROM vw_representantes WHERE codigo IN (${repCods.join(',')})`,
|
||||
)
|
||||
: Promise.resolve([]),
|
||||
cliIds.length
|
||||
? prisma.$queryRawUnsafe<
|
||||
{ id_cliente: number; nome: string | null; razao: string | null }[]
|
||||
>(
|
||||
`SELECT id_cliente, nome, razao FROM vw_clientes WHERE id_cliente IN (${cliIds.join(',')})`,
|
||||
)
|
||||
: Promise.resolve([]),
|
||||
]);
|
||||
const repNameMap = new Map(repNameRows.map((r) => [Number(r.codigo), r.nome]));
|
||||
const cliNameMap = new Map(
|
||||
cliNameRows.map((c) => [Number(c.id_cliente), { nome: c.nome, razao: c.razao }]),
|
||||
);
|
||||
|
||||
const mapPedido = (o: (typeof approvalQueue)[number]) => ({
|
||||
id: o.id,
|
||||
numPedSar: o.numPedSar,
|
||||
idCliente: o.idCliente,
|
||||
nomeCliente: cliNameMap.get(o.idCliente)?.nome ?? null,
|
||||
razaoCliente: cliNameMap.get(o.idCliente)?.razao ?? null,
|
||||
codVendedor: o.codVendedor,
|
||||
nomeVendedor: repNameMap.get(o.codVendedor) ?? null,
|
||||
situa: o.situa,
|
||||
dtPedido: o.dtPedido.toISOString(),
|
||||
total: String(o.total),
|
||||
descontoPerc: String(o.descontoPerc),
|
||||
obs: o.obs,
|
||||
createdAt: o.createdAt.toISOString(),
|
||||
fonte: 'sar' as const,
|
||||
});
|
||||
|
||||
return {
|
||||
approvalQueue: approvalQueue.map(mapPedido),
|
||||
pedidosDia: {
|
||||
count: Number(todayRows[0]?.count ?? 0),
|
||||
total: Number(todayRows[0]?.total ?? 0),
|
||||
@@ -863,7 +956,93 @@ export class DashboardService {
|
||||
nomeVendedor: r.nome_vendedor ?? null,
|
||||
inativosCount: parseInt(r.inativos_count, 10),
|
||||
})),
|
||||
equipeMes: {
|
||||
faturamento: faturamentoMes,
|
||||
pedidos: pedidosMes,
|
||||
ticketMedio: pedidosMes > 0 ? faturamentoMes / pedidosMes : 0,
|
||||
metaTotal,
|
||||
pctMeta: metaTotal > 0 ? Math.round((faturamentoMes / metaTotal) * 100) : 0,
|
||||
},
|
||||
rankingReps,
|
||||
positivacaoReps,
|
||||
syncedAt: now.toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
// Clientes inativos (>30 dias sem compra) de um representante — detalhe do
|
||||
// card "Inativos por Rep". Supervisor só consulta reps da própria equipe;
|
||||
// gerente/admin consultam qualquer rep.
|
||||
async supervisorInativos(codVendedor: number): Promise<RepInativosDetail> {
|
||||
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');
|
||||
if (role === 'supervisor') {
|
||||
const team = await getTeamCodes(prisma, userId ? parseInt(userId, 10) : 0);
|
||||
if (!team.includes(codVendedor)) {
|
||||
throw new ForbiddenException('Representante fora da sua equipe');
|
||||
}
|
||||
}
|
||||
|
||||
// Mesmo corte do resumo inativosPorRep: sem compra há mais de 30 dias.
|
||||
const cutoffStr = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString().slice(0, 10);
|
||||
const rows = await prisma.$queryRawUnsafe<NaoPositivadoRow[]>(`
|
||||
WITH ultimo_pedido AS (
|
||||
SELECT id_cliente, MAX(dt_pedido) AS dt_max
|
||||
FROM vw_pedidos_erp
|
||||
WHERE id_empresa = ${idEmpresa}
|
||||
AND situa != 5
|
||||
GROUP BY id_cliente
|
||||
)
|
||||
SELECT
|
||||
c.id_cliente,
|
||||
TRIM(c.nome) AS nome,
|
||||
TRIM(c.razao) AS razao,
|
||||
TO_CHAR(up.dt_max, 'YYYY-MM-DD') AS dt_ultimo_pedido,
|
||||
(CURRENT_DATE - up.dt_max::date) AS dias_sem_pedido,
|
||||
(up.dt_max IS NOT NULL) AS comprou_antes,
|
||||
ct.whatsapp
|
||||
FROM vw_clientes c
|
||||
LEFT JOIN ultimo_pedido up ON up.id_cliente = c.id_cliente
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT TRIM(whatsapp) AS whatsapp
|
||||
FROM sar.vw_contatos
|
||||
WHERE id_corrent = c.id_cliente
|
||||
AND whatsapp IS NOT NULL AND TRIM(whatsapp) != ''
|
||||
AND ativo = 1
|
||||
LIMIT 1
|
||||
) ct ON true
|
||||
WHERE c.cod_vendedor = ${codVendedor}
|
||||
AND c.ativo = 1
|
||||
AND (up.dt_max IS NULL OR up.dt_max < '${cutoffStr}')
|
||||
ORDER BY up.dt_max ASC NULLS FIRST
|
||||
`);
|
||||
|
||||
const nomeRows = await prisma.$queryRawUnsafe<{ nome: string | null }[]>(
|
||||
`SELECT nome FROM vw_representantes WHERE codigo = ${codVendedor} LIMIT 1`,
|
||||
);
|
||||
|
||||
// Deduplica por idCliente — vw_clientes pode repetir o cliente por empresa.
|
||||
const seen = new Set<number>();
|
||||
const clientes = rows
|
||||
.filter((c) => {
|
||||
const id = Number(c.id_cliente);
|
||||
if (seen.has(id)) return false;
|
||||
seen.add(id);
|
||||
return true;
|
||||
})
|
||||
.map((c) => ({
|
||||
idCliente: Number(c.id_cliente),
|
||||
nome: c.nome,
|
||||
razao: c.razao ?? null,
|
||||
diasSemPedido: c.dias_sem_pedido != null ? Number(c.dias_sem_pedido) : 999,
|
||||
ultimoPedido: c.dt_ultimo_pedido ?? null,
|
||||
comprouAntes: Boolean(c.comprou_antes),
|
||||
whatsapp: c.whatsapp ?? null,
|
||||
}));
|
||||
|
||||
return { codVendedor, nomeVendedor: nomeRows[0]?.nome ?? null, clientes };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
ForbiddenException,
|
||||
Get,
|
||||
HttpCode,
|
||||
Param,
|
||||
@@ -11,17 +10,13 @@ import {
|
||||
Post,
|
||||
Query,
|
||||
} from '@nestjs/common';
|
||||
import { ClsService } from 'nestjs-cls';
|
||||
import { createZodDto } from 'nestjs-zod';
|
||||
import {
|
||||
AprovarPedidoSchema,
|
||||
CancelPedidoSchema,
|
||||
CreatePedidoSchema,
|
||||
UpdatePedidoSchema,
|
||||
PedidoErpConsultaQuerySchema,
|
||||
PedidoListQuerySchema,
|
||||
RecusarPedidoSchema,
|
||||
type AprovarPedido,
|
||||
type CancelPedido,
|
||||
type CreatePedido,
|
||||
type UpdatePedido,
|
||||
@@ -30,25 +25,18 @@ import {
|
||||
type PedidoErpConsultaResponse,
|
||||
type PedidoListQuery,
|
||||
type PedidoListResponse,
|
||||
type RecusarPedido,
|
||||
} from '@sar/api-interface';
|
||||
import type { WorkspaceClsStore } from '../workspace/workspace.types';
|
||||
import { OrdersService } from './orders.service';
|
||||
|
||||
class PedidoListQueryDto extends createZodDto(PedidoListQuerySchema) {}
|
||||
class CreatePedidoDto extends createZodDto(CreatePedidoSchema) {}
|
||||
class UpdatePedidoDto extends createZodDto(UpdatePedidoSchema) {}
|
||||
class CancelPedidoDto extends createZodDto(CancelPedidoSchema) {}
|
||||
class AprovarPedidoDto extends createZodDto(AprovarPedidoSchema) {}
|
||||
class RecusarPedidoDto extends createZodDto(RecusarPedidoSchema) {}
|
||||
class PedidoErpConsultaQueryDto extends createZodDto(PedidoErpConsultaQuerySchema) {}
|
||||
|
||||
@Controller({ path: 'orders' })
|
||||
export class OrdersController {
|
||||
constructor(
|
||||
private readonly orders: OrdersService,
|
||||
private readonly cls: ClsService<WorkspaceClsStore>,
|
||||
) {}
|
||||
constructor(private readonly orders: OrdersService) {}
|
||||
|
||||
@Get()
|
||||
list(@Query() query: PedidoListQueryDto): Promise<PedidoListResponse> {
|
||||
@@ -68,28 +56,6 @@ export class OrdersController {
|
||||
return this.orders.transmit(id);
|
||||
}
|
||||
|
||||
@Patch(':id/approve')
|
||||
approve(
|
||||
@Param('id', ParseUUIDPipe) id: string,
|
||||
@Body() body: AprovarPedidoDto,
|
||||
): Promise<PedidoDetail> {
|
||||
const role = this.cls.get('role') ?? 'rep';
|
||||
if (role === 'rep') throw new ForbiddenException('Apenas supervisores podem aprovar pedidos');
|
||||
const parsed = AprovarPedidoSchema.parse(body) as AprovarPedido;
|
||||
return this.orders.approve(id, parsed);
|
||||
}
|
||||
|
||||
@Patch(':id/reject')
|
||||
reject(
|
||||
@Param('id', ParseUUIDPipe) id: string,
|
||||
@Body() body: RecusarPedidoDto,
|
||||
): Promise<PedidoDetail> {
|
||||
const role = this.cls.get('role') ?? 'rep';
|
||||
if (role === 'rep') throw new ForbiddenException('Apenas supervisores podem recusar pedidos');
|
||||
const parsed = RecusarPedidoSchema.parse(body) as RecusarPedido;
|
||||
return this.orders.reject(id, parsed);
|
||||
}
|
||||
|
||||
@Patch(':id/cancel')
|
||||
cancel(
|
||||
@Param('id', ParseUUIDPipe) id: string,
|
||||
|
||||
@@ -2,7 +2,6 @@ import { BadRequestException, Injectable, NotFoundException } from '@nestjs/comm
|
||||
import { ClsService } from 'nestjs-cls';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import type {
|
||||
AprovarPedido,
|
||||
CancelPedido,
|
||||
CreatePedido,
|
||||
UpdatePedido,
|
||||
@@ -13,16 +12,14 @@ import type {
|
||||
PedidoListQuery,
|
||||
PedidoListResponse,
|
||||
PedidoSummary,
|
||||
RecusarPedido,
|
||||
} from '@sar/api-interface';
|
||||
import type { WorkspaceClsStore } from '../workspace/workspace.types';
|
||||
import { getTeamCodes } from '../workspace/team-scope.util';
|
||||
import { NotificationsService } from '../notifications/notifications.service';
|
||||
|
||||
// Situa SAR: 0=Orçamento, 1=Ag.Aprovação, 2=Confirmado, 3=Cancelado, 4=Faturado
|
||||
// Situa SIG: 1=Pendente, 2=Liberado, 5=Cancelado, 4=Faturado
|
||||
// Situa SAR: 0=Orçamento, 2=Confirmado, 3=Cancelado, 4=Faturado
|
||||
// Situa SIG: 1=Pendente, 2=Liberado, 5=Cancelado, 4=Faturado
|
||||
const SITUA_ORCAMENTO = 0;
|
||||
const SITUA_PENDENTE = 1;
|
||||
const SITUA_APROVADO = 2;
|
||||
const SITUA_CANCELADO = 3;
|
||||
|
||||
@@ -290,20 +287,6 @@ export class OrdersService {
|
||||
return { data, total, page, limit };
|
||||
}
|
||||
|
||||
// Supervisor só age sobre pedidos da própria equipe; gerente/admin passam
|
||||
// direto. NotFound (não Forbidden) para não revelar pedidos de outras equipes.
|
||||
private async assertPedidoDaEquipe(codVendedorPedido: number, idPedido: string): Promise<void> {
|
||||
const role = this.cls.get('role');
|
||||
if (role !== 'supervisor') return;
|
||||
const prisma = this.cls.get('prisma');
|
||||
if (!prisma) throw new Error('prisma não disponível no CLS');
|
||||
const userId = this.cls.get('userId') ?? '0';
|
||||
const team = await getTeamCodes(prisma, parseInt(userId, 10));
|
||||
if (!team.includes(codVendedorPedido)) {
|
||||
throw new NotFoundException(`Pedido ${idPedido} não encontrado`);
|
||||
}
|
||||
}
|
||||
|
||||
async findOne(id: string): Promise<PedidoDetail> {
|
||||
const prisma = this.cls.get('prisma');
|
||||
if (!prisma) throw new Error('prisma não disponível no CLS');
|
||||
@@ -690,115 +673,6 @@ export class OrdersService {
|
||||
}
|
||||
}
|
||||
|
||||
async approve(id: string, dto: AprovarPedido): Promise<PedidoDetail> {
|
||||
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 userId = this.cls.get('userId') ?? '0';
|
||||
const codVendedor = parseInt(userId, 10);
|
||||
|
||||
const pedido = await prisma.pedido.findFirst({ where: { id, idEmpresa } });
|
||||
if (!pedido) throw new NotFoundException(`Pedido ${id} não encontrado`);
|
||||
if (pedido.situa !== SITUA_PENDENTE)
|
||||
throw new BadRequestException(
|
||||
`Pedido não está aguardando aprovação (situa: ${pedido.situa})`,
|
||||
);
|
||||
await this.assertPedidoDaEquipe(pedido.codVendedor, id);
|
||||
|
||||
const now = new Date();
|
||||
const newDescontoPerc = dto.descontoPerc ?? Number(pedido.descontoPerc);
|
||||
const newTotal =
|
||||
Math.round(Number(pedido.totalProdutos) * (1 - newDescontoPerc / 100) * 100) / 100;
|
||||
|
||||
await prisma.pedido.update({
|
||||
where: { id },
|
||||
data: {
|
||||
situa: SITUA_APROVADO,
|
||||
descontoPerc: newDescontoPerc,
|
||||
total: newTotal,
|
||||
aprovadoPor: codVendedor,
|
||||
aprovadoEm: now,
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.historicoPedido.create({
|
||||
data: {
|
||||
idPedido: id,
|
||||
situaAnterior: SITUA_PENDENTE,
|
||||
situaNova: SITUA_APROVADO,
|
||||
changedBy: codVendedor,
|
||||
changedAt: now,
|
||||
nota: dto.nota ?? null,
|
||||
},
|
||||
});
|
||||
|
||||
const final = await prisma.pedido.findUniqueOrThrow({
|
||||
where: { id },
|
||||
include: {
|
||||
itens: { orderBy: { ordem: 'asc' } },
|
||||
historico: { orderBy: { changedAt: 'asc' } },
|
||||
},
|
||||
});
|
||||
|
||||
void this.notifications.notifyUser(String(pedido.codVendedor), {
|
||||
title: 'Pedido aprovado',
|
||||
body: `${final.numPedSar} aprovado${dto.descontoPerc !== undefined ? ` com ${newDescontoPerc}% de desconto` : ''}`,
|
||||
url: `/pedidos/${id}`,
|
||||
});
|
||||
|
||||
return this.mapDetail(final);
|
||||
}
|
||||
|
||||
async reject(id: string, dto: RecusarPedido): Promise<PedidoDetail> {
|
||||
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 userId = this.cls.get('userId') ?? '0';
|
||||
const codVendedor = parseInt(userId, 10);
|
||||
|
||||
const pedido = await prisma.pedido.findFirst({ where: { id, idEmpresa } });
|
||||
if (!pedido) throw new NotFoundException(`Pedido ${id} não encontrado`);
|
||||
if (pedido.situa !== SITUA_PENDENTE)
|
||||
throw new BadRequestException(
|
||||
`Pedido não está aguardando aprovação (situa: ${pedido.situa})`,
|
||||
);
|
||||
await this.assertPedidoDaEquipe(pedido.codVendedor, id);
|
||||
|
||||
const now = new Date();
|
||||
|
||||
await prisma.pedido.update({
|
||||
where: { id },
|
||||
data: { situa: SITUA_CANCELADO, motivoRecusa: dto.motivo },
|
||||
});
|
||||
|
||||
await prisma.historicoPedido.create({
|
||||
data: {
|
||||
idPedido: id,
|
||||
situaAnterior: SITUA_PENDENTE,
|
||||
situaNova: SITUA_CANCELADO,
|
||||
changedBy: codVendedor,
|
||||
changedAt: now,
|
||||
nota: dto.motivo,
|
||||
},
|
||||
});
|
||||
|
||||
const final = await prisma.pedido.findUniqueOrThrow({
|
||||
where: { id },
|
||||
include: {
|
||||
itens: { orderBy: { ordem: 'asc' } },
|
||||
historico: { orderBy: { changedAt: 'asc' } },
|
||||
},
|
||||
});
|
||||
|
||||
void this.notifications.notifyUser(String(pedido.codVendedor), {
|
||||
title: 'Pedido recusado',
|
||||
body: `${final.numPedSar}: ${dto.motivo}`,
|
||||
url: `/pedidos/${id}`,
|
||||
});
|
||||
|
||||
return this.mapDetail(final);
|
||||
}
|
||||
|
||||
// Edita um orçamento (situa 0). Depois de transmitido não é mais editável.
|
||||
// Substitui itens e recalcula totais; alçada valida contra o dono do pedido.
|
||||
async update(id: string, dto: UpdatePedido): Promise<PedidoDetail> {
|
||||
|
||||
Reference in New Issue
Block a user