branch dev
This commit is contained in:
@@ -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 {
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -1,25 +1,24 @@
|
||||
export class Invoice {
|
||||
customer: string;
|
||||
invoiceNumber: number;
|
||||
loadingNumber: number;
|
||||
reasonId: number;
|
||||
reasonText: string;
|
||||
status: string;
|
||||
}
|
||||
|
||||
export class CarInDelivery {
|
||||
finalKm: number;
|
||||
invoices: Invoice[];
|
||||
licensePlate: string;
|
||||
loadingNumber: number;
|
||||
observation: string;
|
||||
images: string[];
|
||||
userId: number;
|
||||
qtdPaletesPbr: number;
|
||||
qtdPaletesCim: number;
|
||||
qtdPaletesDes: number;
|
||||
remnant: string;
|
||||
observationRemnant: string;
|
||||
imagesRemnant: string[];
|
||||
|
||||
}
|
||||
export class Invoice {
|
||||
customer: string;
|
||||
invoiceNumber: number;
|
||||
loadingNumber: number;
|
||||
reasonId: number;
|
||||
reasonText: string;
|
||||
status: string;
|
||||
}
|
||||
|
||||
export class CarInDelivery {
|
||||
finalKm: number;
|
||||
invoices: Invoice[];
|
||||
licensePlate: string;
|
||||
loadingNumber: number;
|
||||
observation: string;
|
||||
images: string[];
|
||||
userId: number;
|
||||
qtdPaletesPbr: number;
|
||||
qtdPaletesCim: number;
|
||||
qtdPaletesDes: number;
|
||||
remnant: string;
|
||||
observationRemnant: string;
|
||||
imagesRemnant: string[];
|
||||
}
|
||||
|
||||
@@ -1,18 +1,16 @@
|
||||
export class CarOutDelivery {
|
||||
helpers: Helper[]; // Array de objetos auxiliares
|
||||
licensePlate: string; // Placa do veículo
|
||||
numberLoading: number[]; // Número do carregamento
|
||||
palletCount: number; // Quantidade de pallets
|
||||
photos: string[]; // Array de URLs das fotos
|
||||
startKm: number; // Quilometragem de início (como string)
|
||||
userCode: number; // Código do usuário
|
||||
vehicleCode: number; // Código do veículo
|
||||
}
|
||||
|
||||
|
||||
export class Helper {
|
||||
id: number;
|
||||
name: string;
|
||||
phone: string;
|
||||
}
|
||||
|
||||
export class CarOutDelivery {
|
||||
helpers: Helper[]; // Array de objetos auxiliares
|
||||
licensePlate: string; // Placa do veículo
|
||||
numberLoading: number[]; // Número do carregamento
|
||||
palletCount: number; // Quantidade de pallets
|
||||
photos: string[]; // Array de URLs das fotos
|
||||
startKm: number; // Quilometragem de início (como string)
|
||||
userCode: number; // Código do usuário
|
||||
vehicleCode: number; // Código do veículo
|
||||
}
|
||||
|
||||
export class Helper {
|
||||
id: number;
|
||||
name: string;
|
||||
phone: string;
|
||||
}
|
||||
|
||||
@@ -1,94 +1,101 @@
|
||||
import { DropAction } from './../../../node_modules/aws-sdk/clients/mailmanager.d';
|
||||
/*
|
||||
https://docs.nestjs.com/controllers#controllers
|
||||
*/
|
||||
|
||||
import {
|
||||
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";
|
||||
|
||||
@Controller('api/v1/base')
|
||||
export class BaseController {
|
||||
constructor(public readonly baseService: BaseService) { }
|
||||
// @UseGuards(JwtAuthGuard)
|
||||
@Get('execute-view')
|
||||
/* @ApiOperation({
|
||||
summary: 'Executa uma view com ou sem parâmetros',
|
||||
})
|
||||
@ApiResponse({
|
||||
status: 200,
|
||||
description: 'Dados retornados com sucesso.',
|
||||
})
|
||||
@ApiResponse({
|
||||
status: 400,
|
||||
description: 'O nome da view é obrigatório.',
|
||||
})
|
||||
@ApiResponse({
|
||||
status: 500,
|
||||
description: 'Erro ao executar a view.',
|
||||
})*/
|
||||
async executeView(
|
||||
@Query('viewName') viewName: string,
|
||||
@Query() params: Record<string, any>,
|
||||
) {
|
||||
if (!viewName) {
|
||||
throw new HttpException(
|
||||
'O nome da view é obrigatório.',
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
}
|
||||
try {
|
||||
return await this.baseService.executeView(viewName, params);
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
`Erro ao executar a view: ${error.message}`,
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@Post('send-image')
|
||||
@UseInterceptors(
|
||||
FileInterceptor('file', {
|
||||
storage: diskStorage({
|
||||
// Pasta onde os arquivos serão salvos; certifique-se que essa pasta exista ou crie-a automaticamente
|
||||
destination: './uploads',
|
||||
filename: (req, file, callback) => {
|
||||
// Gera um nome único para o arquivo
|
||||
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9);
|
||||
const fileExtName = extname(file.originalname);
|
||||
callback(null, `${file.fieldname}-${uniqueSuffix}${fileExtName}`);
|
||||
},
|
||||
}),
|
||||
// Opcional: definir limites (ex.: tamanho máximo do arquivo)
|
||||
limits: { fileSize: 5 * 1024 * 1024 }, // 5MB
|
||||
}),
|
||||
)
|
||||
async sendImage(
|
||||
@UploadedFile() file: Express.Multer.File,
|
||||
@Body('licensePlate') licensePlate: string,
|
||||
) {
|
||||
if (!file) {
|
||||
throw new HttpException('Nenhum arquivo enviado', HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
|
||||
// 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, () => {});
|
||||
return {
|
||||
success: true,
|
||||
message: 'Upload realizado com sucesso',
|
||||
url: `https://jur-saidaretornoveiculo.s3.sa-east-1.amazonaws.com/${file.filename}`,
|
||||
licensePlate,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
import { DropAction } from './../../../node_modules/aws-sdk/clients/mailmanager.d';
|
||||
/*
|
||||
https://docs.nestjs.com/controllers#controllers
|
||||
*/
|
||||
|
||||
import {
|
||||
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';
|
||||
|
||||
@Controller('api/v1/base')
|
||||
export class BaseController {
|
||||
constructor(public readonly baseService: BaseService) {}
|
||||
// @UseGuards(JwtAuthGuard)
|
||||
@Get('execute-view')
|
||||
/* @ApiOperation({
|
||||
summary: 'Executa uma view com ou sem parâmetros',
|
||||
})
|
||||
@ApiResponse({
|
||||
status: 200,
|
||||
description: 'Dados retornados com sucesso.',
|
||||
})
|
||||
@ApiResponse({
|
||||
status: 400,
|
||||
description: 'O nome da view é obrigatório.',
|
||||
})
|
||||
@ApiResponse({
|
||||
status: 500,
|
||||
description: 'Erro ao executar a view.',
|
||||
})*/
|
||||
async executeView(
|
||||
@Query('viewName') viewName: string,
|
||||
@Query() params: Record<string, any>,
|
||||
) {
|
||||
if (!viewName) {
|
||||
throw new HttpException(
|
||||
'O nome da view é obrigatório.',
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
}
|
||||
try {
|
||||
return await this.baseService.executeView(viewName, params);
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
`Erro ao executar a view: ${error.message}`,
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@Post('send-image')
|
||||
@UseInterceptors(
|
||||
FileInterceptor('file', {
|
||||
storage: diskStorage({
|
||||
// Pasta onde os arquivos serão salvos; certifique-se que essa pasta exista ou crie-a automaticamente
|
||||
destination: './uploads',
|
||||
filename: (req, file, callback) => {
|
||||
// Gera um nome único para o arquivo
|
||||
const uniqueSuffix =
|
||||
Date.now() + '-' + Math.round(Math.random() * 1e9);
|
||||
const fileExtName = extname(file.originalname);
|
||||
callback(null, `${file.fieldname}-${uniqueSuffix}${fileExtName}`);
|
||||
},
|
||||
}),
|
||||
// Opcional: definir limites (ex.: tamanho máximo do arquivo)
|
||||
limits: { fileSize: 5 * 1024 * 1024 }, // 5MB
|
||||
}),
|
||||
)
|
||||
async sendImage(
|
||||
@UploadedFile() file: Express.Multer.File,
|
||||
@Body('licensePlate') licensePlate: string,
|
||||
) {
|
||||
if (!file) {
|
||||
throw new HttpException('Nenhum arquivo enviado', HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
|
||||
// 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, () => {});
|
||||
return {
|
||||
success: true,
|
||||
message: 'Upload realizado com sucesso',
|
||||
url: `https://jur-saidaretornoveiculo.s3.sa-east-1.amazonaws.com/${file.filename}`,
|
||||
licensePlate,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +1,14 @@
|
||||
import { BaseController } from './base.controller';
|
||||
/*
|
||||
https://docs.nestjs.com/modules
|
||||
*/
|
||||
|
||||
import { Module } from '@nestjs/common';
|
||||
import { BaseService } from './base.service';
|
||||
|
||||
@Module({
|
||||
imports: [],
|
||||
controllers: [
|
||||
BaseController,],
|
||||
providers: [BaseService,],
|
||||
})
|
||||
export class BaseModule { }
|
||||
import { BaseController } from './base.controller';
|
||||
/*
|
||||
https://docs.nestjs.com/modules
|
||||
*/
|
||||
|
||||
import { Module } from '@nestjs/common';
|
||||
import { BaseService } from './base.service';
|
||||
|
||||
@Module({
|
||||
imports: [],
|
||||
controllers: [BaseController],
|
||||
providers: [BaseService],
|
||||
})
|
||||
export class BaseModule {}
|
||||
|
||||
@@ -1,289 +1,331 @@
|
||||
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";
|
||||
|
||||
@Injectable()
|
||||
export class BaseService {
|
||||
constructor() { }
|
||||
|
||||
async findAll(table: string) {
|
||||
const dataSource = new DataSource(typeOrmConfig);
|
||||
await dataSource.initialize();
|
||||
const queryRunner = dataSource.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
await queryRunner.startTransaction();
|
||||
try {
|
||||
const [rows] = await queryRunner.query(`SELECT * FROM ${table}`);
|
||||
return rows;
|
||||
} catch (error) {
|
||||
this.handleDatabaseError(error, `Erro ao buscar todos os registros da tabela ${table}`);
|
||||
} finally {
|
||||
queryRunner.release();
|
||||
dataSource.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
async findOne(table: string, id: any) {
|
||||
const dataSource = new DataSource(typeOrmConfig);
|
||||
await dataSource.initialize();
|
||||
const queryRunner = dataSource.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
await queryRunner.startTransaction();
|
||||
try {
|
||||
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}`);
|
||||
} finally {
|
||||
queryRunner.release();
|
||||
dataSource.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
async create(table: string, data: any) {
|
||||
const dataSource = new DataSource(typeOrmConfig);
|
||||
await dataSource.initialize();
|
||||
const queryRunner = dataSource.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
await queryRunner.startTransaction();
|
||||
try {
|
||||
const columns = Object.keys(data).map((key) => `${key}`).join(', ');
|
||||
const values = Object.values(data);
|
||||
const placeholders = values.map(() => '?').join(', ');
|
||||
|
||||
const query = `INSERT INTO ${table} (${columns}) VALUES (${placeholders})`;
|
||||
|
||||
const [result] = await queryRunner.query(query, values);
|
||||
return result;
|
||||
} catch (error) {
|
||||
this.handleDatabaseError(error, `Erro ao criar um registro na tabela ${table}`);
|
||||
} finally {
|
||||
queryRunner.release();
|
||||
dataSource.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
async update(table: string, where: any, data: any) {
|
||||
const dataSource = new DataSource(typeOrmConfig);
|
||||
await dataSource.initialize();
|
||||
const queryRunner = dataSource.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
await queryRunner.startTransaction();
|
||||
try {
|
||||
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}`);
|
||||
} finally {
|
||||
queryRunner.release();
|
||||
dataSource.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
async delete(table: string, where: any) {
|
||||
const dataSource = new DataSource(typeOrmConfig);
|
||||
await dataSource.initialize();
|
||||
const queryRunner = dataSource.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
await queryRunner.startTransaction();
|
||||
try {
|
||||
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}`);
|
||||
} finally {
|
||||
queryRunner.release();
|
||||
dataSource.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
async query(queryString: string, params: any[]): Promise<any[]> {
|
||||
const dataSource = new DataSource(typeOrmConfig);
|
||||
await dataSource.initialize();
|
||||
const queryRunner = dataSource.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
await queryRunner.startTransaction();
|
||||
try {
|
||||
const [rows] = await queryRunner.query(queryString, params);
|
||||
return rows as any[];
|
||||
} catch (error) {
|
||||
this.handleDatabaseError(error, `Erro ao executar a consulta SQL personalizada`);
|
||||
} finally {
|
||||
queryRunner.release();
|
||||
dataSource.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
async executeView(viewName: string, params: Record<string, any>) {
|
||||
const dataSource = new DataSource(typeOrmConfig);
|
||||
await dataSource.initialize();
|
||||
const queryRunner = dataSource.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
await queryRunner.startTransaction();
|
||||
try {
|
||||
// Valida se o nome da view foi fornecido
|
||||
if (!viewName) {
|
||||
throw new Error('O nome da view é obrigatório.');
|
||||
}
|
||||
|
||||
console.log(`Iniciando execução da view: ${viewName}`);
|
||||
console.log('Parâmetros recebidos:', params);
|
||||
|
||||
const conditions: string[] = [];
|
||||
const values: any[] = [];
|
||||
|
||||
// Remove o parâmetro viewName dos parâmetros antes de processar
|
||||
const filteredParams = { ...params };
|
||||
delete filteredParams.viewName;
|
||||
|
||||
// Adiciona as condições baseadas nos parâmetros fornecidos
|
||||
if (filteredParams && Object.keys(filteredParams).length > 0) {
|
||||
console.log('Adicionando condições para os parâmetros fornecidos...');
|
||||
for (const [key, value] of Object.entries(filteredParams)) {
|
||||
// Verifica se a chave e o valor são válidos
|
||||
if (value !== undefined && value !== null && value !== '') {
|
||||
console.log(`Parâmetro válido: ${key} = '${value}'`);
|
||||
conditions.push(`${key} = '${value}'`); // Adiciona aspas para evitar problemas de SQL injection
|
||||
values.push(value);
|
||||
} else {
|
||||
console.warn(`Parâmetro ignorado: ${key} = '${value}'`);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
console.log('Nenhum parâmetro válido foi fornecido.');
|
||||
}
|
||||
|
||||
// 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}`;
|
||||
|
||||
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) }`);
|
||||
return rows;
|
||||
} catch (error) {
|
||||
console.error(`Erro ao executar a view ${ viewName }: `, error.message);
|
||||
this.handleDatabaseError(
|
||||
error,
|
||||
`Erro ao executar a view ${ viewName } com parâmetros.`,
|
||||
);
|
||||
} finally {
|
||||
await queryRunner.release();
|
||||
await dataSource.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
async executeProcedure(procedureName: string, params: Record<string, any>) {
|
||||
const dataSource = new DataSource(typeOrmConfig);
|
||||
await dataSource.initialize();
|
||||
const queryRunner = dataSource.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
await queryRunner.startTransaction();
|
||||
try {
|
||||
const placeholders = Object.keys(params)
|
||||
.map(() => '?')
|
||||
.join(', ');
|
||||
const values = Object.values(params);
|
||||
|
||||
const query = `EXECUTE IMMEDIATE ${ procedureName }(${ placeholders })`;
|
||||
|
||||
// Log da query e dos valores
|
||||
console.log('Query executada:', query);
|
||||
console.log('Valores:', values);
|
||||
|
||||
const [result] = await queryRunner.query(query, values);
|
||||
|
||||
// Verifica e converte campos que contenham JSON strings para objetos
|
||||
const parsedResult = Array.isArray(result)
|
||||
? result.map((row) => {
|
||||
const parsedRow = { ...row };
|
||||
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('}')) {
|
||||
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.`);
|
||||
}
|
||||
}
|
||||
return parsedRow;
|
||||
})
|
||||
: result;
|
||||
|
||||
// Retorna os valores e o resultado
|
||||
return {
|
||||
message: 'Procedure executada com sucesso.',
|
||||
executedQuery: query,
|
||||
values: values,
|
||||
result: parsedResult,
|
||||
};
|
||||
} catch (error) {
|
||||
this.handleDatabaseError(
|
||||
error,
|
||||
`Erro ao executar a procedure ${ procedureName } com parâmetros.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private handleDatabaseError(error: any, message: string): never {
|
||||
console.error(message, error); // Log detalhado do erro
|
||||
throw new InternalServerErrorException({
|
||||
message,
|
||||
sqlMessage: error.sqlMessage || error.message,
|
||||
sqlState: error.sqlState,
|
||||
});
|
||||
}
|
||||
|
||||
async sendImages(file: string) {
|
||||
// for (const file of files) {
|
||||
// const file = 'C:\\Temp\\brasil_2.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/', ''));
|
||||
}
|
||||
});
|
||||
}
|
||||
//}
|
||||
}
|
||||
|
||||
async uploadS3(file, bucket, name) {
|
||||
const s3 = this.getS3();
|
||||
const params = {
|
||||
Bucket: bucket,
|
||||
Key: String(name),
|
||||
Body: file,
|
||||
|
||||
};
|
||||
return new Promise((resolve, reject) => {
|
||||
s3.upload(params, (err, data) => {
|
||||
if (err) {
|
||||
console.log(JSON.stringify(err));
|
||||
reject(err.message);
|
||||
}
|
||||
resolve(data);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
getS3() {
|
||||
return new S3({
|
||||
accessKeyId: "AKIAVHJOO6W765ZT2PNI", //process.env.AWS_ACCESS_KEY_ID,
|
||||
secretAccessKey: "IFtP6Foc7JlE6TfR3psBAERUCMlH+4cRMx0GVIx2", // process.env.AWS_SECRET_ACCESS_KEY,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
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';
|
||||
|
||||
@Injectable()
|
||||
export class BaseService {
|
||||
constructor() {}
|
||||
|
||||
async findAll(table: string) {
|
||||
const dataSource = new DataSource(typeOrmConfig);
|
||||
await dataSource.initialize();
|
||||
const queryRunner = dataSource.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
await queryRunner.startTransaction();
|
||||
try {
|
||||
const [rows] = await queryRunner.query(`SELECT * FROM ${table}`);
|
||||
return rows;
|
||||
} catch (error) {
|
||||
this.handleDatabaseError(
|
||||
error,
|
||||
`Erro ao buscar todos os registros da tabela ${table}`,
|
||||
);
|
||||
} finally {
|
||||
queryRunner.release();
|
||||
dataSource.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
async findOne(table: string, id: any) {
|
||||
const dataSource = new DataSource(typeOrmConfig);
|
||||
await dataSource.initialize();
|
||||
const queryRunner = dataSource.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
await queryRunner.startTransaction();
|
||||
try {
|
||||
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}`,
|
||||
);
|
||||
} finally {
|
||||
queryRunner.release();
|
||||
dataSource.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
async create(table: string, data: any) {
|
||||
const dataSource = new DataSource(typeOrmConfig);
|
||||
await dataSource.initialize();
|
||||
const queryRunner = dataSource.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
await queryRunner.startTransaction();
|
||||
try {
|
||||
const columns = Object.keys(data)
|
||||
.map((key) => `${key}`)
|
||||
.join(', ');
|
||||
const values = Object.values(data);
|
||||
const placeholders = values.map(() => '?').join(', ');
|
||||
|
||||
const query = `INSERT INTO ${table} (${columns}) VALUES (${placeholders})`;
|
||||
|
||||
const [result] = await queryRunner.query(query, values);
|
||||
return result;
|
||||
} catch (error) {
|
||||
this.handleDatabaseError(
|
||||
error,
|
||||
`Erro ao criar um registro na tabela ${table}`,
|
||||
);
|
||||
} finally {
|
||||
queryRunner.release();
|
||||
dataSource.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
async update(table: string, where: any, data: any) {
|
||||
const dataSource = new DataSource(typeOrmConfig);
|
||||
await dataSource.initialize();
|
||||
const queryRunner = dataSource.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
await queryRunner.startTransaction();
|
||||
try {
|
||||
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}`,
|
||||
);
|
||||
} finally {
|
||||
queryRunner.release();
|
||||
dataSource.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
async delete(table: string, where: any) {
|
||||
const dataSource = new DataSource(typeOrmConfig);
|
||||
await dataSource.initialize();
|
||||
const queryRunner = dataSource.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
await queryRunner.startTransaction();
|
||||
try {
|
||||
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}`,
|
||||
);
|
||||
} finally {
|
||||
queryRunner.release();
|
||||
dataSource.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
async query(queryString: string, params: any[]): Promise<any[]> {
|
||||
const dataSource = new DataSource(typeOrmConfig);
|
||||
await dataSource.initialize();
|
||||
const queryRunner = dataSource.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
await queryRunner.startTransaction();
|
||||
try {
|
||||
const [rows] = await queryRunner.query(queryString, params);
|
||||
return rows as any[];
|
||||
} catch (error) {
|
||||
this.handleDatabaseError(
|
||||
error,
|
||||
`Erro ao executar a consulta SQL personalizada`,
|
||||
);
|
||||
} finally {
|
||||
queryRunner.release();
|
||||
dataSource.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
async executeView(viewName: string, params: Record<string, any>) {
|
||||
const dataSource = new DataSource(typeOrmConfig);
|
||||
await dataSource.initialize();
|
||||
const queryRunner = dataSource.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
await queryRunner.startTransaction();
|
||||
try {
|
||||
// Valida se o nome da view foi fornecido
|
||||
if (!viewName) {
|
||||
throw new Error('O nome da view é obrigatório.');
|
||||
}
|
||||
|
||||
console.log(`Iniciando execução da view: ${viewName}`);
|
||||
console.log('Parâmetros recebidos:', params);
|
||||
|
||||
const conditions: string[] = [];
|
||||
const values: any[] = [];
|
||||
|
||||
// Remove o parâmetro viewName dos parâmetros antes de processar
|
||||
const filteredParams = { ...params };
|
||||
delete filteredParams.viewName;
|
||||
|
||||
// Adiciona as condições baseadas nos parâmetros fornecidos
|
||||
if (filteredParams && Object.keys(filteredParams).length > 0) {
|
||||
console.log('Adicionando condições para os parâmetros fornecidos...');
|
||||
for (const [key, value] of Object.entries(filteredParams)) {
|
||||
// Verifica se a chave e o valor são válidos
|
||||
if (value !== undefined && value !== null && value !== '') {
|
||||
console.log(`Parâmetro válido: ${key} = '${value}'`);
|
||||
conditions.push(`${key} = '${value}'`); // Adiciona aspas para evitar problemas de SQL injection
|
||||
values.push(value);
|
||||
} else {
|
||||
console.warn(`Parâmetro ignorado: ${key} = '${value}'`);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
console.log('Nenhum parâmetro válido foi fornecido.');
|
||||
}
|
||||
|
||||
// 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}`;
|
||||
|
||||
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,
|
||||
)}`,
|
||||
);
|
||||
return rows;
|
||||
} catch (error) {
|
||||
console.error(`Erro ao executar a view ${viewName}: `, error.message);
|
||||
this.handleDatabaseError(
|
||||
error,
|
||||
`Erro ao executar a view ${viewName} com parâmetros.`,
|
||||
);
|
||||
} finally {
|
||||
await queryRunner.release();
|
||||
await dataSource.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
async executeProcedure(procedureName: string, params: Record<string, any>) {
|
||||
const dataSource = new DataSource(typeOrmConfig);
|
||||
await dataSource.initialize();
|
||||
const queryRunner = dataSource.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
await queryRunner.startTransaction();
|
||||
try {
|
||||
const placeholders = Object.keys(params)
|
||||
.map(() => '?')
|
||||
.join(', ');
|
||||
const values = Object.values(params);
|
||||
|
||||
const query = `EXECUTE IMMEDIATE ${procedureName}(${placeholders})`;
|
||||
|
||||
// Log da query e dos valores
|
||||
console.log('Query executada:', query);
|
||||
console.log('Valores:', values);
|
||||
|
||||
const [result] = await queryRunner.query(query, values);
|
||||
|
||||
// Verifica e converte campos que contenham JSON strings para objetos
|
||||
const parsedResult = Array.isArray(result)
|
||||
? result.map((row) => {
|
||||
const parsedRow = { ...row };
|
||||
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('}')
|
||||
) {
|
||||
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.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
return parsedRow;
|
||||
})
|
||||
: result;
|
||||
|
||||
// Retorna os valores e o resultado
|
||||
return {
|
||||
message: 'Procedure executada com sucesso.',
|
||||
executedQuery: query,
|
||||
values: values,
|
||||
result: parsedResult,
|
||||
};
|
||||
} catch (error) {
|
||||
this.handleDatabaseError(
|
||||
error,
|
||||
`Erro ao executar a procedure ${procedureName} com parâmetros.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private handleDatabaseError(error: any, message: string): never {
|
||||
console.error(message, error); // Log detalhado do erro
|
||||
throw new InternalServerErrorException({
|
||||
message,
|
||||
sqlMessage: error.sqlMessage || error.message,
|
||||
sqlState: error.sqlState,
|
||||
});
|
||||
}
|
||||
|
||||
async sendImages(file: string) {
|
||||
// for (const file of files) {
|
||||
// const file = 'C:\\Temp\\brasil_2.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/', ''),
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
//}
|
||||
}
|
||||
|
||||
async uploadS3(file, bucket, name) {
|
||||
const s3 = this.getS3();
|
||||
const params = {
|
||||
Bucket: bucket,
|
||||
Key: String(name),
|
||||
Body: file,
|
||||
};
|
||||
return new Promise((resolve, reject) => {
|
||||
s3.upload(params, (err, data) => {
|
||||
if (err) {
|
||||
console.log(JSON.stringify(err));
|
||||
reject(err.message);
|
||||
}
|
||||
resolve(data);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
getS3() {
|
||||
return new S3({
|
||||
accessKeyId: 'AKIAVHJOO6W765ZT2PNI', //process.env.AWS_ACCESS_KEY_ID,
|
||||
secretAccessKey: 'IFtP6Foc7JlE6TfR3psBAERUCMlH+4cRMx0GVIx2', // process.env.AWS_SECRET_ACCESS_KEY,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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];
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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()
|
||||
|
||||
Reference in New Issue
Block a user