Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -285,7 +285,7 @@ Cada domínio expõe:
"images": []
}
```
- `POST /cars|boats|aircrafts/import-csv` — aceita `.xlsx` (template) ou `.csv`. Só `valor` e `currency` (`BRL`/`USD`) são obrigatórios. Sem `identificador`, o import gera `auto-<hash>` a partir dos campos descritivos da linha (sem valor/moeda/folder_url), então reimportar a mesma linha atualiza em vez de duplicar. Na criação, campos vazios viram padrão: `marca` = tipo (Carro/Lancha/Aeronave), `modelo` = identificador, `estado` = "não informado", `ano` = null; no update, campos vazios não sobrescrevem o que existe.
- `POST /cars|boats|aircrafts/import-csv` — aceita `.xlsx` (template) ou `.csv`. Só `valor` e `currency` (`BRL`/`USD`) são obrigatórios. Sem `identificador`, o import gera `auto-<hash>` a partir da linha inteira, inclusive `valor`, `currency` e `folder_url` (normalizados: `450000` = `450000.00`; link da pasta comparado pelo ID do Drive). Reimportar a linha idêntica atualiza o mesmo produto (e reativa se estiver desativado); mudar qualquer dado, inclusive o preço, cria outro produto. Para atualizar uma linha depois, preencha o `identificador`. A prévia (`impact.autoIdentifierNewItems`/`autoIdentifierReactivatedItems`) e o resultado (`autoIdentifierCreatedCount`/`autoIdentifierReactivatedCount`) mostram quantas linhas sem identificador criam ou reativam produto. `folder_url` precisa ser link ou ID de pasta do Drive; no `.xlsx`, hyperlink e fórmula `HYPERLINK` valem pelo destino (só nessa coluna). Na criação, campos vazios viram padrão: `marca` = tipo (Carro/Lancha/Aeronave), `modelo` = identificador, `estado` = "não informado", `ano` = null; no update, campos vazios não sobrescrevem o que existe.
- payload:
```json
{
Expand Down Expand Up @@ -357,7 +357,7 @@ Cada domínio expõe:
"updated": true
}
```
- `PATCH /cars|boats|aircrafts/:id/specialist` (somente ADMIN) — transfere o produto para outro especialista ativo da mesma especialidade. `409 PRODUCT_HAS_OPEN_PROCESSES` se houver processo não concluído/rejeitado ou agendamento pendente/agendado; processos antigos mantêm o especialista original. Auditado como `PRODUCT_TRANSFER`.
- `PATCH /cars|boats|aircrafts/:id/specialist` (somente ADMIN) — transfere o produto para outro especialista ativo da mesma especialidade. `409 PRODUCT_HAS_OPEN_PROCESSES` se houver processo não concluído/rejeitado ou agendamento pendente/agendado; `409 PRODUCT_IDENTIFIER_CONFLICT` se o especialista de destino já tiver produto com o mesmo `identificador`; processos antigos mantêm o especialista original. Auditado como `PRODUCT_TRANSFER`.
- payload:
```json
{
Expand Down
12 changes: 12 additions & 0 deletions backend/src/features/contracts/contracts.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,18 @@ describe('ContractsService — prefillContract', () => {
expect(result.product.price).toBe(120000);
});

it('keeps the year empty when the product was imported without one', async () => {
const prisma = mkPrisma();
prisma.process.findUnique.mockResolvedValue(
processFixture({ car: { ...carFixture, ano: null } }),
);
const service = mkSvc(prisma, mkPlatformCompanyService(10));

const result = await service.prefillContract('process-1', 'specialist-1');

expect(result.product.year).toBeNull();
});

it('rejects contract prefill without a negotiation snapshot', async () => {
const prisma = mkPrisma();
prisma.process.findUnique.mockResolvedValue(
Expand Down
8 changes: 4 additions & 4 deletions backend/src/features/contracts/contracts.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -733,7 +733,7 @@ export class ContractsService {
id: string;
brand: string;
model: string;
year: number;
year: number | null;
price: number;
registration_id?: string;
serial_number?: string;
Expand All @@ -760,7 +760,7 @@ export class ContractsService {
id: processData.car.id,
brand: processData.car.marca || '',
model: processData.car.modelo || '',
year: processData.car.ano || 0,
year: processData.car.ano ?? null,
price: frozenProductPrice,
registration_id: '', // Placa - preenchido pelo especialista
serial_number: '', // Chassi - preenchido pelo especialista
Expand All @@ -787,7 +787,7 @@ export class ContractsService {
id: processData.boat.id,
brand: processData.boat.marca || '',
model: processData.boat.modelo || '',
year: processData.boat.ano || 0,
year: processData.boat.ano ?? null,
price: frozenProductPrice,
registration_id: '', // Inscrição - preenchido pelo especialista
serial_number: '', // Hull number - preenchido pelo especialista
Expand All @@ -814,7 +814,7 @@ export class ContractsService {
id: processData.aircraft.id,
brand: processData.aircraft.marca || '',
model: processData.aircraft.modelo || '',
year: processData.aircraft.ano || 0,
year: processData.aircraft.ano ?? null,
price: frozenProductPrice,
registration_id: '', // Prefixo - preenchido pelo especialista
serial_number: '', // Serial number - preenchido pelo especialista
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ export class PrefillContractResponseDto {
id: string;
brand: string;
model: string;
year: number;
year: number | null; // null quando o produto foi importado sem ano
price: number;
registration_id?: string; // placa/inscrição/prefixo
serial_number?: string; // chassi/hull_number/serial
Expand Down
16 changes: 16 additions & 0 deletions backend/src/features/drive-import/drive-folder-id.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/**
* ID da pasta do Google Drive a partir do link (`/folders/<id>` ou `?id=<id>`)
* ou do próprio ID. `null` quando não é nenhum dos dois.
*
* Variações do mesmo link (`?usp=sharing`, `/u/0/`) dão o mesmo ID.
*/
export function extractDriveFolderId(urlOrId: string): string | null {
const trimmed = urlOrId.trim();
const fromFolderPath = trimmed.match(/\/folders\/([a-zA-Z0-9_-]{10,})/)?.[1];
if (fromFolderPath) return fromFolderPath;

const fromQuery = trimmed.match(/[?&]id=([a-zA-Z0-9_-]{10,})/)?.[1];
if (fromQuery) return fromQuery;

return /^[a-zA-Z0-9_-]{10,}$/.test(trimmed) ? trimmed : null;
}
17 changes: 3 additions & 14 deletions backend/src/features/drive-import/drive-import.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { PrismaService } from 'src/prisma/prisma.service';
import { S3Service } from 'src/aws/s3.service';
import { ImportDriveImagesDto } from './dto/import-drive-images.dto';
import { UserEntity } from 'src/auth/entities/user.entity';
import { extractDriveFolderId } from './drive-folder-id';

type DriveFile = {
id: string;
Expand Down Expand Up @@ -426,20 +427,8 @@ export class DriveImportService {
}

private extractFolderId(urlOrId: string): string {
const trimmed = urlOrId.trim();
const folderRegex = /\/folders\/([a-zA-Z0-9_-]{10,})/;
const idRegex = /[?&]id=([a-zA-Z0-9_-]{10,})/;

const fromFolderPath = trimmed.match(folderRegex)?.[1];
if (fromFolderPath) return fromFolderPath;

const fromQuery = trimmed.match(idRegex)?.[1];
if (fromQuery) return fromQuery;

if (/^[a-zA-Z0-9_-]{10,}$/.test(trimmed)) {
return trimmed;
}

const folderId = extractDriveFolderId(urlOrId);
if (folderId) return folderId;
throw new BadRequestException('Link/ID da pasta do Google Drive inválido');
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -448,7 +448,9 @@ describe('ProductImportJobsService', () => {

it('exige confirmação explícita para sincronizar', async () => {
const xlsxImportService = {
parseCsv: jest.fn().mockReturnValue({ rows: [validCarRow] }),
parseCsv: jest
.fn()
.mockReturnValue({ rows: [validCarRow], rowNumbers: [2] }),
validateStructure: jest.fn().mockReturnValue({ valid: true }),
} as any;
const service = new ProductImportJobsService(
Expand Down Expand Up @@ -481,6 +483,7 @@ describe('ProductImportJobsService', () => {
const xlsxImportService = {
parseCsv: jest.fn().mockReturnValue({
rows: [validCarRow, { ...validCarRow, modelo: 'Duplicado' }],
rowNumbers: [2, 3],
}),
validateStructure: jest.fn().mockReturnValue({ valid: true }),
} as any;
Expand All @@ -502,7 +505,9 @@ describe('ProductImportJobsService', () => {

it('exige token da prévia mesmo quando a sincronização foi confirmada', async () => {
const xlsxImportService = {
parseCsv: jest.fn().mockReturnValue({ rows: [validCarRow] }),
parseCsv: jest
.fn()
.mockReturnValue({ rows: [validCarRow], rowNumbers: [2] }),
validateStructure: jest.fn().mockReturnValue({ valid: true }),
} as any;
const prisma = {
Expand Down Expand Up @@ -554,7 +559,9 @@ describe('ProductImportJobsService', () => {

it('calcula o impacto da sincronização antes de criar o job', async () => {
const xlsxImportService = {
parseCsv: jest.fn().mockReturnValue({ rows: [validCarRow] }),
parseCsv: jest
.fn()
.mockReturnValue({ rows: [validCarRow], rowNumbers: [2] }),
validateStructure: jest.fn().mockReturnValue({ valid: true }),
} as any;
const prisma = {
Expand Down Expand Up @@ -611,7 +618,9 @@ describe('ProductImportJobsService', () => {
catalogReads.shift() ?? [productA, productC],
);
const xlsxImportService = {
parseCsv: jest.fn().mockReturnValue({ rows: [validCarRow] }),
parseCsv: jest
.fn()
.mockReturnValue({ rows: [validCarRow], rowNumbers: [2] }),
validateStructure: jest.fn().mockReturnValue({ valid: true }),
} as any;
const prisma = {
Expand Down Expand Up @@ -680,7 +689,9 @@ describe('ProductImportJobsService', () => {
{ id: '22222222-2222-4222-8222-222222222222', identificador: 'STALE-B' },
];
const xlsxImportService = {
parseCsv: jest.fn().mockReturnValue({ rows: [validCarRow] }),
parseCsv: jest
.fn()
.mockReturnValue({ rows: [validCarRow], rowNumbers: [2] }),
validateStructure: jest.fn().mockReturnValue({ valid: true }),
} as any;
const findMany = jest.fn().mockImplementation(async () => [...activeProducts]);
Expand Down Expand Up @@ -843,49 +854,185 @@ describe('ProductImportJobsService', () => {
new XlsxImportService(),
{} as any,
);
return (service as any).parseImportRows(
const { rows } = await (service as any).parseImportRows(
Buffer.from(lines.join('\n'), 'utf-8'),
ProductType.CAR,
mode,
);
return rows;
};

it('a mesma linha gera o mesmo identificador, mesmo com outro preço', async () => {
const [first] = await parse(['marca;modelo;valor;currency', 'BMW;X5;450000;BRL']);
const [repriced] = await parse(['marca;modelo;valor;currency', 'bmw;X5;399000;USD']);
const [other] = await parse(['marca;modelo;valor;currency', 'BMW;X6;450000;BRL']);
it('a mesma linha gera o mesmo identificador em importações diferentes', async () => {
const header = 'marca;modelo;valor;currency;folder_url';
const [first] = await parse([header, 'BMW;X5;450000;BRL;https://drive.google.com/drive/folders/1AbCdEfGhIjK']);
const [again] = await parse([header, 'bmw;X5;450000;brl;https://drive.google.com/drive/folders/1AbCdEfGhIjK']);
const [other] = await parse([header, 'BMW;X6;450000;BRL;https://drive.google.com/drive/folders/1AbCdEfGhIjK']);

expect(first.identificador).toMatch(/^auto-[0-9a-f]{12}$/);
expect(repriced.identificador).toBe(first.identificador);
expect(again.identificador).toBe(first.identificador);
expect(other.identificador).not.toBe(first.identificador);
});

it('unidades que só diferem no preço, na moeda ou nas fotos não se fundem', async () => {
const header = 'marca;modelo;ano;valor;currency;folder_url';
const [base] = await parse([
header,
'BMW;X5;2023;450000;BRL;https://drive.google.com/drive/folders/1AbCdEfGhIjK',
]);
const variants = await Promise.all(
[
'BMW;X5;2023;500000;BRL;https://drive.google.com/drive/folders/1AbCdEfGhIjK',
'BMW;X5;2023;450000;USD;https://drive.google.com/drive/folders/1AbCdEfGhIjK',
'BMW;X5;2023;450000;BRL;https://drive.google.com/drive/folders/2ZyXwVuTsRqP',
].map(async (line) => (await parse([header, line]))[0]),
);

for (const variant of variants) {
expect(variant.identificador).not.toBe(base.identificador);
}
});

it('linhas só com valor e moeda se distinguem pelo preço', async () => {
const rows = await parse(['valor;currency', '100;BRL', '200;BRL']);

expect(rows[0].identificador).not.toBe(rows[1].identificador);
});

it('estado com maiúscula ou acento vira o valor do formulário', async () => {
const rows = await parse([
'identificador;estado;valor;currency',
'A;Seminovo;1;BRL',
'B;Coleção;1;BRL',
'C;usado;1;BRL',
]);

expect(rows.map((row: any) => row.estado)).toEqual([
'seminovo',
'colecao',
'usado',
]);
});

it('mesmo preço ou mesma pasta escritos de outro jeito geram o mesmo id', async () => {
const header = 'marca;valor;currency;folder_url';
const folder = 'https://drive.google.com/drive/folders/1AbCdEfGhIjK';
const [base] = await parse([header, `BMW;450000;BRL;${folder}`]);
const [variant] = await parse([
header,
`BMW;450000.00;BRL;${folder}?usp=sharing`,
]);

expect(variant.identificador).toBe(base.identificador);
});

it('recusa folder_url que não é link de pasta do Drive', async () => {
await expect(
parse([
'identificador;valor;currency;folder_url',
'A;1;BRL;https://drive.google.com/drive/folders/1AbCdEfGhIjK',
'B;1;BRL;Fotos',
]),
).rejects.toThrow(/folder_url.*linhas 3\./);
});

it('conta linhas sem identificador que criam ou reativam produto', () => {
const service = new ProductImportJobsService(
{} as any,
{} as any,
{} as any,
);
const impact = (service as any).autoIdentifierImpact(
[
{ identificador: 'auto-novo' },
{ identificador: 'auto-ativo' },
{ identificador: 'auto-inativo' },
{ identificador: 'MANUAL-1' },
],
[
{ identificador: 'auto-ativo', isActive: true },
{ identificador: 'auto-inativo', isActive: false },
{ identificador: 'MANUAL-1', isActive: false },
],
);

expect(impact).toEqual({
autoIdentifierNewItems: 1,
autoIdentifierReactivatedItems: 1,
});
});

it('resultado informa produtos criados e reativados sem identificador', () => {
const service = new ProductImportJobsService(
{} as any,
{} as any,
{} as any,
);
const item = (overrides: Record<string, unknown>) => ({
row_number: 2,
status: 'COMPLETED',
action: 'CREATED',
product_id: 'p',
error_message: null,
warnings: null,
...overrides,
});
const result = (service as any).buildImportResponse([
item({ payload: { identificador: 'auto-a' } }),
item({
action: 'UPDATED',
payload: {
identificador: 'auto-b',
__productImportEffect: { reactivated: true },
},
}),
item({ payload: { identificador: 'MANUAL-1' } }),
]);

expect(result).toMatchObject({
autoIdentifierCreatedCount: 1,
autoIdentifierReactivatedCount: 1,
});
});

it('identificador informado é mantido', async () => {
const [row] = await parse(['identificador;valor;currency', 'BMW-1;100;BRL']);
const [row] = await parse([
'identificador;valor;currency',
'BMW-1;100;BRL',
]);

expect(row.identificador).toBe('BMW-1');
});

it('rejeita linhas sem identificador com os mesmos dados', async () => {
await expect(
parse(['marca;valor;currency', 'BMW;100;BRL', 'BMW;200;BRL']),
parse(['marca;valor;currency', 'BMW;100;BRL', 'BMW;100;BRL']),
).rejects.toThrow(/sem identificador com os mesmos dados/);
});

it('sincronização exige identificador em todas as linhas', async () => {
const lines = ['identificador;valor;currency', 'BMW-1;100;BRL', ';200;BRL'];
const lines = [
'identificador;valor;currency',
'BMW-1;100;BRL',
';200;BRL',
];

await expect(parse(lines, 'SYNCHRONIZE')).rejects.toThrow(
/preencha o identificador.*linhas 3\)/,
);
await expect(parse(lines)).resolves.toHaveLength(2);
});

it('aponta a linha real do arquivo quando há linhas em branco', async () => {
const lines = [
'identificador;valor;currency',
'BMW-1;100;BRL',
'',
'BMW-2;150;BRL',
';200;BRL',
];

await expect(parse(lines, 'SYNCHRONIZE')).rejects.toThrow(/linhas 5\)/);
});
});

it('lanca erro quando identificador vem vazio', async () => {
Expand Down
Loading