feat(api,web): c2 consulta de clientes — list + search + auth flow
prisma: modelo Client + migração 20260527225728_add_client + seed dev (10 clientes)
api: GET /clients (list, busca, filtro atividade/financeiro, paginação) + GET /clients/:id
rep vê carteira própria; supervisor/admin vê tudo; activityStatus calculado de lastOrderAt
@sar/api-interface: ClientSummarySchema, ClientDetailSchema, ClientListResponseSchema
web: ClientsPage (tabela AntD, busca, filtro), DevLogin (token dev), authStore, Bearer no apiFetch
oq-4 resolvida: creditLimit gerenciado no SAR
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
132
apps/api/src/app/clients/clients.service.ts
Normal file
132
apps/api/src/app/clients/clients.service.ts
Normal file
@@ -0,0 +1,132 @@
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { ClsService } from 'nestjs-cls';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import type {
|
||||
ClientDetail,
|
||||
ClientListQuery,
|
||||
ClientListResponse,
|
||||
ClientSummary,
|
||||
ActivityStatus,
|
||||
} from '@sar/api-interface';
|
||||
import type { WorkspaceClsStore } from '../workspace/workspace.types';
|
||||
|
||||
// Thresholds de atividade (FR-2.3). Configuráveis por workspace 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);
|
||||
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;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class ClientsService {
|
||||
constructor(private readonly cls: ClsService<WorkspaceClsStore>) {}
|
||||
|
||||
async list(query: ClientListQuery, userId: string, role: string): Promise<ClientListResponse> {
|
||||
const prisma = this.cls.get('prisma');
|
||||
if (!prisma) throw new Error('prisma não disponível no CLS');
|
||||
|
||||
const { q, status, financialStatus, page, limit } = query;
|
||||
const skip = (page - 1) * limit;
|
||||
|
||||
// Rep vê apenas sua carteira; supervisor/manager/admin vê tudo (FR-2.1).
|
||||
const repFilter: Prisma.ClientWhereInput = role === 'rep' ? { repId: userId } : {};
|
||||
|
||||
const searchFilter: Prisma.ClientWhereInput = q
|
||||
? {
|
||||
OR: [
|
||||
{ name: { contains: q, mode: 'insensitive' } },
|
||||
{ tradeName: { contains: q, mode: 'insensitive' } },
|
||||
{ taxId: { contains: q } },
|
||||
],
|
||||
}
|
||||
: {};
|
||||
|
||||
const financialFilter: Prisma.ClientWhereInput = financialStatus ? { financialStatus } : {};
|
||||
|
||||
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,
|
||||
}));
|
||||
|
||||
const filtered = status ? mapped.filter((c) => c.activityStatus === status) : mapped;
|
||||
|
||||
return { data: filtered, total, page, limit };
|
||||
}
|
||||
|
||||
async findOne(id: string, userId: string, role: string): Promise<ClientDetail> {
|
||||
const prisma = this.cls.get('prisma');
|
||||
if (!prisma) throw new Error('prisma não disponível no CLS');
|
||||
|
||||
const repFilter: Prisma.ClientWhereInput = role === 'rep' ? { repId: userId } : {};
|
||||
|
||||
const client = await prisma.client.findFirst({
|
||||
where: { id, deletedAt: null, ...repFilter },
|
||||
});
|
||||
|
||||
if (!client) throw new NotFoundException(`Cliente ${id} 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(),
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user