|
| 1 | +import { Injectable, NotFoundException } from '@nestjs/common'; |
| 2 | +import * as PDFDocument from 'pdfkit'; |
| 3 | +import * as Papa from 'papaparse'; |
| 4 | +import { Readable } from 'stream'; |
| 5 | + |
| 6 | +@Injectable() |
| 7 | +export class ReportingService { |
| 8 | + private async getReportData(jurisdiction: string): Promise<any[]> { |
| 9 | + const mockData = { |
| 10 | + USA: [ |
| 11 | + { id: 'TX-123', amount: 5000, currency: 'USD', status: 'approved' }, |
| 12 | + { id: 'NY-456', amount: 12000, currency: 'USD', status: 'pending' }, |
| 13 | + ], |
| 14 | + EU: [ |
| 15 | + { id: 'DE-789', amount: 8000, currency: 'EUR', status: 'approved' }, |
| 16 | + { id: 'FR-101', amount: 7500, currency: 'EUR', status: 'declined' }, |
| 17 | + ], |
| 18 | + }; |
| 19 | + |
| 20 | + const data = mockData[jurisdiction.toUpperCase()]; |
| 21 | + if (!data) { |
| 22 | + throw new NotFoundException( |
| 23 | + `No data found for jurisdiction: ${jurisdiction}`, |
| 24 | + ); |
| 25 | + } |
| 26 | + return data; |
| 27 | + } |
| 28 | + |
| 29 | + async generateReport( |
| 30 | + jurisdiction: string, |
| 31 | + format: 'csv' | 'pdf', |
| 32 | + ): Promise<Readable> { |
| 33 | + const data = await this.getReportData(jurisdiction); |
| 34 | + |
| 35 | + if (format === 'csv') { |
| 36 | + return this.generateCsv(data); |
| 37 | + } else { |
| 38 | + return this.generatePdf(data, jurisdiction); |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + private generateCsv(data: any[]): Readable { |
| 43 | + const csvString = Papa.unparse(data); |
| 44 | + const stream = new Readable(); |
| 45 | + stream.push(csvString); |
| 46 | + stream.push(null); |
| 47 | + return stream; |
| 48 | + } |
| 49 | + |
| 50 | + private generatePdf(data: any[], jurisdiction: string): Readable { |
| 51 | + const doc = new PDFDocument({ margin: 50 }); |
| 52 | + |
| 53 | + doc.fontSize(20).text(`Regulatory Report: ${jurisdiction.toUpperCase()}`, { |
| 54 | + align: 'center', |
| 55 | + }); |
| 56 | + doc.moveDown(); |
| 57 | + |
| 58 | + const tableTop = 150; |
| 59 | + const itemX = 50; |
| 60 | + const amountX = 250; |
| 61 | + const currencyX = 350; |
| 62 | + const statusX = 450; |
| 63 | + |
| 64 | + doc |
| 65 | + .fontSize(12) |
| 66 | + .text('Transaction ID', itemX, tableTop) |
| 67 | + .text('Amount', amountX, tableTop) |
| 68 | + .text('Currency', currencyX, tableTop) |
| 69 | + .text('Status', statusX, tableTop); |
| 70 | + |
| 71 | + let i = 0; |
| 72 | + for (const item of data) { |
| 73 | + const y = tableTop + 25 + i * 25; |
| 74 | + doc |
| 75 | + .fontSize(10) |
| 76 | + .text(item.id, itemX, y) |
| 77 | + .text(item.amount.toString(), amountX, y) |
| 78 | + .text(item.currency, currencyX, y) |
| 79 | + .text(item.status, statusX, y); |
| 80 | + i++; |
| 81 | + } |
| 82 | + |
| 83 | + doc.end(); |
| 84 | + return doc; |
| 85 | + } |
| 86 | +} |
0 commit comments