import { Body, Controller, HttpCode, HttpStatus, Post, Query, Request, Res, UseGuards } from '@nestjs/common'; import { Response } from 'express'; import * as fs from 'fs'; import * as path from 'path'; import { ExportService } from '../service/export.service'; import { JwtAuthGuard } from '../../auth/guards/jwt.guard'; @Controller() export class ExportController { constructor(private readonly exportService: ExportService) { } @HttpCode(HttpStatus.OK) @UseGuards(JwtAuthGuard) @Post('download-report') async downloadExcel( @Body() body: any, @Request() req: Request & { user: any }, @Query() queryParams: Record, @Res() res: Response, @Query('level_type') levelType?: string, @Query('level_id') levelId?: number, @Query('appcode') appCode?: string, ) { try { const loggedInUser = req.user.userData; const { entity_type, quickFilter, savedFilterCode, attributeFilter, tabs, sortby, view } = body; const { ...otherQueryParams } = queryParams; const filePath = await this.exportService.generateExcelReport({ entity_type, quickFilter, savedFilterCode, attributeFilter, tabs, sortby, page: null, size: null, loggedInUser, queryParams: otherQueryParams, // only remaining query params customLevelType: levelType, customLevelId: levelId, customAppCode: appCode, view }, ); if (!filePath || !fs.existsSync(filePath)) { return res.status(404).json({ message: 'File not found' }); } res.setHeader( 'Content-Disposition', `attachment; filename=${path.basename(filePath)}`, ); res.setHeader( 'Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', ); const fileStream = fs.createReadStream(filePath); fileStream.pipe(res); // Optional: Delete file after sending response fileStream.on('end', () => { fs.unlinkSync(filePath); }); } catch (error) { console.error('Error downloading Excel file:', error); res.status(500).json({ message: 'Internal server error' }); } } }