import { BadRequestException, Body, Controller, Delete, Get, Param, Patch, Post, Query, Res, StreamableFile, UploadedFile, UseGuards, UseInterceptors, } from '@nestjs/common'; import { FileInterceptor } from '@nestjs/platform-express'; import { memoryStorage } from 'multer'; import type { Response } from 'express'; import { JwtAuthGuard } from '../auth/jwt-auth.guard'; import { CurrentUser } from '../auth/current-user.decorator'; import type { Actor } from '../common/record-scope'; import { CompaniesService } from './companies.service'; import { CreateCompanyDto, ListQueryDto, UpdateCompanyDto } from './dto'; import { ContactsExcelService } from './contacts-excel.service'; import { brand } from '@mento/shared'; const excelUpload = FileInterceptor('file', { storage: memoryStorage(), limits: { fileSize: 15_000_000 }, }); @Controller('companies') @UseGuards(JwtAuthGuard) export class CompaniesController { constructor( private readonly companiesService: CompaniesService, private readonly excelService: ContactsExcelService, ) {} @Get() list(@CurrentUser() user: Actor, @Query() query: ListQueryDto) { return this.companiesService.list( user, query.q, query.page ?? 1, query.limit ?? 20, ); } @Get('export') async export( @CurrentUser() user: Actor, @Query('q') q: string | undefined, @Res({ passthrough: true }) res: Response, ) { const buffer = await this.excelService.exportCompanies(user, q); res.set({ 'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'Content-Disposition': `attachment; filename="${brand.filePrefix}-companies.xlsx"`, }); return new StreamableFile(buffer); } @Post('import/preview') @UseInterceptors(excelUpload) previewImport(@UploadedFile() file?: Express.Multer.File) { if (!file?.buffer?.length) { throw new BadRequestException('فایل ارسال نشده'); } return this.excelService.previewCompanies(file); } @Post('import') @UseInterceptors(excelUpload) import( @CurrentUser() user: Actor, @UploadedFile() file?: Express.Multer.File, @Body('mapping') mapping?: string, @Body('sessionId') sessionId?: string, @Body('offset') offset?: string, @Body('limit') limit?: string, ) { if (!file?.buffer?.length && !sessionId) { throw new BadRequestException('فایل ارسال نشده'); } return this.excelService.importCompanies(user, file, mapping, { sessionId, offset, limit, }); } @Get(':id') get(@CurrentUser() user: Actor, @Param('id') id: string) { return this.companiesService.get(user, id); } @Post() create(@CurrentUser() user: Actor, @Body() dto: CreateCompanyDto) { return this.companiesService.create(user, dto); } @Patch(':id') update( @CurrentUser() user: Actor, @Param('id') id: string, @Body() dto: UpdateCompanyDto, ) { return this.companiesService.update(user, id, dto); } @Delete(':id') async remove(@CurrentUser() user: Actor, @Param('id') id: string) { await this.companiesService.remove(user, id); return { ok: true }; } }