|
| 1 | +import { |
| 2 | + Injectable, |
| 3 | + Logger, |
| 4 | + NotFoundException, |
| 5 | + BadRequestException, |
| 6 | +} from '@nestjs/common'; |
| 7 | +import { InjectRepository } from '@nestjs/typeorm'; |
| 8 | +import { Repository } from 'typeorm'; |
| 9 | +import { OnEvent } from '@nestjs/event-emitter'; |
| 10 | +import { randomBytes } from 'crypto'; |
| 11 | +import * as fs from 'fs'; |
| 12 | +import * as path from 'path'; |
| 13 | +import * as os from 'os'; |
| 14 | +import * as archiver from 'archiver'; |
| 15 | +import { |
| 16 | + DataExportRequest, |
| 17 | + ExportStatus, |
| 18 | +} from './entities/data-export-request.entity'; |
| 19 | +import { User } from '../user/entities/user.entity'; |
| 20 | +import { Transaction } from '../transactions/entities/transaction.entity'; |
| 21 | +import { Notification } from '../notifications/entities/notification.entity'; |
| 22 | +import { SavingsGoal } from '../savings/entities/savings-goal.entity'; |
| 23 | +import { MailService } from '../mail/mail.service'; |
| 24 | + |
| 25 | +const EXPORT_DIR = path.join(os.tmpdir(), 'nestera-exports'); |
| 26 | +const LINK_EXPIRY_DAYS = 7; |
| 27 | + |
| 28 | +@Injectable() |
| 29 | +export class DataExportService { |
| 30 | + private readonly logger = new Logger(DataExportService.name); |
| 31 | + |
| 32 | + constructor( |
| 33 | + @InjectRepository(DataExportRequest) |
| 34 | + private readonly exportRepository: Repository<DataExportRequest>, |
| 35 | + @InjectRepository(User) |
| 36 | + private readonly userRepository: Repository<User>, |
| 37 | + @InjectRepository(Transaction) |
| 38 | + private readonly transactionRepository: Repository<Transaction>, |
| 39 | + @InjectRepository(Notification) |
| 40 | + private readonly notificationRepository: Repository<Notification>, |
| 41 | + @InjectRepository(SavingsGoal) |
| 42 | + private readonly savingsGoalRepository: Repository<SavingsGoal>, |
| 43 | + private readonly mailService: MailService, |
| 44 | + ) { |
| 45 | + fs.mkdirSync(EXPORT_DIR, { recursive: true }); |
| 46 | + } |
| 47 | + |
| 48 | + /** |
| 49 | + * Create an export request and trigger async processing. |
| 50 | + */ |
| 51 | + async requestExport(userId: string): Promise<{ requestId: string; message: string }> { |
| 52 | + const user = await this.userRepository.findOne({ where: { id: userId } }); |
| 53 | + if (!user) throw new NotFoundException('User not found'); |
| 54 | + |
| 55 | + const request = this.exportRepository.create({ userId, status: ExportStatus.PENDING }); |
| 56 | + const saved = await this.exportRepository.save(request); |
| 57 | + |
| 58 | + this.logger.log(`Data export requested for user ${userId}, request ${saved.id}`); |
| 59 | + |
| 60 | + // Trigger async processing (fire-and-forget) |
| 61 | + this.processExport(saved.id, user).catch((err) => |
| 62 | + this.logger.error(`Export ${saved.id} failed`, err), |
| 63 | + ); |
| 64 | + |
| 65 | + return { |
| 66 | + requestId: saved.id, |
| 67 | + message: 'Export request received. You will receive an email when your data is ready.', |
| 68 | + }; |
| 69 | + } |
| 70 | + |
| 71 | + /** |
| 72 | + * Download a ready export by token. |
| 73 | + */ |
| 74 | + async getExportFile(token: string): Promise<{ filePath: string; userId: string }> { |
| 75 | + const request = await this.exportRepository.findOne({ where: { token } }); |
| 76 | + if (!request || request.status !== ExportStatus.READY) { |
| 77 | + throw new NotFoundException('Export not found or not ready'); |
| 78 | + } |
| 79 | + if (request.expiresAt && request.expiresAt < new Date()) { |
| 80 | + await this.exportRepository.update(request.id, { status: ExportStatus.EXPIRED }); |
| 81 | + throw new BadRequestException('Export link has expired'); |
| 82 | + } |
| 83 | + if (!request.filePath || !fs.existsSync(request.filePath)) { |
| 84 | + throw new NotFoundException('Export file not found'); |
| 85 | + } |
| 86 | + return { filePath: request.filePath, userId: request.userId }; |
| 87 | + } |
| 88 | + |
| 89 | + /** |
| 90 | + * Get export request status. |
| 91 | + */ |
| 92 | + async getExportStatus(requestId: string, userId: string) { |
| 93 | + const request = await this.exportRepository.findOne({ |
| 94 | + where: { id: requestId, userId }, |
| 95 | + }); |
| 96 | + if (!request) throw new NotFoundException('Export request not found'); |
| 97 | + return { |
| 98 | + requestId: request.id, |
| 99 | + status: request.status, |
| 100 | + createdAt: request.createdAt, |
| 101 | + completedAt: request.completedAt, |
| 102 | + expiresAt: request.expiresAt, |
| 103 | + }; |
| 104 | + } |
| 105 | + |
| 106 | + /** |
| 107 | + * Async: build ZIP, update record, email user. |
| 108 | + */ |
| 109 | + private async processExport(requestId: string, user: User): Promise<void> { |
| 110 | + await this.exportRepository.update(requestId, { status: ExportStatus.PROCESSING }); |
| 111 | + |
| 112 | + try { |
| 113 | + const [transactions, notifications, goals] = await Promise.all([ |
| 114 | + this.transactionRepository.find({ where: { userId: user.id } }), |
| 115 | + this.notificationRepository.find({ where: { userId: user.id } }), |
| 116 | + this.savingsGoalRepository.find({ where: { userId: user.id } }), |
| 117 | + ]); |
| 118 | + |
| 119 | + const zipPath = path.join(EXPORT_DIR, `${requestId}.zip`); |
| 120 | + await this.buildZip(zipPath, { |
| 121 | + 'profile.json': { id: user.id, email: user.email, name: user.name, createdAt: user.createdAt }, |
| 122 | + 'transactions.json': transactions, |
| 123 | + 'goals.json': goals, |
| 124 | + 'notifications.json': notifications, |
| 125 | + }); |
| 126 | + |
| 127 | + const token = randomBytes(32).toString('hex'); |
| 128 | + const expiresAt = new Date(Date.now() + LINK_EXPIRY_DAYS * 86_400_000); |
| 129 | + |
| 130 | + await this.exportRepository.update(requestId, { |
| 131 | + status: ExportStatus.READY, |
| 132 | + token, |
| 133 | + filePath: zipPath, |
| 134 | + expiresAt, |
| 135 | + completedAt: new Date(), |
| 136 | + }); |
| 137 | + |
| 138 | + // Email the download link |
| 139 | + const downloadUrl = `/users/data/export/download/${token}`; |
| 140 | + await this.mailService.sendRawMail( |
| 141 | + user.email, |
| 142 | + 'Your Nestera data export is ready', |
| 143 | + `Hi ${user.name || 'there'},\n\nYour data export is ready. Download it here:\n${downloadUrl}\n\nThis link expires in ${LINK_EXPIRY_DAYS} days.\n\nNestera Team`, |
| 144 | + ); |
| 145 | + |
| 146 | + this.logger.log(`Export ${requestId} completed for user ${user.id}`); |
| 147 | + } catch (err) { |
| 148 | + await this.exportRepository.update(requestId, { status: ExportStatus.FAILED }); |
| 149 | + throw err; |
| 150 | + } |
| 151 | + } |
| 152 | + |
| 153 | + private buildZip( |
| 154 | + outputPath: string, |
| 155 | + files: Record<string, unknown>, |
| 156 | + ): Promise<void> { |
| 157 | + return new Promise((resolve, reject) => { |
| 158 | + const output = fs.createWriteStream(outputPath); |
| 159 | + const archive = archiver('zip', { zlib: { level: 6 } }); |
| 160 | + |
| 161 | + output.on('close', resolve); |
| 162 | + archive.on('error', reject); |
| 163 | + archive.pipe(output); |
| 164 | + |
| 165 | + for (const [name, data] of Object.entries(files)) { |
| 166 | + archive.append(JSON.stringify(data, null, 2), { name }); |
| 167 | + } |
| 168 | + |
| 169 | + archive.finalize(); |
| 170 | + }); |
| 171 | + } |
| 172 | +} |
0 commit comments