anexado guardar en minio y cambios generales en la interfaz de osp

This commit is contained in:
2026-02-24 11:00:50 -04:00
parent fed90d9ff1
commit c70e146ce2
22 changed files with 5139 additions and 696 deletions

View File

@@ -1,12 +1,11 @@
import { HttpException, HttpStatus, Inject, Injectable, NotFoundException } from '@nestjs/common';
import { MinioService } from '@/common/minio/minio.service';
import { HttpException, HttpStatus, Inject, Injectable } from '@nestjs/common';
import { and, eq, gte, ilike, lte, or, SQL, sql } from 'drizzle-orm';
import { NodePgDatabase } from 'drizzle-orm/node-postgres';
import * as fs from 'fs';
import * as path from 'path';
import { DRIZZLE_PROVIDER } from 'src/database/drizzle-provider';
import * as schema from 'src/database/index';
import { municipalities, parishes, states, trainingSurveys } from 'src/database/index';
import XlsxPopulate from 'xlsx-populate';
import { states, trainingSurveys } from 'src/database/index';
import { PaginationDto } from '../../common/dto/pagination.dto';
import { CreateTrainingDto } from './dto/create-training.dto';
import { TrainingStatisticsFilterDto } from './dto/training-statistics-filter.dto';
@@ -16,7 +15,8 @@ import { UpdateTrainingDto } from './dto/update-training.dto';
export class TrainingService {
constructor(
@Inject(DRIZZLE_PROVIDER) private drizzle: NodePgDatabase<typeof schema>,
) { }
private readonly minioService: MinioService,
) {}
async findAll(paginationDto?: PaginationDto) {
const {
@@ -232,33 +232,33 @@ export class TrainingService {
private async saveFiles(files: Express.Multer.File[]): Promise<string[]> {
if (!files || files.length === 0) return [];
const uploadDir = './uploads/training';
if (!fs.existsSync(uploadDir)) {
fs.mkdirSync(uploadDir, { recursive: true });
}
const savedPaths: string[] = [];
for (const file of files) {
const fileName = `${Date.now()}-${Math.round(Math.random() * 1e9)}${path.extname(file.originalname)}`;
const filePath = path.join(uploadDir, fileName);
fs.writeFileSync(filePath, file.buffer);
savedPaths.push(`/assets/training/${fileName}`);
const objectName = await this.minioService.upload(file, 'training');
const fileUrl = this.minioService.getPublicUrl(objectName);
savedPaths.push(fileUrl);
}
return savedPaths;
}
private deleteFile(assetPath: string) {
if (!assetPath) return;
// Map /assets/training/filename.webp back to ./uploads/training/filename.webp
const relativePath = assetPath.replace('/assets/training/', '');
const fullPath = path.join('./uploads/training', relativePath);
private async deleteFile(fileUrl: string) {
if (!fileUrl) return;
if (fs.existsSync(fullPath)) {
try {
fs.unlinkSync(fullPath);
} catch (err) {
console.error(`Error deleting file ${fullPath}:`, err);
}
// Extract object name from URL
// URL format: http://endpoint:port/bucket/folder/filename
// Or it could be just the path if we decided that.
// Assuming fileUrl is the full public URL from getPublicUrl
try {
const url = new URL(fileUrl);
const pathname = url.pathname; // /bucket/folder/filename
const parts = pathname.split('/');
// parts[0] is '', parts[1] is bucket, parts[2..] is objectName
const objectName = parts.slice(2).join('/');
await this.minioService.delete(objectName);
} catch (error) {
// If it's not a valid URL, maybe it's just the object name stored from before
await this.minioService.delete(fileUrl);
}
}
@@ -268,11 +268,13 @@ export class TrainingService {
userId: number,
) {
// 1. Guardar fotos
const photoPaths = await this.saveFiles(files);
// 2. Extraer solo visitDate para formatearlo.
// Ya NO extraemos state, municipality, etc. porque no vienen en el DTO.
const { visitDate, state, municipality, parish, ...rest } = createTrainingDto;
const { visitDate, state, municipality, parish, ...rest } =
createTrainingDto;
const [newRecord] = await this.drizzle
.insert(trainingSurveys)
@@ -305,45 +307,48 @@ export class TrainingService {
userId: number,
) {
const currentRecord = await this.findOne(id);
const photoFields = ['photo1', 'photo2', 'photo3'] as const;
const photoPaths = await this.saveFiles(files);
// 1. Guardar fotos nuevas en MinIO
const newFilePaths = await this.saveFiles(files);
const updateData: any = { ...updateTrainingDto };
// Handle photo updates/removals
const photoFields = ['photo1', 'photo2', 'photo3'] as const;
// 1. First, handle explicit deletions (where field is '')
photoFields.forEach((field) => {
if (updateData[field] === '') {
const oldPath = currentRecord[field];
if (oldPath) this.deleteFile(oldPath);
updateData[field] = null;
// 2. Determinar el estado final de las fotos (diff)
// - Si el DTO tiene un valor (URL existente o ''), lo usamos.
// - Si el DTO no tiene el campo (undefined), mantenemos el de la DB.
const finalPhotos: (string | null)[] = photoFields.map((field) => {
const dtoValue = updateData[field];
if (dtoValue !== undefined) {
return dtoValue === '' ? null : dtoValue;
}
return currentRecord[field];
});
// 2. We need to find which slots are currently "available" (null) after deletions
// and which ones have existing URLs that we want to keep.
// Let's determine the final state of the 3 slots.
const finalPhotos: (string | null)[] = [
updateData.photo1 !== undefined ? updateData.photo1 : currentRecord.photo1,
updateData.photo2 !== undefined ? updateData.photo2 : currentRecord.photo2,
updateData.photo3 !== undefined ? updateData.photo3 : currentRecord.photo3,
];
// 3. Fill the available (null) slots with NEW photo paths
if (photoPaths.length > 0) {
let photoPathIdx = 0;
for (let i = 0; i < 3 && photoPathIdx < photoPaths.length; i++) {
// 3. Asignar los nuevos paths subidos a los slots que quedaron vacíos
if (newFilePaths.length > 0) {
let newIdx = 0;
for (let i = 0; i < 3 && newIdx < newFilePaths.length; i++) {
if (!finalPhotos[i]) {
finalPhotos[i] = photoPaths[photoPathIdx];
photoPathIdx++;
finalPhotos[i] = newFilePaths[newIdx];
newIdx++;
}
}
}
// Assign back to updateData
// 4. LIMPIEZA: Borrar de MinIO los archivos que ya no están en ningún slot
const oldPhotos = photoFields
.map((f) => currentRecord[f])
.filter((p): p is string => Boolean(p));
const newPhotosSet = new Set(finalPhotos.filter(Boolean));
for (const oldPath of oldPhotos) {
if (!newPhotosSet.has(oldPath)) {
await this.deleteFile(oldPath);
}
}
// 5. Preparar datos finales para la DB
updateData.photo1 = finalPhotos[0];
updateData.photo2 = finalPhotos[1];
updateData.photo3 = finalPhotos[2];
@@ -368,9 +373,9 @@ export class TrainingService {
const record = await this.findOne(id);
// Delete associated files
if (record.photo1) this.deleteFile(record.photo1);
if (record.photo2) this.deleteFile(record.photo2);
if (record.photo3) this.deleteFile(record.photo3);
if (record.photo1) await this.deleteFile(record.photo1);
if (record.photo2) await this.deleteFile(record.photo2);
if (record.photo3) await this.deleteFile(record.photo3);
const [deletedRecord] = await this.drizzle
.delete(trainingSurveys)
@@ -499,139 +504,182 @@ export class TrainingService {
// return await workbook.outputAsync();
// }
async exportTemplate(id: number) {
// async exportTemplate(id: number) {
// // Validar que el registro exista
// const exist = await this.findOne(id);
// if (!exist) throw new NotFoundException(`No se encontro el registro`);
// Validar que el registro exista
const exist = await this.findOne(id);
if (!exist) throw new NotFoundException(`No se encontro el registro`);
// // Obtener los datos del registro
// const records = await this.drizzle
// .select({
// // id: trainingSurveys.id,
// visitDate: trainingSurveys.visitDate,
// ospName: trainingSurveys.ospName,
// productiveSector: trainingSurveys.productiveSector,
// ospAddress: trainingSurveys.ospAddress,
// ospRif: trainingSurveys.ospRif,
// Obtener los datos del registro
const records = await this.drizzle
.select({
// id: trainingSurveys.id,
visitDate: trainingSurveys.visitDate,
ospName: trainingSurveys.ospName,
productiveSector: trainingSurveys.productiveSector,
ospAddress: trainingSurveys.ospAddress,
ospRif: trainingSurveys.ospRif,
// siturCodeCommune: trainingSurveys.siturCodeCommune,
// communeEmail: trainingSurveys.communeEmail,
// communeRif: trainingSurveys.communeRif,
// communeSpokespersonName: trainingSurveys.communeSpokespersonName,
// communeSpokespersonPhone: trainingSurveys.communeSpokespersonPhone,
siturCodeCommune: trainingSurveys.siturCodeCommune,
communeEmail: trainingSurveys.communeEmail,
communeRif: trainingSurveys.communeRif,
communeSpokespersonName: trainingSurveys.communeSpokespersonName,
communeSpokespersonPhone: trainingSurveys.communeSpokespersonPhone,
// siturCodeCommunalCouncil: trainingSurveys.siturCodeCommunalCouncil,
// communalCouncilRif: trainingSurveys.communalCouncilRif,
// communalCouncilSpokespersonName:
// trainingSurveys.communalCouncilSpokespersonName,
// communalCouncilSpokespersonPhone:
// trainingSurveys.communalCouncilSpokespersonPhone,
siturCodeCommunalCouncil: trainingSurveys.siturCodeCommunalCouncil,
communalCouncilRif: trainingSurveys.communalCouncilRif,
communalCouncilSpokespersonName: trainingSurveys.communalCouncilSpokespersonName,
communalCouncilSpokespersonPhone: trainingSurveys.communalCouncilSpokespersonPhone,
// ospType: trainingSurveys.ospType,
// productiveActivity: trainingSurveys.productiveActivity, // Sector Productivo
// companyConstitutionYear: trainingSurveys.companyConstitutionYear,
// infrastructureMt2: trainingSurveys.infrastructureMt2,
ospType: trainingSurveys.ospType,
productiveActivity: trainingSurveys.productiveActivity, // Sector Productivo
companyConstitutionYear: trainingSurveys.companyConstitutionYear,
infrastructureMt2: trainingSurveys.infrastructureMt2,
// hasTransport: trainingSurveys.hasTransport,
// structureType: trainingSurveys.structureType,
// isOpenSpace: trainingSurveys.isOpenSpace,
hasTransport: trainingSurveys.hasTransport,
structureType: trainingSurveys.structureType,
isOpenSpace: trainingSurveys.isOpenSpace,
// ospResponsibleFullname: trainingSurveys.ospResponsibleFullname,
// ospResponsibleCedula: trainingSurveys.ospResponsibleCedula,
// ospResponsiblePhone: trainingSurveys.ospResponsiblePhone,
ospResponsibleFullname: trainingSurveys.ospResponsibleFullname,
ospResponsibleCedula: trainingSurveys.ospResponsibleCedula,
ospResponsiblePhone: trainingSurveys.ospResponsiblePhone,
// productList: trainingSurveys.productList,
// equipmentList: trainingSurveys.equipmentList,
// productionList: trainingSurveys.productionList,
productList: trainingSurveys.productList,
equipmentList: trainingSurveys.equipmentList,
productionList: trainingSurveys.productionList,
// // photo1: trainingSurveys.photo1
// })
// .from(trainingSurveys)
// .where(eq(trainingSurveys.id, id));
// // .leftJoin(states, eq(trainingSurveys.state, states.id))
// // .leftJoin(municipalities,eq(trainingSurveys.municipality, municipalities.id))
// // .leftJoin(parishes, eq(trainingSurveys.parish, parishes.id))
// photo1: trainingSurveys.photo1
})
.from(trainingSurveys)
.where(eq(trainingSurveys.id, id))
// .leftJoin(states, eq(trainingSurveys.state, states.id))
// .leftJoin(municipalities,eq(trainingSurveys.municipality, municipalities.id))
// .leftJoin(parishes, eq(trainingSurveys.parish, parishes.id))
// let equipmentList: any[] = Array.isArray(records[0].equipmentList)
// ? records[0].equipmentList
// : [];
// let productList: any[] = Array.isArray(records[0].productList)
// ? records[0].productList
// : [];
// let productionList: any[] = Array.isArray(records[0].productionList)
// ? records[0].productionList
// : [];
let equipmentList: any[] = Array.isArray(records[0].equipmentList) ? records[0].equipmentList : [];
let productList: any[] = Array.isArray(records[0].productList) ? records[0].productList : [];
let productionList: any[] = Array.isArray(records[0].productionList) ? records[0].productionList : [];
// console.log('equipmentList', equipmentList);
// console.log('productList', productList);
// console.log('productionList', productionList);
console.log('equipmentList', equipmentList);
console.log('productList', productList);
console.log('productionList', productionList);
// let equipmentListArray: any[] = [];
// let productListArray: any[] = [];
// let productionListArray: any[] = [];
let equipmentListArray: any[] = [];
let productListArray: any[] = [];
let productionListArray: any[] = [];
// const equipmentListCount = equipmentList.length;
// for (let i = 0; i < equipmentListCount; i++) {
// equipmentListArray.push([
// equipmentList[i].machine,
// '',
// equipmentList[i].quantity,
// ]);
// }
const equipmentListCount = equipmentList.length;
for (let i = 0; i < equipmentListCount; i++) {
equipmentListArray.push([equipmentList[i].machine, '', equipmentList[i].quantity]);
}
// const productListCount = productList.length;
// for (let i = 0; i < productListCount; i++) {
// productListArray.push([
// productList[i].productName,
// productList[i].dailyCount,
// productList[i].weeklyCount,
// productList[i].monthlyCount,
// ]);
// }
const productListCount = productList.length;
for (let i = 0; i < productListCount; i++) {
productListArray.push([productList[i].productName, productList[i].dailyCount, productList[i].weeklyCount, productList[i].monthlyCount]);
}
// const productionListCount = productionList.length;
// for (let i = 0; i < productionListCount; i++) {
// productionListArray.push([
// productionList[i].rawMaterial,
// '',
// productionList[i].quantity,
// ]);
// }
const productionListCount = productionList.length;
for (let i = 0; i < productionListCount; i++) {
productionListArray.push([productionList[i].rawMaterial, '', productionList[i].quantity]);
}
// // Ruta de la plantilla
// const templatePath = path.join(
// __dirname,
// 'export_template',
// 'excel.osp.xlsx',
// );
// Ruta de la plantilla
const templatePath = path.join(
__dirname,
'export_template',
'excel.osp.xlsx',
);
// // Cargar la plantilla
// const book = await XlsxPopulate.fromFileAsync(templatePath);
// Cargar la plantilla
const book = await XlsxPopulate.fromFileAsync(templatePath);
// const isoString = records[0].visitDate;
// const dateObj = new Date(isoString);
// const fechaFormateada = dateObj.toLocaleDateString('es-ES');
// const horaFormateada = dateObj.toLocaleTimeString('es-ES', {
// hour: '2-digit',
// minute: '2-digit',
// });
const isoString = records[0].visitDate;
const dateObj = new Date(isoString);
const fechaFormateada = dateObj.toLocaleDateString('es-ES');
const horaFormateada = dateObj.toLocaleTimeString('es-ES', { hour: '2-digit', minute: '2-digit' });
// // Llenar los datos
// book.sheet(0).cell('A6').value(records[0].productiveSector);
// book.sheet(0).cell('D6').value(records[0].ospName);
// book.sheet(0).cell('L5').value(fechaFormateada);
// book.sheet(0).cell('L6').value(horaFormateada);
// book.sheet(0).cell('B10').value(records[0].ospAddress);
// book.sheet(0).cell('C11').value(records[0].communeEmail);
// book.sheet(0).cell('C12').value(records[0].communeSpokespersonName);
// book.sheet(0).cell('G11').value(records[0].communeRif);
// book.sheet(0).cell('G12').value(records[0].communeSpokespersonPhone);
// book.sheet(0).cell('C13').value(records[0].siturCodeCommune);
// book.sheet(0).cell('G13').value(records[0].siturCodeCommunalCouncil);
// book.sheet(0).cell('G14').value(records[0].communalCouncilRif);
// book.sheet(0).cell('C15').value(records[0].communalCouncilSpokespersonName);
// book
// .sheet(0)
// .cell('G15')
// .value(records[0].communalCouncilSpokespersonPhone);
// book.sheet(0).cell('C16').value(records[0].ospType);
// book.sheet(0).cell('C17').value(records[0].ospName);
// book.sheet(0).cell('C18').value(records[0].productiveActivity);
// book.sheet(0).cell('C19').value('Proveedores');
// book.sheet(0).cell('C20').value(records[0].companyConstitutionYear);
// book.sheet(0).cell('C21').value(records[0].infrastructureMt2);
// book.sheet(0).cell('G17').value(records[0].ospRif);
// Llenar los datos
book.sheet(0).cell('A6').value(records[0].productiveSector);
book.sheet(0).cell('D6').value(records[0].ospName);
book.sheet(0).cell('L5').value(fechaFormateada);
book.sheet(0).cell('L6').value(horaFormateada);
book.sheet(0).cell('B10').value(records[0].ospAddress);
book.sheet(0).cell('C11').value(records[0].communeEmail);
book.sheet(0).cell('C12').value(records[0].communeSpokespersonName);
book.sheet(0).cell('G11').value(records[0].communeRif);
book.sheet(0).cell('G12').value(records[0].communeSpokespersonPhone);
book.sheet(0).cell('C13').value(records[0].siturCodeCommune);
book.sheet(0).cell('G13').value(records[0].siturCodeCommunalCouncil);
book.sheet(0).cell('G14').value(records[0].communalCouncilRif);
book.sheet(0).cell('C15').value(records[0].communalCouncilSpokespersonName);
book.sheet(0).cell('G15').value(records[0].communalCouncilSpokespersonPhone);
book.sheet(0).cell('C16').value(records[0].ospType);
book.sheet(0).cell('C17').value(records[0].ospName);
book.sheet(0).cell('C18').value(records[0].productiveActivity);
book.sheet(0).cell('C19').value('Proveedores');
book.sheet(0).cell('C20').value(records[0].companyConstitutionYear);
book.sheet(0).cell('C21').value(records[0].infrastructureMt2);
book.sheet(0).cell('G17').value(records[0].ospRif);
// book
// .sheet(0)
// .cell(records[0].hasTransport === true ? 'J19' : 'L19')
// .value('X');
// book
// .sheet(0)
// .cell(records[0].structureType === 'CASA' ? 'J20' : 'L20')
// .value('X');
// book
// .sheet(0)
// .cell(records[0].isOpenSpace === true ? 'J21' : 'L21')
// .value('X');
book.sheet(0).cell(records[0].hasTransport === true ? 'J19' : 'L19').value('X');
book.sheet(0).cell(records[0].structureType === 'CASA' ? 'J20' : 'L20').value('X');
book.sheet(0).cell(records[0].isOpenSpace === true ? 'J21' : 'L21').value('X');
// book.sheet(0).cell('A24').value(records[0].ospResponsibleFullname);
// book.sheet(0).cell('C24').value(records[0].ospResponsibleCedula);
// book.sheet(0).cell('E24').value(records[0].ospResponsiblePhone);
book.sheet(0).cell('A24').value(records[0].ospResponsibleFullname);
book.sheet(0).cell('C24').value(records[0].ospResponsibleCedula);
book.sheet(0).cell('E24').value(records[0].ospResponsiblePhone);
// book.sheet(0).cell('J24').value('N Femenino');
// book.sheet(0).cell('L24').value('N Masculino');
// book
// .sheet(0)
// .range(`A28:C${equipmentListCount + 28}`)
// .value(equipmentListArray);
// book
// .sheet(0)
// .range(`E28:G${productionListCount + 28}`)
// .value(productionListArray);
// book
// .sheet(0)
// .range(`I28:L${productListCount + 28}`)
// .value(productListArray);
book.sheet(0).cell('J24').value('N Femenino');
book.sheet(0).cell('L24').value('N Masculino');
book.sheet(0).range(`A28:C${equipmentListCount + 28}`).value(equipmentListArray);
book.sheet(0).range(`E28:G${productionListCount + 28}`).value(productionListArray);
book.sheet(0).range(`I28:L${productListCount + 28}`).value(productListArray);
return book.outputAsync();
}
// return book.outputAsync();
// }
}