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:
@@ -0,0 +1,60 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { OrdersService } from '../orders.service';
|
||||
import { OrdersRepository } from '../../repositories/orders.repository';
|
||||
import { IRedisClient } from '../../../core/configs/cache/IRedisClient';
|
||||
import { RedisClientToken } from '../../../core/configs/cache/redis-client.adapter.provider';
|
||||
|
||||
export const createMockRepository = (
|
||||
methods: Partial<OrdersRepository> = {},
|
||||
) =>
|
||||
({
|
||||
findOrders: jest.fn(),
|
||||
getCompletedDeliveries: jest.fn(),
|
||||
...methods,
|
||||
} as any);
|
||||
|
||||
export const createMockRedisClient = () =>
|
||||
({
|
||||
get: jest.fn().mockResolvedValue(null),
|
||||
set: jest.fn().mockResolvedValue(undefined),
|
||||
} as any);
|
||||
|
||||
export interface OrdersServiceTestContext {
|
||||
service: OrdersService;
|
||||
mockRepository: jest.Mocked<OrdersRepository>;
|
||||
mockRedisClient: jest.Mocked<IRedisClient>;
|
||||
}
|
||||
|
||||
export async function createOrdersServiceTestModule(
|
||||
repositoryMethods: Partial<OrdersRepository> = {},
|
||||
redisClientMethods: Partial<IRedisClient> = {},
|
||||
): Promise<OrdersServiceTestContext> {
|
||||
const mockRepository = createMockRepository(repositoryMethods);
|
||||
const mockRedisClient = {
|
||||
...createMockRedisClient(),
|
||||
...redisClientMethods,
|
||||
} as any;
|
||||
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [
|
||||
OrdersService,
|
||||
{
|
||||
provide: OrdersRepository,
|
||||
useValue: mockRepository,
|
||||
},
|
||||
{
|
||||
provide: RedisClientToken,
|
||||
useValue: mockRedisClient,
|
||||
},
|
||||
],
|
||||
}).compile();
|
||||
|
||||
const service = module.get<OrdersService>(OrdersService);
|
||||
|
||||
return {
|
||||
service,
|
||||
mockRepository,
|
||||
mockRedisClient,
|
||||
};
|
||||
}
|
||||
|
||||
303
src/orders/application/__tests__/orders.service.spec.ts
Normal file
303
src/orders/application/__tests__/orders.service.spec.ts
Normal file
@@ -0,0 +1,303 @@
|
||||
import { createOrdersServiceTestModule } from './orders.service.spec.helper';
|
||||
import { FindOrdersDto } from '../../dto/find-orders.dto';
|
||||
import { OrderResponseDto } from '../../dto/order-response.dto';
|
||||
import { DeliveryCompleted } from '../../dto/delivery-completed.dto';
|
||||
|
||||
describe('OrdersService', () => {
|
||||
describe('findOrders', () => {
|
||||
let context: Awaited<ReturnType<typeof createOrdersServiceTestModule>>;
|
||||
|
||||
beforeEach(async () => {
|
||||
context = await createOrdersServiceTestModule();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('Tests that expose problems', () => {
|
||||
it('should return orders from repository when cache is empty', async () => {
|
||||
const query: FindOrdersDto = {
|
||||
codfilial: '1',
|
||||
};
|
||||
|
||||
const mockOrders: OrderResponseDto[] = [
|
||||
{
|
||||
orderId: 1,
|
||||
invoiceNumber: 12345,
|
||||
customerName: 'Cliente 1',
|
||||
} as OrderResponseDto,
|
||||
{
|
||||
orderId: 2,
|
||||
invoiceNumber: 12346,
|
||||
customerName: 'Cliente 2',
|
||||
} as OrderResponseDto,
|
||||
];
|
||||
|
||||
context.mockRedisClient.get.mockResolvedValue(null);
|
||||
context.mockRepository.findOrders.mockResolvedValue(mockOrders);
|
||||
|
||||
const result = await context.service.findOrders(query);
|
||||
|
||||
expect(result).toEqual(mockOrders);
|
||||
expect(context.mockRepository.findOrders).toHaveBeenCalledWith(query);
|
||||
expect(context.mockRedisClient.get).toHaveBeenCalled();
|
||||
expect(context.mockRedisClient.set).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should return cached orders when cache exists', async () => {
|
||||
const query: FindOrdersDto = {
|
||||
codfilial: '1',
|
||||
};
|
||||
|
||||
const cachedOrders: OrderResponseDto[] = [
|
||||
{
|
||||
orderId: 1,
|
||||
invoiceNumber: 12345,
|
||||
customerName: 'Cliente 1',
|
||||
} as OrderResponseDto,
|
||||
];
|
||||
|
||||
context.mockRedisClient.get.mockResolvedValue(cachedOrders);
|
||||
|
||||
const result = await context.service.findOrders(query);
|
||||
|
||||
expect(result).toEqual(cachedOrders);
|
||||
expect(context.mockRepository.findOrders).not.toHaveBeenCalled();
|
||||
expect(context.mockRedisClient.set).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should return orders without completed deliveries when includeCompletedDeliveries is false', async () => {
|
||||
const query: FindOrdersDto = {
|
||||
codfilial: '1',
|
||||
includeCompletedDeliveries: false,
|
||||
};
|
||||
|
||||
const mockOrders: OrderResponseDto[] = [
|
||||
{
|
||||
orderId: 1,
|
||||
invoiceNumber: 12345,
|
||||
customerName: 'Cliente 1',
|
||||
} as OrderResponseDto,
|
||||
];
|
||||
|
||||
context.mockRedisClient.get.mockResolvedValue(null);
|
||||
context.mockRepository.findOrders.mockResolvedValue(mockOrders);
|
||||
|
||||
const result = await context.service.findOrders(query);
|
||||
|
||||
expect(result).toEqual(mockOrders);
|
||||
expect(context.mockRepository.getCompletedDeliveries).not.toHaveBeenCalled();
|
||||
expect(result[0].completedDeliveries).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should include completed deliveries when includeCompletedDeliveries is true', async () => {
|
||||
const query: FindOrdersDto = {
|
||||
codfilial: '1',
|
||||
includeCompletedDeliveries: true,
|
||||
};
|
||||
|
||||
const mockOrders: OrderResponseDto[] = [
|
||||
{
|
||||
orderId: 1,
|
||||
invoiceNumber: 12345,
|
||||
customerName: 'Cliente 1',
|
||||
} as OrderResponseDto,
|
||||
{
|
||||
orderId: 2,
|
||||
invoiceNumber: 12346,
|
||||
customerName: 'Cliente 2',
|
||||
} as OrderResponseDto,
|
||||
];
|
||||
|
||||
const mockDeliveries1: DeliveryCompleted[] = [
|
||||
{
|
||||
outId: 1,
|
||||
transactionId: 100,
|
||||
invoiceNumber: '12345',
|
||||
customerName: 'Cliente 1',
|
||||
} as DeliveryCompleted,
|
||||
];
|
||||
|
||||
const mockDeliveries2: DeliveryCompleted[] = [
|
||||
{
|
||||
outId: 2,
|
||||
transactionId: 101,
|
||||
invoiceNumber: '12346',
|
||||
customerName: 'Cliente 2',
|
||||
} as DeliveryCompleted,
|
||||
];
|
||||
|
||||
context.mockRedisClient.get.mockResolvedValue(null);
|
||||
context.mockRepository.findOrders.mockResolvedValue(mockOrders);
|
||||
context.mockRepository.getCompletedDeliveries
|
||||
.mockResolvedValueOnce(mockDeliveries1)
|
||||
.mockResolvedValueOnce(mockDeliveries2);
|
||||
|
||||
const result = await context.service.findOrders(query);
|
||||
|
||||
expect(result).toHaveLength(2);
|
||||
expect(result[0].completedDeliveries).toEqual(mockDeliveries1);
|
||||
expect(result[1].completedDeliveries).toEqual(mockDeliveries2);
|
||||
expect(context.mockRepository.getCompletedDeliveries).toHaveBeenCalledTimes(2);
|
||||
expect(context.mockRepository.getCompletedDeliveries).toHaveBeenCalledWith({
|
||||
orderNumber: 12345,
|
||||
limit: 10,
|
||||
offset: 0,
|
||||
});
|
||||
expect(context.mockRepository.getCompletedDeliveries).toHaveBeenCalledWith({
|
||||
orderNumber: 12346,
|
||||
limit: 10,
|
||||
offset: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it('should set completedDeliveries to empty array when getCompletedDeliveries throws error', async () => {
|
||||
const query: FindOrdersDto = {
|
||||
codfilial: '1',
|
||||
includeCompletedDeliveries: true,
|
||||
};
|
||||
|
||||
const mockOrders: OrderResponseDto[] = [
|
||||
{
|
||||
orderId: 1,
|
||||
invoiceNumber: 12345,
|
||||
customerName: 'Cliente 1',
|
||||
} as OrderResponseDto,
|
||||
];
|
||||
|
||||
context.mockRedisClient.get.mockResolvedValue(null);
|
||||
context.mockRepository.findOrders.mockResolvedValue(mockOrders);
|
||||
context.mockRepository.getCompletedDeliveries.mockRejectedValue(
|
||||
new Error('Database error'),
|
||||
);
|
||||
|
||||
const result = await context.service.findOrders(query);
|
||||
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].completedDeliveries).toEqual([]);
|
||||
expect(context.mockRepository.getCompletedDeliveries).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should handle empty orders array', async () => {
|
||||
const query: FindOrdersDto = {
|
||||
codfilial: '1',
|
||||
};
|
||||
|
||||
context.mockRedisClient.get.mockResolvedValue(null);
|
||||
context.mockRepository.findOrders.mockResolvedValue([]);
|
||||
|
||||
const result = await context.service.findOrders(query);
|
||||
|
||||
expect(result).toEqual([]);
|
||||
expect(context.mockRepository.findOrders).toHaveBeenCalledWith(query);
|
||||
});
|
||||
|
||||
it('should handle orders with includeCompletedDeliveries when some deliveries fail', async () => {
|
||||
const query: FindOrdersDto = {
|
||||
codfilial: '1',
|
||||
includeCompletedDeliveries: true,
|
||||
};
|
||||
|
||||
const mockOrders: OrderResponseDto[] = [
|
||||
{
|
||||
orderId: 1,
|
||||
invoiceNumber: 12345,
|
||||
customerName: 'Cliente 1',
|
||||
} as OrderResponseDto,
|
||||
{
|
||||
orderId: 2,
|
||||
invoiceNumber: 12346,
|
||||
customerName: 'Cliente 2',
|
||||
} as OrderResponseDto,
|
||||
];
|
||||
|
||||
const mockDeliveries1: DeliveryCompleted[] = [
|
||||
{
|
||||
outId: 1,
|
||||
transactionId: 100,
|
||||
invoiceNumber: '12345',
|
||||
customerName: 'Cliente 1',
|
||||
} as DeliveryCompleted,
|
||||
];
|
||||
|
||||
context.mockRedisClient.get.mockResolvedValue(null);
|
||||
context.mockRepository.findOrders.mockResolvedValue(mockOrders);
|
||||
context.mockRepository.getCompletedDeliveries
|
||||
.mockResolvedValueOnce(mockDeliveries1)
|
||||
.mockRejectedValueOnce(new Error('Database error'));
|
||||
|
||||
const result = await context.service.findOrders(query);
|
||||
|
||||
expect(result).toHaveLength(2);
|
||||
expect(result[0].completedDeliveries).toEqual(mockDeliveries1);
|
||||
expect(result[1].completedDeliveries).toEqual([]);
|
||||
});
|
||||
|
||||
it('should use correct cache key based on query parameters', async () => {
|
||||
const query: FindOrdersDto = {
|
||||
codfilial: '1',
|
||||
customerId: 123,
|
||||
};
|
||||
|
||||
const mockOrders: OrderResponseDto[] = [];
|
||||
|
||||
context.mockRedisClient.get.mockResolvedValue(null);
|
||||
context.mockRepository.findOrders.mockResolvedValue(mockOrders);
|
||||
|
||||
await context.service.findOrders(query);
|
||||
|
||||
expect(context.mockRedisClient.get).toHaveBeenCalled();
|
||||
const cacheKey = context.mockRedisClient.get.mock.calls[0][0];
|
||||
expect(cacheKey).toContain('orders:query:');
|
||||
});
|
||||
|
||||
it('should handle orders without invoiceNumber when includeCompletedDeliveries is true', async () => {
|
||||
const query: FindOrdersDto = {
|
||||
codfilial: '1',
|
||||
includeCompletedDeliveries: true,
|
||||
};
|
||||
|
||||
const mockOrders: OrderResponseDto[] = [
|
||||
{
|
||||
orderId: 1,
|
||||
invoiceNumber: null,
|
||||
customerName: 'Cliente 1',
|
||||
} as any,
|
||||
];
|
||||
|
||||
context.mockRedisClient.get.mockResolvedValue(null);
|
||||
context.mockRepository.findOrders.mockResolvedValue(mockOrders);
|
||||
context.mockRepository.getCompletedDeliveries.mockResolvedValue([]);
|
||||
|
||||
const result = await context.service.findOrders(query);
|
||||
|
||||
expect(result).toHaveLength(1);
|
||||
expect(context.mockRepository.getCompletedDeliveries).toHaveBeenCalledWith({
|
||||
orderNumber: null,
|
||||
limit: 10,
|
||||
offset: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it('should validate that cache TTL is set correctly', async () => {
|
||||
const query: FindOrdersDto = {
|
||||
codfilial: '1',
|
||||
};
|
||||
|
||||
const mockOrders: OrderResponseDto[] = [];
|
||||
|
||||
context.mockRedisClient.get.mockResolvedValue(null);
|
||||
context.mockRepository.findOrders.mockResolvedValue(mockOrders);
|
||||
|
||||
await context.service.findOrders(query);
|
||||
|
||||
expect(context.mockRedisClient.set).toHaveBeenCalled();
|
||||
const setCall = context.mockRedisClient.set.mock.calls[0];
|
||||
const ttl = setCall[2];
|
||||
expect(ttl).toBe(60);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,25 +1,22 @@
|
||||
import { ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { Type } from 'class-transformer';
|
||||
import { ValidateNested } from 'class-validator';
|
||||
import { CustomerDto } from 'src/data-consult/dto/customer.dto';
|
||||
|
||||
|
||||
import {
|
||||
IsOptional,
|
||||
IsString,
|
||||
IsNumber,
|
||||
IsDateString,
|
||||
IsIn,
|
||||
IsBoolean
|
||||
IsBoolean,
|
||||
} from 'class-validator';
|
||||
|
||||
export class FindOrdersDto {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@ApiPropertyOptional()
|
||||
@ApiPropertyOptional({
|
||||
description: 'Código da filial (pode ser múltiplas filiais separadas por vírgula, ex: "1,2,3")',
|
||||
})
|
||||
codfilial?: string;
|
||||
|
||||
|
||||
@IsOptional()
|
||||
@Type(() => Boolean)
|
||||
@IsBoolean()
|
||||
@@ -28,12 +25,13 @@ export class FindOrdersDto {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@ApiPropertyOptional()
|
||||
|
||||
filialretira?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@ApiPropertyOptional({ description: 'ID da transportadora para filtrar pedidos' })
|
||||
@ApiPropertyOptional({
|
||||
description: 'ID da transportadora para filtrar pedidos',
|
||||
})
|
||||
carrier?: string;
|
||||
|
||||
@IsOptional()
|
||||
@@ -68,15 +66,12 @@ export class FindOrdersDto {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@ApiPropertyOptional()
|
||||
|
||||
sellerId?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@ApiPropertyOptional()
|
||||
sellerName?: string;
|
||||
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@ApiPropertyOptional()
|
||||
sellerName?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
@@ -158,7 +153,7 @@ sellerName?: string;
|
||||
@IsString()
|
||||
@ApiPropertyOptional({
|
||||
description: 'Filtrar por status de transferência',
|
||||
enum: ['Em Trânsito', 'Em Separação', 'Aguardando Separação', 'Concluída']
|
||||
enum: ['Em Trânsito', 'Em Separação', 'Aguardando Separação', 'Concluída'],
|
||||
})
|
||||
statusTransfer?: string;
|
||||
|
||||
@@ -173,7 +168,6 @@ sellerName?: string;
|
||||
@IsString()
|
||||
@ApiPropertyOptional({
|
||||
description: 'Nome da marca para filtrar pedidos',
|
||||
|
||||
})
|
||||
markName?: string;
|
||||
|
||||
@@ -181,35 +175,36 @@ sellerName?: string;
|
||||
@Type(() => Boolean)
|
||||
@IsBoolean()
|
||||
@ApiPropertyOptional({
|
||||
description: 'Filtrar pedidos que tenham registros na tabela de transfer log'
|
||||
description:
|
||||
'Filtrar pedidos que tenham registros na tabela de transfer log',
|
||||
})
|
||||
hasPreBox?: boolean;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@ApiPropertyOptional({
|
||||
description: 'Código da filial de origem da transferência (Pre-Box)'
|
||||
description: 'Código da filial de origem da transferência (Pre-Box)',
|
||||
})
|
||||
preBoxFilial?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@ApiPropertyOptional({
|
||||
description: 'Código da filial de destino da transferência'
|
||||
description: 'Código da filial de destino da transferência',
|
||||
})
|
||||
transferDestFilial?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsDateString()
|
||||
@ApiPropertyOptional({
|
||||
description: 'Data de transferência inicial (formato YYYY-MM-DD)'
|
||||
description: 'Data de transferência inicial (formato YYYY-MM-DD)',
|
||||
})
|
||||
transferDateIni?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsDateString()
|
||||
@ApiPropertyOptional({
|
||||
description: 'Data de transferência final (formato YYYY-MM-DD)'
|
||||
description: 'Data de transferência final (formato YYYY-MM-DD)',
|
||||
})
|
||||
transferDateEnd?: string;
|
||||
|
||||
@@ -217,7 +212,7 @@ sellerName?: string;
|
||||
@Type(() => Boolean)
|
||||
@IsBoolean()
|
||||
@ApiPropertyOptional({
|
||||
description: 'Incluir dados de entregas realizadas para cada pedido'
|
||||
description: 'Incluir dados de entregas realizadas para cada pedido',
|
||||
})
|
||||
includeCompletedDeliveries?: boolean;
|
||||
|
||||
@@ -225,7 +220,7 @@ sellerName?: string;
|
||||
@Type(() => Number)
|
||||
@IsNumber()
|
||||
@ApiPropertyOptional({
|
||||
description: 'Limite de registros por página'
|
||||
description: 'Limite de registros por página',
|
||||
})
|
||||
limit?: number;
|
||||
|
||||
@@ -233,7 +228,7 @@ sellerName?: string;
|
||||
@Type(() => Number)
|
||||
@IsNumber()
|
||||
@ApiPropertyOptional({
|
||||
description: 'Offset para paginação'
|
||||
description: 'Offset para paginação',
|
||||
})
|
||||
offset?: number;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { DeliveryCompleted } from './delivery-completed.dto';
|
||||
|
||||
export class OrderResponseDto {
|
||||
@ApiProperty({
|
||||
@@ -257,4 +258,11 @@ export class OrderResponseDto {
|
||||
description: 'Entrega agendada',
|
||||
})
|
||||
schedulerDelivery: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'Entregas completadas',
|
||||
type: [Object],
|
||||
required: false,
|
||||
})
|
||||
completedDeliveries?: DeliveryCompleted[];
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user