branch dev

This commit is contained in:
JurTI-BR
2025-03-28 11:29:34 -03:00
parent 41e56dda12
commit 8af4b05f28
18 changed files with 4289 additions and 7731 deletions

9623
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -8,12 +8,11 @@
"scripts": {
"prebuild": "rimraf dist",
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"format": "prettier --write \"../../**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
@@ -28,6 +27,8 @@
"@nestjs/passport": "^10.0.3",
"@nestjs/platform-express": "^7.5.1",
"@nestjs/typeorm": "^10.0.2",
"@types/eslint": "^9.6.1",
"@types/estree": "^1.0.7",
"aws-sdk": "^2.1692.0",
"axios": "^1.7.9",
"fs": "0.0.1-security",
@@ -54,11 +55,8 @@
"@types/express": "^4.17.8",
"@types/jest": "^26.0.15",
"@types/multer": "^1.4.12",
"@types/node": "^14.14.6",
"@types/node": "^22.13.14",
"@types/supertest": "^2.0.10",
"@typescript-eslint/eslint-plugin": "^4.6.1",
"@typescript-eslint/parser": "^4.6.1",
"eslint": "^7.12.1",
"eslint-config-prettier": "^6.15.0",
"eslint-plugin-prettier": "^3.1.4",
"jest": "^26.6.3",
@@ -68,7 +66,7 @@
"ts-loader": "^8.0.8",
"ts-node": "^9.0.0",
"tsconfig-paths": "^3.9.0",
"typescript": "^4.0.5"
"typescript": "^5.8.2"
},
"jest": {
"moduleFileExtensions": [

View File

@@ -9,10 +9,10 @@ import {
} from '@nestjs/common';
import { AuthService } from './auth.service';
import { UsersService } from '../users/users.service';
import { UserModel } from 'src/core/models/user.model';
import { ResultModel } from 'src/core/models/result.model';
import { ResetPasswordModel } from 'src/core/models/reset-password.model';
import { ChangePasswordModel } from 'src/core/models/change-password.model';
import { UserModel } from '../../core/models/user.model';
import { ResultModel } from '../../core/models/result.model';
import { ResetPasswordModel } from '../../core/models/reset-password.model';
import { ChangePasswordModel } from '../../core/models/change-password.model';
@Controller('api/v1/auth')
export class AuthController {

View File

@@ -4,8 +4,8 @@ import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { DataSource } from 'typeorm';
import md5 = require('md5');
import { Guid } from "guid-typescript";
import { typeOrmConfig } from 'src/core/configs/typeorm.config';
import { UserModel } from 'src/core/models/user.model';
import { typeOrmConfig } from '../../core/configs/typeorm.config';
import { UserModel } from '../../core/models/user.model';
@Injectable()

View File

@@ -5,9 +5,9 @@ export class Invoice {
reasonId: number;
reasonText: string;
status: string;
}
}
export class CarInDelivery {
export class CarInDelivery {
finalKm: number;
invoices: Invoice[];
licensePlate: string;
@@ -21,5 +21,4 @@ export class Invoice {
remnant: string;
observationRemnant: string;
imagesRemnant: string[];
}
}

View File

@@ -9,10 +9,8 @@ export class CarOutDelivery {
vehicleCode: number; // Código do veículo
}
export class Helper {
id: number;
name: string;
phone: string;
}

View File

@@ -4,18 +4,26 @@ https://docs.nestjs.com/controllers#controllers
*/
import {
Body, Controller, Get, HttpException, HttpStatus, Post, Query, Req, UseInterceptors,
UploadedFile
Body,
Controller,
Get,
HttpException,
HttpStatus,
Post,
Query,
Req,
UseInterceptors,
UploadedFile,
} from '@nestjs/common';
import { BaseService } from './base.service';
import { FileInterceptor } from '@nestjs/platform-express';
import { diskStorage } from 'multer';
import { extname } from 'path';
import * as fs from "fs";
import * as fs from 'fs';
@Controller('api/v1/base')
export class BaseController {
constructor(public readonly baseService: BaseService) { }
constructor(public readonly baseService: BaseService) {}
// @UseGuards(JwtAuthGuard)
@Get('execute-view')
/* @ApiOperation({
@@ -61,7 +69,8 @@ export class BaseController {
destination: './uploads',
filename: (req, file, callback) => {
// Gera um nome único para o arquivo
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9);
const uniqueSuffix =
Date.now() + '-' + Math.round(Math.random() * 1e9);
const fileExtName = extname(file.originalname);
callback(null, `${file.fieldname}-${uniqueSuffix}${fileExtName}`);
},
@@ -80,8 +89,8 @@ export class BaseController {
// Aqui você pode processar o arquivo (ex.: enviar para o S3) ou armazená-lo no disco mesmo.
// Neste exemplo, retornamos a URL do arquivo salvo localmente.
this.baseService.sendImages('./uploads/'+file.filename);
fs.unlink('./uploads/'+file.filename, () => {});
this.baseService.sendImages('./uploads/' + file.filename);
fs.unlink('./uploads/' + file.filename, () => {});
return {
success: true,
message: 'Upload realizado com sucesso',
@@ -89,6 +98,4 @@ export class BaseController {
licensePlate,
};
}
}

View File

@@ -8,8 +8,7 @@ import { BaseService } from './base.service';
@Module({
imports: [],
controllers: [
BaseController,],
providers: [BaseService,],
controllers: [BaseController],
providers: [BaseService],
})
export class BaseModule { }
export class BaseModule {}

View File

@@ -1,12 +1,16 @@
import { Inject, Injectable, InternalServerErrorException } from '@nestjs/common';
import {
Inject,
Injectable,
InternalServerErrorException,
} from '@nestjs/common';
import { DataSource } from 'typeorm';
import { typeOrmConfig } from '../configs/typeorm.config';
import { S3 } from 'aws-sdk';
import * as fs from "fs";
import * as fs from 'fs';
@Injectable()
export class BaseService {
constructor() { }
constructor() {}
async findAll(table: string) {
const dataSource = new DataSource(typeOrmConfig);
@@ -18,7 +22,10 @@ export class BaseService {
const [rows] = await queryRunner.query(`SELECT * FROM ${table}`);
return rows;
} catch (error) {
this.handleDatabaseError(error, `Erro ao buscar todos os registros da tabela ${table}`);
this.handleDatabaseError(
error,
`Erro ao buscar todos os registros da tabela ${table}`,
);
} finally {
queryRunner.release();
dataSource.destroy();
@@ -32,10 +39,15 @@ export class BaseService {
await queryRunner.connect();
await queryRunner.startTransaction();
try {
const [rows] = await queryRunner.query(`SELECT * FROM ${table} WHERE id = '${id}'`);
const [rows] = await queryRunner.query(
`SELECT * FROM ${table} WHERE id = '${id}'`,
);
return rows[0];
} catch (error) {
this.handleDatabaseError(error, `Erro ao buscar o registro com ID ${id} na tabela ${table}`);
this.handleDatabaseError(
error,
`Erro ao buscar o registro com ID ${id} na tabela ${table}`,
);
} finally {
queryRunner.release();
dataSource.destroy();
@@ -49,7 +61,9 @@ export class BaseService {
await queryRunner.connect();
await queryRunner.startTransaction();
try {
const columns = Object.keys(data).map((key) => `${key}`).join(', ');
const columns = Object.keys(data)
.map((key) => `${key}`)
.join(', ');
const values = Object.values(data);
const placeholders = values.map(() => '?').join(', ');
@@ -58,7 +72,10 @@ export class BaseService {
const [result] = await queryRunner.query(query, values);
return result;
} catch (error) {
this.handleDatabaseError(error, `Erro ao criar um registro na tabela ${table}`);
this.handleDatabaseError(
error,
`Erro ao criar um registro na tabela ${table}`,
);
} finally {
queryRunner.release();
dataSource.destroy();
@@ -72,10 +89,15 @@ export class BaseService {
await queryRunner.connect();
await queryRunner.startTransaction();
try {
const [result] = await queryRunner.query(`UPDATE ${table} SET ${data} WHERE ${where}`);
const [result] = await queryRunner.query(
`UPDATE ${table} SET ${data} WHERE ${where}`,
);
return result;
} catch (error) {
this.handleDatabaseError(error, `Erro ao atualizar o registro com ${where} na tabela ${table}`);
this.handleDatabaseError(
error,
`Erro ao atualizar o registro com ${where} na tabela ${table}`,
);
} finally {
queryRunner.release();
dataSource.destroy();
@@ -89,10 +111,15 @@ export class BaseService {
await queryRunner.connect();
await queryRunner.startTransaction();
try {
const [result] = await queryRunner.query(`DELETE FROM ${table} WHERE ${where}`);
const [result] = await queryRunner.query(
`DELETE FROM ${table} WHERE ${where}`,
);
return result;
} catch (error) {
this.handleDatabaseError(error, `Erro ao deletar o registro com ID ${where} na tabela ${table}`);
this.handleDatabaseError(
error,
`Erro ao deletar o registro com ID ${where} na tabela ${table}`,
);
} finally {
queryRunner.release();
dataSource.destroy();
@@ -109,7 +136,10 @@ export class BaseService {
const [rows] = await queryRunner.query(queryString, params);
return rows as any[];
} catch (error) {
this.handleDatabaseError(error, `Erro ao executar a consulta SQL personalizada`);
this.handleDatabaseError(
error,
`Erro ao executar a consulta SQL personalizada`,
);
} finally {
queryRunner.release();
dataSource.destroy();
@@ -156,22 +186,27 @@ export class BaseService {
}
// Monta a cláusula WHERE somente se houver condições
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
const query = `SELECT * FROM ${ viewName } ${whereClause}`;
const whereClause =
conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
const query = `SELECT * FROM ${viewName} ${whereClause}`;
console.log(`Consulta SQL montada: ${ query }`);
console.log(`Consulta SQL montada: ${query}`);
console.log(`{Valores para a consulta:, ${values}`);
// Executa a consulta
const rows = await queryRunner.query(query);
console.log(`Consulta executada com sucesso.Linhas retornadas: ${ JSON.stringify(rows) }`);
console.log(
`Consulta executada com sucesso.Linhas retornadas: ${JSON.stringify(
rows,
)}`,
);
return rows;
} catch (error) {
console.error(`Erro ao executar a view ${ viewName }: `, error.message);
console.error(`Erro ao executar a view ${viewName}: `, error.message);
this.handleDatabaseError(
error,
`Erro ao executar a view ${ viewName } com parâmetros.`,
`Erro ao executar a view ${viewName} com parâmetros.`,
);
} finally {
await queryRunner.release();
@@ -191,7 +226,7 @@ export class BaseService {
.join(', ');
const values = Object.values(params);
const query = `EXECUTE IMMEDIATE ${ procedureName }(${ placeholders })`;
const query = `EXECUTE IMMEDIATE ${procedureName}(${placeholders})`;
// Log da query e dos valores
console.log('Query executada:', query);
@@ -206,12 +241,18 @@ export class BaseService {
for (const [key, value] of Object.entries(parsedRow)) {
try {
// Tenta converter strings JSON para objetos
if (typeof value === 'string' && value.trim().startsWith('{') && value.trim().endsWith('}')) {
if (
typeof value === 'string' &&
value.trim().startsWith('{') &&
value.trim().endsWith('}')
) {
parsedRow[key] = JSON.parse(value);
}
} catch (error) {
// Ignora se a conversão falhar
console.warn(`Campo ${ key } não é um JSON válido.Mantendo como string.`);
console.warn(
`Campo ${key} não é um JSON válido.Mantendo como string.`,
);
}
}
return parsedRow;
@@ -228,7 +269,7 @@ export class BaseService {
} catch (error) {
this.handleDatabaseError(
error,
`Erro ao executar a procedure ${ procedureName } com parâmetros.`,
`Erro ao executar a procedure ${procedureName} com parâmetros.`,
);
}
}
@@ -245,14 +286,18 @@ export class BaseService {
async sendImages(file: string) {
// for (const file of files) {
// const file = 'C:\\Temp\\brasil_2.jpg'
if (file.endsWith(".jpg")) {
if (file.endsWith('.jpg')) {
const fileName = file; //directoryImages + '\\' + file;
fs.readFile(fileName, (err, data) => {
if (err) throw err;
if (err) {
console.log(`WRITE ERROR: ${err}`);
} else {
this.uploadS3(data, 'jur-saidaretornoveiculo', file.replace('./uploads/', ''));
this.uploadS3(
data,
'jur-saidaretornoveiculo',
file.replace('./uploads/', ''),
);
}
});
}
@@ -265,7 +310,6 @@ export class BaseService {
Bucket: bucket,
Key: String(name),
Body: file,
};
return new Promise((resolve, reject) => {
s3.upload(params, (err, data) => {
@@ -280,10 +324,8 @@ export class BaseService {
getS3() {
return new S3({
accessKeyId: "AKIAVHJOO6W765ZT2PNI", //process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: "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", // process.env.AWS_SECRET_ACCESS_KEY,
accessKeyId: 'AKIAVHJOO6W765ZT2PNI', //process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: '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', // process.env.AWS_SECRET_ACCESS_KEY,
});
}
}

View File

@@ -6,7 +6,7 @@ https://docs.nestjs.com/providers#services
*/
import { Injectable } from '@nestjs/common';
import { typeOrmConfig } from 'src/core/configs/typeorm.config';
import { typeOrmConfig } from '../core/configs/typeorm.config';
import { DataSource } from 'typeorm';
@Injectable()

View File

@@ -6,8 +6,8 @@ https://docs.nestjs.com/controllers#controllers
import { Body, Controller, Get, Param, Post } from '@nestjs/common';
import { LogisticService } from './logistic.service';
import { CarOutDelivery } from 'src/core/models/car-out-delivery.model';
import { CarInDelivery } from 'src/core/models/car-in-delivery.model';
import { CarOutDelivery } from '../core/models/car-out-delivery.model';
import { CarInDelivery } from '../core/models/car-in-delivery.model';
@Controller('api/v1/logistic')
export class LogisticController {

View File

@@ -1,16 +1,8 @@
import { Length } from './../../node_modules/aws-sdk/clients/quicksight.d';
import { count } from './../../node_modules/aws-sdk/clients/health.d';
/* eslint-disable prettier/prettier */
/* eslint-disable @typescript-eslint/no-unused-vars */
import { Get, HttpException, HttpStatus, Injectable, Query, UseGuards } from '@nestjs/common';
import { stringify } from 'querystring';
import { typeOrmConfig, typeOrmPgConfig } from 'src/core/configs/typeorm.config';
import { CarOutDelivery } from 'src/core/models/car-out-delivery.model';
import { BaseService } from 'src/core/services/base.service';
import { typeOrmConfig, typeOrmPgConfig } from '../core/configs/typeorm.config';
import { CarOutDelivery } from '../core/models/car-out-delivery.model';
import { DataSource } from 'typeorm';
import { CarInDelivery } from 'src/core/models/car-in-delivery.model';
import { CarInDelivery } from '../core/models/car-in-delivery.model';
@Injectable()
export class LogisticService {
@@ -205,13 +197,13 @@ export class LogisticService {
const sqlSequence = `SELECT ESS_SAIDAVEICULO.NEXTVAL as "id" FROM DUAL`;
const dataSequence = await queryRunner.query(sqlSequence);
let i = 0;
let helperId1: number = 0;
let helperId2: number = 0;
let helperId3: number = 0;
let image1: string = '';
let image2: string = '';
let image3: string = '';
let image4: string = '';
let helperId1 = 0;
let helperId2 = 0;
let helperId3 = 0;
const image1 = '';
const image2 = '';
const image3 = '';
const image4 = '';
data.helpers.forEach(helper => {
switch (i) {
@@ -290,11 +282,11 @@ export class LogisticService {
throw new HttpException('Não foi localiza viagens em aberto para este veículo.', HttpStatus.BAD_REQUEST );
}
let i = 0;
let image1: string = '';
let image2: string = '';
let image3: string = '';
let image4: string = '';
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];

View File

@@ -6,7 +6,7 @@ https://docs.nestjs.com/providers#services
*/
import { Injectable } from '@nestjs/common';
import { typeOrmConfig } from 'src/core/configs/typeorm.config';
import { typeOrmConfig } from '../core/configs/typeorm.config';
import { DataSource } from 'typeorm';
@Injectable()

View File

@@ -5,7 +5,7 @@ https://docs.nestjs.com/providers#services
*/
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { typeOrmConfig } from 'src/core/configs/typeorm.config';
import { typeOrmConfig } from '../core/configs/typeorm.config';
import { DataSource } from 'typeorm';
@Injectable()

View File

@@ -7,7 +7,7 @@ https://docs.nestjs.com/controllers#controllers
import { Body, Controller, Get, Param, Post } from '@nestjs/common';
import { ProductsService } from './products.service';
import { ExposedProduct } from 'src/core/models/exposed-product.model';
import { ExposedProduct } from '../core/models/exposed-product.model';
@Controller('api/v1/products')
export class ProductsController {

View File

@@ -6,8 +6,8 @@ https://docs.nestjs.com/providers#services
*/
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { typeOrmConfig } from 'src/core/configs/typeorm.config';
import { ExposedProduct } from 'src/core/models/exposed-product.model';
import { typeOrmConfig } from '../core/configs/typeorm.config';
import { ExposedProduct } from '../core/models/exposed-product.model';
import { DataSource } from 'typeorm';
@Injectable()

View File

@@ -1,7 +1,7 @@
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import * as request from 'supertest';
import { AppModule } from './../src/app.module';
import { AppModule } from './../../../app.module';
describe('AppController (e2e)', () => {
let app: INestApplication;