import { Injectable } from '@nestjs/common'; import { FilterRequestDto } from '../../filter/dto/filter-request.dto'; import { ExcelData } from '../../../utils/dto/excel-data.dto'; import * as path from 'path'; import * as fs from 'fs'; import { ExcelHelper } from '../../../utils/service/excel-helper.service'; import { ExcelsheetData } from '../../../utils/dto/excelsheet-data.dto'; import { AttributeMasterService } from '../../meta/service/attribute-master.service'; import { EntityMasterService } from '../../meta/service/entity-master.service'; import { FilterService } from '../../filter/service/filter.service'; import { LayoutPreferenceRepository } from '../../layout_preference/repository/layout_preference.repository'; @Injectable() export class ExportService { constructor( private readonly attributeMasterService: AttributeMasterService, private readonly entityMasterService: EntityMasterService, private readonly filterService: FilterService, private readonly layoutPreferenceRepo: LayoutPreferenceRepository, ) { } async generateExcelReport( dto: FilterRequestDto, ): Promise { let fileName: string; try { const excelData = new ExcelData(); await this.populateExcelData( excelData, dto, ); const modifiedDate = new Date().toISOString().replace(/[-T:.Z]/g, ''); const tempDir = path.join(__dirname, '../../temp'); if (!fs.existsSync(tempDir)) { fs.mkdirSync(tempDir, { recursive: true }); } fileName = path.join(tempDir, `export_${modifiedDate}.xlsx`); excelData.filePath = fileName; ExcelHelper.writeExcel(excelData); } catch (error) { throw error; } return fileName; } private async populateExcelData( excelData: ExcelData, dto: FilterRequestDto, ) { const entityMeta = await this.entityMasterService.getEntityData( dto.entity_type, dto.loggedInUser, ); let labelValueJson = [] as any; if ('current' === dto.view?.toLowerCase()) { const layoutPreference = await this.layoutPreferenceRepo.findByEntityUserId( dto.entity_type, dto.loggedInUser.level_id, dto.loggedInUser.level_type, dto.loggedInUser.id, 'layout', ); if (layoutPreference) { const layoutJson = layoutPreference.mapped_json; labelValueJson = layoutJson.column.show_list; } } else { const attributes = await this.attributeMasterService.findAttributesByMappedEntityType( dto.entity_type, dto.loggedInUser, ); attributes.map(attibute => labelValueJson.push({label: attibute.name , value: attibute.attribute_key})); } let filterData = await this.filterService.applyFilterWrapper(dto); let entityList = filterData.data.entity_list; const sheet: ExcelsheetData = { sheetName: entityMeta?.name || 'sheet', headers: [], rowList: [], }; if (labelValueJson) { sheet.headers = labelValueJson.map((col) => col.label); const attributeList = labelValueJson.map( (col) => col.value, ); sheet.rowList = entityList.map((item) => attributeList.map((attr) => item[attr] !== undefined ? item[attr] : null, ), ); excelData.addSheet(sheet); } } }