fix(core): Migrate file I/O to @push.rocks/smartfs, adopt TC39 decorators v3 accessor in web components, and update docs/tests

This commit is contained in:
2025-12-10 21:37:21 +00:00
parent 627df17b2b
commit 9f92c6e3ae
22 changed files with 319 additions and 1909 deletions

337
readme.md
View File

@@ -1,199 +1,276 @@
# @design.estate/dees-document
A comprehensive tool for dynamically generating and rendering business documents like invoices using modern web technologies.
A powerful TypeScript framework for dynamically generating professional business documents like invoices with web components and PDF export capabilities. 🧾
## Install
## Issue Reporting and Security
To incorporate `@design.estate/dees-document` into your project, execute the following command in your terminal:
For reporting bugs, issues, or security vulnerabilities, please visit [community.foss.global/](https://community.foss.global/). This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a [code.foss.global/](https://code.foss.global/) account to submit Pull Requests directly.
## Installation
```shell
npm install @design.estate/dees-document --save
pnpm install @design.estate/dees-document
```
This command will install the package and add it to your project's dependencies, thus making all the necessary modules available within your `node_modules` directory.
## Features
- 📄 **PDF Generation** - Server-side PDF creation from structured data using Puppeteer
- 🎨 **Web Components** - Lit-based custom elements for document rendering
- 🌍 **Multi-language Support** - Built-in translation system (EN, DE, ES)
- 📱 **Automatic Pagination** - Smart content overflow handling across pages
- 💳 **QR Payment Codes** - EPC QR codes for SEPA payments
- 🖨️ **Print Mode** - Optimized rendering for both screen and print
- 📐 **A4 Format** - Precise DIN A4 document dimensions
-**Theming** - Customizable colors, backgrounds, and branding
## Usage
The `@design.estate/dees-document` package serves as a robust framework to facilitate the generation of business documents, such as invoices, contracts, and reports. Leveraging modern web technologies, this package integrates seamlessly with TypeScript and ES modules, offering a type-safe environment conducive to efficient, dynamic document creation.
Below, we provide a detailed guide for utilizing this package, from initializing your environment to generating complete PDF documents.
### Setting Up the Environment
Before diving into document creation, ensure your environment is properly configured. Make sure to import necessary dependencies and setup configurations:
### Server-Side PDF Generation
```typescript
import { PdfService, IPdfServiceConstructorOptions } from '@design.estate/dees-document';
import { PdfService } from '@design.estate/dees-document';
import type { TInvoice } from '@tsclass/tsclass/finance';
async function setupPdfService() {
const options: IPdfServiceConstructorOptions = {
// Configure your options here
};
// Initialize the PDF service
const pdfService = new PdfService({});
await pdfService.start();
const pdfService = await PdfService.createAndStart(options);
console.log('PDF Service started successfully.');
return pdfService;
}
```
In this setup snippet, you set up the `PdfService` which is the core component for PDF generation. The configuration options should be adjusted to fit your needs, especially considering options such as file paths, languages, and template directories.
### Creating a Document Template
To create documents, particularly invoices, you'll first need to define a template. This template describes the structure of your document:
```typescript
import { ILetter } from '@design.estate/dees-document';
const invoiceTemplate: ILetter = {
// Create invoice data
const invoice: TInvoice = {
type: 'invoice',
invoiceType: 'debitnote',
id: 'INV-2024-001',
invoiceId: 'INV-2024-001',
date: Date.now(),
currency: 'EUR',
dueInDays: 30,
reverseCharge: false,
from: {
name: 'Your Company Name',
name: 'Your Company GmbH',
type: 'company',
status: 'active',
address: {
streetName: 'Your Street',
streetName: 'Business Street',
houseNumber: '123',
city: 'Your City',
country: 'Your Country',
postalCode: '12345',
city: 'Berlin',
country: 'Germany',
postalCode: '10115',
},
sepaConnection: {
bic: 'DEUTDEFF',
iban: 'DE89370400440532013000',
},
registrationDetails: {
vatId: 'DE123456789',
registrationName: 'Amtsgericht Berlin',
registrationId: 'HRB 12345',
},
email: 'your-email@example.com',
phone: '123-456-7890',
},
to: {
name: 'Recipient Company Name',
name: 'Customer Inc.',
type: 'company',
status: 'active',
address: {
streetName: 'Recipient Street',
streetName: 'Client Avenue',
houseNumber: '456',
city: 'Recipient City',
country: 'Recipient Country',
postalCode: '67890',
city: 'Munich',
country: 'Germany',
postalCode: '80331',
},
email: 'recipient-email@example.com',
phone: '098-765-4321',
},
content: {
invoiceData: {
items: [
{
name: 'Service or Product Name',
unitQuantity: 2,
unitNetPrice: 100.0,
unitType: 'service',
vatPercentage: 19,
currency: 'EUR',
},
],
registrationDetails: {
vatId: 'DE987654321',
},
},
subject: 'Invoice for Services Rendered',
date: new Date().getTime(),
items: [
{
name: 'Web Development Services',
unitQuantity: 40,
unitNetPrice: 95,
unitType: 'hours',
vatPercentage: 19,
position: 1,
},
{
name: 'Hosting (Annual)',
unitQuantity: 1,
unitNetPrice: 299,
unitType: 'item',
vatPercentage: 19,
position: 2,
},
],
subject: 'Invoice INV-2024-001',
versionInfo: {
type: 'final',
version: '1.0.0',
},
};
// Generate PDF
const pdfResult = await pdfService.createPdfFromLetterObject({
letterData: invoice,
documentSettings: {
languageCode: 'EN',
enableDefaultHeader: true,
enableDefaultFooter: true,
enableFoldMarks: true,
dateStyle: 'long',
},
});
// Save to file
import { SmartFs, SmartFsProviderNode } from '@push.rocks/smartfs';
const fs = new SmartFs(new SmartFsProviderNode());
await fs.file('./invoice.pdf').write(Buffer.from(pdfResult.buffer));
// Don't forget to stop the service when done
await pdfService.stop();
```
The `invoiceTemplate` object utilizes the `ILetter` interface which specifies the structure for invoice data, including sender and recipient details, itemization, and pricing.
### Document Settings
### Generating the Document
Once a template is established, the next step is generating a PDF:
Customize document appearance with `IDocumentSettings`:
```typescript
async function generateInvoice(pdfService: PdfService, invoiceData: ILetter) {
const pdfBuffer = await pdfService.createPdfFromLetterObject(invoiceData);
console.log('Invoice PDF generated successfully.');
const documentSettings = {
// Language for translations
languageCode: 'DE', // 'EN' | 'DE' | 'ES'
// Here you could save the PDF to your filesystem, send it via email, etc.
}
// Layout options
enableDefaultHeader: true,
enableDefaultFooter: true,
enableFoldMarks: true,
enableTopDraftText: true,
enableInvoiceContractRefSection: true,
// Display options
vatGroupPositions: true,
dateStyle: 'long', // 'short' | 'medium' | 'long' | 'full'
// Theming
theme: {
colorPrimaryForeground: '#ffffff',
colorPrimaryBackground: '#e4002b',
colorAccentForeground: '#333333',
colorAccentBackground: '#f5f5f5',
pageBackground: 'url(your-watermark.png)',
coverPageBackground: 'url(your-cover.png)',
},
};
```
In this function, the `createPdfFromLetterObject` method converts your invoice data into a `Buffer` containing the PDF. This `Buffer` can subsequently be saved as a file or sent over HTTP.
### Web Component Usage
### Comprehensive Example
Below is an example integrating all previous steps into a single coherent script:
For browser-based document viewing:
```typescript
async function main() {
const pdfService = await setupPdfService();
const invoiceData: ILetter = {
// Populate your invoice object
};
await generateInvoice(pdfService, invoiceData);
}
import '@design.estate/dees-document/web';
main().then(() => console.log('Invoice generation process completed.'));
// In your HTML/Lit template
html`
<dedocument-viewer
.letterData=${invoiceData}
.documentSettings=${documentSettings}
></dedocument-viewer>
`;
// Or render the document directly
html`
<dedocument-dedocument
.letterData=${invoiceData}
.documentSettings=${documentSettings}
></dedocument-dedocument>
`;
```
This script encompasses initializing services and generating a PDF in a streamlined, efficient workflow.
### Translation System
### Advanced Features
`@design.estate/dees-document` provides several advanced functionalities, enabling rich document creation:
1. **Custom Templates & Styling**
- Customize the styling through CSS or using inline styles in TypeScript.
- Templates can be adjusted to present different document types (e.g., contracts, reports).
2. **Modular Components and Reuse**
- Utilize modular components to create reusable parts across different documents, enhancing maintainability and reducing redundancy.
3. **Interactive Documents**
- Integrate interactivities like forms, buttons, and interactive charts within your documents.
4. **Localization Support**
- Documents can be localized to support multiple languages, enhancing accessibility and usability.
5. **Responsive and Adaptive Designs**
- Create documents that adjust layout dynamically depending on print or digital medium, maintaining consistency across platforms.
6. **Security Features**
- Apply digital signatures and encrypt sensitive documents to ensure secure and authentic document distribution.
7. **Complex Business Logic**
- Implement complex logic for feature-rich documents such as inventory systems, automatic tax calculations, or real-time pricing adjustments.
### Utilize Translation for Localization
The package offers a translation mechanism to adapt your documents for international clients:
The package includes a translation system for multi-language document generation:
```typescript
import { translate } from '@design.estate/dees-document/shared';
const languageCode: 'DE' | 'EN' | 'ES' = 'EN'; // Set required language code
console.log(translate(languageCode, 'invoice', 'Invoice')); // Translated output
// Translate document labels
translate('DE', 'invoice@@totalGross'); // "Gesamtbetrag (Brutto)"
translate('EN', 'invoice@@totalGross'); // "Total (Gross)"
translate('ES', 'invoice@@totalGross'); // "Total (Bruto)"
```
Different language settings can be applied, enabling the seamless presentation of document contents tailored to regional and linguistic preferences.
## Module Exports
### Conclusion
The package provides multiple entry points:
The `@design.estate/dees-document` package is a versatile and powerful solution for businesses seeking to automate and streamline their document generation processes using modern web technologies. By integrating seamlessly with TypeScript, it offers robust capabilities for creating complex, customizable, and interactive documents that can meet a variety of business needs.
```typescript
// Node.js server-side (PDF generation)
import { PdfService } from '@design.estate/dees-document';
import { PdfService } from '@design.estate/dees-document/node';
From custom templates to localization and advanced security features, this module provides the flexibility and power to create polished and professional documents efficiently. Whether you're generating invoices, contracts, or detailed reports, `@design.estate/dees-document` has the tools to support your enterprise workflows with ease and precision.
// Browser web components
import '@design.estate/dees-document/web';
// Shared utilities and types
import { translate, IDocumentSettings } from '@design.estate/dees-document/shared';
// TypeScript interfaces
import type { IDocumentSettings } from '@design.estate/dees-document/interfaces';
```
## Document Components
The framework includes these web components:
| Component | Description |
|-----------|-------------|
| `<dedocument-dedocument>` | Main document container with pagination |
| `<dedocument-viewer>` | Document viewer with controls |
| `<dedocument-page>` | Single A4 page with scaling support |
| `<dedocument-pageheader>` | Company logo and branding header |
| `<dedocument-letterheader>` | Sender/recipient addresses |
| `<dedocument-pagecontent>` | Main content area |
| `<dedocument-pagefooter>` | Company info and page numbers |
| `<dedocument-contentinvoice>` | Invoice-specific content layout |
| `<dedocument-paymentcode>` | EPC QR code for SEPA payments |
## Draft vs Final Documents
Control document version display:
```typescript
const invoice = {
// ... other fields
versionInfo: {
type: 'draft', // Shows watermark "DRAFT" across pages
version: '0.1.0',
},
};
// For final documents
const invoice = {
// ... other fields
versionInfo: {
type: 'final', // Clean document without watermark
version: '1.0.0',
},
};
```
## License and Legal Information
This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository.
This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the [LICENSE](./LICENSE) file.
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
### Trademarks
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH or third parties, and are not included within the scope of the MIT license granted herein.
Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar.
### Company Information
Task Venture Capital GmbH
Registered at District court Bremen HRB 35230 HB, Germany
Task Venture Capital GmbH
Registered at District Court Bremen HRB 35230 HB, Germany
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
For any legal inquiries or further information, please contact us via email at hello@task.vc.
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.