- 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
341 lines
17 KiB
TypeScript
341 lines
17 KiB
TypeScript
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
|
|
import { createOracleConfig } from '../core/configs/typeorm.oracle.config';
|
|
import { createPostgresConfig } from '../core/configs/typeorm.postgres.config';
|
|
import { CarOutDelivery } from '../core/models/car-out-delivery.model';
|
|
import { DataSource } from 'typeorm';
|
|
import { CarInDelivery } from '../core/models/car-in-delivery.model';
|
|
import { ConfigService } from '@nestjs/config';
|
|
|
|
@Injectable()
|
|
export class LogisticService {
|
|
constructor(private readonly configService: ConfigService) {}
|
|
|
|
async getExpedicao() {
|
|
const dataSource = new DataSource(createPostgresConfig(this.configService));
|
|
await dataSource.initialize();
|
|
const queryRunner = dataSource.createQueryRunner();
|
|
await queryRunner.connect();
|
|
try {
|
|
const sqlWMS = `select dados.*,
|
|
( select count(distinct v.numero_carga) quantidade_cargas_embarcadas
|
|
from volume v, carga c2
|
|
where v.numero_carga = c2.numero
|
|
and c2.data_integracao >= TO_DATE('01/02/2025', 'DD/MM/YYYY')
|
|
and TO_DATE(RIGHT(c2.observacao, 10), 'DD/MM/YYYY') = dados.dataHoje
|
|
and v.embarcado = 'S' ) quantidade_cargas_embarcadas
|
|
FROM ( select date_trunc('day', (CURRENT_DATE + INTERVAL '1 day'))::date data_saida, --TO_DATE(RIGHT(c.observacao, 10), 'DD/MM/YYYY') data_saida,
|
|
date_trunc('day', (CURRENT_DATE + INTERVAL '1 day'))::date dataHoje,
|
|
SUM(c.qt_itens_conferidos) total_itens_conferidos,
|
|
SUM(c.qt_itens_separados) total_itens_separados,
|
|
SUM(c.qt_total_itens) quantidade_total_itens,
|
|
SUM(c.qt_total_pedidos) quantidade_total,
|
|
SUM(m.qt * p.peso_unidade) total_kg,
|
|
COUNT(DISTINCT c.numero) quantidade_cargas,
|
|
COUNT(DISTINCT (CASE WHEN m.data_fim_separacao is not null then c.numero else null end)) quantidade_cargas_separacao_finalizadas,
|
|
COUNT(DISTINCT (CASE WHEN m.data_fim_conferencia is not null then c.numero else null end)) quantidade_cargas_conferencia_finalizadas,
|
|
SUM(case when m.data_inicio_separacao is null then m.qt * p.peso_unidade else 0 end) total_peso_separacao_nao_iniciada,
|
|
SUM(case when m.data_inicio_separacao is not null and m.data_fim_separacao is null then m.qt * p.peso_unidade else 0 end) total_peso_em_separacao,
|
|
SUM(case when m.data_fim_separacao is not null then m.qt * p.peso_unidade else 0 end) total_peso_separado,
|
|
SUM(case when m.data_fim_separacao is not null and m.data_inicio_conferencia is null then m.qt * p.peso_unidade else 0 end) total_conferencia_nao_iniciada,
|
|
SUM(case when m.data_fim_separacao is not null and m.data_inicio_conferencia is not null and m.data_fim_conferencia is null then m.qt * p.peso_unidade else 0 end) total_peso_em_conferencia,
|
|
SUM(case when m.data_fim_conferencia is not null then m.qt * p.peso_unidade else 0 end) total_peso_conferido
|
|
from movimentacao m , carga c , produto p
|
|
where m.numero_carga = c.numero
|
|
and m.produto_id = p.id
|
|
and m.data_integracao >= TO_DATE('01/01/2025', 'DD/MM/YYYY')
|
|
and c.data_faturamento IS NULL
|
|
and c.destino not like '%TRANSF%'
|
|
and m.empresa_id in ( 3, 4 )
|
|
--group by TO_DATE(RIGHT(c.observacao, 10), 'DD/MM/YYYY')
|
|
) dados
|
|
where dados.data_saida >= current_date
|
|
ORDER BY dados.data_saida desc `;
|
|
|
|
const _sql = `SELECT COUNT(DISTINCT PCCARREG.NUMCAR) as "qtde"
|
|
,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 NOT NULL
|
|
AND PCPEDC.DTFINALSEP IS NULL THEN PCPEDI.QT ELSE 0 END * PCPRODUT.PESOBRUTO) as "total_em_separacao"
|
|
,SUM(CASE WHEN PCPEDC.DTFINALSEP IS NOT NULL THEN PCPEDI.QT ELSE 0 END * PCPRODUT.PESOBRUTO) as "total_separado"
|
|
,SUM(CASE WHEN PCPEDC.DTFINALSEP IS NOT NULL
|
|
AND PCPEDC.DTINICIALCHECKOUT IS NULL THEN PCPEDI.QT ELSE 0 END * PCPRODUT.PESOBRUTO) as "total_conferencia_nao_iniciada"
|
|
,SUM(CASE WHEN PCPEDC.DTFINALSEP IS NOT NULL
|
|
AND PCPEDC.DTINICIALCHECKOUT IS NOT NULL
|
|
AND PCPEDC.DTFINALCHECKOUT IS NULL THEN PCPEDI.QT ELSE 0 END * PCPRODUT.PESOBRUTO) as "total_em_conferencia"
|
|
,SUM(CASE WHEN PCPEDC.DTFINALSEP IS NOT NULL
|
|
AND PCPEDC.DTFINALCHECKOUT IS NOT NULL THEN PCPEDI.QT ELSE 0 END * PCPRODUT.PESOBRUTO) as "total_coferencia_finalizada"
|
|
FROM PCPEDI, PCPEDC, PCPRODUT, PCCARREG
|
|
WHERE PCPEDI.NUMPED = PCPEDC.NUMPED
|
|
AND PCPEDI.CODPROD = PCPRODUT.CODPROD
|
|
AND PCPEDI.NUMCAR = PCCARREG.NUMCAR
|
|
AND PCPEDC.CODFILIAL = 12
|
|
AND PCPEDI.TIPOENTREGA IN ('EN', 'EF')
|
|
AND PCCARREG.DTSAIDA = TRUNC(SYSDATE)`;
|
|
|
|
const mov = await queryRunner.manager.query(sqlWMS);
|
|
|
|
const hoje = new Date();
|
|
|
|
let amanha = new Date(hoje);
|
|
amanha.setDate(hoje.getDate() + 1);
|
|
const amanhaString = amanha.toISOString().split('T')[0];
|
|
amanha = new Date(amanhaString);
|
|
|
|
console.log(amanha);
|
|
console.log(JSON.stringify(mov));
|
|
|
|
const movFiltered = mov.filter(
|
|
(m) =>
|
|
m.data_saida.toISOString().split('T')[0] ==
|
|
amanha.toISOString().split('T')[0],
|
|
);
|
|
|
|
return movFiltered;
|
|
} catch (e) {
|
|
console.log(e);
|
|
} finally {
|
|
await queryRunner.release();
|
|
await dataSource.destroy();
|
|
}
|
|
}
|
|
|
|
async getDeliveries(_placa: string) {
|
|
const dataSource = new DataSource(createOracleConfig(this.configService));
|
|
await dataSource.initialize();
|
|
const queryRunner = dataSource.createQueryRunner();
|
|
await queryRunner.connect();
|
|
try {
|
|
const sql = `SELECT PCCARREG.NUMCAR as "id"
|
|
,PCCARREG.DTSAIDA as "createDate"
|
|
,PCCARREG.DESTINO as "comment"
|
|
,PCCARREG.TOTPESO as "weight"
|
|
,PCCARREG.NUMNOTAS as "invoices"
|
|
,( SELECT COUNT(DISTINCT NVL(PCCLIENTENDENT.CODPRACAENT, PCPEDC.CODPRACA))
|
|
FROM PCPEDC, PCCLIENTENDENT
|
|
WHERE PCPEDC.NUMCAR = PCCARREG.NUMCAR
|
|
AND PCPEDC.CODENDENTCLI = PCCLIENTENDENT.CODENDENTCLI (+) ) as "citys"
|
|
,( SELECT COUNT(DISTINCT PCPEDC.CODCLI) FROM PCPEDC
|
|
WHERE PCPEDC.NUMCAR = PCCARREG.NUMCAR) as "deliveries"
|
|
,PCCARREG.CODMOTORISTA as "driverId"
|
|
,PCEMPR.NOME as "driverName"
|
|
,PCVEICUL.CODVEICULO as "carId"
|
|
,PCVEICUL.DESCRICAO as "carDescription"
|
|
,PCVEICUL.PLACA as "identification"
|
|
,PCCARREG.CODFUNCAJUD as "helperId"
|
|
,PCCARREG.CODFUNCAJUD2 as "helperId1"
|
|
,PCCARREG.CODFUNCAJUD3 as "helperId2"
|
|
FROM PCCARREG, PCVEICUL, PCEMPR
|
|
WHERE PCCARREG.CODVEICULO = PCVEICUL.codveiculo (+)
|
|
AND PCCARREG.CODMOTORISTA = PCEMPR.MATRICULA (+)
|
|
AND PCCARREG.DTFECHA IS NULL
|
|
AND PCCARREG.DTSAIDA >= TRUNC(SYSDATE)`;
|
|
|
|
const deliveries = await queryRunner.manager.query(sql);
|
|
|
|
return deliveries;
|
|
} catch (e) {
|
|
console.log(e);
|
|
} finally {
|
|
await queryRunner.release();
|
|
await dataSource.destroy();
|
|
}
|
|
}
|
|
|
|
async getStatusCar(placa: string) {
|
|
const dataSource = new DataSource(createPostgresConfig(this.configService));
|
|
await dataSource.initialize();
|
|
const queryRunner = dataSource.createQueryRunner();
|
|
await queryRunner.connect();
|
|
try {
|
|
const sql = `SELECT ESTSAIDAVEICULO.CODSAIDA FROM ESTSAIDAVEICULO, PCVEICUL
|
|
WHERE ESTSAIDAVEICULO.CODVEICULO = PCVEICUL.CODVEICULO
|
|
AND PCVEICUL.PLACA = '${placa}'
|
|
AND ESTSAIDAVEICULO.DTRETORNO IS NULL`;
|
|
|
|
const outCar = await queryRunner.manager.query(sql);
|
|
|
|
return { veiculoEmViagem: outCar.length > 0 ? true : false };
|
|
} catch (e) {
|
|
console.log(e);
|
|
} finally {
|
|
await queryRunner.release();
|
|
await dataSource.destroy();
|
|
}
|
|
}
|
|
|
|
async getEmployee() {
|
|
const dataSource = new DataSource(createOracleConfig(this.configService));
|
|
await dataSource.initialize();
|
|
const queryRunner = dataSource.createQueryRunner();
|
|
await queryRunner.connect();
|
|
try {
|
|
const sql = `SELECT PCEMPR.MATRICULA as "id"
|
|
,PCEMPR.NOME as "name"
|
|
,PCEMPR.FUNCAO as "fuctionName"
|
|
FROM PCEMPR, PCCONSUM
|
|
WHERE PCEMPR.DTDEMISSAO IS NULL
|
|
AND PCEMPR.CODSETOR = PCCONSUM.CODSETOREXPED
|
|
ORDER BY PCEMPR.NOME `;
|
|
const dataEmployee = await queryRunner.query(sql);
|
|
|
|
return dataEmployee;
|
|
} finally {
|
|
await queryRunner.release();
|
|
await dataSource.destroy();
|
|
}
|
|
}
|
|
|
|
async createCarOut(data: CarOutDelivery) {
|
|
const dataSource = new DataSource(createPostgresConfig(this.configService));
|
|
await dataSource.initialize();
|
|
const queryRunner = dataSource.createQueryRunner();
|
|
await queryRunner.connect();
|
|
await queryRunner.startTransaction();
|
|
try {
|
|
const sqlSequence = `SELECT ESS_SAIDAVEICULO.NEXTVAL as "id" FROM DUAL`;
|
|
const dataSequence = await queryRunner.query(sqlSequence);
|
|
let i = 0;
|
|
let helperId1 = 0;
|
|
let helperId2 = 0;
|
|
let helperId3 = 0;
|
|
const _image1 = '';
|
|
const _image2 = '';
|
|
const _image3 = '';
|
|
const _image4 = '';
|
|
|
|
data.helpers.forEach((helper) => {
|
|
switch (i) {
|
|
case 0:
|
|
helperId1 = helper.id;
|
|
break;
|
|
case 1:
|
|
helperId2 = helper.id;
|
|
break;
|
|
case 2:
|
|
helperId3 = helper.id;
|
|
break;
|
|
}
|
|
i++;
|
|
});
|
|
|
|
for (let y = 0; y < data.photos.length; y++) {
|
|
const sqlImage = `INSERT INTO ESTSAIDAVEICULOIMAGENS ( CODSAIDA, TIPO, URL )
|
|
VALUES (${dataSequence[0].id}, 'SA', '${data.photos[y]}' )`;
|
|
await queryRunner.query(sqlImage);
|
|
}
|
|
|
|
const sqlSaidaVeiculo = `INSERT INTO ESTSAIDAVEICULO ( CODSAIDA, CODVEICULO, DTSAIDA, QTAJUDANTES, CODFUNCSAIDA )
|
|
VALUES ( ${dataSequence[0].id}, ${data.vehicleCode}, SYSDATE, ${data.helpers.length},
|
|
${data.userCode} )`;
|
|
await queryRunner.query(sqlSaidaVeiculo);
|
|
|
|
for (let y = 0; y < data.numberLoading.length; y++) {
|
|
const sqlLoading = `INSERT INTO ESTSAIDAVEICULOCARREG ( CODSAIDA, NUMCAR )
|
|
VALUES ( ${dataSequence[0].id}, ${data.numberLoading[y]})`;
|
|
await queryRunner.query(sqlLoading);
|
|
|
|
const sql = `UPDATE PCCARREG SET
|
|
DTSAIDAVEICULO = SYSDATE
|
|
,CODFUNCAJUD = ${helperId1}
|
|
,CODFUNCAJUD2 = ${helperId2}
|
|
,CODFUNCAJUD3 = ${helperId3}
|
|
,KMINICIAL = ${data.startKm}
|
|
WHERE NUMCAR = ${data.numberLoading[y]}`;
|
|
await queryRunner.query(sql);
|
|
}
|
|
|
|
await queryRunner.commitTransaction();
|
|
|
|
return { message: 'Dados da saída de veículo gravada com sucesso!' };
|
|
} catch (e) {
|
|
await queryRunner.rollbackTransaction();
|
|
throw e;
|
|
} finally {
|
|
await queryRunner.release();
|
|
await dataSource.destroy();
|
|
}
|
|
}
|
|
|
|
async createCarIn(data: CarInDelivery) {
|
|
const dataSource = new DataSource(createPostgresConfig(this.configService));
|
|
await dataSource.initialize();
|
|
const queryRunner = dataSource.createQueryRunner();
|
|
await queryRunner.connect();
|
|
await queryRunner.startTransaction();
|
|
try {
|
|
const sqlOutCar = `SELECT ESTSAIDAVEICULO.CODSAIDA as "id"
|
|
FROM PCCARREG, PCVEICUL, ESTSAIDAVEICULO, ESTSAIDAVEICULOCARREG
|
|
WHERE PCCARREG.CODVEICULO = PCVEICUL.CODVEICULO
|
|
AND PCCARREG.NUMCAR = ESTSAIDAVEICULOCARREG.NUMCAR
|
|
AND ESTSAIDAVEICULOCARREG.CODSAIDA = ESTSAIDAVEICULO.CODSAIDA
|
|
-- AND ESTSAIDAVEICULO.DTRETORNO IS NULL
|
|
AND PCVEICUL.PLACA = '${data.licensePlate}'`;
|
|
const dataOutCar = await queryRunner.query(sqlOutCar);
|
|
|
|
if (dataOutCar.length == 0) {
|
|
throw new HttpException(
|
|
'Não foi localiza viagens em aberto para este veículo.',
|
|
HttpStatus.BAD_REQUEST,
|
|
);
|
|
}
|
|
|
|
const _i = 0;
|
|
const _image1 = '';
|
|
const _image2 = '';
|
|
const _image3 = '';
|
|
const _image4 = '';
|
|
|
|
for (let y = 0; y < data.invoices.length; y++) {
|
|
const invoice = data.invoices[y];
|
|
const sqlInvoice = `INSERT INTO ESTRETORNONF ( CODSAIDA, NUMCAR, NUMNOTA, SITUACAO, MOTIVO )
|
|
VALUES ( ${dataOutCar[0].id}, ${invoice.loadingNumber}, ${invoice.invoiceNumber},
|
|
'${invoice.status}', '${invoice.reasonText}')`;
|
|
await queryRunner.query(sqlInvoice);
|
|
}
|
|
|
|
const updateCarreg = `UPDATE PCCARREG SET
|
|
PCCARREG.DTRETORNO = SYSDATE
|
|
,PCCARREG.KMFINAL = ${data.finalKm}
|
|
WHERE PCCARREG.NUMCAR IN ( SELECT SC.NUMCAR
|
|
FROM ESTSAIDAVEICULOCARREG SC
|
|
WHERE SC.CODSAIDA = ${dataOutCar[0].id} )`;
|
|
await queryRunner.query(updateCarreg);
|
|
|
|
for (let i = 0; i < data.images.length; i++) {
|
|
const sqlImage = `INSERT INTO ESTSAIDAVEICULOIMAGENS ( CODSAIDA, TIPO, URL )
|
|
VALUES (${dataOutCar[0].id}, 'RE', '${data.images[i]}' )`;
|
|
await queryRunner.query(sqlImage);
|
|
}
|
|
|
|
const sqlInCar = `UPDATE ESTSAIDAVEICULO SET
|
|
ESTSAIDAVEICULO.DTRETORNO = SYSDATE
|
|
,ESTSAIDAVEICULO.QTPALETES_PBR = ${data.qtdPaletesPbr}
|
|
,ESTSAIDAVEICULO.QTPALETES_CIM = ${data.qtdPaletesCim}
|
|
,ESTSAIDAVEICULO.QTPALETES_DES = ${data.qtdPaletesDes}
|
|
,ESTSAIDAVEICULO.codfuncretorno = ${data.userId}
|
|
,ESTSAIDAVEICULO.obsretorno = '${data.observation}'
|
|
,ESTSAIDAVEICULO.HOUVESOBRA = '${data.remnant}'
|
|
,ESTSAIDAVEICULO.OBSSOBRA = '${data.observationRemnant}'
|
|
WHERE ESTSAIDAVEICULO.CODSAIDA = ${dataOutCar[0].id}`;
|
|
|
|
await queryRunner.query(sqlInCar);
|
|
for (let i = 0; i < data.imagesRemnant.length; i++) {
|
|
const sqlImage = `INSERT INTO ESTSAIDAVEICULOIMAGENS ( CODSAIDA, TIPO, URL )
|
|
VALUES (${dataOutCar[0].id}, 'SO', '${data.imagesRemnant[i]}' )`;
|
|
await queryRunner.query(sqlImage);
|
|
}
|
|
|
|
await queryRunner.commitTransaction();
|
|
|
|
return { message: 'Dados de retorno do veículo gravada com sucesso!' };
|
|
} catch (e) {
|
|
await queryRunner.rollbackTransaction();
|
|
console.log(e);
|
|
throw e;
|
|
} finally {
|
|
await queryRunner.release();
|
|
await dataSource.destroy();
|
|
}
|
|
}
|
|
}
|