feat(invoices): Persian line items + elegant client-side PDF download

- Translate persisted English invoice line labels/descriptions/reasons to
  Persian at display time (new lib/invoice-labels.ts), covering both new and
  historical invoices without a data migration.
- Generate a styled, RTL Persian invoice PDF on the client (lib/invoice-pdf.ts)
  with the Abrban logo, line-item table and totals, via html2canvas + jsPDF.
- Wire both the user and admin invoice pages to the translator and new download.
- Add invoices.pdf dictionary keys (fa/en).
- Remove the now-dead ASCII-only backend PDF endpoints and generateInvoicePdf.
- Add frontend/.npmrc (npmmirror registry + high timeouts) for Iran-network installs.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
keyhan
2026-06-19 19:59:22 +03:30
parent 78ed95b29b
commit 4d64fda227
11 changed files with 677 additions and 133 deletions
-31
View File
@@ -9,13 +9,11 @@ import {
Query,
UseGuards,
Request,
Res,
BadRequestException,
Inject,
forwardRef,
ForbiddenException,
} from '@nestjs/common';
import { Response } from 'express';
import { AuthGuard } from '@nestjs/passport';
import { ApiTags, ApiOperation, ApiBearerAuth } from '@nestjs/swagger';
import { BillingService } from './billing.service';
@@ -174,20 +172,6 @@ export class BillingController {
});
}
@Get('invoices/:id/pdf')
@ApiOperation({ summary: 'Download invoice as PDF' })
async downloadInvoicePdf(
@Request() req: any,
@Param('id') id: string,
@Res() res: Response,
) {
const invoice = await this.billingService.getInvoiceForUser(id, req.user);
const pdf = this.billingService.generateInvoicePdf(invoice);
res.setHeader('Content-Type', 'application/pdf');
res.setHeader('Content-Disposition', `attachment; filename="${invoice.invoiceNumber}.pdf"`);
res.send(pdf);
}
@Get('invoices/:id')
@ApiOperation({ summary: 'Get one invoice with line items and transactions' })
async getInvoice(@Request() req: any, @Param('id') id: string) {
@@ -372,21 +356,6 @@ export class BillingController {
return this.billingService.getInvoiceForUser(id, req.user);
}
@Get('admin/invoices/:id/pdf')
@Roles(UserRole.ADMIN)
@ApiOperation({ summary: 'Download invoice PDF (Admin)' })
async downloadAdminInvoicePdf(
@Request() req: any,
@Param('id') id: string,
@Res() res: Response,
) {
const invoice = await this.billingService.getInvoiceForUser(id, req.user);
const pdf = this.billingService.generateInvoicePdf(invoice);
res.setHeader('Content-Type', 'application/pdf');
res.setHeader('Content-Disposition', `attachment; filename="${invoice.invoiceNumber}.pdf"`);
res.send(pdf);
}
@Patch('admin/invoices/:id/status')
@Roles(UserRole.ADMIN)
@ApiOperation({ summary: 'Update invoice status with reason (Admin)' })
-65
View File
@@ -521,71 +521,6 @@ export class BillingService {
return this.invoiceRepo.save(invoice);
}
generateInvoicePdf(invoice: Invoice): Buffer {
const formatAmount = (amount: number) => `${Number(amount || 0).toLocaleString('en-US')} Toman`;
const formatDate = (date?: Date) => (date ? new Date(date).toLocaleString('en-US') : '-');
const clean = (value: unknown) =>
String(value ?? '-')
.replace(/[^\x20-\x7E]/g, '?')
.replace(/[\\()]/g, (match) => `\\${match}`);
const lines = [
'CloudHost Invoice',
`Invoice Number: ${invoice.invoiceNumber}`,
`Status: ${invoice.status}`,
`Payment Method: ${invoice.paymentMethod || '-'}`,
`Customer: ${invoice.user?.email || invoice.userId}`,
`Application: ${invoice.application?.name || invoice.applicationId || '-'}`,
`Created At: ${formatDate(invoice.createdAt)}`,
`Paid At: ${formatDate(invoice.paidAt)}`,
'',
'Line Items:',
...(invoice.lines || []).map(
(line) => `- ${line.label}${line.description ? ` (${line.description})` : ''}: ${formatAmount(Number(line.amount))}`,
),
'',
`Subtotal: ${formatAmount(Number(invoice.subtotal))}`,
`Total: ${formatAmount(Number(invoice.total))}`,
`Paid: ${formatAmount(Number(invoice.paidAmount))}`,
`Due: ${formatAmount(Number(invoice.dueAmount))}`,
`Gateway Tracking: ${invoice.gatewayTrackingCode || '-'}`,
].map(clean);
const content = [
'BT',
'/F1 12 Tf',
'50 790 Td',
'16 TL',
...lines.map((line, index) => `${index === 0 ? '' : 'T* '}(${line}) Tj`),
'ET',
].join('\n');
const objects = [
'1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n',
'2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n',
'3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] /Resources << /Font << /F1 4 0 R >> >> /Contents 5 0 R >>\nendobj\n',
'4 0 obj\n<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>\nendobj\n',
`5 0 obj\n<< /Length ${Buffer.byteLength(content, 'utf8')} >>\nstream\n${content}\nendstream\nendobj\n`,
];
let pdf = '%PDF-1.4\n';
const offsets = [0];
for (const object of objects) {
offsets.push(Buffer.byteLength(pdf, 'utf8'));
pdf += object;
}
const xrefOffset = Buffer.byteLength(pdf, 'utf8');
pdf += `xref\n0 ${objects.length + 1}\n`;
pdf += '0000000000 65535 f \n';
for (let i = 1; i < offsets.length; i += 1) {
pdf += `${String(offsets[i]).padStart(10, '0')} 00000 n \n`;
}
pdf += `trailer\n<< /Size ${objects.length + 1} /Root 1 0 R >>\nstartxref\n${xrefOffset}\n%%EOF\n`;
return Buffer.from(pdf, 'utf8');
}
/**
* Calculate cost for an existing Application entity.
* Used by lifecycle service for auto-renew.