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 { ApiPropertyOptional } from '@nestjs/swagger';
|
||||||
import { Type } from 'class-transformer';
|
import { Type } from 'class-transformer';
|
||||||
import { ValidateNested } from 'class-validator';
|
|
||||||
import { CustomerDto } from 'src/data-consult/dto/customer.dto';
|
|
||||||
|
|
||||||
|
|
||||||
import {
|
import {
|
||||||
IsOptional,
|
IsOptional,
|
||||||
IsString,
|
IsString,
|
||||||
IsNumber,
|
IsNumber,
|
||||||
IsDateString,
|
IsDateString,
|
||||||
IsIn,
|
IsBoolean,
|
||||||
IsBoolean
|
|
||||||
} from 'class-validator';
|
} from 'class-validator';
|
||||||
|
|
||||||
export class FindOrdersDto {
|
export class FindOrdersDto {
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsString()
|
@IsString()
|
||||||
@ApiPropertyOptional()
|
@ApiPropertyOptional({
|
||||||
|
description: 'Código da filial (pode ser múltiplas filiais separadas por vírgula, ex: "1,2,3")',
|
||||||
|
})
|
||||||
codfilial?: string;
|
codfilial?: string;
|
||||||
|
|
||||||
|
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@Type(() => Boolean)
|
@Type(() => Boolean)
|
||||||
@IsBoolean()
|
@IsBoolean()
|
||||||
@@ -28,12 +25,13 @@ export class FindOrdersDto {
|
|||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsString()
|
@IsString()
|
||||||
@ApiPropertyOptional()
|
@ApiPropertyOptional()
|
||||||
|
|
||||||
filialretira?: string;
|
filialretira?: string;
|
||||||
|
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsString()
|
@IsString()
|
||||||
@ApiPropertyOptional({ description: 'ID da transportadora para filtrar pedidos' })
|
@ApiPropertyOptional({
|
||||||
|
description: 'ID da transportadora para filtrar pedidos',
|
||||||
|
})
|
||||||
carrier?: string;
|
carrier?: string;
|
||||||
|
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@@ -68,15 +66,12 @@ export class FindOrdersDto {
|
|||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsString()
|
@IsString()
|
||||||
@ApiPropertyOptional()
|
@ApiPropertyOptional()
|
||||||
|
|
||||||
sellerId?: string;
|
sellerId?: string;
|
||||||
|
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsString()
|
@IsString()
|
||||||
@ApiPropertyOptional()
|
@ApiPropertyOptional()
|
||||||
sellerName?: string;
|
sellerName?: string;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsNumber()
|
@IsNumber()
|
||||||
@@ -158,7 +153,7 @@ sellerName?: string;
|
|||||||
@IsString()
|
@IsString()
|
||||||
@ApiPropertyOptional({
|
@ApiPropertyOptional({
|
||||||
description: 'Filtrar por status de transferência',
|
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;
|
statusTransfer?: string;
|
||||||
|
|
||||||
@@ -173,7 +168,6 @@ sellerName?: string;
|
|||||||
@IsString()
|
@IsString()
|
||||||
@ApiPropertyOptional({
|
@ApiPropertyOptional({
|
||||||
description: 'Nome da marca para filtrar pedidos',
|
description: 'Nome da marca para filtrar pedidos',
|
||||||
|
|
||||||
})
|
})
|
||||||
markName?: string;
|
markName?: string;
|
||||||
|
|
||||||
@@ -181,35 +175,36 @@ sellerName?: string;
|
|||||||
@Type(() => Boolean)
|
@Type(() => Boolean)
|
||||||
@IsBoolean()
|
@IsBoolean()
|
||||||
@ApiPropertyOptional({
|
@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;
|
hasPreBox?: boolean;
|
||||||
|
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsString()
|
@IsString()
|
||||||
@ApiPropertyOptional({
|
@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;
|
preBoxFilial?: string;
|
||||||
|
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsString()
|
@IsString()
|
||||||
@ApiPropertyOptional({
|
@ApiPropertyOptional({
|
||||||
description: 'Código da filial de destino da transferência'
|
description: 'Código da filial de destino da transferência',
|
||||||
})
|
})
|
||||||
transferDestFilial?: string;
|
transferDestFilial?: string;
|
||||||
|
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsDateString()
|
@IsDateString()
|
||||||
@ApiPropertyOptional({
|
@ApiPropertyOptional({
|
||||||
description: 'Data de transferência inicial (formato YYYY-MM-DD)'
|
description: 'Data de transferência inicial (formato YYYY-MM-DD)',
|
||||||
})
|
})
|
||||||
transferDateIni?: string;
|
transferDateIni?: string;
|
||||||
|
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsDateString()
|
@IsDateString()
|
||||||
@ApiPropertyOptional({
|
@ApiPropertyOptional({
|
||||||
description: 'Data de transferência final (formato YYYY-MM-DD)'
|
description: 'Data de transferência final (formato YYYY-MM-DD)',
|
||||||
})
|
})
|
||||||
transferDateEnd?: string;
|
transferDateEnd?: string;
|
||||||
|
|
||||||
@@ -217,7 +212,7 @@ sellerName?: string;
|
|||||||
@Type(() => Boolean)
|
@Type(() => Boolean)
|
||||||
@IsBoolean()
|
@IsBoolean()
|
||||||
@ApiPropertyOptional({
|
@ApiPropertyOptional({
|
||||||
description: 'Incluir dados de entregas realizadas para cada pedido'
|
description: 'Incluir dados de entregas realizadas para cada pedido',
|
||||||
})
|
})
|
||||||
includeCompletedDeliveries?: boolean;
|
includeCompletedDeliveries?: boolean;
|
||||||
|
|
||||||
@@ -225,7 +220,7 @@ sellerName?: string;
|
|||||||
@Type(() => Number)
|
@Type(() => Number)
|
||||||
@IsNumber()
|
@IsNumber()
|
||||||
@ApiPropertyOptional({
|
@ApiPropertyOptional({
|
||||||
description: 'Limite de registros por página'
|
description: 'Limite de registros por página',
|
||||||
})
|
})
|
||||||
limit?: number;
|
limit?: number;
|
||||||
|
|
||||||
@@ -233,7 +228,7 @@ sellerName?: string;
|
|||||||
@Type(() => Number)
|
@Type(() => Number)
|
||||||
@IsNumber()
|
@IsNumber()
|
||||||
@ApiPropertyOptional({
|
@ApiPropertyOptional({
|
||||||
description: 'Offset para paginação'
|
description: 'Offset para paginação',
|
||||||
})
|
})
|
||||||
offset?: number;
|
offset?: number;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { ApiProperty } from '@nestjs/swagger';
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { DeliveryCompleted } from './delivery-completed.dto';
|
||||||
|
|
||||||
export class OrderResponseDto {
|
export class OrderResponseDto {
|
||||||
@ApiProperty({
|
@ApiProperty({
|
||||||
@@ -257,4 +258,11 @@ export class OrderResponseDto {
|
|||||||
description: 'Entrega agendada',
|
description: 'Entrega agendada',
|
||||||
})
|
})
|
||||||
schedulerDelivery: string;
|
schedulerDelivery: string;
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
description: 'Entregas completadas',
|
||||||
|
type: [Object],
|
||||||
|
required: false,
|
||||||
|
})
|
||||||
|
completedDeliveries?: DeliveryCompleted[];
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,30 +1,30 @@
|
|||||||
import { Injectable, HttpException, HttpStatus } from "@nestjs/common";
|
import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
|
||||||
import { EstLogTransferFilterDto, EstLogTransferResponseDto } from "../dto/estlogtransfer.dto";
|
import {
|
||||||
import { DataSource } from "typeorm";
|
EstLogTransferFilterDto,
|
||||||
import { InjectDataSource } from "@nestjs/typeorm";
|
EstLogTransferResponseDto,
|
||||||
import { FindOrdersDto } from "../dto/find-orders.dto";
|
} from '../dto/estlogtransfer.dto';
|
||||||
import { OrderItemDto } from "../dto/OrderItemDto";
|
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 { CutItemDto } from '../dto/CutItemDto';
|
||||||
import { OrderDeliveryDto } from '../dto/OrderDeliveryDto';
|
import { OrderDeliveryDto } from '../dto/OrderDeliveryDto';
|
||||||
import { OrderTransferDto } from '../dto/OrderTransferDto';
|
import { OrderTransferDto } from '../dto/OrderTransferDto';
|
||||||
import { OrderStatusDto } from '../dto/OrderStatusDto';
|
import { OrderStatusDto } from '../dto/OrderStatusDto';
|
||||||
import { InvoiceCheckDto } from '../dto/invoice-check.dto';
|
import { InvoiceCheckDto } from '../dto/invoice-check.dto';
|
||||||
import { LeadtimeDto } from "../dto/leadtime.dto";
|
import { LeadtimeDto } from '../dto/leadtime.dto';
|
||||||
import { MarkData } from "../interface/markdata";
|
import { MarkData } from '../interface/markdata';
|
||||||
import { DeliveryCompletedQuery } from "../dto/delivery-completed-query.dto";
|
import { DeliveryCompletedQuery } from '../dto/delivery-completed-query.dto';
|
||||||
import { DeliveryCompleted } from "../dto/delivery-completed.dto";
|
import { DeliveryCompleted } from '../dto/delivery-completed.dto';
|
||||||
|
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class OrdersRepository {
|
export class OrdersRepository {
|
||||||
constructor(
|
constructor(
|
||||||
@InjectDataSource("oracle") private readonly oracleDataSource: DataSource,
|
@InjectDataSource('oracle') private readonly oracleDataSource: DataSource,
|
||||||
@InjectDataSource("postgres") private readonly postgresDataSource: DataSource
|
@InjectDataSource('postgres')
|
||||||
|
private readonly postgresDataSource: DataSource,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Busca log de transferência por ID do pedido
|
* Busca log de transferência por ID do pedido
|
||||||
* @param orderId - ID do pedido
|
* @param orderId - ID do pedido
|
||||||
@@ -33,7 +33,7 @@ export class OrdersRepository {
|
|||||||
*/
|
*/
|
||||||
async estlogtransfer(
|
async estlogtransfer(
|
||||||
orderId: number,
|
orderId: number,
|
||||||
filters?: EstLogTransferFilterDto
|
filters?: EstLogTransferFilterDto,
|
||||||
): Promise<EstLogTransferResponseDto[] | null> {
|
): Promise<EstLogTransferResponseDto[] | null> {
|
||||||
if (!orderId || orderId <= 0) {
|
if (!orderId || orderId <= 0) {
|
||||||
throw new HttpException('OrderId inválido', HttpStatus.BAD_REQUEST);
|
throw new HttpException('OrderId inválido', HttpStatus.BAD_REQUEST);
|
||||||
@@ -69,36 +69,30 @@ WHERE E.NUMPEDLOJA = :orderId
|
|||||||
`;
|
`;
|
||||||
|
|
||||||
const parameters: any[] = [orderId];
|
const parameters: any[] = [orderId];
|
||||||
let paramIndex = 1;
|
|
||||||
|
|
||||||
if (filters?.dttransf) {
|
if (filters?.dttransf) {
|
||||||
sql += ` AND DTTRANSF = TO_DATE(:dttransf, 'YYYY-MM-DD')`;
|
sql += ` AND DTTRANSF = TO_DATE(:dttransf, 'YYYY-MM-DD')`;
|
||||||
parameters.push(filters.dttransf);
|
parameters.push(filters.dttransf);
|
||||||
paramIndex++;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (filters?.codfilial) {
|
if (filters?.codfilial) {
|
||||||
sql += ` AND CODFILIAL = :codfilial`;
|
sql += ` AND CODFILIAL = :codfilial`;
|
||||||
parameters.push(filters.codfilial);
|
parameters.push(filters.codfilial);
|
||||||
paramIndex++;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (filters?.codfilialdest) {
|
if (filters?.codfilialdest) {
|
||||||
sql += ` AND CODFILIALDEST = :codfilialdest`;
|
sql += ` AND CODFILIALDEST = :codfilialdest`;
|
||||||
parameters.push(filters.codfilialdest);
|
parameters.push(filters.codfilialdest);
|
||||||
paramIndex++;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (filters?.numpedloja) {
|
if (filters?.numpedloja) {
|
||||||
sql += ` AND NUMPEDLOJA = :numpedloja`;
|
sql += ` AND NUMPEDLOJA = :numpedloja`;
|
||||||
parameters.push(filters.numpedloja);
|
parameters.push(filters.numpedloja);
|
||||||
paramIndex++;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (filters?.numpedtransf) {
|
if (filters?.numpedtransf) {
|
||||||
sql += ` AND NUMPEDTRANSF = :numpedtransf`;
|
sql += ` AND NUMPEDTRANSF = :numpedtransf`;
|
||||||
parameters.push(filters.numpedtransf);
|
parameters.push(filters.numpedtransf);
|
||||||
paramIndex++;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
sql += ` ORDER BY DTTRANSF DESC`;
|
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
|
* @returns Dados dos logs de transferência ou null se não encontrado
|
||||||
*/
|
*/
|
||||||
async estlogtransfers(
|
async estlogtransfers(
|
||||||
filters?: EstLogTransferFilterDto
|
filters?: EstLogTransferFilterDto,
|
||||||
): Promise<EstLogTransferResponseDto[] | null> {
|
): Promise<EstLogTransferResponseDto[] | null> {
|
||||||
let sql = `
|
let sql = `
|
||||||
SELECT
|
SELECT
|
||||||
@@ -145,51 +139,42 @@ WHERE 1=1
|
|||||||
`;
|
`;
|
||||||
|
|
||||||
const parameters: any[] = [];
|
const parameters: any[] = [];
|
||||||
let paramIndex = 0;
|
|
||||||
|
|
||||||
if (filters?.dttransf) {
|
if (filters?.dttransf) {
|
||||||
sql += ` AND DTTRANSF = TO_DATE(:dttransf, 'YYYY-MM-DD')`;
|
sql += ` AND DTTRANSF = TO_DATE(:dttransf, 'YYYY-MM-DD')`;
|
||||||
parameters.push(filters.dttransf);
|
parameters.push(filters.dttransf);
|
||||||
paramIndex++;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (filters?.dttransfIni && filters?.dttransfEnd) {
|
if (filters?.dttransfIni && filters?.dttransfEnd) {
|
||||||
sql += ` AND DTTRANSF BETWEEN TO_DATE(:dttransfIni, 'YYYY-MM-DD') AND TO_DATE(:dttransfEnd, 'YYYY-MM-DD')`;
|
sql += ` AND DTTRANSF BETWEEN TO_DATE(:dttransfIni, 'YYYY-MM-DD') AND TO_DATE(:dttransfEnd, 'YYYY-MM-DD')`;
|
||||||
parameters.push(filters.dttransfIni);
|
parameters.push(filters.dttransfIni);
|
||||||
parameters.push(filters.dttransfEnd);
|
parameters.push(filters.dttransfEnd);
|
||||||
paramIndex += 2;
|
|
||||||
} else if (filters?.dttransfIni) {
|
} else if (filters?.dttransfIni) {
|
||||||
sql += ` AND DTTRANSF >= TO_DATE(:dttransfIni, 'YYYY-MM-DD')`;
|
sql += ` AND DTTRANSF >= TO_DATE(:dttransfIni, 'YYYY-MM-DD')`;
|
||||||
parameters.push(filters.dttransfIni);
|
parameters.push(filters.dttransfIni);
|
||||||
paramIndex++;
|
|
||||||
} else if (filters?.dttransfEnd) {
|
} else if (filters?.dttransfEnd) {
|
||||||
sql += ` AND DTTRANSF <= TO_DATE(:dttransfEnd, 'YYYY-MM-DD')`;
|
sql += ` AND DTTRANSF <= TO_DATE(:dttransfEnd, 'YYYY-MM-DD')`;
|
||||||
parameters.push(filters.dttransfEnd);
|
parameters.push(filters.dttransfEnd);
|
||||||
paramIndex++;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (filters?.codfilial) {
|
if (filters?.codfilial) {
|
||||||
sql += ` AND CODFILIAL = :codfilial`;
|
sql += ` AND CODFILIAL = :codfilial`;
|
||||||
parameters.push(filters.codfilial);
|
parameters.push(filters.codfilial);
|
||||||
paramIndex++;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (filters?.codfilialdest) {
|
if (filters?.codfilialdest) {
|
||||||
sql += ` AND CODFILIALDEST = :codfilialdest`;
|
sql += ` AND CODFILIALDEST = :codfilialdest`;
|
||||||
parameters.push(filters.codfilialdest);
|
parameters.push(filters.codfilialdest);
|
||||||
paramIndex++;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (filters?.numpedloja) {
|
if (filters?.numpedloja) {
|
||||||
sql += ` AND NUMPEDLOJA = :numpedloja`;
|
sql += ` AND NUMPEDLOJA = :numpedloja`;
|
||||||
parameters.push(filters.numpedloja);
|
parameters.push(filters.numpedloja);
|
||||||
paramIndex++;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (filters?.numpedtransf) {
|
if (filters?.numpedtransf) {
|
||||||
sql += ` AND NUMPEDTRANSF = :numpedtransf`;
|
sql += ` AND NUMPEDTRANSF = :numpedtransf`;
|
||||||
parameters.push(filters.numpedtransf);
|
parameters.push(filters.numpedtransf);
|
||||||
paramIndex++;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
sql += ` ORDER BY DTTRANSF ASC`;
|
sql += ` ORDER BY DTTRANSF ASC`;
|
||||||
@@ -198,13 +183,12 @@ WHERE 1=1
|
|||||||
return result.length > 0 ? result : null;
|
return result.length > 0 ? result : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retorna dados de um pedido específico cruzados com seu fechamento de caixa,
|
* Retorna dados de um pedido específico cruzados com seu fechamento de caixa,
|
||||||
* filtrados apenas pelo número do pedido. Retorna apenas um registro.
|
* 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 = `
|
const sql = `
|
||||||
SELECT p.MARCA, p.CODMARCA, p.ATIVO
|
SELECT p.MARCA, p.CODMARCA, p.ATIVO
|
||||||
FROM PCMARCA p
|
FROM PCMARCA p
|
||||||
@@ -215,7 +199,6 @@ WHERE 1=1
|
|||||||
return results[0] || null;
|
return results[0] || null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
async findOrderWithCheckoutByOrder(orderId: number): Promise<any | null> {
|
async findOrderWithCheckoutByOrder(orderId: number): Promise<any | null> {
|
||||||
const sql = `
|
const sql = `
|
||||||
SELECT
|
SELECT
|
||||||
@@ -239,8 +222,6 @@ WHERE
|
|||||||
return results[0] || null;
|
return results[0] || null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
async findOrders(query: FindOrdersDto): Promise<any[]> {
|
async findOrders(query: FindOrdersDto): Promise<any[]> {
|
||||||
const queryRunner = this.oracleDataSource.createQueryRunner();
|
const queryRunner = this.oracleDataSource.createQueryRunner();
|
||||||
await queryRunner.connect();
|
await queryRunner.connect();
|
||||||
@@ -395,26 +376,34 @@ WHERE
|
|||||||
const conditions: string[] = [];
|
const conditions: string[] = [];
|
||||||
|
|
||||||
if (query.codfilial) {
|
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) {
|
if (query.filialretira) {
|
||||||
conditions.push(
|
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) {
|
if (query.sellerId) {
|
||||||
const sellerIds = query.sellerId
|
const sellerIds = query.sellerId
|
||||||
.split(",")
|
.split(',')
|
||||||
.map((s) => s.trim())
|
.map((s) => s.trim())
|
||||||
.filter((s) => s)
|
.filter((s) => s)
|
||||||
.join(",");
|
.join(',');
|
||||||
conditions.push(`AND PCPEDC.CODUSUR IN (${sellerIds})`);
|
conditions.push(`AND PCPEDC.CODUSUR IN (${sellerIds})`);
|
||||||
}
|
}
|
||||||
if (query.customerId) {
|
if (query.customerId) {
|
||||||
conditions.push(`AND PCPEDC.CODCLI = :customerId`);
|
conditions.push(`AND PCPEDC.CODCLI = :customerId`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
if (query.billingId) {
|
if (query.billingId) {
|
||||||
conditions.push(`AND PCPEDC.CODCOB = :billingId`);
|
conditions.push(`AND PCPEDC.CODCOB = :billingId`);
|
||||||
}
|
}
|
||||||
@@ -423,7 +412,7 @@ WHERE
|
|||||||
}
|
}
|
||||||
if (query.orderId) {
|
if (query.orderId) {
|
||||||
conditions.push(
|
conditions.push(
|
||||||
`AND (PCPEDC.NUMPED = :orderId OR PCPEDC.NUMPEDENTFUT = :orderId)`
|
`AND (PCPEDC.NUMPED = :orderId OR PCPEDC.NUMPEDENTFUT = :orderId)`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
if (query.invoiceId) {
|
if (query.invoiceId) {
|
||||||
@@ -431,27 +420,27 @@ WHERE
|
|||||||
}
|
}
|
||||||
if (query.productId) {
|
if (query.productId) {
|
||||||
conditions.push(
|
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) {
|
if (query.createDateIni) {
|
||||||
conditions.push(
|
conditions.push(
|
||||||
`AND PCPEDC.DATA >= TO_DATE(:createDateIni, 'YYYY-MM-DD')`
|
`AND PCPEDC.DATA >= TO_DATE(:createDateIni, 'YYYY-MM-DD')`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
if (query.createDateEnd) {
|
if (query.createDateEnd) {
|
||||||
conditions.push(
|
conditions.push(
|
||||||
`AND PCPEDC.DATA <= TO_DATE(:createDateEnd, 'YYYY-MM-DD')`
|
`AND PCPEDC.DATA <= TO_DATE(:createDateEnd, 'YYYY-MM-DD')`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
if (query.invoiceDateIni) {
|
if (query.invoiceDateIni) {
|
||||||
conditions.push(
|
conditions.push(
|
||||||
`AND PCPEDC.DTFAT >= TO_DATE(:invoiceDateIni, 'YYYY-MM-DD')`
|
`AND PCPEDC.DTFAT >= TO_DATE(:invoiceDateIni, 'YYYY-MM-DD')`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
if (query.invoiceDateEnd) {
|
if (query.invoiceDateEnd) {
|
||||||
conditions.push(
|
conditions.push(
|
||||||
`AND PCPEDC.DTFAT <= TO_DATE(:invoiceDateEnd, 'YYYY-MM-DD')`
|
`AND PCPEDC.DTFAT <= TO_DATE(:invoiceDateEnd, 'YYYY-MM-DD')`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
if (query.shippimentId) {
|
if (query.shippimentId) {
|
||||||
@@ -464,10 +453,14 @@ WHERE
|
|||||||
conditions.push(`AND PCMARCA.CODMARCA = :markId`);
|
conditions.push(`AND PCMARCA.CODMARCA = :markId`);
|
||||||
}
|
}
|
||||||
if (query.markName) {
|
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) {
|
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) {
|
if (query.preBoxFilial) {
|
||||||
@@ -501,25 +494,25 @@ WHERE
|
|||||||
|
|
||||||
if (query.deliveryType) {
|
if (query.deliveryType) {
|
||||||
const types = query.deliveryType
|
const types = query.deliveryType
|
||||||
.split(",")
|
.split(',')
|
||||||
.map((t) => `'${t}'`)
|
.map((t) => `'${t}'`)
|
||||||
.join(",");
|
.join(',');
|
||||||
conditions.push(
|
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) {
|
if (query.status) {
|
||||||
const statusList = query.status
|
const statusList = query.status
|
||||||
.split(",")
|
.split(',')
|
||||||
.map((s) => `'${s}'`)
|
.map((s) => `'${s}'`)
|
||||||
.join(",");
|
.join(',');
|
||||||
conditions.push(`AND PCPEDC.POSICAO IN (${statusList})`);
|
conditions.push(`AND PCPEDC.POSICAO IN (${statusList})`);
|
||||||
}
|
}
|
||||||
if (query.type) {
|
if (query.type) {
|
||||||
const types = query.type
|
const types = query.type
|
||||||
.split(",")
|
.split(',')
|
||||||
.map((t) => `'${t}'`)
|
.map((t) => `'${t}'`)
|
||||||
.join(",");
|
.join(',');
|
||||||
conditions.push(`AND PCPEDC.CONDVENDA IN (${types})`);
|
conditions.push(`AND PCPEDC.CONDVENDA IN (${types})`);
|
||||||
}
|
}
|
||||||
if (query.onlyPendingTransfer === true) {
|
if (query.onlyPendingTransfer === true) {
|
||||||
@@ -532,47 +525,56 @@ WHERE
|
|||||||
|
|
||||||
if (query.statusTransfer) {
|
if (query.statusTransfer) {
|
||||||
const statusTransferList = query.statusTransfer
|
const statusTransferList = query.statusTransfer
|
||||||
.split(",")
|
.split(',')
|
||||||
.map((s) => s.trim());
|
.map((s) => s.trim());
|
||||||
|
|
||||||
const statusConditions = statusTransferList.map(status => {
|
const statusConditions = statusTransferList
|
||||||
switch (status) {
|
.map((status) => {
|
||||||
case 'Em Trânsito':
|
switch (status) {
|
||||||
return `(PCPEDC.CONDVENDA = 10 AND PCPEDC.POSICAO = 'F' AND
|
case 'Em Trânsito':
|
||||||
|
return `(PCPEDC.CONDVENDA = 10 AND PCPEDC.POSICAO = 'F' AND
|
||||||
(SELECT COUNT(1) FROM PCNFENT, PCFILIAL
|
(SELECT COUNT(1) FROM PCNFENT, PCFILIAL
|
||||||
WHERE PCFILIAL.CODIGO = PCPEDC.CODFILIAL
|
WHERE PCFILIAL.CODIGO = PCPEDC.CODFILIAL
|
||||||
AND PCFILIAL.CODFORNEC = PCNFENT.CODFORNEC
|
AND PCFILIAL.CODFORNEC = PCNFENT.CODFORNEC
|
||||||
AND PCNFENT.NUMNOTA = PCPEDC.NUMNOTA) = 0)`;
|
AND PCNFENT.NUMNOTA = PCPEDC.NUMNOTA) = 0)`;
|
||||||
case 'Em Separação':
|
case 'Em Separação':
|
||||||
return `(PCPEDC.CONDVENDA = 10 AND PCPEDC.POSICAO = 'M')`;
|
return `(PCPEDC.CONDVENDA = 10 AND PCPEDC.POSICAO = 'M')`;
|
||||||
case 'Aguardando Separação':
|
case 'Aguardando Separação':
|
||||||
return `(PCPEDC.CONDVENDA = 10 AND PCPEDC.POSICAO IN ('L', 'P'))`;
|
return `(PCPEDC.CONDVENDA = 10 AND PCPEDC.POSICAO IN ('L', 'P'))`;
|
||||||
case 'Concluída':
|
case 'Concluída':
|
||||||
return `(PCPEDC.CONDVENDA = 10 AND
|
return `(PCPEDC.CONDVENDA = 10 AND
|
||||||
(SELECT COUNT(1) FROM PCNFENT, PCFILIAL
|
(SELECT COUNT(1) FROM PCNFENT, PCFILIAL
|
||||||
WHERE PCFILIAL.CODIGO = PCPEDC.CODFILIAL
|
WHERE PCFILIAL.CODIGO = PCPEDC.CODFILIAL
|
||||||
AND PCFILIAL.CODFORNEC = PCNFENT.CODFORNEC
|
AND PCFILIAL.CODFORNEC = PCNFENT.CODFORNEC
|
||||||
AND PCNFENT.NUMNOTA = PCPEDC.NUMNOTA) > 0)`;
|
AND PCNFENT.NUMNOTA = PCPEDC.NUMNOTA) > 0)`;
|
||||||
default:
|
default:
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}).filter(condition => condition !== null);
|
})
|
||||||
|
.filter((condition) => condition !== null);
|
||||||
|
|
||||||
if (statusConditions.length > 0) {
|
if (statusConditions.length > 0) {
|
||||||
conditions.push(`AND (${statusConditions.join(' OR ')})`);
|
conditions.push(`AND (${statusConditions.join(' OR ')})`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
sql += "\n" + conditions.join("\n");
|
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 +=
|
||||||
sql += "\nORDER BY PCPEDC.NUMPED DESC";
|
'\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 += "\nFETCH FIRST 5000 ROWS ONLY";
|
sql += '\nORDER BY PCPEDC.NUMPED DESC';
|
||||||
|
sql += '\nFETCH FIRST 5000 ROWS ONLY';
|
||||||
|
|
||||||
const parameters: any = {};
|
const parameters: any = {};
|
||||||
|
|
||||||
// Add parameters for bind variables
|
// Add parameters for bind variables
|
||||||
if (query.codfilial) {
|
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) {
|
if (query.filialretira) {
|
||||||
parameters.storeStockId = query.filialretira;
|
parameters.storeStockId = query.filialretira;
|
||||||
@@ -793,25 +795,34 @@ WHERE
|
|||||||
// Filtros específicos para data de entrega
|
// Filtros específicos para data de entrega
|
||||||
if (query.deliveryDateIni) {
|
if (query.deliveryDateIni) {
|
||||||
conditions.push(
|
conditions.push(
|
||||||
`AND PCPEDC.DTENTREGA >= TO_DATE(:deliveryDateIni, 'YYYY-MM-DD')`
|
`AND PCPEDC.DTENTREGA >= TO_DATE(:deliveryDateIni, 'YYYY-MM-DD')`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
if (query.deliveryDateEnd) {
|
if (query.deliveryDateEnd) {
|
||||||
conditions.push(
|
conditions.push(
|
||||||
`AND PCPEDC.DTENTREGA <= TO_DATE(:deliveryDateEnd, 'YYYY-MM-DD')`
|
`AND PCPEDC.DTENTREGA <= TO_DATE(:deliveryDateEnd, 'YYYY-MM-DD')`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Filtros adicionais
|
// Filtros adicionais
|
||||||
if (query.codfilial) {
|
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) {
|
if (query.sellerId) {
|
||||||
const sellerIds = query.sellerId
|
const sellerIds = query.sellerId
|
||||||
.split(",")
|
.split(',')
|
||||||
.map((s) => s.trim())
|
.map((s) => s.trim())
|
||||||
.filter((s) => s)
|
.filter((s) => s)
|
||||||
.join(",");
|
.join(',');
|
||||||
conditions.push(`AND PCPEDC.CODUSUR IN (${sellerIds})`);
|
conditions.push(`AND PCPEDC.CODUSUR IN (${sellerIds})`);
|
||||||
}
|
}
|
||||||
if (query.customerId) {
|
if (query.customerId) {
|
||||||
@@ -819,70 +830,76 @@ WHERE
|
|||||||
}
|
}
|
||||||
if (query.orderId) {
|
if (query.orderId) {
|
||||||
conditions.push(
|
conditions.push(
|
||||||
`AND (PCPEDC.NUMPED = :orderId OR PCPEDC.NUMPEDENTFUT = :orderId)`
|
`AND (PCPEDC.NUMPED = :orderId OR PCPEDC.NUMPEDENTFUT = :orderId)`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
if (query.deliveryType) {
|
if (query.deliveryType) {
|
||||||
const types = query.deliveryType
|
const types = query.deliveryType
|
||||||
.split(",")
|
.split(',')
|
||||||
.map((t) => `'${t}'`)
|
.map((t) => `'${t}'`)
|
||||||
.join(",");
|
.join(',');
|
||||||
conditions.push(
|
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) {
|
if (query.status) {
|
||||||
const statusList = query.status
|
const statusList = query.status
|
||||||
.split(",")
|
.split(',')
|
||||||
.map((s) => `'${s}'`)
|
.map((s) => `'${s}'`)
|
||||||
.join(",");
|
.join(',');
|
||||||
conditions.push(`AND PCPEDC.POSICAO IN (${statusList})`);
|
conditions.push(`AND PCPEDC.POSICAO IN (${statusList})`);
|
||||||
}
|
}
|
||||||
if (query.markId) {
|
if (query.markId) {
|
||||||
conditions.push(`AND PCMARCA.CODMARCA = :markId`);
|
conditions.push(`AND PCMARCA.CODMARCA = :markId`);
|
||||||
}
|
}
|
||||||
if (query.markName) {
|
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) {
|
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) {
|
if (query.statusTransfer) {
|
||||||
const statusTransferList = query.statusTransfer
|
const statusTransferList = query.statusTransfer
|
||||||
.split(",")
|
.split(',')
|
||||||
.map((s) => s.trim());
|
.map((s) => s.trim());
|
||||||
|
|
||||||
const statusConditions = statusTransferList.map(status => {
|
const statusConditions = statusTransferList
|
||||||
switch (status) {
|
.map((status) => {
|
||||||
case 'Em Trânsito':
|
switch (status) {
|
||||||
return `(PCPEDC.CONDVENDA = 10 AND PCPEDC.POSICAO = 'F' AND
|
case 'Em Trânsito':
|
||||||
|
return `(PCPEDC.CONDVENDA = 10 AND PCPEDC.POSICAO = 'F' AND
|
||||||
(SELECT COUNT(1) FROM PCNFENT, PCFILIAL
|
(SELECT COUNT(1) FROM PCNFENT, PCFILIAL
|
||||||
WHERE PCFILIAL.CODIGO = PCPEDC.CODFILIAL
|
WHERE PCFILIAL.CODIGO = PCPEDC.CODFILIAL
|
||||||
AND PCFILIAL.CODFORNEC = PCNFENT.CODFORNEC
|
AND PCFILIAL.CODFORNEC = PCNFENT.CODFORNEC
|
||||||
AND PCNFENT.NUMNOTA = PCPEDC.NUMNOTA) = 0)`;
|
AND PCNFENT.NUMNOTA = PCPEDC.NUMNOTA) = 0)`;
|
||||||
case 'Em Separação':
|
case 'Em Separação':
|
||||||
return `(PCPEDC.CONDVENDA = 10 AND PCPEDC.POSICAO = 'M')`;
|
return `(PCPEDC.CONDVENDA = 10 AND PCPEDC.POSICAO = 'M')`;
|
||||||
case 'Aguardando Separação':
|
case 'Aguardando Separação':
|
||||||
return `(PCPEDC.CONDVENDA = 10 AND PCPEDC.POSICAO IN ('L', 'P'))`;
|
return `(PCPEDC.CONDVENDA = 10 AND PCPEDC.POSICAO IN ('L', 'P'))`;
|
||||||
case 'Concluída':
|
case 'Concluída':
|
||||||
return `(PCPEDC.CONDVENDA = 10 AND
|
return `(PCPEDC.CONDVENDA = 10 AND
|
||||||
(SELECT COUNT(1) FROM PCNFENT, PCFILIAL
|
(SELECT COUNT(1) FROM PCNFENT, PCFILIAL
|
||||||
WHERE PCFILIAL.CODIGO = PCPEDC.CODFILIAL
|
WHERE PCFILIAL.CODIGO = PCPEDC.CODFILIAL
|
||||||
AND PCFILIAL.CODFORNEC = PCNFENT.CODFORNEC
|
AND PCFILIAL.CODFORNEC = PCNFENT.CODFORNEC
|
||||||
AND PCNFENT.NUMNOTA = PCPEDC.NUMNOTA) > 0)`;
|
AND PCNFENT.NUMNOTA = PCPEDC.NUMNOTA) > 0)`;
|
||||||
default:
|
default:
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}).filter(condition => condition !== null);
|
})
|
||||||
|
.filter((condition) => condition !== null);
|
||||||
|
|
||||||
if (statusConditions.length > 0) {
|
if (statusConditions.length > 0) {
|
||||||
conditions.push(`AND (${statusConditions.join(' OR ')})`);
|
conditions.push(`AND (${statusConditions.join(' OR ')})`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
sql += "\n" + conditions.join("\n");
|
sql += '\n' + conditions.join('\n');
|
||||||
sql += "\nAND ROWNUM < 5000";
|
sql += '\nAND ROWNUM < 5000';
|
||||||
|
|
||||||
const parameters: any = {};
|
const parameters: any = {};
|
||||||
|
|
||||||
@@ -894,7 +911,13 @@ WHERE
|
|||||||
parameters.deliveryDateEnd = query.deliveryDateEnd;
|
parameters.deliveryDateEnd = query.deliveryDateEnd;
|
||||||
}
|
}
|
||||||
if (query.codfilial) {
|
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) {
|
if (query.customerId) {
|
||||||
parameters.customerId = query.customerId;
|
parameters.customerId = query.customerId;
|
||||||
@@ -942,7 +965,10 @@ WHERE
|
|||||||
|
|
||||||
const invoice = await queryRunner.manager.query(sql);
|
const invoice = await queryRunner.manager.query(sql);
|
||||||
if (!invoice || invoice.length === 0) {
|
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 = `
|
const sqlItem = `
|
||||||
@@ -983,7 +1009,7 @@ WHERE
|
|||||||
const queryRunner = this.oracleDataSource.createQueryRunner();
|
const queryRunner = this.oracleDataSource.createQueryRunner();
|
||||||
await queryRunner.connect();
|
await queryRunner.connect();
|
||||||
try {
|
try {
|
||||||
const sql = `SELECT PCPEDI.CODPROD as "productId"
|
const sql = `SELECT PCPEDI.CODPROD as "productId"
|
||||||
, PCPRODUT.DESCRICAO as "description"
|
, PCPRODUT.DESCRICAO as "description"
|
||||||
, PCPRODUT.EMBALAGEM as "pacth"
|
, PCPRODUT.EMBALAGEM as "pacth"
|
||||||
, NVL(PCPEDI.COMPLEMENTO,
|
, NVL(PCPEDI.COMPLEMENTO,
|
||||||
@@ -1133,7 +1159,7 @@ WHERE
|
|||||||
await queryRunner.connect();
|
await queryRunner.connect();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const sql = `SELECT pcpedc.numped AS "orderId",
|
const sql = `SELECT pcpedc.numped AS "orderId",
|
||||||
'Digitação pedido' AS "status",
|
'Digitação pedido' AS "status",
|
||||||
TO_DATE (TO_CHAR(pcpedc.data, 'DD/MM/YYYY') || ' ' || pcpedc.hora || ':' || pcpedc.minuto,
|
TO_DATE (TO_CHAR(pcpedc.data, 'DD/MM/YYYY') || ' ' || pcpedc.hora || ':' || pcpedc.minuto,
|
||||||
'DD/MM/YYYY HH24:MI')
|
'DD/MM/YYYY HH24:MI')
|
||||||
@@ -1266,7 +1292,9 @@ WHERE
|
|||||||
await queryRunner.release();
|
await queryRunner.release();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
async createInvoiceCheck(invoice: InvoiceCheckDto): Promise<{ message: string }> {
|
async createInvoiceCheck(
|
||||||
|
invoice: InvoiceCheckDto,
|
||||||
|
): Promise<{ message: string }> {
|
||||||
const queryRunner = this.oracleDataSource.createQueryRunner();
|
const queryRunner = this.oracleDataSource.createQueryRunner();
|
||||||
await queryRunner.connect();
|
await queryRunner.connect();
|
||||||
await queryRunner.startTransaction();
|
await queryRunner.startTransaction();
|
||||||
@@ -1309,7 +1337,7 @@ WHERE
|
|||||||
await queryRunner.release();
|
await queryRunner.release();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
async getOrderDeliveries(orderId: string, query: any) {
|
async getOrderDeliveries(orderId: string) {
|
||||||
const queryRunnerOracle = this.oracleDataSource.createQueryRunner();
|
const queryRunnerOracle = this.oracleDataSource.createQueryRunner();
|
||||||
const queryRunnerPostgres = this.postgresDataSource.createQueryRunner();
|
const queryRunnerPostgres = this.postgresDataSource.createQueryRunner();
|
||||||
|
|
||||||
@@ -1317,7 +1345,7 @@ WHERE
|
|||||||
await queryRunnerPostgres.connect();
|
await queryRunnerPostgres.connect();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const sqlOracle = `SELECT PCPEDC.CODFILIAL as "storeId"
|
const sqlOracle = `SELECT PCPEDC.CODFILIAL as "storeId"
|
||||||
,PCPEDC.DATA as "createDate"
|
,PCPEDC.DATA as "createDate"
|
||||||
,PCPEDC.NUMPED as "orderId"
|
,PCPEDC.NUMPED as "orderId"
|
||||||
,PCPEDC.NUMPEDENTFUT as "orderIdSale"
|
,PCPEDC.NUMPEDENTFUT as "orderIdSale"
|
||||||
@@ -1351,7 +1379,6 @@ WHERE
|
|||||||
AND PCCARREG.CODMOTORISTA = PCEMPR.MATRICULA (+)
|
AND PCCARREG.CODMOTORISTA = PCEMPR.MATRICULA (+)
|
||||||
AND ( PCPEDC.NUMPEDENTFUT = ${orderId} OR PCPEDC.NUMPEDORIGEM = ${orderId} )`;
|
AND ( PCPEDC.NUMPEDENTFUT = ${orderId} OR PCPEDC.NUMPEDORIGEM = ${orderId} )`;
|
||||||
|
|
||||||
|
|
||||||
const orders = await queryRunnerOracle.manager.query(sqlOracle);
|
const orders = await queryRunnerOracle.manager.query(sqlOracle);
|
||||||
|
|
||||||
// Consulta no WMS (Postgres) - Modificada para buscar pelo número do pedido
|
// 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
|
// 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
|
// Converter orderId para número para evitar erro de tipo
|
||||||
const numericOrderId = parseInt(orderId, 10);
|
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
|
// Atualizar status baseado no WMS
|
||||||
for (const order of orders) {
|
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) {
|
if (orderWMS && !order.deliveryConfirmationDate) {
|
||||||
order.status = orderWMS.situacaoPedido;
|
order.status = orderWMS.situacaoPedido;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return orders;
|
return orders;
|
||||||
} catch (error) {
|
} catch (_error) {
|
||||||
console.error(error);
|
throw new HttpException(
|
||||||
throw new HttpException('Erro ao buscar pedidos', HttpStatus.INTERNAL_SERVER_ERROR);
|
'Erro ao buscar pedidos',
|
||||||
|
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||||
|
);
|
||||||
} finally {
|
} finally {
|
||||||
await queryRunnerOracle.release();
|
await queryRunnerOracle.release();
|
||||||
await queryRunnerPostgres.release();
|
await queryRunnerPostgres.release();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
async getLeadtimeWMS(orderId: string): Promise<LeadtimeDto[]> {
|
async getLeadtimeWMS(orderId: string): Promise<LeadtimeDto[]> {
|
||||||
const queryRunnerPostgres = this.postgresDataSource.createQueryRunner();
|
const queryRunnerPostgres = this.postgresDataSource.createQueryRunner();
|
||||||
const queryRunnerOracle = this.oracleDataSource.createQueryRunner();
|
const queryRunnerOracle = this.oracleDataSource.createQueryRunner();
|
||||||
@@ -1514,16 +1547,21 @@ WHERE
|
|||||||
WHERE DADOS.numero_pedido = $1
|
WHERE DADOS.numero_pedido = $1
|
||||||
ORDER BY DADOS.numero_pedido, DADOS.ETAPA;
|
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
|
// Junta os dados Oracle + Postgres
|
||||||
const leadtime = [...dataOracle, ...dataPostgres];
|
const leadtime = [...dataOracle, ...dataPostgres];
|
||||||
|
|
||||||
// Ordena pela etapa (opcional, para garantir ordem)
|
// Ordena pela etapa (opcional, para garantir ordem)
|
||||||
return leadtime.sort((a, b) => a.etapa - b.etapa);
|
return leadtime.sort((a, b) => a.etapa - b.etapa);
|
||||||
} catch (error) {
|
} catch (_error) {
|
||||||
console.error(error);
|
throw new HttpException(
|
||||||
throw new HttpException('Erro ao buscar dados de leadtime do WMS', HttpStatus.INTERNAL_SERVER_ERROR);
|
'Erro ao buscar dados de leadtime do WMS',
|
||||||
|
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||||
|
);
|
||||||
} finally {
|
} finally {
|
||||||
await queryRunnerPostgres.release();
|
await queryRunnerPostgres.release();
|
||||||
await queryRunnerOracle.release();
|
await queryRunnerOracle.release();
|
||||||
@@ -1597,7 +1635,11 @@ WHERE
|
|||||||
* @param query - Filtros para a consulta de entregas realizadas incluindo transactionId
|
* @param query - Filtros para a consulta de entregas realizadas incluindo transactionId
|
||||||
* @returns Lista de entregas realizadas
|
* @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 = `
|
const sql = `
|
||||||
SELECT
|
SELECT
|
||||||
ESTENTREGAS.CODSAIDA AS "outId"
|
ESTENTREGAS.CODSAIDA AS "outId"
|
||||||
@@ -1638,7 +1680,7 @@ WHERE
|
|||||||
const deliveries = await this.oracleDataSource.query(sql, [
|
const deliveries = await this.oracleDataSource.query(sql, [
|
||||||
query.transactionId,
|
query.transactionId,
|
||||||
query.offset,
|
query.offset,
|
||||||
query.limit
|
query.limit,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
// Buscar imagens para cada entrega
|
// Buscar imagens para cada entrega
|
||||||
@@ -1650,7 +1692,10 @@ WHERE
|
|||||||
WHERE CODSAIDA = :1
|
WHERE CODSAIDA = :1
|
||||||
AND NUMTRANSVENDA = :2
|
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);
|
delivery.urlImages = images.map((image: any) => image.URL);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1685,7 +1730,9 @@ WHERE
|
|||||||
* @param query - Filtros para a consulta de entregas realizadas
|
* @param query - Filtros para a consulta de entregas realizadas
|
||||||
* @returns Lista de entregas realizadas
|
* @returns Lista de entregas realizadas
|
||||||
*/
|
*/
|
||||||
async getCompletedDeliveries(query: DeliveryCompletedQuery): Promise<DeliveryCompleted[]> {
|
async getCompletedDeliveries(
|
||||||
|
query: DeliveryCompletedQuery,
|
||||||
|
): Promise<DeliveryCompleted[]> {
|
||||||
let sql = `
|
let sql = `
|
||||||
SELECT
|
SELECT
|
||||||
ESTENTREGAS.CODSAIDA AS "outId"
|
ESTENTREGAS.CODSAIDA AS "outId"
|
||||||
@@ -1778,7 +1825,9 @@ WHERE
|
|||||||
// Paginação
|
// Paginação
|
||||||
const limit = query.limit || 100;
|
const limit = query.limit || 100;
|
||||||
const offset = query.offset || 0;
|
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(offset);
|
||||||
parameters.push(limit);
|
parameters.push(limit);
|
||||||
|
|
||||||
@@ -1793,7 +1842,10 @@ WHERE
|
|||||||
WHERE CODSAIDA = :1
|
WHERE CODSAIDA = :1
|
||||||
AND NUMTRANSVENDA = :2
|
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);
|
delivery.urlImages = images.map((image: any) => image.URL);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user