fix: corrige erros do ESLint e configura variáveis globais
- Adiciona variáveis globais do Node.js (process, console, __dirname, require, module, exports) - Adiciona variáveis globais do Jest (describe, it, beforeEach, fail, etc.) - Configura ESLint para arquivos JavaScript de configuração - Remove diretivas eslint-disable não utilizadas - Corrige variáveis não usadas prefixando com _ - Ajusta regras do ESLint para ignorar variáveis que começam com _ - Formata código com Prettier
This commit is contained in:
@@ -18,6 +18,13 @@ module.exports = [
|
|||||||
globals: {
|
globals: {
|
||||||
node: true,
|
node: true,
|
||||||
jest: true,
|
jest: true,
|
||||||
|
process: 'readonly',
|
||||||
|
console: 'readonly',
|
||||||
|
__dirname: 'readonly',
|
||||||
|
__filename: 'readonly',
|
||||||
|
require: 'readonly',
|
||||||
|
module: 'readonly',
|
||||||
|
exports: 'readonly',
|
||||||
describe: 'readonly',
|
describe: 'readonly',
|
||||||
it: 'readonly',
|
it: 'readonly',
|
||||||
test: 'readonly',
|
test: 'readonly',
|
||||||
@@ -26,6 +33,7 @@ module.exports = [
|
|||||||
afterEach: 'readonly',
|
afterEach: 'readonly',
|
||||||
beforeAll: 'readonly',
|
beforeAll: 'readonly',
|
||||||
afterAll: 'readonly',
|
afterAll: 'readonly',
|
||||||
|
fail: 'readonly',
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
plugins: {
|
plugins: {
|
||||||
@@ -38,6 +46,17 @@ module.exports = [
|
|||||||
'@typescript-eslint/explicit-function-return-type': 'off',
|
'@typescript-eslint/explicit-function-return-type': 'off',
|
||||||
'@typescript-eslint/explicit-module-boundary-types': 'off',
|
'@typescript-eslint/explicit-module-boundary-types': 'off',
|
||||||
'@typescript-eslint/no-explicit-any': 'off',
|
'@typescript-eslint/no-explicit-any': 'off',
|
||||||
|
'@typescript-eslint/no-require-imports': 'warn',
|
||||||
|
'@typescript-eslint/no-unused-vars': [
|
||||||
|
'error',
|
||||||
|
{
|
||||||
|
argsIgnorePattern: '^_',
|
||||||
|
varsIgnorePattern: '^_',
|
||||||
|
caughtErrorsIgnorePattern: '^_',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
'no-useless-escape': 'warn',
|
||||||
|
'no-import-assign': 'off',
|
||||||
'prettier/prettier': 'error',
|
'prettier/prettier': 'error',
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -54,8 +73,37 @@ module.exports = [
|
|||||||
beforeAll: 'readonly',
|
beforeAll: 'readonly',
|
||||||
afterAll: 'readonly',
|
afterAll: 'readonly',
|
||||||
jest: 'readonly',
|
jest: 'readonly',
|
||||||
|
fail: 'readonly',
|
||||||
|
require: 'readonly',
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
rules: {
|
||||||
|
'@typescript-eslint/no-require-imports': 'off',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
files: ['**/*.js'],
|
||||||
|
languageOptions: {
|
||||||
|
globals: {
|
||||||
|
node: true,
|
||||||
|
jest: true,
|
||||||
|
process: 'readonly',
|
||||||
|
console: 'readonly',
|
||||||
|
__dirname: 'readonly',
|
||||||
|
__filename: 'readonly',
|
||||||
|
require: 'readonly',
|
||||||
|
module: 'readonly',
|
||||||
|
exports: 'readonly',
|
||||||
|
global: 'readonly',
|
||||||
|
Buffer: 'readonly',
|
||||||
|
},
|
||||||
|
ecmaVersion: 'latest',
|
||||||
|
sourceType: 'commonjs',
|
||||||
|
},
|
||||||
|
rules: {
|
||||||
|
'no-undef': 'off',
|
||||||
|
'@typescript-eslint/no-require-imports': 'off',
|
||||||
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
ignores: ['dist/**', 'node_modules/**', 'coverage/**'],
|
ignores: ['dist/**', 'node_modules/**', 'coverage/**'],
|
||||||
|
|||||||
@@ -12,7 +12,6 @@ import {
|
|||||||
Query,
|
Query,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { CommandBus } from '@nestjs/cqrs';
|
import { CommandBus } from '@nestjs/cqrs';
|
||||||
import { CqrsModule } from '@nestjs/cqrs';
|
|
||||||
import { AuthenticateUserCommand } from './commands/authenticate-user.command';
|
import { AuthenticateUserCommand } from './commands/authenticate-user.command';
|
||||||
import { LoginResponseDto } from './dto/LoginResponseDto';
|
import { LoginResponseDto } from './dto/LoginResponseDto';
|
||||||
import { LoginDto } from './dto/login.dto';
|
import { LoginDto } from './dto/login.dto';
|
||||||
|
|||||||
@@ -63,11 +63,7 @@ export class AuthService {
|
|||||||
throw new BadRequestException('ID de usuário inválido');
|
throw new BadRequestException('ID de usuário inválido');
|
||||||
}
|
}
|
||||||
|
|
||||||
if (
|
if (sellerId !== null && sellerId !== undefined && sellerId < 0) {
|
||||||
sellerId !== null &&
|
|
||||||
sellerId !== undefined &&
|
|
||||||
sellerId < 0
|
|
||||||
) {
|
|
||||||
throw new BadRequestException('ID de vendedor inválido');
|
throw new BadRequestException('ID de vendedor inválido');
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -299,7 +295,7 @@ export class AuthService {
|
|||||||
let decoded: JwtPayload | null = null;
|
let decoded: JwtPayload | null = null;
|
||||||
try {
|
try {
|
||||||
decoded = this.jwtService.decode(token) as JwtPayload;
|
decoded = this.jwtService.decode(token) as JwtPayload;
|
||||||
} catch (error) {
|
} catch (_error) {
|
||||||
throw new BadRequestException(
|
throw new BadRequestException(
|
||||||
'Token inválido ou não pode ser decodificado',
|
'Token inválido ou não pode ser decodificado',
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import { RateLimitingService } from '../../services/rate-limiting.service';
|
|||||||
|
|
||||||
describe('RateLimitingGuard - Tests that expose problems', () => {
|
describe('RateLimitingGuard - Tests that expose problems', () => {
|
||||||
let guard: RateLimitingGuard;
|
let guard: RateLimitingGuard;
|
||||||
let rateLimitingService: RateLimitingService;
|
let _rateLimitingService: RateLimitingService;
|
||||||
let mockExecutionContext: ExecutionContext;
|
let mockExecutionContext: ExecutionContext;
|
||||||
let mockGetRequest: jest.Mock;
|
let mockGetRequest: jest.Mock;
|
||||||
|
|
||||||
@@ -27,7 +27,7 @@ describe('RateLimitingGuard - Tests that expose problems', () => {
|
|||||||
}).compile();
|
}).compile();
|
||||||
|
|
||||||
guard = module.get<RateLimitingGuard>(RateLimitingGuard);
|
guard = module.get<RateLimitingGuard>(RateLimitingGuard);
|
||||||
rateLimitingService = module.get<RateLimitingService>(RateLimitingService);
|
_rateLimitingService = module.get<RateLimitingService>(RateLimitingService);
|
||||||
|
|
||||||
mockGetRequest = jest.fn().mockReturnValue({
|
mockGetRequest = jest.fn().mockReturnValue({
|
||||||
headers: {},
|
headers: {},
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
/* eslint-disable prettier/prettier */
|
|
||||||
export interface JwtPayload {
|
export interface JwtPayload {
|
||||||
id: number;
|
id: number;
|
||||||
sellerId: number | null;
|
sellerId: number | null;
|
||||||
@@ -8,4 +7,3 @@ export interface JwtPayload {
|
|||||||
exp?: number; // Timestamp de expiração do JWT
|
exp?: number; // Timestamp de expiração do JWT
|
||||||
sessionId?: string; // ID da sessão atual
|
sessionId?: string; // ID da sessão atual
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -61,4 +61,3 @@ export async function createRefreshTokenServiceTestModule(
|
|||||||
mockJwtService,
|
mockJwtService,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -389,4 +389,3 @@ describe('RefreshTokenService', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -59,4 +59,3 @@ export async function createTokenBlacklistServiceTestModule(
|
|||||||
mockJwtService,
|
mockJwtService,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -90,9 +90,9 @@ describe('TokenBlacklistService', () => {
|
|||||||
|
|
||||||
context.mockJwtService.decode.mockReturnValue(null);
|
context.mockJwtService.decode.mockReturnValue(null);
|
||||||
|
|
||||||
await expect(
|
await expect(context.service.addToBlacklist(mockToken)).rejects.toThrow(
|
||||||
context.service.addToBlacklist(mockToken),
|
'Token inválido',
|
||||||
).rejects.toThrow('Token inválido');
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('deve lançar erro quando decode falha', async () => {
|
it('deve lançar erro quando decode falha', async () => {
|
||||||
@@ -102,9 +102,9 @@ describe('TokenBlacklistService', () => {
|
|||||||
throw new Error('Token malformado');
|
throw new Error('Token malformado');
|
||||||
});
|
});
|
||||||
|
|
||||||
await expect(
|
await expect(context.service.addToBlacklist(mockToken)).rejects.toThrow(
|
||||||
context.service.addToBlacklist(mockToken),
|
'Erro ao adicionar token à blacklist',
|
||||||
).rejects.toThrow('Erro ao adicionar token à blacklist');
|
);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -169,9 +169,7 @@ describe('TokenBlacklistService', () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
context.mockJwtService.decode.mockReturnValue(mockPayload);
|
context.mockJwtService.decode.mockReturnValue(mockPayload);
|
||||||
context.mockRedisClient.get.mockRejectedValue(
|
context.mockRedisClient.get.mockRejectedValue(new Error('Redis error'));
|
||||||
new Error('Redis error'),
|
|
||||||
);
|
|
||||||
|
|
||||||
const result = await context.service.isBlacklisted(mockToken);
|
const result = await context.service.isBlacklisted(mockToken);
|
||||||
|
|
||||||
@@ -254,4 +252,3 @@ describe('TokenBlacklistService', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -193,7 +193,6 @@ export class LoginAuditService {
|
|||||||
const cutoffDate = new Date(
|
const cutoffDate = new Date(
|
||||||
DateUtil.nowTimestamp() - 30 * 24 * 60 * 60 * 1000,
|
DateUtil.nowTimestamp() - 30 * 24 * 60 * 60 * 1000,
|
||||||
);
|
);
|
||||||
const cutoffDateStr = DateUtil.toBrazilString(cutoffDate, 'yyyy-MM-dd');
|
|
||||||
|
|
||||||
const oldDates = this.getDateRange(new Date('2020-01-01'), cutoffDate);
|
const oldDates = this.getDateRange(new Date('2020-01-01'), cutoffDate);
|
||||||
for (const date of oldDates) {
|
for (const date of oldDates) {
|
||||||
|
|||||||
@@ -62,16 +62,15 @@ export class RateLimitingService {
|
|||||||
finalConfig.blockDurationMs,
|
finalConfig.blockDurationMs,
|
||||||
)) as [number, number];
|
)) as [number, number];
|
||||||
|
|
||||||
const [attempts, isBlockedResult] = result;
|
const [_attempts, isBlockedResult] = result;
|
||||||
return isBlockedResult === 0;
|
return isBlockedResult === 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
async recordAttempt(
|
async recordAttempt(
|
||||||
ip: string,
|
ip: string,
|
||||||
success: boolean,
|
success: boolean,
|
||||||
config?: Partial<RateLimitConfig>,
|
_config?: Partial<RateLimitConfig>,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
const finalConfig = { ...this.defaultConfig, ...config };
|
|
||||||
const key = this.buildAttemptKey(ip);
|
const key = this.buildAttemptKey(ip);
|
||||||
const blockKey = this.buildBlockKey(ip);
|
const blockKey = this.buildBlockKey(ip);
|
||||||
|
|
||||||
|
|||||||
@@ -80,7 +80,7 @@ export class RefreshTokenService {
|
|||||||
sessionId: sessionId || tokenData.sessionId,
|
sessionId: sessionId || tokenData.sessionId,
|
||||||
tokenId,
|
tokenId,
|
||||||
} as JwtPayload;
|
} as JwtPayload;
|
||||||
} catch (error) {
|
} catch (_error) {
|
||||||
throw new UnauthorizedException('Refresh token inválido');
|
throw new UnauthorizedException('Refresh token inválido');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ export class TokenBlacklistService {
|
|||||||
const blacklistKey = this.buildBlacklistKey(token);
|
const blacklistKey = this.buildBlacklistKey(token);
|
||||||
const result = await this.redis.get(blacklistKey);
|
const result = await this.redis.get(blacklistKey);
|
||||||
return result === 'blacklisted';
|
return result === 'blacklisted';
|
||||||
} catch (error) {
|
} catch (_error) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -61,7 +61,7 @@ describe('JwtStrategy', () => {
|
|||||||
* - Lançar UnauthorizedException
|
* - Lançar UnauthorizedException
|
||||||
* - Com mensagem 'Payload inválido ou incompleto'
|
* - Com mensagem 'Payload inválido ou incompleto'
|
||||||
*/
|
*/
|
||||||
testCases.forEach(({ payload, description }) => {
|
testCases.forEach(({ payload, description: _description }) => {
|
||||||
expect(() => {
|
expect(() => {
|
||||||
if (!payload.id || !payload.sessionId) {
|
if (!payload.id || !payload.sessionId) {
|
||||||
throw new UnauthorizedException('Payload inválido ou incompleto');
|
throw new UnauthorizedException('Payload inválido ou incompleto');
|
||||||
|
|||||||
@@ -3,15 +3,16 @@ import { Injectable } from '@nestjs/common';
|
|||||||
@Injectable()
|
@Injectable()
|
||||||
export class EmailService {
|
export class EmailService {
|
||||||
async sendPasswordReset(email: string, newPassword: string) {
|
async sendPasswordReset(email: string, newPassword: string) {
|
||||||
const sql = `
|
// SQL query would be executed here if database connection was available
|
||||||
INSERT INTO CORRESPONDENCIAS (
|
// const sql = `
|
||||||
CORRESPONDENCIA_ID, DTINCLUSAO, TITULO, MENSAGEM, EMAIL, DESTINATARIO
|
// INSERT INTO CORRESPONDENCIAS (
|
||||||
) VALUES (
|
// CORRESPONDENCIA_ID, DTINCLUSAO, TITULO, MENSAGEM, EMAIL, DESTINATARIO
|
||||||
SEQ_CORRESPONDENCIAS.NEXTVAL, SYSDATE, 'Alteração de senha - CoteLivia',
|
// ) VALUES (
|
||||||
'Sua nova senha para acesso ao portal COTELIVIA é ${newPassword}',
|
// SEQ_CORRESPONDENCIAS.NEXTVAL, SYSDATE, 'Alteração de senha - CoteLivia',
|
||||||
:email, :email
|
// 'Sua nova senha para acesso ao portal COTELIVIA é ${newPassword}',
|
||||||
)
|
// :email, :email
|
||||||
`;
|
// )
|
||||||
|
// `;
|
||||||
|
|
||||||
console.log(`[Email enviado para ${email}] Senha: ${newPassword}`);
|
console.log(`[Email enviado para ${email}] Senha: ${newPassword}`);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ export function IsSanitized(validationOptions?: ValidationOptions) {
|
|||||||
propertyName: propertyName,
|
propertyName: propertyName,
|
||||||
options: validationOptions,
|
options: validationOptions,
|
||||||
validator: {
|
validator: {
|
||||||
validate(value: any, args: ValidationArguments) {
|
validate(value: any, _args: ValidationArguments) {
|
||||||
if (typeof value !== 'string') return true; // Skip non-string values
|
if (typeof value !== 'string') return true; // Skip non-string values
|
||||||
|
|
||||||
const sqlInjectionRegex =
|
const sqlInjectionRegex =
|
||||||
@@ -24,7 +24,7 @@ export function IsSanitized(validationOptions?: ValidationOptions) {
|
|||||||
|
|
||||||
// Check for NoSQL injection patterns (MongoDB)
|
// Check for NoSQL injection patterns (MongoDB)
|
||||||
const noSqlInjectionRegex =
|
const noSqlInjectionRegex =
|
||||||
/(\$where|\$ne|\$gt|\$lt|\$gte|\$lte|\$in|\$nin|\$or|\$and|\$regex|\$options|\$elemMatch|\{.*\:.*\})/i;
|
/(\$where|\$ne|\$gt|\$lt|\$gte|\$lte|\$in|\$nin|\$or|\$and|\$regex|\$options|\$elemMatch|\{.*:.*\})/i;
|
||||||
if (noSqlInjectionRegex.test(value)) {
|
if (noSqlInjectionRegex.test(value)) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -38,7 +38,7 @@ export function IsSanitized(validationOptions?: ValidationOptions) {
|
|||||||
|
|
||||||
return true;
|
return true;
|
||||||
},
|
},
|
||||||
defaultMessage(args: ValidationArguments) {
|
defaultMessage(_args: ValidationArguments) {
|
||||||
return 'A entrada contém caracteres inválidos ou padrões potencialmente maliciosos';
|
return 'A entrada contém caracteres inválidos ou padrões potencialmente maliciosos';
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -55,7 +55,7 @@ export function IsSecureId(validationOptions?: ValidationOptions) {
|
|||||||
propertyName: propertyName,
|
propertyName: propertyName,
|
||||||
options: validationOptions,
|
options: validationOptions,
|
||||||
validator: {
|
validator: {
|
||||||
validate(value: any, args: ValidationArguments) {
|
validate(value: any, _args: ValidationArguments) {
|
||||||
if (typeof value !== 'string' && typeof value !== 'number')
|
if (typeof value !== 'string' && typeof value !== 'number')
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
@@ -69,7 +69,7 @@ export function IsSecureId(validationOptions?: ValidationOptions) {
|
|||||||
// Se for número, deve ser positivo
|
// Se for número, deve ser positivo
|
||||||
return value > 0;
|
return value > 0;
|
||||||
},
|
},
|
||||||
defaultMessage(args: ValidationArguments) {
|
defaultMessage(_args: ValidationArguments) {
|
||||||
return 'O ID fornecido não é seguro ou está em formato inválido';
|
return 'O ID fornecido não é seguro ou está em formato inválido';
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ export class RedisClientAdapter implements IRedisClient {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
return JSON.parse(data);
|
return JSON.parse(data);
|
||||||
} catch (error) {
|
} catch (_error) {
|
||||||
// If it's not valid JSON, return the raw string value
|
// If it's not valid JSON, return the raw string value
|
||||||
return data as T;
|
return data as T;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
/* eslint-disable prettier/prettier */
|
|
||||||
export class ChangePasswordModel {
|
export class ChangePasswordModel {
|
||||||
id: number;
|
id: number;
|
||||||
password: string;
|
password: string;
|
||||||
newPassword: string;
|
newPassword: string;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
/* eslint-disable prettier/prettier */
|
|
||||||
export class ExposedProduct {
|
export class ExposedProduct {
|
||||||
ean: string;
|
ean: string;
|
||||||
storeId: string;
|
storeId: string;
|
||||||
userId: number;
|
userId: number;
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,3 @@
|
|||||||
/* eslint-disable prettier/prettier */
|
|
||||||
export class ResetPasswordModel {
|
export class ResetPasswordModel {
|
||||||
document: string;
|
document: string;
|
||||||
email: string;
|
email: string;
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
/* eslint-disable prettier/prettier */
|
|
||||||
export class ResultModel {
|
export class ResultModel {
|
||||||
|
constructor(
|
||||||
constructor(
|
public success: boolean,
|
||||||
public success: boolean,
|
public message: string,
|
||||||
public message: string,
|
public data: any,
|
||||||
public data: any,
|
public errors: any,
|
||||||
public errors: any) {};
|
) {}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -74,11 +74,11 @@ export async function createDataConsultServiceTestModule(
|
|||||||
error: jest.fn(),
|
error: jest.fn(),
|
||||||
};
|
};
|
||||||
|
|
||||||
jest.spyOn(Logger.prototype, 'error').mockImplementation(
|
jest
|
||||||
(message: any, ...optionalParams: any[]) => {
|
.spyOn(Logger.prototype, 'error')
|
||||||
|
.mockImplementation((message: any, ...optionalParams: any[]) => {
|
||||||
mockLogger.error(message, ...optionalParams);
|
mockLogger.error(message, ...optionalParams);
|
||||||
},
|
});
|
||||||
);
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
service,
|
service,
|
||||||
|
|||||||
@@ -623,15 +623,15 @@ describe('DataConsultService', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should throw error when filter is invalid', async () => {
|
it('should throw error when filter is invalid', async () => {
|
||||||
await expect(
|
await expect(context.service.products(null as any)).rejects.toThrow(
|
||||||
context.service.products(null as any),
|
HttpException,
|
||||||
).rejects.toThrow(HttpException);
|
);
|
||||||
await expect(
|
await expect(
|
||||||
context.service.products(undefined as any),
|
context.service.products(undefined as any),
|
||||||
).rejects.toThrow(HttpException);
|
).rejects.toThrow(HttpException);
|
||||||
await expect(
|
await expect(context.service.products('' as any)).rejects.toThrow(
|
||||||
context.service.products('' as any),
|
HttpException,
|
||||||
).rejects.toThrow(HttpException);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should log error when repository throws exception', async () => {
|
it('should log error when repository throws exception', async () => {
|
||||||
|
|||||||
@@ -1,6 +1,4 @@
|
|||||||
import {
|
import { ApiTags } from '@nestjs/swagger';
|
||||||
ApiTags,
|
|
||||||
} from '@nestjs/swagger';
|
|
||||||
import { Controller, Get, Param } from '@nestjs/common';
|
import { Controller, Get, Param } from '@nestjs/common';
|
||||||
import { clientesService } from './clientes.service';
|
import { clientesService } from './clientes.service';
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,3 @@
|
|||||||
/* eslint-disable prettier/prettier */
|
|
||||||
|
|
||||||
import { clientesService } from './clientes.service';
|
import { clientesService } from './clientes.service';
|
||||||
import { clientesController } from './clientes.controller';
|
import { clientesController } from './clientes.controller';
|
||||||
|
|
||||||
@@ -10,10 +8,8 @@ https://docs.nestjs.com/modules
|
|||||||
import { Module } from '@nestjs/common';
|
import { Module } from '@nestjs/common';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [],
|
imports: [],
|
||||||
controllers: [
|
controllers: [clientesController],
|
||||||
clientesController,],
|
providers: [clientesService],
|
||||||
providers: [
|
|
||||||
clientesService,],
|
|
||||||
})
|
})
|
||||||
export class clientes { }
|
export class clientes {}
|
||||||
|
|||||||
@@ -142,9 +142,7 @@ export class clientesService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async clearCustomersCache(_pattern?: string) {
|
||||||
async clearCustomersCache(pattern?: string) {
|
// Cache clearing logic would be implemented here
|
||||||
const cachePattern = pattern || 'clientes:*';
|
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -87,13 +87,18 @@ export class DataConsultController {
|
|||||||
@ApiBearerAuth()
|
@ApiBearerAuth()
|
||||||
@Get('products/codauxiliar/:codauxiliar')
|
@Get('products/codauxiliar/:codauxiliar')
|
||||||
@ApiOperation({ summary: 'Busca produtos por código auxiliar (EAN)' })
|
@ApiOperation({ summary: 'Busca produtos por código auxiliar (EAN)' })
|
||||||
@ApiParam({ name: 'codauxiliar', description: 'Código auxiliar (EAN) do produto' })
|
@ApiParam({
|
||||||
|
name: 'codauxiliar',
|
||||||
|
description: 'Código auxiliar (EAN) do produto',
|
||||||
|
})
|
||||||
@ApiResponse({
|
@ApiResponse({
|
||||||
status: 200,
|
status: 200,
|
||||||
description: 'Lista de produtos encontrados por código auxiliar',
|
description: 'Lista de produtos encontrados por código auxiliar',
|
||||||
type: [ProductDto],
|
type: [ProductDto],
|
||||||
})
|
})
|
||||||
async productsByCodauxiliar(@Param('codauxiliar') codauxiliar: string): Promise<ProductDto[]> {
|
async productsByCodauxiliar(
|
||||||
|
@Param('codauxiliar') codauxiliar: string,
|
||||||
|
): Promise<ProductDto[]> {
|
||||||
return this.dataConsultService.productsByCodauxiliar(codauxiliar);
|
return this.dataConsultService.productsByCodauxiliar(codauxiliar);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -124,7 +124,10 @@ export class DataConsultRepository {
|
|||||||
WHERE PCPRODUT.CODPROD = :0
|
WHERE PCPRODUT.CODPROD = :0
|
||||||
OR REGEXP_REPLACE(PCPRODUT.CODAUXILIAR, '[^0-9]', '') = :1
|
OR REGEXP_REPLACE(PCPRODUT.CODAUXILIAR, '[^0-9]', '') = :1
|
||||||
`;
|
`;
|
||||||
const results = await this.executeQuery<ProductDto[]>(sql, [filter, cleanedFilter]);
|
const results = await this.executeQuery<ProductDto[]>(sql, [
|
||||||
|
filter,
|
||||||
|
cleanedFilter,
|
||||||
|
]);
|
||||||
return results.map((result) => new ProductDto(result));
|
return results.map((result) => new ProductDto(result));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,10 @@
|
|||||||
import { Injectable, HttpException, HttpStatus, Inject, Logger } from '@nestjs/common';
|
import {
|
||||||
|
Injectable,
|
||||||
|
HttpException,
|
||||||
|
HttpStatus,
|
||||||
|
Inject,
|
||||||
|
Logger,
|
||||||
|
} from '@nestjs/common';
|
||||||
import { DataConsultRepository } from './data-consult.repository';
|
import { DataConsultRepository } from './data-consult.repository';
|
||||||
import { StoreDto } from './dto/store.dto';
|
import { StoreDto } from './dto/store.dto';
|
||||||
import { SellerDto } from './dto/seller.dto';
|
import { SellerDto } from './dto/seller.dto';
|
||||||
@@ -231,9 +237,14 @@ export class DataConsultService {
|
|||||||
this.logger.log(`Buscando produtos por codauxiliar: ${codauxiliar}`);
|
this.logger.log(`Buscando produtos por codauxiliar: ${codauxiliar}`);
|
||||||
try {
|
try {
|
||||||
if (!codauxiliar || typeof codauxiliar !== 'string') {
|
if (!codauxiliar || typeof codauxiliar !== 'string') {
|
||||||
throw new HttpException('Código auxiliar inválido', HttpStatus.BAD_REQUEST);
|
throw new HttpException(
|
||||||
|
'Código auxiliar inválido',
|
||||||
|
HttpStatus.BAD_REQUEST,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
const products = await this.repository.findProductsByCodauxiliar(codauxiliar);
|
const products = await this.repository.findProductsByCodauxiliar(
|
||||||
|
codauxiliar,
|
||||||
|
);
|
||||||
return products.map((product) => new ProductDto(product));
|
return products.map((product) => new ProductDto(product));
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.logger.error('Erro ao buscar produtos por codauxiliar', error);
|
this.logger.error('Erro ao buscar produtos por codauxiliar', error);
|
||||||
|
|||||||
@@ -1,5 +1,3 @@
|
|||||||
/* eslint-disable prettier/prettier */
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
https://docs.nestjs.com/controllers#controllers
|
https://docs.nestjs.com/controllers#controllers
|
||||||
*/
|
*/
|
||||||
@@ -7,59 +5,50 @@ https://docs.nestjs.com/controllers#controllers
|
|||||||
import { LogisticService } from './logistic.service';
|
import { LogisticService } from './logistic.service';
|
||||||
import { CarOutDelivery } from '../core/models/car-out-delivery.model';
|
import { CarOutDelivery } from '../core/models/car-out-delivery.model';
|
||||||
import { CarInDelivery } from '../core/models/car-in-delivery.model';
|
import { CarInDelivery } from '../core/models/car-in-delivery.model';
|
||||||
import {
|
import { Body, Controller, Get, Param, Post, UseGuards } from '@nestjs/common';
|
||||||
Body,
|
import { JwtAuthGuard } from 'src/auth/guards/jwt-auth.guard';
|
||||||
Controller,
|
import { ApiBearerAuth, ApiTags, ApiOperation } from '@nestjs/swagger';
|
||||||
Get,
|
|
||||||
Param,
|
|
||||||
Post,
|
|
||||||
UseGuards
|
|
||||||
} from '@nestjs/common';
|
|
||||||
import { JwtAuthGuard } from 'src/auth/guards/jwt-auth.guard';
|
|
||||||
import { ApiBearerAuth, ApiTags, ApiOperation } from '@nestjs/swagger';
|
|
||||||
|
|
||||||
|
@ApiTags('Logística')
|
||||||
|
@ApiBearerAuth()
|
||||||
|
@UseGuards(JwtAuthGuard)
|
||||||
|
@Controller('api/v1/logistic')
|
||||||
|
export class LogisticController {
|
||||||
|
constructor(private readonly logisticService: LogisticService) {}
|
||||||
|
|
||||||
@ApiTags('Logística')
|
@Get('expedicao')
|
||||||
@ApiBearerAuth()
|
@ApiOperation({ summary: 'Retorna informações de expedição' })
|
||||||
@UseGuards(JwtAuthGuard)
|
getExpedicao() {
|
||||||
@Controller('api/v1/logistic')
|
return this.logisticService.getExpedicao();
|
||||||
export class LogisticController {
|
|
||||||
constructor(private readonly logisticService: LogisticService) {}
|
|
||||||
|
|
||||||
@Get('expedicao')
|
|
||||||
@ApiOperation({ summary: 'Retorna informações de expedição' })
|
|
||||||
getExpedicao() {
|
|
||||||
return this.logisticService.getExpedicao();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Get('employee')
|
|
||||||
@ApiOperation({ summary: 'Retorna lista de funcionários' })
|
|
||||||
getEmployee() {
|
|
||||||
return this.logisticService.getEmployee();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Get('deliveries/:placa')
|
|
||||||
@ApiOperation({ summary: 'Retorna entregas por placa' })
|
|
||||||
getDelivery(@Param('placa') placa: string) {
|
|
||||||
return this.logisticService.getDeliveries(placa);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Get('status-car/:placa')
|
|
||||||
@ApiOperation({ summary: 'Retorna status do veículo por placa' })
|
|
||||||
getStatusCar(@Param('placa') placa: string) {
|
|
||||||
return this.logisticService.getStatusCar(placa);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Post('create')
|
|
||||||
@ApiOperation({ summary: 'Registra saída de veículo' })
|
|
||||||
createOutCar(@Body() data: CarOutDelivery) {
|
|
||||||
return this.logisticService.createCarOut(data);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Post('return-car')
|
|
||||||
@ApiOperation({ summary: 'Registra retorno de veículo' })
|
|
||||||
createinCar(@Body() data: CarInDelivery) {
|
|
||||||
return this.logisticService.createCarIn(data);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Get('employee')
|
||||||
|
@ApiOperation({ summary: 'Retorna lista de funcionários' })
|
||||||
|
getEmployee() {
|
||||||
|
return this.logisticService.getEmployee();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get('deliveries/:placa')
|
||||||
|
@ApiOperation({ summary: 'Retorna entregas por placa' })
|
||||||
|
getDelivery(@Param('placa') placa: string) {
|
||||||
|
return this.logisticService.getDeliveries(placa);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get('status-car/:placa')
|
||||||
|
@ApiOperation({ summary: 'Retorna status do veículo por placa' })
|
||||||
|
getStatusCar(@Param('placa') placa: string) {
|
||||||
|
return this.logisticService.getStatusCar(placa);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('create')
|
||||||
|
@ApiOperation({ summary: 'Registra saída de veículo' })
|
||||||
|
createOutCar(@Body() data: CarOutDelivery) {
|
||||||
|
return this.logisticService.createCarOut(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('return-car')
|
||||||
|
@ApiOperation({ summary: 'Registra retorno de veículo' })
|
||||||
|
createinCar(@Body() data: CarInDelivery) {
|
||||||
|
return this.logisticService.createCarIn(data);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,15 +1,10 @@
|
|||||||
/* eslint-disable prettier/prettier */
|
|
||||||
|
|
||||||
|
|
||||||
import { LogisticController } from './logistic.controller';
|
import { LogisticController } from './logistic.controller';
|
||||||
import { LogisticService } from './logistic.service';
|
import { LogisticService } from './logistic.service';
|
||||||
import { Module } from '@nestjs/common';
|
import { Module } from '@nestjs/common';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [],
|
imports: [],
|
||||||
controllers: [
|
controllers: [LogisticController],
|
||||||
LogisticController,],
|
providers: [LogisticService],
|
||||||
providers: [
|
|
||||||
LogisticService,],
|
|
||||||
})
|
})
|
||||||
export class LogisticModule { }
|
export class LogisticModule {}
|
||||||
|
|||||||
@@ -1,8 +1,4 @@
|
|||||||
import {
|
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
|
||||||
HttpException,
|
|
||||||
HttpStatus,
|
|
||||||
Injectable,
|
|
||||||
} from '@nestjs/common';
|
|
||||||
import { createOracleConfig } from '../core/configs/typeorm.oracle.config';
|
import { createOracleConfig } from '../core/configs/typeorm.oracle.config';
|
||||||
import { createPostgresConfig } from '../core/configs/typeorm.postgres.config';
|
import { createPostgresConfig } from '../core/configs/typeorm.postgres.config';
|
||||||
import { CarOutDelivery } from '../core/models/car-out-delivery.model';
|
import { CarOutDelivery } from '../core/models/car-out-delivery.model';
|
||||||
@@ -55,7 +51,7 @@ export class LogisticService {
|
|||||||
where dados.data_saida >= current_date
|
where dados.data_saida >= current_date
|
||||||
ORDER BY dados.data_saida desc `;
|
ORDER BY dados.data_saida desc `;
|
||||||
|
|
||||||
const sql = `SELECT COUNT(DISTINCT PCCARREG.NUMCAR) as "qtde"
|
const _sql = `SELECT COUNT(DISTINCT PCCARREG.NUMCAR) as "qtde"
|
||||||
,SUM(PCPEDI.QT * PCPRODUT.PESOBRUTO) as "totalKG"
|
,SUM(PCPEDI.QT * PCPRODUT.PESOBRUTO) as "totalKG"
|
||||||
,SUM(CASE WHEN PCPEDC.DTINICIALSEP IS NULL THEN PCPEDI.QT ELSE 0 END * PCPRODUT.PESOBRUTO) as "total_nao_iniciado"
|
,SUM(CASE WHEN PCPEDC.DTINICIALSEP IS NULL THEN PCPEDI.QT ELSE 0 END * PCPRODUT.PESOBRUTO) as "total_nao_iniciado"
|
||||||
,SUM(CASE WHEN PCPEDC.DTINICIALSEP IS NOT NULL
|
,SUM(CASE WHEN PCPEDC.DTINICIALSEP IS NOT NULL
|
||||||
@@ -103,7 +99,7 @@ export class LogisticService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async getDeliveries(placa: string) {
|
async getDeliveries(_placa: string) {
|
||||||
const dataSource = new DataSource(createOracleConfig(this.configService));
|
const dataSource = new DataSource(createOracleConfig(this.configService));
|
||||||
await dataSource.initialize();
|
await dataSource.initialize();
|
||||||
const queryRunner = dataSource.createQueryRunner();
|
const queryRunner = dataSource.createQueryRunner();
|
||||||
@@ -202,10 +198,10 @@ export class LogisticService {
|
|||||||
let helperId1 = 0;
|
let helperId1 = 0;
|
||||||
let helperId2 = 0;
|
let helperId2 = 0;
|
||||||
let helperId3 = 0;
|
let helperId3 = 0;
|
||||||
const image1 = '';
|
const _image1 = '';
|
||||||
const image2 = '';
|
const _image2 = '';
|
||||||
const image3 = '';
|
const _image3 = '';
|
||||||
const image4 = '';
|
const _image4 = '';
|
||||||
|
|
||||||
data.helpers.forEach((helper) => {
|
data.helpers.forEach((helper) => {
|
||||||
switch (i) {
|
switch (i) {
|
||||||
@@ -283,11 +279,11 @@ export class LogisticService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const i = 0;
|
const _i = 0;
|
||||||
const image1 = '';
|
const _image1 = '';
|
||||||
const image2 = '';
|
const _image2 = '';
|
||||||
const image3 = '';
|
const _image3 = '';
|
||||||
const image4 = '';
|
const _image4 = '';
|
||||||
|
|
||||||
for (let y = 0; y < data.invoices.length; y++) {
|
for (let y = 0; y < data.invoices.length; y++) {
|
||||||
const invoice = data.invoices[y];
|
const invoice = data.invoices[y];
|
||||||
|
|||||||
@@ -2,9 +2,7 @@ import { Test, TestingModule } from '@nestjs/testing';
|
|||||||
import { DebService } from '../deb.service';
|
import { DebService } from '../deb.service';
|
||||||
import { DebRepository } from '../../repositories/deb.repository';
|
import { DebRepository } from '../../repositories/deb.repository';
|
||||||
|
|
||||||
export const createMockRepository = (
|
export const createMockRepository = (methods: Partial<DebRepository> = {}) =>
|
||||||
methods: Partial<DebRepository> = {},
|
|
||||||
) =>
|
|
||||||
({
|
({
|
||||||
findByCpfCgcent: jest.fn(),
|
findByCpfCgcent: jest.fn(),
|
||||||
...methods,
|
...methods,
|
||||||
@@ -37,4 +35,3 @@ export async function createDebServiceTestModule(
|
|||||||
mockRepository,
|
mockRepository,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -81,10 +81,7 @@ describe('DebService', () => {
|
|||||||
|
|
||||||
context.mockRepository.findByCpfCgcent.mockResolvedValue(mockDebs);
|
context.mockRepository.findByCpfCgcent.mockResolvedValue(mockDebs);
|
||||||
|
|
||||||
const result = await context.service.findByCpfCgcent(
|
const result = await context.service.findByCpfCgcent('12345678900', 1498);
|
||||||
'12345678900',
|
|
||||||
1498,
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(result).toHaveLength(1);
|
expect(result).toHaveLength(1);
|
||||||
expect(context.mockRepository.findByCpfCgcent).toHaveBeenCalledWith(
|
expect(context.mockRepository.findByCpfCgcent).toHaveBeenCalledWith(
|
||||||
@@ -178,9 +175,7 @@ describe('DebService', () => {
|
|||||||
|
|
||||||
it('deve propagar erro do repositório', async () => {
|
it('deve propagar erro do repositório', async () => {
|
||||||
const repositoryError = new Error('Database connection failed');
|
const repositoryError = new Error('Database connection failed');
|
||||||
context.mockRepository.findByCpfCgcent.mockRejectedValue(
|
context.mockRepository.findByCpfCgcent.mockRejectedValue(repositoryError);
|
||||||
repositoryError,
|
|
||||||
);
|
|
||||||
|
|
||||||
await expect(
|
await expect(
|
||||||
context.service.findByCpfCgcent('12345678900'),
|
context.service.findByCpfCgcent('12345678900'),
|
||||||
@@ -188,4 +183,3 @@ describe('DebService', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -4,9 +4,7 @@ import { OrdersRepository } from '../../repositories/orders.repository';
|
|||||||
import { IRedisClient } from '../../../core/configs/cache/IRedisClient';
|
import { IRedisClient } from '../../../core/configs/cache/IRedisClient';
|
||||||
import { RedisClientToken } from '../../../core/configs/cache/redis-client.adapter.provider';
|
import { RedisClientToken } from '../../../core/configs/cache/redis-client.adapter.provider';
|
||||||
|
|
||||||
export const createMockRepository = (
|
export const createMockRepository = (methods: Partial<OrdersRepository> = {}) =>
|
||||||
methods: Partial<OrdersRepository> = {},
|
|
||||||
) =>
|
|
||||||
({
|
({
|
||||||
findOrders: jest.fn(),
|
findOrders: jest.fn(),
|
||||||
getCompletedDeliveries: jest.fn(),
|
getCompletedDeliveries: jest.fn(),
|
||||||
@@ -57,4 +55,3 @@ export async function createOrdersServiceTestModule(
|
|||||||
mockRedisClient,
|
mockRedisClient,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -87,7 +87,9 @@ describe('OrdersService', () => {
|
|||||||
const result = await context.service.findOrders(query);
|
const result = await context.service.findOrders(query);
|
||||||
|
|
||||||
expect(result).toEqual(mockOrders);
|
expect(result).toEqual(mockOrders);
|
||||||
expect(context.mockRepository.getCompletedDeliveries).not.toHaveBeenCalled();
|
expect(
|
||||||
|
context.mockRepository.getCompletedDeliveries,
|
||||||
|
).not.toHaveBeenCalled();
|
||||||
expect(result[0].completedDeliveries).toBeUndefined();
|
expect(result[0].completedDeliveries).toBeUndefined();
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -139,13 +141,19 @@ describe('OrdersService', () => {
|
|||||||
expect(result).toHaveLength(2);
|
expect(result).toHaveLength(2);
|
||||||
expect(result[0].completedDeliveries).toEqual(mockDeliveries1);
|
expect(result[0].completedDeliveries).toEqual(mockDeliveries1);
|
||||||
expect(result[1].completedDeliveries).toEqual(mockDeliveries2);
|
expect(result[1].completedDeliveries).toEqual(mockDeliveries2);
|
||||||
expect(context.mockRepository.getCompletedDeliveries).toHaveBeenCalledTimes(2);
|
expect(
|
||||||
expect(context.mockRepository.getCompletedDeliveries).toHaveBeenCalledWith({
|
context.mockRepository.getCompletedDeliveries,
|
||||||
|
).toHaveBeenCalledTimes(2);
|
||||||
|
expect(
|
||||||
|
context.mockRepository.getCompletedDeliveries,
|
||||||
|
).toHaveBeenCalledWith({
|
||||||
orderNumber: 12345,
|
orderNumber: 12345,
|
||||||
limit: 10,
|
limit: 10,
|
||||||
offset: 0,
|
offset: 0,
|
||||||
});
|
});
|
||||||
expect(context.mockRepository.getCompletedDeliveries).toHaveBeenCalledWith({
|
expect(
|
||||||
|
context.mockRepository.getCompletedDeliveries,
|
||||||
|
).toHaveBeenCalledWith({
|
||||||
orderNumber: 12346,
|
orderNumber: 12346,
|
||||||
limit: 10,
|
limit: 10,
|
||||||
offset: 0,
|
offset: 0,
|
||||||
@@ -176,7 +184,9 @@ describe('OrdersService', () => {
|
|||||||
|
|
||||||
expect(result).toHaveLength(1);
|
expect(result).toHaveLength(1);
|
||||||
expect(result[0].completedDeliveries).toEqual([]);
|
expect(result[0].completedDeliveries).toEqual([]);
|
||||||
expect(context.mockRepository.getCompletedDeliveries).toHaveBeenCalled();
|
expect(
|
||||||
|
context.mockRepository.getCompletedDeliveries,
|
||||||
|
).toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should handle empty orders array', async () => {
|
it('should handle empty orders array', async () => {
|
||||||
@@ -273,7 +283,9 @@ describe('OrdersService', () => {
|
|||||||
const result = await context.service.findOrders(query);
|
const result = await context.service.findOrders(query);
|
||||||
|
|
||||||
expect(result).toHaveLength(1);
|
expect(result).toHaveLength(1);
|
||||||
expect(context.mockRepository.getCompletedDeliveries).toHaveBeenCalledWith({
|
expect(
|
||||||
|
context.mockRepository.getCompletedDeliveries,
|
||||||
|
).toHaveBeenCalledWith({
|
||||||
orderNumber: null,
|
orderNumber: null,
|
||||||
limit: 10,
|
limit: 10,
|
||||||
offset: 0,
|
offset: 0,
|
||||||
@@ -300,4 +312,3 @@ describe('OrdersService', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -66,7 +66,7 @@ export class OrdersService {
|
|||||||
deliveryQuery,
|
deliveryQuery,
|
||||||
);
|
);
|
||||||
order.completedDeliveries = deliveries;
|
order.completedDeliveries = deliveries;
|
||||||
} catch (error) {
|
} catch (_error) {
|
||||||
order.completedDeliveries = [];
|
order.completedDeliveries = [];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -242,7 +242,7 @@ export class OrdersService {
|
|||||||
deliveryQuery,
|
deliveryQuery,
|
||||||
);
|
);
|
||||||
orderDelivery.completedDeliveries = deliveries;
|
orderDelivery.completedDeliveries = deliveries;
|
||||||
} catch (error) {
|
} catch (_error) {
|
||||||
orderDelivery.completedDeliveries = [];
|
orderDelivery.completedDeliveries = [];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -13,7 +13,8 @@ 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")',
|
description:
|
||||||
|
'Código da filial (pode ser múltiplas filiais separadas por vírgula, ex: "1,2,3")',
|
||||||
})
|
})
|
||||||
codfilial?: string;
|
codfilial?: string;
|
||||||
|
|
||||||
@@ -56,7 +57,8 @@ export class FindOrdersDto {
|
|||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsString()
|
@IsString()
|
||||||
@ApiPropertyOptional({
|
@ApiPropertyOptional({
|
||||||
description: 'Código do usuário 2 (pode ser múltiplos valores separados por vírgula)',
|
description:
|
||||||
|
'Código do usuário 2 (pode ser múltiplos valores separados por vírgula)',
|
||||||
})
|
})
|
||||||
codusur2?: string;
|
codusur2?: string;
|
||||||
|
|
||||||
|
|||||||
@@ -419,9 +419,10 @@ WHERE
|
|||||||
.filter((c) => c)
|
.filter((c) => c)
|
||||||
.map((c) => Number(c))
|
.map((c) => Number(c))
|
||||||
.filter((c) => !isNaN(c));
|
.filter((c) => !isNaN(c));
|
||||||
const codusur2Condition = codusur2List.length === 1
|
const codusur2Condition =
|
||||||
? `AND PCPEDC.CODUSUR2 = :codusur2`
|
codusur2List.length === 1
|
||||||
: `AND PCPEDC.CODUSUR2 IN (${codusur2List.join(',')})`;
|
? `AND PCPEDC.CODUSUR2 = :codusur2`
|
||||||
|
: `AND PCPEDC.CODUSUR2 IN (${codusur2List.join(',')})`;
|
||||||
conditions.push(codusur2Condition);
|
conditions.push(codusur2Condition);
|
||||||
}
|
}
|
||||||
if (query.orderId) {
|
if (query.orderId) {
|
||||||
|
|||||||
@@ -38,4 +38,3 @@ export async function createProductsServiceTestModule(
|
|||||||
mockDataSource,
|
mockDataSource,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
import { HttpException } from '@nestjs/common';
|
import { HttpException } from '@nestjs/common';
|
||||||
import { createProductsServiceTestModule } from './products.service.spec.helper';
|
import { createProductsServiceTestModule } from './products.service.spec.helper';
|
||||||
import { ProductDetailQueryDto } from '../dto/product-detail-query.dto';
|
import { ProductDetailQueryDto } from '../dto/product-detail-query.dto';
|
||||||
import { ProductDetailResponseDto } from '../dto/product-detail-response.dto';
|
|
||||||
|
|
||||||
describe('ProductsService', () => {
|
describe('ProductsService', () => {
|
||||||
describe('getProductDetails', () => {
|
describe('getProductDetails', () => {
|
||||||
@@ -147,12 +146,12 @@ describe('ProductsService', () => {
|
|||||||
codfilial: '1',
|
codfilial: '1',
|
||||||
};
|
};
|
||||||
|
|
||||||
await expect(
|
await expect(context.service.getProductDetails(query)).rejects.toThrow(
|
||||||
context.service.getProductDetails(query),
|
HttpException,
|
||||||
).rejects.toThrow(HttpException);
|
);
|
||||||
await expect(
|
await expect(context.service.getProductDetails(query)).rejects.toThrow(
|
||||||
context.service.getProductDetails(query),
|
'É necessário informar codprod ou codauxiliar.',
|
||||||
).rejects.toThrow('É necessário informar codprod ou codauxiliar.');
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('deve lançar exceção quando codauxiliar é array vazio', async () => {
|
it('deve lançar exceção quando codauxiliar é array vazio', async () => {
|
||||||
@@ -162,14 +161,13 @@ describe('ProductsService', () => {
|
|||||||
codfilial: '1',
|
codfilial: '1',
|
||||||
};
|
};
|
||||||
|
|
||||||
await expect(
|
await expect(context.service.getProductDetails(query)).rejects.toThrow(
|
||||||
context.service.getProductDetails(query),
|
HttpException,
|
||||||
).rejects.toThrow(HttpException);
|
);
|
||||||
await expect(
|
await expect(context.service.getProductDetails(query)).rejects.toThrow(
|
||||||
context.service.getProductDetails(query),
|
'É necessário informar codprod ou codauxiliar.',
|
||||||
).rejects.toThrow('É necessário informar codprod ou codauxiliar.');
|
);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,11 @@
|
|||||||
import { ApiProperty } from '@nestjs/swagger';
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
import { IsArray, IsNotEmpty, IsNumber, IsOptional, IsString } from 'class-validator';
|
import {
|
||||||
|
IsArray,
|
||||||
|
IsNotEmpty,
|
||||||
|
IsNumber,
|
||||||
|
IsOptional,
|
||||||
|
IsString,
|
||||||
|
} from 'class-validator';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* DTO para requisição de detalhes de produtos
|
* DTO para requisição de detalhes de produtos
|
||||||
@@ -14,7 +20,8 @@ export class ProductDetailQueryDto {
|
|||||||
numregiao: number;
|
numregiao: number;
|
||||||
|
|
||||||
@ApiProperty({
|
@ApiProperty({
|
||||||
description: 'Array de códigos de produtos (opcional se codauxiliar for informado)',
|
description:
|
||||||
|
'Array de códigos de produtos (opcional se codauxiliar for informado)',
|
||||||
example: [1, 2, 3],
|
example: [1, 2, 3],
|
||||||
type: [Number],
|
type: [Number],
|
||||||
required: false,
|
required: false,
|
||||||
@@ -24,7 +31,8 @@ export class ProductDetailQueryDto {
|
|||||||
codprod?: number[];
|
codprod?: number[];
|
||||||
|
|
||||||
@ApiProperty({
|
@ApiProperty({
|
||||||
description: 'Array de códigos auxiliares (opcional se codprod for informado)',
|
description:
|
||||||
|
'Array de códigos auxiliares (opcional se codprod for informado)',
|
||||||
example: ['7891234567890', '7891234567891'],
|
example: ['7891234567890', '7891234567891'],
|
||||||
type: [String],
|
type: [String],
|
||||||
required: false,
|
required: false,
|
||||||
|
|||||||
@@ -22,7 +22,8 @@ export class RotinaA4QueryDto {
|
|||||||
codprod?: number;
|
codprod?: number;
|
||||||
|
|
||||||
@ApiProperty({
|
@ApiProperty({
|
||||||
description: 'Código auxiliar do produto (opcional se codprod for informado)',
|
description:
|
||||||
|
'Código auxiliar do produto (opcional se codprod for informado)',
|
||||||
example: '7891234567890',
|
example: '7891234567890',
|
||||||
required: false,
|
required: false,
|
||||||
})
|
})
|
||||||
@@ -37,4 +38,3 @@ export class RotinaA4QueryDto {
|
|||||||
@IsNotEmpty()
|
@IsNotEmpty()
|
||||||
codfilial: string;
|
codfilial: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -23,7 +23,8 @@ export class RotinaA4ResponseDto {
|
|||||||
CODAUXILIAR: string;
|
CODAUXILIAR: string;
|
||||||
|
|
||||||
@ApiProperty({
|
@ApiProperty({
|
||||||
description: 'Preço normal do produto formatado como moeda brasileira (com decimais)',
|
description:
|
||||||
|
'Preço normal do produto formatado como moeda brasileira (com decimais)',
|
||||||
example: '1.109,90',
|
example: '1.109,90',
|
||||||
})
|
})
|
||||||
PRECO_NORMAL: string;
|
PRECO_NORMAL: string;
|
||||||
@@ -35,7 +36,8 @@ export class RotinaA4ResponseDto {
|
|||||||
UNIDADE: string;
|
UNIDADE: string;
|
||||||
|
|
||||||
@ApiProperty({
|
@ApiProperty({
|
||||||
description: 'Valor de venda formatado como moeda brasileira (sem decimais)',
|
description:
|
||||||
|
'Valor de venda formatado como moeda brasileira (sem decimais)',
|
||||||
example: 'R$ 2.499',
|
example: 'R$ 2.499',
|
||||||
})
|
})
|
||||||
VALOR_VENDA: string;
|
VALOR_VENDA: string;
|
||||||
@@ -52,4 +54,3 @@ export class RotinaA4ResponseDto {
|
|||||||
})
|
})
|
||||||
MARCA: string;
|
MARCA: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -29,4 +29,3 @@ export class UnifiedProductSearchDto {
|
|||||||
@IsNotEmpty()
|
@IsNotEmpty()
|
||||||
codfilial: string;
|
codfilial: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,21 +1,33 @@
|
|||||||
/* eslint-disable prettier/prettier */
|
import {
|
||||||
/* eslint-disable @typescript-eslint/no-unused-vars */
|
Body,
|
||||||
|
Controller,
|
||||||
import { Body, Controller, Get, Param, Post, Query, UseGuards } from '@nestjs/common';
|
Get,
|
||||||
|
Param,
|
||||||
|
Post,
|
||||||
|
Query,
|
||||||
|
// UseGuards, // Comentado para uso futuro
|
||||||
|
} from '@nestjs/common';
|
||||||
import { ProductsService } from './products.service';
|
import { ProductsService } from './products.service';
|
||||||
import { ExposedProduct } from 'src/core/models/exposed-product.model';
|
import { ExposedProduct } from 'src/core/models/exposed-product.model';
|
||||||
import { JwtAuthGuard } from 'src/auth/guards/jwt-auth.guard';
|
// import { JwtAuthGuard } from 'src/auth/guards/jwt-auth.guard'; // Comentado para uso futuro
|
||||||
import { ExposedProductDto } from './dto/exposed-product.dto';
|
import { ExposedProductDto } from './dto/exposed-product.dto';
|
||||||
import { ProductValidationDto } from './dto/ProductValidationDto';
|
import { ProductValidationDto } from './dto/ProductValidationDto';
|
||||||
import { ProductEcommerceDto } from './dto/product-ecommerce.dto';
|
import { ProductEcommerceDto } from './dto/product-ecommerce.dto';
|
||||||
import { ApiTags, ApiOperation, ApiParam, ApiQuery, ApiBody, ApiResponse, ApiBearerAuth } from '@nestjs/swagger';
|
import {
|
||||||
|
ApiTags,
|
||||||
|
ApiOperation,
|
||||||
|
ApiParam,
|
||||||
|
ApiQuery,
|
||||||
|
ApiBody,
|
||||||
|
ApiResponse,
|
||||||
|
// ApiBearerAuth, // Comentado para uso futuro
|
||||||
|
} from '@nestjs/swagger';
|
||||||
import { ProductDetailQueryDto } from './dto/product-detail-query.dto';
|
import { ProductDetailQueryDto } from './dto/product-detail-query.dto';
|
||||||
import { ProductDetailResponseDto } from './dto/product-detail-response.dto';
|
import { ProductDetailResponseDto } from './dto/product-detail-response.dto';
|
||||||
import { RotinaA4QueryDto } from './dto/rotina-a4-query.dto';
|
import { RotinaA4QueryDto } from './dto/rotina-a4-query.dto';
|
||||||
import { RotinaA4ResponseDto } from './dto/rotina-a4-response.dto';
|
import { RotinaA4ResponseDto } from './dto/rotina-a4-response.dto';
|
||||||
import { UnifiedProductSearchDto } from './dto/unified-product-search.dto';
|
import { UnifiedProductSearchDto } from './dto/unified-product-search.dto';
|
||||||
|
|
||||||
|
|
||||||
//@ApiBearerAuth()
|
//@ApiBearerAuth()
|
||||||
//@UseGuards(JwtAuthGuard)
|
//@UseGuards(JwtAuthGuard)
|
||||||
@ApiTags('Produtos')
|
@ApiTags('Produtos')
|
||||||
@@ -23,43 +35,57 @@ import { UnifiedProductSearchDto } from './dto/unified-product-search.dto';
|
|||||||
export class ProductsController {
|
export class ProductsController {
|
||||||
constructor(private readonly productsService: ProductsService) {}
|
constructor(private readonly productsService: ProductsService) {}
|
||||||
|
|
||||||
///enpoit produtos-ecommecer
|
///enpoit produtos-ecommecer
|
||||||
@Get('products-ecommerce')
|
@Get('products-ecommerce')
|
||||||
@ApiOperation({ summary: 'Lista produtos para o e-commerce' })
|
@ApiOperation({ summary: 'Lista produtos para o e-commerce' })
|
||||||
@ApiResponse({
|
@ApiResponse({
|
||||||
status: 200,
|
status: 200,
|
||||||
description: 'Lista de produtos retornada com sucesso.',
|
description: 'Lista de produtos retornada com sucesso.',
|
||||||
type: ProductEcommerceDto,
|
type: ProductEcommerceDto,
|
||||||
isArray: true
|
isArray: true,
|
||||||
})
|
})
|
||||||
|
|
||||||
///ENDPOIT DE VALIDAR PRODUTO POR FILTRO
|
///ENDPOIT DE VALIDAR PRODUTO POR FILTRO
|
||||||
@Get('product-validation/:storeId/:filtro')
|
@Get('product-validation/:storeId/:filtro')
|
||||||
@ApiOperation({ summary: 'Valida produto pelo filtro (código, EAN ou descrição)' })
|
@ApiOperation({
|
||||||
|
summary: 'Valida produto pelo filtro (código, EAN ou descrição)',
|
||||||
|
})
|
||||||
@ApiParam({ name: 'storeId', type: String, description: 'ID da loja' })
|
@ApiParam({ name: 'storeId', type: String, description: 'ID da loja' })
|
||||||
@ApiParam({ name: 'filtro', type: String, description: 'Filtro de busca (código, EAN ou descrição)' })
|
@ApiParam({
|
||||||
@ApiQuery({ name: 'tipoBusca', required: false, enum: ['codauxiliar', 'codprod', 'descricao', 'todos'], description: 'Tipo de busca específica (opcional). Padrão: busca em todos os campos' })
|
name: 'filtro',
|
||||||
|
type: String,
|
||||||
|
description: 'Filtro de busca (código, EAN ou descrição)',
|
||||||
|
})
|
||||||
|
@ApiQuery({
|
||||||
|
name: 'tipoBusca',
|
||||||
|
required: false,
|
||||||
|
enum: ['codauxiliar', 'codprod', 'descricao', 'todos'],
|
||||||
|
description:
|
||||||
|
'Tipo de busca específica (opcional). Padrão: busca em todos os campos',
|
||||||
|
})
|
||||||
@ApiResponse({
|
@ApiResponse({
|
||||||
status: 200,
|
status: 200,
|
||||||
description: 'Produto encontrado com sucesso.',
|
description: 'Produto encontrado com sucesso.',
|
||||||
type: ProductValidationDto
|
type: ProductValidationDto,
|
||||||
})
|
})
|
||||||
@ApiResponse({ status: 404, description: 'Produto não localizado.' })
|
@ApiResponse({ status: 404, description: 'Produto não localizado.' })
|
||||||
async productValidation(
|
async productValidation(
|
||||||
@Param('storeId') storeId: string,
|
@Param('storeId') storeId: string,
|
||||||
@Param('filtro') filtro: string,
|
@Param('filtro') filtro: string,
|
||||||
@Query('tipoBusca') tipoBusca?: 'codauxiliar' | 'codprod' | 'descricao' | 'todos',
|
@Query('tipoBusca')
|
||||||
|
tipoBusca?: 'codauxiliar' | 'codprod' | 'descricao' | 'todos',
|
||||||
): Promise<ProductValidationDto> {
|
): Promise<ProductValidationDto> {
|
||||||
return this.productsService.productsValidation(storeId, filtro, tipoBusca);
|
return this.productsService.productsValidation(storeId, filtro, tipoBusca);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/// ENDPOIT PRODUTOS EXPOSTOS
|
/// ENDPOIT PRODUTOS EXPOSTOS
|
||||||
@Post('exposed-product')
|
@Post('exposed-product')
|
||||||
@ApiOperation({ summary: 'Registra produto em exposição' })
|
@ApiOperation({ summary: 'Registra produto em exposição' })
|
||||||
@ApiBody({ type: ExposedProductDto })
|
@ApiBody({ type: ExposedProductDto })
|
||||||
@ApiResponse({ status: 201, description: 'Produto exposto registrado com sucesso.' })
|
@ApiResponse({
|
||||||
|
status: 201,
|
||||||
|
description: 'Produto exposto registrado com sucesso.',
|
||||||
|
})
|
||||||
async exposedProduct(@Body() exposedProduct: ExposedProduct) {
|
async exposedProduct(@Body() exposedProduct: ExposedProduct) {
|
||||||
return this.productsService.exposedProduct(exposedProduct);
|
return this.productsService.exposedProduct(exposedProduct);
|
||||||
}
|
}
|
||||||
@@ -74,10 +100,12 @@ export class ProductsController {
|
|||||||
status: 200,
|
status: 200,
|
||||||
description: 'Lista de produtos com detalhes retornada com sucesso.',
|
description: 'Lista de produtos com detalhes retornada com sucesso.',
|
||||||
type: ProductDetailResponseDto,
|
type: ProductDetailResponseDto,
|
||||||
isArray: true
|
isArray: true,
|
||||||
})
|
})
|
||||||
@ApiResponse({ status: 400, description: 'Parâmetros inválidos.' })
|
@ApiResponse({ status: 400, description: 'Parâmetros inválidos.' })
|
||||||
async getProductDetails(@Body() query: ProductDetailQueryDto): Promise<ProductDetailResponseDto[]> {
|
async getProductDetails(
|
||||||
|
@Body() query: ProductDetailQueryDto,
|
||||||
|
): Promise<ProductDetailResponseDto[]> {
|
||||||
return this.productsService.getProductDetails(query);
|
return this.productsService.getProductDetails(query);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -90,10 +118,15 @@ export class ProductsController {
|
|||||||
@ApiResponse({
|
@ApiResponse({
|
||||||
status: 200,
|
status: 200,
|
||||||
description: 'Dados do produto retornados com sucesso.',
|
description: 'Dados do produto retornados com sucesso.',
|
||||||
type: RotinaA4ResponseDto
|
type: RotinaA4ResponseDto,
|
||||||
})
|
})
|
||||||
@ApiResponse({ status: 404, description: 'Produto não encontrado para os parâmetros informados.' })
|
@ApiResponse({
|
||||||
async getRotinaA4(@Body() query: RotinaA4QueryDto): Promise<RotinaA4ResponseDto> {
|
status: 404,
|
||||||
|
description: 'Produto não encontrado para os parâmetros informados.',
|
||||||
|
})
|
||||||
|
async getRotinaA4(
|
||||||
|
@Body() query: RotinaA4QueryDto,
|
||||||
|
): Promise<RotinaA4ResponseDto> {
|
||||||
return this.productsService.getRotinaA4(query);
|
return this.productsService.getRotinaA4(query);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -101,16 +134,21 @@ export class ProductsController {
|
|||||||
* Endpoint para busca unificada de produtos por nome, código de barras ou codprod
|
* Endpoint para busca unificada de produtos por nome, código de barras ou codprod
|
||||||
*/
|
*/
|
||||||
@Post('unified-search')
|
@Post('unified-search')
|
||||||
@ApiOperation({ summary: 'Busca unificada de produtos por nome, código de barras ou codprod' })
|
@ApiOperation({
|
||||||
|
summary:
|
||||||
|
'Busca unificada de produtos por nome, código de barras ou codprod',
|
||||||
|
})
|
||||||
@ApiBody({ type: UnifiedProductSearchDto })
|
@ApiBody({ type: UnifiedProductSearchDto })
|
||||||
@ApiResponse({
|
@ApiResponse({
|
||||||
status: 200,
|
status: 200,
|
||||||
description: 'Lista de produtos encontrados retornada com sucesso.',
|
description: 'Lista de produtos encontrados retornada com sucesso.',
|
||||||
type: ProductDetailResponseDto,
|
type: ProductDetailResponseDto,
|
||||||
isArray: true
|
isArray: true,
|
||||||
})
|
})
|
||||||
@ApiResponse({ status: 400, description: 'Parâmetros inválidos.' })
|
@ApiResponse({ status: 400, description: 'Parâmetros inválidos.' })
|
||||||
async unifiedProductSearch(@Body() query: UnifiedProductSearchDto): Promise<ProductDetailResponseDto[]> {
|
async unifiedProductSearch(
|
||||||
|
@Body() query: UnifiedProductSearchDto,
|
||||||
|
): Promise<ProductDetailResponseDto[]> {
|
||||||
return this.productsService.unifiedProductSearch(query);
|
return this.productsService.unifiedProductSearch(query);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,3 @@
|
|||||||
/* eslint-disable prettier/prettier */
|
|
||||||
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
https://docs.nestjs.com/modules
|
https://docs.nestjs.com/modules
|
||||||
*/
|
*/
|
||||||
@@ -10,10 +7,8 @@ import { ProductsService } from './products.service';
|
|||||||
import { ProductsController } from './products.controller';
|
import { ProductsController } from './products.controller';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [],
|
imports: [],
|
||||||
controllers: [
|
controllers: [ProductsController],
|
||||||
ProductsController,],
|
providers: [ProductsService],
|
||||||
providers: [
|
|
||||||
ProductsService,],
|
|
||||||
})
|
})
|
||||||
export class ProductsModule { }
|
export class ProductsModule {}
|
||||||
|
|||||||
@@ -21,21 +21,23 @@ export class ProductsService {
|
|||||||
): { whereCondition: string; useSingleParam: boolean } {
|
): { whereCondition: string; useSingleParam: boolean } {
|
||||||
if (tipoBusca === 'codauxiliar') {
|
if (tipoBusca === 'codauxiliar') {
|
||||||
return {
|
return {
|
||||||
whereCondition: 'PCPRODUT.CODAUXILIAR = REGEXP_REPLACE(:filtro, \'[^0-9]\', \'\')',
|
whereCondition:
|
||||||
|
"PCPRODUT.CODAUXILIAR = REGEXP_REPLACE(:filtro, '[^0-9]', '')",
|
||||||
useSingleParam: true,
|
useSingleParam: true,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
if (tipoBusca === 'codprod') {
|
if (tipoBusca === 'codprod') {
|
||||||
return {
|
return {
|
||||||
whereCondition: 'PCPRODUT.CODPROD = REGEXP_REPLACE(:filtro, \'[^0-9]\', \'\')',
|
whereCondition:
|
||||||
|
"PCPRODUT.CODPROD = REGEXP_REPLACE(:filtro, '[^0-9]', '')",
|
||||||
useSingleParam: true,
|
useSingleParam: true,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
if (tipoBusca === 'descricao') {
|
if (tipoBusca === 'descricao') {
|
||||||
return {
|
return {
|
||||||
whereCondition: 'PCPRODUT.DESCRICAO LIKE \'%\' || :filtro || \'%\'',
|
whereCondition: "PCPRODUT.DESCRICAO LIKE '%' || :filtro || '%'",
|
||||||
useSingleParam: true,
|
useSingleParam: true,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -170,7 +172,11 @@ export class ProductsService {
|
|||||||
const hasCodauxiliar = codauxiliar?.length > 0;
|
const hasCodauxiliar = codauxiliar?.length > 0;
|
||||||
|
|
||||||
if (hasCodprod && hasCodauxiliar) {
|
if (hasCodprod && hasCodauxiliar) {
|
||||||
return this.buildWhereConditionWithBoth(codprod, codauxiliar, startParamIndex);
|
return this.buildWhereConditionWithBoth(
|
||||||
|
codprod,
|
||||||
|
codauxiliar,
|
||||||
|
startParamIndex,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (hasCodprod) {
|
if (hasCodprod) {
|
||||||
@@ -178,7 +184,10 @@ export class ProductsService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (hasCodauxiliar) {
|
if (hasCodauxiliar) {
|
||||||
return this.buildWhereConditionWithCodauxiliar(codauxiliar, startParamIndex);
|
return this.buildWhereConditionWithCodauxiliar(
|
||||||
|
codauxiliar,
|
||||||
|
startParamIndex,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return { whereCondition: '', params: [], nextParamIndex: startParamIndex };
|
return { whereCondition: '', params: [], nextParamIndex: startParamIndex };
|
||||||
@@ -204,7 +213,11 @@ export class ProductsService {
|
|||||||
paramIndex++;
|
paramIndex++;
|
||||||
});
|
});
|
||||||
|
|
||||||
const whereCondition = `(PCPRODUT.CODPROD IN (${codprodPlaceholders.join(',')}) OR REGEXP_REPLACE(PCPRODUT.CODAUXILIAR, '[^0-9]', '') IN (${codauxiliarPlaceholders.join(',')}))`;
|
const whereCondition = `(PCPRODUT.CODPROD IN (${codprodPlaceholders.join(
|
||||||
|
',',
|
||||||
|
)}) OR REGEXP_REPLACE(PCPRODUT.CODAUXILIAR, '[^0-9]', '') IN (${codauxiliarPlaceholders.join(
|
||||||
|
',',
|
||||||
|
)}))`;
|
||||||
|
|
||||||
params.push(...codprod);
|
params.push(...codprod);
|
||||||
codauxiliar.forEach((aux) => {
|
codauxiliar.forEach((aux) => {
|
||||||
@@ -245,7 +258,9 @@ export class ProductsService {
|
|||||||
paramIndex++;
|
paramIndex++;
|
||||||
});
|
});
|
||||||
|
|
||||||
const whereCondition = `REGEXP_REPLACE(PCPRODUT.CODAUXILIAR, '[^0-9]', '') IN (${placeholders.join(',')})`;
|
const whereCondition = `REGEXP_REPLACE(PCPRODUT.CODAUXILIAR, '[^0-9]', '') IN (${placeholders.join(
|
||||||
|
',',
|
||||||
|
)})`;
|
||||||
codauxiliar.forEach((aux) => {
|
codauxiliar.forEach((aux) => {
|
||||||
params.push(aux.replace(/\D/g, ''));
|
params.push(aux.replace(/\D/g, ''));
|
||||||
});
|
});
|
||||||
@@ -394,7 +409,7 @@ export class ProductsService {
|
|||||||
if (hasCodprod && hasCodauxiliar) {
|
if (hasCodprod && hasCodauxiliar) {
|
||||||
return {
|
return {
|
||||||
whereCondition:
|
whereCondition:
|
||||||
'and (pcprodut.codprod = :3 OR REGEXP_REPLACE(pcprodut.CODAUXILIAR, \'[^0-9]\', \'\') = REGEXP_REPLACE(:4, \'[^0-9]\', \'\'))',
|
"and (pcprodut.codprod = :3 OR REGEXP_REPLACE(pcprodut.CODAUXILIAR, '[^0-9]', '') = REGEXP_REPLACE(:4, '[^0-9]', ''))",
|
||||||
params: [codprod, codauxiliar],
|
params: [codprod, codauxiliar],
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -409,7 +424,7 @@ export class ProductsService {
|
|||||||
if (hasCodauxiliar) {
|
if (hasCodauxiliar) {
|
||||||
return {
|
return {
|
||||||
whereCondition:
|
whereCondition:
|
||||||
'and REGEXP_REPLACE(pcprodut.CODAUXILIAR, \'[^0-9]\', \'\') = REGEXP_REPLACE(:3, \'[^0-9]\', \'\')',
|
"and REGEXP_REPLACE(pcprodut.CODAUXILIAR, '[^0-9]', '') = REGEXP_REPLACE(:3, '[^0-9]', '')",
|
||||||
params: [codauxiliar],
|
params: [codauxiliar],
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user