feat: adiciona suporte a múltiplas filiais no findOrders e testes TDD
- Adiciona suporte para buscar pedidos em múltiplas filiais separadas por vírgula (ex: codfilial=1,2,3) - Implementa testes TDD completos para o método findOrders seguindo padrão do projeto - Adiciona propriedade completedDeliveries ao OrderResponseDto para tipagem correta - Atualiza repository para suportar múltiplas filiais nos métodos findOrders e findOrdersByDeliveryDate
This commit is contained in:
@@ -1,30 +1,30 @@
|
||||
import { Injectable, HttpException, HttpStatus } from "@nestjs/common";
|
||||
import { EstLogTransferFilterDto, EstLogTransferResponseDto } from "../dto/estlogtransfer.dto";
|
||||
import { DataSource } from "typeorm";
|
||||
import { InjectDataSource } from "@nestjs/typeorm";
|
||||
import { FindOrdersDto } from "../dto/find-orders.dto";
|
||||
import { OrderItemDto } from "../dto/OrderItemDto";
|
||||
import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
|
||||
import {
|
||||
EstLogTransferFilterDto,
|
||||
EstLogTransferResponseDto,
|
||||
} from '../dto/estlogtransfer.dto';
|
||||
import { DataSource } from 'typeorm';
|
||||
import { InjectDataSource } from '@nestjs/typeorm';
|
||||
import { FindOrdersDto } from '../dto/find-orders.dto';
|
||||
import { OrderItemDto } from '../dto/OrderItemDto';
|
||||
import { CutItemDto } from '../dto/CutItemDto';
|
||||
import { OrderDeliveryDto } from '../dto/OrderDeliveryDto';
|
||||
import { OrderTransferDto } from '../dto/OrderTransferDto';
|
||||
import { OrderStatusDto } from '../dto/OrderStatusDto';
|
||||
import { InvoiceCheckDto } from '../dto/invoice-check.dto';
|
||||
import { LeadtimeDto } from "../dto/leadtime.dto";
|
||||
import { MarkData } from "../interface/markdata";
|
||||
import { DeliveryCompletedQuery } from "../dto/delivery-completed-query.dto";
|
||||
import { DeliveryCompleted } from "../dto/delivery-completed.dto";
|
||||
|
||||
import { LeadtimeDto } from '../dto/leadtime.dto';
|
||||
import { MarkData } from '../interface/markdata';
|
||||
import { DeliveryCompletedQuery } from '../dto/delivery-completed-query.dto';
|
||||
import { DeliveryCompleted } from '../dto/delivery-completed.dto';
|
||||
|
||||
@Injectable()
|
||||
export class OrdersRepository {
|
||||
constructor(
|
||||
@InjectDataSource("oracle") private readonly oracleDataSource: DataSource,
|
||||
@InjectDataSource("postgres") private readonly postgresDataSource: DataSource
|
||||
@InjectDataSource('oracle') private readonly oracleDataSource: DataSource,
|
||||
@InjectDataSource('postgres')
|
||||
private readonly postgresDataSource: DataSource,
|
||||
) {}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Busca log de transferência por ID do pedido
|
||||
* @param orderId - ID do pedido
|
||||
@@ -33,7 +33,7 @@ export class OrdersRepository {
|
||||
*/
|
||||
async estlogtransfer(
|
||||
orderId: number,
|
||||
filters?: EstLogTransferFilterDto
|
||||
filters?: EstLogTransferFilterDto,
|
||||
): Promise<EstLogTransferResponseDto[] | null> {
|
||||
if (!orderId || orderId <= 0) {
|
||||
throw new HttpException('OrderId inválido', HttpStatus.BAD_REQUEST);
|
||||
@@ -69,36 +69,30 @@ WHERE E.NUMPEDLOJA = :orderId
|
||||
`;
|
||||
|
||||
const parameters: any[] = [orderId];
|
||||
let paramIndex = 1;
|
||||
|
||||
if (filters?.dttransf) {
|
||||
sql += ` AND DTTRANSF = TO_DATE(:dttransf, 'YYYY-MM-DD')`;
|
||||
parameters.push(filters.dttransf);
|
||||
paramIndex++;
|
||||
}
|
||||
|
||||
if (filters?.codfilial) {
|
||||
sql += ` AND CODFILIAL = :codfilial`;
|
||||
parameters.push(filters.codfilial);
|
||||
paramIndex++;
|
||||
}
|
||||
|
||||
if (filters?.codfilialdest) {
|
||||
sql += ` AND CODFILIALDEST = :codfilialdest`;
|
||||
parameters.push(filters.codfilialdest);
|
||||
paramIndex++;
|
||||
}
|
||||
|
||||
if (filters?.numpedloja) {
|
||||
sql += ` AND NUMPEDLOJA = :numpedloja`;
|
||||
parameters.push(filters.numpedloja);
|
||||
paramIndex++;
|
||||
}
|
||||
|
||||
if (filters?.numpedtransf) {
|
||||
sql += ` AND NUMPEDTRANSF = :numpedtransf`;
|
||||
parameters.push(filters.numpedtransf);
|
||||
paramIndex++;
|
||||
}
|
||||
|
||||
sql += ` ORDER BY DTTRANSF DESC`;
|
||||
@@ -113,7 +107,7 @@ WHERE E.NUMPEDLOJA = :orderId
|
||||
* @returns Dados dos logs de transferência ou null se não encontrado
|
||||
*/
|
||||
async estlogtransfers(
|
||||
filters?: EstLogTransferFilterDto
|
||||
filters?: EstLogTransferFilterDto,
|
||||
): Promise<EstLogTransferResponseDto[] | null> {
|
||||
let sql = `
|
||||
SELECT
|
||||
@@ -145,51 +139,42 @@ WHERE 1=1
|
||||
`;
|
||||
|
||||
const parameters: any[] = [];
|
||||
let paramIndex = 0;
|
||||
|
||||
if (filters?.dttransf) {
|
||||
sql += ` AND DTTRANSF = TO_DATE(:dttransf, 'YYYY-MM-DD')`;
|
||||
parameters.push(filters.dttransf);
|
||||
paramIndex++;
|
||||
}
|
||||
|
||||
if (filters?.dttransfIni && filters?.dttransfEnd) {
|
||||
sql += ` AND DTTRANSF BETWEEN TO_DATE(:dttransfIni, 'YYYY-MM-DD') AND TO_DATE(:dttransfEnd, 'YYYY-MM-DD')`;
|
||||
parameters.push(filters.dttransfIni);
|
||||
parameters.push(filters.dttransfEnd);
|
||||
paramIndex += 2;
|
||||
} else if (filters?.dttransfIni) {
|
||||
sql += ` AND DTTRANSF >= TO_DATE(:dttransfIni, 'YYYY-MM-DD')`;
|
||||
parameters.push(filters.dttransfIni);
|
||||
paramIndex++;
|
||||
} else if (filters?.dttransfEnd) {
|
||||
sql += ` AND DTTRANSF <= TO_DATE(:dttransfEnd, 'YYYY-MM-DD')`;
|
||||
parameters.push(filters.dttransfEnd);
|
||||
paramIndex++;
|
||||
}
|
||||
|
||||
if (filters?.codfilial) {
|
||||
sql += ` AND CODFILIAL = :codfilial`;
|
||||
parameters.push(filters.codfilial);
|
||||
paramIndex++;
|
||||
}
|
||||
|
||||
if (filters?.codfilialdest) {
|
||||
sql += ` AND CODFILIALDEST = :codfilialdest`;
|
||||
parameters.push(filters.codfilialdest);
|
||||
paramIndex++;
|
||||
}
|
||||
|
||||
if (filters?.numpedloja) {
|
||||
sql += ` AND NUMPEDLOJA = :numpedloja`;
|
||||
parameters.push(filters.numpedloja);
|
||||
paramIndex++;
|
||||
}
|
||||
|
||||
if (filters?.numpedtransf) {
|
||||
sql += ` AND NUMPEDTRANSF = :numpedtransf`;
|
||||
parameters.push(filters.numpedtransf);
|
||||
paramIndex++;
|
||||
}
|
||||
|
||||
sql += ` ORDER BY DTTRANSF ASC`;
|
||||
@@ -198,13 +183,12 @@ WHERE 1=1
|
||||
return result.length > 0 ? result : null;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Retorna dados de um pedido específico cruzados com seu fechamento de caixa,
|
||||
* filtrados apenas pelo número do pedido. Retorna apenas um registro.
|
||||
*/
|
||||
|
||||
async findorderbymark(orderId: number): Promise<MarkData | null> {
|
||||
async findorderbymark(orderId: number): Promise<MarkData | null> {
|
||||
const sql = `
|
||||
SELECT p.MARCA, p.CODMARCA, p.ATIVO
|
||||
FROM PCMARCA p
|
||||
@@ -215,7 +199,6 @@ WHERE 1=1
|
||||
return results[0] || null;
|
||||
}
|
||||
|
||||
|
||||
async findOrderWithCheckoutByOrder(orderId: number): Promise<any | null> {
|
||||
const sql = `
|
||||
SELECT
|
||||
@@ -239,8 +222,6 @@ WHERE
|
||||
return results[0] || null;
|
||||
}
|
||||
|
||||
|
||||
|
||||
async findOrders(query: FindOrdersDto): Promise<any[]> {
|
||||
const queryRunner = this.oracleDataSource.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
@@ -395,26 +376,34 @@ WHERE
|
||||
const conditions: string[] = [];
|
||||
|
||||
if (query.codfilial) {
|
||||
conditions.push(`AND PCPEDC.CODFILIAL = :storeId`);
|
||||
const filiais = query.codfilial
|
||||
.split(',')
|
||||
.map((f) => f.trim())
|
||||
.filter((f) => f);
|
||||
if (filiais.length === 1) {
|
||||
conditions.push(`AND PCPEDC.CODFILIAL = :storeId`);
|
||||
} else {
|
||||
const filiaisList = filiais.join(',');
|
||||
conditions.push(`AND PCPEDC.CODFILIAL IN (${filiaisList})`);
|
||||
}
|
||||
}
|
||||
if (query.filialretira) {
|
||||
conditions.push(
|
||||
`AND EXISTS(SELECT 1 FROM PCPEDI WHERE PCPEDI.NUMPED = PCPEDC.NUMPED AND PCPEDI.CODFILIALRETIRA = :storeStockId)`
|
||||
`AND EXISTS(SELECT 1 FROM PCPEDI WHERE PCPEDI.NUMPED = PCPEDC.NUMPED AND PCPEDI.CODFILIALRETIRA = :storeStockId)`,
|
||||
);
|
||||
}
|
||||
if (query.sellerId) {
|
||||
const sellerIds = query.sellerId
|
||||
.split(",")
|
||||
.split(',')
|
||||
.map((s) => s.trim())
|
||||
.filter((s) => s)
|
||||
.join(",");
|
||||
.join(',');
|
||||
conditions.push(`AND PCPEDC.CODUSUR IN (${sellerIds})`);
|
||||
}
|
||||
if (query.customerId) {
|
||||
conditions.push(`AND PCPEDC.CODCLI = :customerId`);
|
||||
}
|
||||
|
||||
|
||||
if (query.billingId) {
|
||||
conditions.push(`AND PCPEDC.CODCOB = :billingId`);
|
||||
}
|
||||
@@ -423,7 +412,7 @@ WHERE
|
||||
}
|
||||
if (query.orderId) {
|
||||
conditions.push(
|
||||
`AND (PCPEDC.NUMPED = :orderId OR PCPEDC.NUMPEDENTFUT = :orderId)`
|
||||
`AND (PCPEDC.NUMPED = :orderId OR PCPEDC.NUMPEDENTFUT = :orderId)`,
|
||||
);
|
||||
}
|
||||
if (query.invoiceId) {
|
||||
@@ -431,27 +420,27 @@ WHERE
|
||||
}
|
||||
if (query.productId) {
|
||||
conditions.push(
|
||||
`AND EXISTS(SELECT 1 FROM PCPEDI WHERE PCPEDI.NUMPED = PCPEDC.NUMPED AND PCPEDI.CODPROD = :productId)`
|
||||
`AND EXISTS(SELECT 1 FROM PCPEDI WHERE PCPEDI.NUMPED = PCPEDC.NUMPED AND PCPEDI.CODPROD = :productId)`,
|
||||
);
|
||||
}
|
||||
if (query.createDateIni) {
|
||||
conditions.push(
|
||||
`AND PCPEDC.DATA >= TO_DATE(:createDateIni, 'YYYY-MM-DD')`
|
||||
`AND PCPEDC.DATA >= TO_DATE(:createDateIni, 'YYYY-MM-DD')`,
|
||||
);
|
||||
}
|
||||
if (query.createDateEnd) {
|
||||
conditions.push(
|
||||
`AND PCPEDC.DATA <= TO_DATE(:createDateEnd, 'YYYY-MM-DD')`
|
||||
`AND PCPEDC.DATA <= TO_DATE(:createDateEnd, 'YYYY-MM-DD')`,
|
||||
);
|
||||
}
|
||||
if (query.invoiceDateIni) {
|
||||
conditions.push(
|
||||
`AND PCPEDC.DTFAT >= TO_DATE(:invoiceDateIni, 'YYYY-MM-DD')`
|
||||
`AND PCPEDC.DTFAT >= TO_DATE(:invoiceDateIni, 'YYYY-MM-DD')`,
|
||||
);
|
||||
}
|
||||
if (query.invoiceDateEnd) {
|
||||
conditions.push(
|
||||
`AND PCPEDC.DTFAT <= TO_DATE(:invoiceDateEnd, 'YYYY-MM-DD')`
|
||||
`AND PCPEDC.DTFAT <= TO_DATE(:invoiceDateEnd, 'YYYY-MM-DD')`,
|
||||
);
|
||||
}
|
||||
if (query.shippimentId) {
|
||||
@@ -464,10 +453,14 @@ WHERE
|
||||
conditions.push(`AND PCMARCA.CODMARCA = :markId`);
|
||||
}
|
||||
if (query.markName) {
|
||||
conditions.push(`AND UPPER(PCMARCA.MARCA) LIKE UPPER('%' || :markName || '%')`);
|
||||
conditions.push(
|
||||
`AND UPPER(PCMARCA.MARCA) LIKE UPPER('%' || :markName || '%')`,
|
||||
);
|
||||
}
|
||||
if (query.hasPreBox === true) {
|
||||
conditions.push(`AND EXISTS (SELECT 1 FROM SEVEN.ESTLOGTRANSFCD WHERE NUMPEDLOJA = PCPEDC.NUMPED)`);
|
||||
conditions.push(
|
||||
`AND EXISTS (SELECT 1 FROM SEVEN.ESTLOGTRANSFCD WHERE NUMPEDLOJA = PCPEDC.NUMPED)`,
|
||||
);
|
||||
}
|
||||
|
||||
if (query.preBoxFilial) {
|
||||
@@ -501,25 +494,25 @@ WHERE
|
||||
|
||||
if (query.deliveryType) {
|
||||
const types = query.deliveryType
|
||||
.split(",")
|
||||
.split(',')
|
||||
.map((t) => `'${t}'`)
|
||||
.join(",");
|
||||
.join(',');
|
||||
conditions.push(
|
||||
`AND EXISTS(SELECT 1 FROM PCPEDI WHERE PCPEDI.NUMPED = PCPEDC.NUMPED AND PCPEDI.TIPOENTREGA IN (${types}))`
|
||||
`AND EXISTS(SELECT 1 FROM PCPEDI WHERE PCPEDI.NUMPED = PCPEDC.NUMPED AND PCPEDI.TIPOENTREGA IN (${types}))`,
|
||||
);
|
||||
}
|
||||
if (query.status) {
|
||||
const statusList = query.status
|
||||
.split(",")
|
||||
.split(',')
|
||||
.map((s) => `'${s}'`)
|
||||
.join(",");
|
||||
.join(',');
|
||||
conditions.push(`AND PCPEDC.POSICAO IN (${statusList})`);
|
||||
}
|
||||
if (query.type) {
|
||||
const types = query.type
|
||||
.split(",")
|
||||
.split(',')
|
||||
.map((t) => `'${t}'`)
|
||||
.join(",");
|
||||
.join(',');
|
||||
conditions.push(`AND PCPEDC.CONDVENDA IN (${types})`);
|
||||
}
|
||||
if (query.onlyPendingTransfer === true) {
|
||||
@@ -532,47 +525,56 @@ WHERE
|
||||
|
||||
if (query.statusTransfer) {
|
||||
const statusTransferList = query.statusTransfer
|
||||
.split(",")
|
||||
.split(',')
|
||||
.map((s) => s.trim());
|
||||
|
||||
const statusConditions = statusTransferList.map(status => {
|
||||
switch (status) {
|
||||
case 'Em Trânsito':
|
||||
return `(PCPEDC.CONDVENDA = 10 AND PCPEDC.POSICAO = 'F' AND
|
||||
const statusConditions = statusTransferList
|
||||
.map((status) => {
|
||||
switch (status) {
|
||||
case 'Em Trânsito':
|
||||
return `(PCPEDC.CONDVENDA = 10 AND PCPEDC.POSICAO = 'F' AND
|
||||
(SELECT COUNT(1) FROM PCNFENT, PCFILIAL
|
||||
WHERE PCFILIAL.CODIGO = PCPEDC.CODFILIAL
|
||||
AND PCFILIAL.CODFORNEC = PCNFENT.CODFORNEC
|
||||
AND PCNFENT.NUMNOTA = PCPEDC.NUMNOTA) = 0)`;
|
||||
case 'Em Separação':
|
||||
return `(PCPEDC.CONDVENDA = 10 AND PCPEDC.POSICAO = 'M')`;
|
||||
case 'Aguardando Separação':
|
||||
return `(PCPEDC.CONDVENDA = 10 AND PCPEDC.POSICAO IN ('L', 'P'))`;
|
||||
case 'Concluída':
|
||||
return `(PCPEDC.CONDVENDA = 10 AND
|
||||
case 'Em Separação':
|
||||
return `(PCPEDC.CONDVENDA = 10 AND PCPEDC.POSICAO = 'M')`;
|
||||
case 'Aguardando Separação':
|
||||
return `(PCPEDC.CONDVENDA = 10 AND PCPEDC.POSICAO IN ('L', 'P'))`;
|
||||
case 'Concluída':
|
||||
return `(PCPEDC.CONDVENDA = 10 AND
|
||||
(SELECT COUNT(1) FROM PCNFENT, PCFILIAL
|
||||
WHERE PCFILIAL.CODIGO = PCPEDC.CODFILIAL
|
||||
AND PCFILIAL.CODFORNEC = PCNFENT.CODFORNEC
|
||||
AND PCNFENT.NUMNOTA = PCPEDC.NUMNOTA) > 0)`;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}).filter(condition => condition !== null);
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
})
|
||||
.filter((condition) => condition !== null);
|
||||
|
||||
if (statusConditions.length > 0) {
|
||||
conditions.push(`AND (${statusConditions.join(' OR ')})`);
|
||||
}
|
||||
}
|
||||
|
||||
sql += "\n" + conditions.join("\n");
|
||||
sql += "\nGROUP BY PCPEDC.DATA, PCPEDC.CODFILIAL, PCPEDC.CODFILIALLOJA, PCPEDC.NUMPED, PCPEDC.CODCLI, PCPEDC.CODENDENTCLI, PCPEDC.CODPRACA, PCPEDC.CODUSUR, PCPEDC.CODUSUR3, PCPEDC.CODSUPERVISOR, PCPEDC.CONDVENDA, PCPEDC.VLATEND, PCPEDC.VLTOTAL, PCPEDC.DTENTREGA, PCPEDC.TIPOPRIORIDADEENTREGA, PCPEDC.NUMCAR, PCPEDC.DTLIBERA, PCPEDC.CODFUNCLIBERA, PCPEDC.NUMTRANSVENDA, PCPEDC.CODPLPAG, PCPEDC.CODCOB, PCPEDC.DTFAT, PCPEDC.HORAFAT, PCPEDC.MINUTOFAT, PCPEDC.NUMNOTA, PCPEDC.MOTIVOPOSICAO, PCPEDC.TOTPESO, PCPEDC.POSICAO, PCPEDC.DTFINALSEP, PCPEDC.NUMPEDENTFUT, PCPEDC.CODFORNECFRETE, PCPEDC.CODEMITENTE, PCCLIENT.CLIENTE, PCUSUARI.NOME, PCSUPERV.NOME, PCCARREG.DTSAIDA, PCCARREG.DATAMON, PCCARREG.DTFECHA, PCCARREG.CODFUNCFAT, PCNFSAID.CODEMITENTE, PCPLPAG.DESCRICAO, PCCOB.COBRANCA, PCNFSAID.DTCANHOTO, MOTORISTA.MATRICULA, MOTORISTA.NOME, PCVEICUL.DESCRICAO, PCVEICUL.PLACA, PCFORNEC.FORNECEDOR, PCPEDCTEMP.DTENTREGAORIG, ESTPARCEIRO.NOME";
|
||||
sql += "\nORDER BY PCPEDC.NUMPED DESC";
|
||||
sql += "\nFETCH FIRST 5000 ROWS ONLY";
|
||||
sql += '\n' + conditions.join('\n');
|
||||
sql +=
|
||||
'\nGROUP BY PCPEDC.DATA, PCPEDC.CODFILIAL, PCPEDC.CODFILIALLOJA, PCPEDC.NUMPED, PCPEDC.CODCLI, PCPEDC.CODENDENTCLI, PCPEDC.CODPRACA, PCPEDC.CODUSUR, PCPEDC.CODUSUR3, PCPEDC.CODSUPERVISOR, PCPEDC.CONDVENDA, PCPEDC.VLATEND, PCPEDC.VLTOTAL, PCPEDC.DTENTREGA, PCPEDC.TIPOPRIORIDADEENTREGA, PCPEDC.NUMCAR, PCPEDC.DTLIBERA, PCPEDC.CODFUNCLIBERA, PCPEDC.NUMTRANSVENDA, PCPEDC.CODPLPAG, PCPEDC.CODCOB, PCPEDC.DTFAT, PCPEDC.HORAFAT, PCPEDC.MINUTOFAT, PCPEDC.NUMNOTA, PCPEDC.MOTIVOPOSICAO, PCPEDC.TOTPESO, PCPEDC.POSICAO, PCPEDC.DTFINALSEP, PCPEDC.NUMPEDENTFUT, PCPEDC.CODFORNECFRETE, PCPEDC.CODEMITENTE, PCCLIENT.CLIENTE, PCUSUARI.NOME, PCSUPERV.NOME, PCCARREG.DTSAIDA, PCCARREG.DATAMON, PCCARREG.DTFECHA, PCCARREG.CODFUNCFAT, PCNFSAID.CODEMITENTE, PCPLPAG.DESCRICAO, PCCOB.COBRANCA, PCNFSAID.DTCANHOTO, MOTORISTA.MATRICULA, MOTORISTA.NOME, PCVEICUL.DESCRICAO, PCVEICUL.PLACA, PCFORNEC.FORNECEDOR, PCPEDCTEMP.DTENTREGAORIG, ESTPARCEIRO.NOME';
|
||||
sql += '\nORDER BY PCPEDC.NUMPED DESC';
|
||||
sql += '\nFETCH FIRST 5000 ROWS ONLY';
|
||||
|
||||
const parameters: any = {};
|
||||
|
||||
// Add parameters for bind variables
|
||||
if (query.codfilial) {
|
||||
parameters.storeId = query.codfilial;
|
||||
const filiais = query.codfilial
|
||||
.split(',')
|
||||
.map((f) => f.trim())
|
||||
.filter((f) => f);
|
||||
if (filiais.length === 1) {
|
||||
parameters.storeId = filiais[0];
|
||||
}
|
||||
}
|
||||
if (query.filialretira) {
|
||||
parameters.storeStockId = query.filialretira;
|
||||
@@ -793,25 +795,34 @@ WHERE
|
||||
// Filtros específicos para data de entrega
|
||||
if (query.deliveryDateIni) {
|
||||
conditions.push(
|
||||
`AND PCPEDC.DTENTREGA >= TO_DATE(:deliveryDateIni, 'YYYY-MM-DD')`
|
||||
`AND PCPEDC.DTENTREGA >= TO_DATE(:deliveryDateIni, 'YYYY-MM-DD')`,
|
||||
);
|
||||
}
|
||||
if (query.deliveryDateEnd) {
|
||||
conditions.push(
|
||||
`AND PCPEDC.DTENTREGA <= TO_DATE(:deliveryDateEnd, 'YYYY-MM-DD')`
|
||||
`AND PCPEDC.DTENTREGA <= TO_DATE(:deliveryDateEnd, 'YYYY-MM-DD')`,
|
||||
);
|
||||
}
|
||||
|
||||
// Filtros adicionais
|
||||
if (query.codfilial) {
|
||||
conditions.push(`AND PCPEDC.CODFILIAL = :storeId`);
|
||||
const filiais = query.codfilial
|
||||
.split(',')
|
||||
.map((f) => f.trim())
|
||||
.filter((f) => f);
|
||||
if (filiais.length === 1) {
|
||||
conditions.push(`AND PCPEDC.CODFILIAL = :storeId`);
|
||||
} else {
|
||||
const filiaisList = filiais.join(',');
|
||||
conditions.push(`AND PCPEDC.CODFILIAL IN (${filiaisList})`);
|
||||
}
|
||||
}
|
||||
if (query.sellerId) {
|
||||
const sellerIds = query.sellerId
|
||||
.split(",")
|
||||
.split(',')
|
||||
.map((s) => s.trim())
|
||||
.filter((s) => s)
|
||||
.join(",");
|
||||
.join(',');
|
||||
conditions.push(`AND PCPEDC.CODUSUR IN (${sellerIds})`);
|
||||
}
|
||||
if (query.customerId) {
|
||||
@@ -819,70 +830,76 @@ WHERE
|
||||
}
|
||||
if (query.orderId) {
|
||||
conditions.push(
|
||||
`AND (PCPEDC.NUMPED = :orderId OR PCPEDC.NUMPEDENTFUT = :orderId)`
|
||||
`AND (PCPEDC.NUMPED = :orderId OR PCPEDC.NUMPEDENTFUT = :orderId)`,
|
||||
);
|
||||
}
|
||||
if (query.deliveryType) {
|
||||
const types = query.deliveryType
|
||||
.split(",")
|
||||
.split(',')
|
||||
.map((t) => `'${t}'`)
|
||||
.join(",");
|
||||
.join(',');
|
||||
conditions.push(
|
||||
`AND EXISTS(SELECT 1 FROM PCPEDI WHERE PCPEDI.NUMPED = PCPEDC.NUMPED AND PCPEDI.TIPOENTREGA IN (${types}))`
|
||||
`AND EXISTS(SELECT 1 FROM PCPEDI WHERE PCPEDI.NUMPED = PCPEDC.NUMPED AND PCPEDI.TIPOENTREGA IN (${types}))`,
|
||||
);
|
||||
}
|
||||
if (query.status) {
|
||||
const statusList = query.status
|
||||
.split(",")
|
||||
.split(',')
|
||||
.map((s) => `'${s}'`)
|
||||
.join(",");
|
||||
.join(',');
|
||||
conditions.push(`AND PCPEDC.POSICAO IN (${statusList})`);
|
||||
}
|
||||
if (query.markId) {
|
||||
conditions.push(`AND PCMARCA.CODMARCA = :markId`);
|
||||
}
|
||||
if (query.markName) {
|
||||
conditions.push(`AND UPPER(PCMARCA.MARCA) LIKE UPPER('%' || :markName || '%')`);
|
||||
conditions.push(
|
||||
`AND UPPER(PCMARCA.MARCA) LIKE UPPER('%' || :markName || '%')`,
|
||||
);
|
||||
}
|
||||
if (query.hasPreBox === true) {
|
||||
conditions.push(`AND EXISTS (SELECT 1 FROM SEVEN.ESTLOGTRANSFCD WHERE NUMPEDLOJA = PCPEDC.NUMPED)`);
|
||||
conditions.push(
|
||||
`AND EXISTS (SELECT 1 FROM SEVEN.ESTLOGTRANSFCD WHERE NUMPEDLOJA = PCPEDC.NUMPED)`,
|
||||
);
|
||||
}
|
||||
|
||||
if (query.statusTransfer) {
|
||||
const statusTransferList = query.statusTransfer
|
||||
.split(",")
|
||||
.split(',')
|
||||
.map((s) => s.trim());
|
||||
|
||||
const statusConditions = statusTransferList.map(status => {
|
||||
switch (status) {
|
||||
case 'Em Trânsito':
|
||||
return `(PCPEDC.CONDVENDA = 10 AND PCPEDC.POSICAO = 'F' AND
|
||||
const statusConditions = statusTransferList
|
||||
.map((status) => {
|
||||
switch (status) {
|
||||
case 'Em Trânsito':
|
||||
return `(PCPEDC.CONDVENDA = 10 AND PCPEDC.POSICAO = 'F' AND
|
||||
(SELECT COUNT(1) FROM PCNFENT, PCFILIAL
|
||||
WHERE PCFILIAL.CODIGO = PCPEDC.CODFILIAL
|
||||
AND PCFILIAL.CODFORNEC = PCNFENT.CODFORNEC
|
||||
AND PCNFENT.NUMNOTA = PCPEDC.NUMNOTA) = 0)`;
|
||||
case 'Em Separação':
|
||||
return `(PCPEDC.CONDVENDA = 10 AND PCPEDC.POSICAO = 'M')`;
|
||||
case 'Aguardando Separação':
|
||||
return `(PCPEDC.CONDVENDA = 10 AND PCPEDC.POSICAO IN ('L', 'P'))`;
|
||||
case 'Concluída':
|
||||
return `(PCPEDC.CONDVENDA = 10 AND
|
||||
case 'Em Separação':
|
||||
return `(PCPEDC.CONDVENDA = 10 AND PCPEDC.POSICAO = 'M')`;
|
||||
case 'Aguardando Separação':
|
||||
return `(PCPEDC.CONDVENDA = 10 AND PCPEDC.POSICAO IN ('L', 'P'))`;
|
||||
case 'Concluída':
|
||||
return `(PCPEDC.CONDVENDA = 10 AND
|
||||
(SELECT COUNT(1) FROM PCNFENT, PCFILIAL
|
||||
WHERE PCFILIAL.CODIGO = PCPEDC.CODFILIAL
|
||||
AND PCFILIAL.CODFORNEC = PCNFENT.CODFORNEC
|
||||
AND PCNFENT.NUMNOTA = PCPEDC.NUMNOTA) > 0)`;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}).filter(condition => condition !== null);
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
})
|
||||
.filter((condition) => condition !== null);
|
||||
|
||||
if (statusConditions.length > 0) {
|
||||
conditions.push(`AND (${statusConditions.join(' OR ')})`);
|
||||
}
|
||||
}
|
||||
|
||||
sql += "\n" + conditions.join("\n");
|
||||
sql += "\nAND ROWNUM < 5000";
|
||||
sql += '\n' + conditions.join('\n');
|
||||
sql += '\nAND ROWNUM < 5000';
|
||||
|
||||
const parameters: any = {};
|
||||
|
||||
@@ -894,7 +911,13 @@ WHERE
|
||||
parameters.deliveryDateEnd = query.deliveryDateEnd;
|
||||
}
|
||||
if (query.codfilial) {
|
||||
parameters.storeId = query.codfilial;
|
||||
const filiais = query.codfilial
|
||||
.split(',')
|
||||
.map((f) => f.trim())
|
||||
.filter((f) => f);
|
||||
if (filiais.length === 1) {
|
||||
parameters.storeId = filiais[0];
|
||||
}
|
||||
}
|
||||
if (query.customerId) {
|
||||
parameters.customerId = query.customerId;
|
||||
@@ -942,7 +965,10 @@ WHERE
|
||||
|
||||
const invoice = await queryRunner.manager.query(sql);
|
||||
if (!invoice || invoice.length === 0) {
|
||||
throw new HttpException('Nota fiscal não foi localizada no sistema', HttpStatus.BAD_REQUEST);
|
||||
throw new HttpException(
|
||||
'Nota fiscal não foi localizada no sistema',
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
}
|
||||
|
||||
const sqlItem = `
|
||||
@@ -983,7 +1009,7 @@ WHERE
|
||||
const queryRunner = this.oracleDataSource.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
try {
|
||||
const sql = `SELECT PCPEDI.CODPROD as "productId"
|
||||
const sql = `SELECT PCPEDI.CODPROD as "productId"
|
||||
, PCPRODUT.DESCRICAO as "description"
|
||||
, PCPRODUT.EMBALAGEM as "pacth"
|
||||
, NVL(PCPEDI.COMPLEMENTO,
|
||||
@@ -1133,7 +1159,7 @@ WHERE
|
||||
await queryRunner.connect();
|
||||
|
||||
try {
|
||||
const sql = `SELECT pcpedc.numped AS "orderId",
|
||||
const sql = `SELECT pcpedc.numped AS "orderId",
|
||||
'Digitação pedido' AS "status",
|
||||
TO_DATE (TO_CHAR(pcpedc.data, 'DD/MM/YYYY') || ' ' || pcpedc.hora || ':' || pcpedc.minuto,
|
||||
'DD/MM/YYYY HH24:MI')
|
||||
@@ -1266,7 +1292,9 @@ WHERE
|
||||
await queryRunner.release();
|
||||
}
|
||||
}
|
||||
async createInvoiceCheck(invoice: InvoiceCheckDto): Promise<{ message: string }> {
|
||||
async createInvoiceCheck(
|
||||
invoice: InvoiceCheckDto,
|
||||
): Promise<{ message: string }> {
|
||||
const queryRunner = this.oracleDataSource.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
await queryRunner.startTransaction();
|
||||
@@ -1309,7 +1337,7 @@ WHERE
|
||||
await queryRunner.release();
|
||||
}
|
||||
}
|
||||
async getOrderDeliveries(orderId: string, query: any) {
|
||||
async getOrderDeliveries(orderId: string) {
|
||||
const queryRunnerOracle = this.oracleDataSource.createQueryRunner();
|
||||
const queryRunnerPostgres = this.postgresDataSource.createQueryRunner();
|
||||
|
||||
@@ -1317,7 +1345,7 @@ WHERE
|
||||
await queryRunnerPostgres.connect();
|
||||
|
||||
try {
|
||||
const sqlOracle = `SELECT PCPEDC.CODFILIAL as "storeId"
|
||||
const sqlOracle = `SELECT PCPEDC.CODFILIAL as "storeId"
|
||||
,PCPEDC.DATA as "createDate"
|
||||
,PCPEDC.NUMPED as "orderId"
|
||||
,PCPEDC.NUMPEDENTFUT as "orderIdSale"
|
||||
@@ -1351,7 +1379,6 @@ WHERE
|
||||
AND PCCARREG.CODMOTORISTA = PCEMPR.MATRICULA (+)
|
||||
AND ( PCPEDC.NUMPEDENTFUT = ${orderId} OR PCPEDC.NUMPEDORIGEM = ${orderId} )`;
|
||||
|
||||
|
||||
const orders = await queryRunnerOracle.manager.query(sqlOracle);
|
||||
|
||||
// Consulta no WMS (Postgres) - Modificada para buscar pelo número do pedido
|
||||
@@ -1405,31 +1432,37 @@ WHERE
|
||||
`;
|
||||
|
||||
// Criar array com os IDs de pedidos obtidos do Oracle
|
||||
const orderIds = orders.map(o => o.orderId?.toString() || '');
|
||||
const orderIds = orders.map((o) => o.orderId?.toString() || '');
|
||||
|
||||
// Converter orderId para número para evitar erro de tipo
|
||||
const numericOrderId = parseInt(orderId, 10);
|
||||
const ordersWMS = await queryRunnerPostgres.manager.query(sqlWMS, [numericOrderId, orderIds]);
|
||||
const ordersWMS = await queryRunnerPostgres.manager.query(sqlWMS, [
|
||||
numericOrderId,
|
||||
orderIds,
|
||||
]);
|
||||
|
||||
// Atualizar status baseado no WMS
|
||||
for (const order of orders) {
|
||||
const orderWMS = ordersWMS.find(o => Number(o.numero) === Number(order.orderId));
|
||||
const orderWMS = ordersWMS.find(
|
||||
(o) => Number(o.numero) === Number(order.orderId),
|
||||
);
|
||||
if (orderWMS && !order.deliveryConfirmationDate) {
|
||||
order.status = orderWMS.situacaoPedido;
|
||||
}
|
||||
}
|
||||
|
||||
return orders;
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
throw new HttpException('Erro ao buscar pedidos', HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
} catch (_error) {
|
||||
throw new HttpException(
|
||||
'Erro ao buscar pedidos',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
} finally {
|
||||
await queryRunnerOracle.release();
|
||||
await queryRunnerPostgres.release();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
async getLeadtimeWMS(orderId: string): Promise<LeadtimeDto[]> {
|
||||
const queryRunnerPostgres = this.postgresDataSource.createQueryRunner();
|
||||
const queryRunnerOracle = this.oracleDataSource.createQueryRunner();
|
||||
@@ -1514,16 +1547,21 @@ WHERE
|
||||
WHERE DADOS.numero_pedido = $1
|
||||
ORDER BY DADOS.numero_pedido, DADOS.ETAPA;
|
||||
`;
|
||||
const dataPostgres = await queryRunnerPostgres.manager.query(sqlPostgres, [orderId]);
|
||||
const dataPostgres = await queryRunnerPostgres.manager.query(
|
||||
sqlPostgres,
|
||||
[orderId],
|
||||
);
|
||||
|
||||
// Junta os dados Oracle + Postgres
|
||||
const leadtime = [...dataOracle, ...dataPostgres];
|
||||
|
||||
// Ordena pela etapa (opcional, para garantir ordem)
|
||||
return leadtime.sort((a, b) => a.etapa - b.etapa);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
throw new HttpException('Erro ao buscar dados de leadtime do WMS', HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
} catch (_error) {
|
||||
throw new HttpException(
|
||||
'Erro ao buscar dados de leadtime do WMS',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
} finally {
|
||||
await queryRunnerPostgres.release();
|
||||
await queryRunnerOracle.release();
|
||||
@@ -1587,7 +1625,7 @@ WHERE
|
||||
FROM PCPEDC
|
||||
WHERE NUMPED = :1
|
||||
`;
|
||||
|
||||
|
||||
const result = await this.oracleDataSource.query(sql, [orderId]);
|
||||
return result.length > 0 ? result[0].NUMTRANSVENDA : null;
|
||||
}
|
||||
@@ -1597,7 +1635,11 @@ WHERE
|
||||
* @param query - Filtros para a consulta de entregas realizadas incluindo transactionId
|
||||
* @returns Lista de entregas realizadas
|
||||
*/
|
||||
async getCompletedDeliveriesByTransactionId(query: { transactionId: number; limit: number; offset: number }): Promise<DeliveryCompleted[]> {
|
||||
async getCompletedDeliveriesByTransactionId(query: {
|
||||
transactionId: number;
|
||||
limit: number;
|
||||
offset: number;
|
||||
}): Promise<DeliveryCompleted[]> {
|
||||
const sql = `
|
||||
SELECT
|
||||
ESTENTREGAS.CODSAIDA AS "outId"
|
||||
@@ -1638,7 +1680,7 @@ WHERE
|
||||
const deliveries = await this.oracleDataSource.query(sql, [
|
||||
query.transactionId,
|
||||
query.offset,
|
||||
query.limit
|
||||
query.limit,
|
||||
]);
|
||||
|
||||
// Buscar imagens para cada entrega
|
||||
@@ -1650,7 +1692,10 @@ WHERE
|
||||
WHERE CODSAIDA = :1
|
||||
AND NUMTRANSVENDA = :2
|
||||
`;
|
||||
const images = await this.oracleDataSource.query(sqlImages, [delivery.outId, delivery.transactionId]);
|
||||
const images = await this.oracleDataSource.query(sqlImages, [
|
||||
delivery.outId,
|
||||
delivery.transactionId,
|
||||
]);
|
||||
delivery.urlImages = images.map((image: any) => image.URL);
|
||||
}
|
||||
|
||||
@@ -1685,7 +1730,9 @@ WHERE
|
||||
* @param query - Filtros para a consulta de entregas realizadas
|
||||
* @returns Lista de entregas realizadas
|
||||
*/
|
||||
async getCompletedDeliveries(query: DeliveryCompletedQuery): Promise<DeliveryCompleted[]> {
|
||||
async getCompletedDeliveries(
|
||||
query: DeliveryCompletedQuery,
|
||||
): Promise<DeliveryCompleted[]> {
|
||||
let sql = `
|
||||
SELECT
|
||||
ESTENTREGAS.CODSAIDA AS "outId"
|
||||
@@ -1778,7 +1825,9 @@ WHERE
|
||||
// Paginação
|
||||
const limit = query.limit || 100;
|
||||
const offset = query.offset || 0;
|
||||
sql += ` OFFSET :${paramIndex} ROWS FETCH NEXT :${paramIndex + 1} ROWS ONLY`;
|
||||
sql += ` OFFSET :${paramIndex} ROWS FETCH NEXT :${
|
||||
paramIndex + 1
|
||||
} ROWS ONLY`;
|
||||
parameters.push(offset);
|
||||
parameters.push(limit);
|
||||
|
||||
@@ -1793,7 +1842,10 @@ WHERE
|
||||
WHERE CODSAIDA = :1
|
||||
AND NUMTRANSVENDA = :2
|
||||
`;
|
||||
const images = await this.oracleDataSource.query(sqlImages, [delivery.outId, delivery.transactionId]);
|
||||
const images = await this.oracleDataSource.query(sqlImages, [
|
||||
delivery.outId,
|
||||
delivery.transactionId,
|
||||
]);
|
||||
delivery.urlImages = images.map((image: any) => image.URL);
|
||||
}
|
||||
|
||||
@@ -1822,4 +1874,4 @@ WHERE
|
||||
urlImages: [...row.urlImages],
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user