@fin.cx/skr 1.1.0 → 1.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist_ts/00_commitinfo_data.d.ts +8 -0
- package/dist_ts/00_commitinfo_data.js +9 -0
- package/dist_ts/index.d.ts +6 -0
- package/dist_ts/index.js +7 -1
- package/dist_ts/plugins.d.ts +8 -1
- package/dist_ts/plugins.js +10 -2
- package/dist_ts/skr.api.d.ts +70 -0
- package/dist_ts/skr.api.js +348 -1
- package/dist_ts/skr.classes.account.d.ts +28 -0
- package/dist_ts/skr.classes.account.js +87 -4
- package/dist_ts/skr.classes.journalentry.js +56 -4
- package/dist_ts/skr.classes.ledger.js +5 -1
- package/dist_ts/skr.export.accounts.d.ts +53 -0
- package/dist_ts/skr.export.accounts.js +111 -0
- package/dist_ts/skr.export.balances.d.ts +59 -0
- package/dist_ts/skr.export.balances.js +205 -0
- package/dist_ts/skr.export.d.ts +110 -0
- package/dist_ts/skr.export.js +315 -0
- package/dist_ts/skr.export.ledger.d.ts +95 -0
- package/dist_ts/skr.export.ledger.js +164 -0
- package/dist_ts/skr.export.pdf.d.ts +82 -0
- package/dist_ts/skr.export.pdf.js +548 -0
- package/dist_ts/skr.invoice.adapter.d.ts +98 -0
- package/dist_ts/skr.invoice.adapter.js +476 -0
- package/dist_ts/skr.invoice.booking.d.ts +102 -0
- package/dist_ts/skr.invoice.booking.js +578 -0
- package/dist_ts/skr.invoice.entity.d.ts +287 -0
- package/dist_ts/skr.invoice.entity.js +2 -0
- package/dist_ts/skr.invoice.mapper.d.ts +69 -0
- package/dist_ts/skr.invoice.mapper.js +401 -0
- package/dist_ts/skr.invoice.storage.d.ts +140 -0
- package/dist_ts/skr.invoice.storage.js +529 -0
- package/dist_ts/skr.postingkeys.d.ts +56 -0
- package/dist_ts/skr.postingkeys.js +196 -0
- package/dist_ts/skr.security.d.ts +65 -0
- package/dist_ts/skr.security.js +319 -0
- package/dist_ts/skr.types.d.ts +19 -0
- package/dist_ts/skr03.data.js +3 -1
- package/dist_ts/skr04.data.js +3 -1
- package/package.json +17 -12
- package/readme.hints.md +54 -1
- package/readme.md +207 -16
- package/ts/00_commitinfo_data.ts +8 -0
- package/ts/index.ts +6 -0
- package/ts/plugins.ts +22 -1
- package/ts/skr.api.ts +485 -0
- package/ts/skr.classes.account.ts +106 -3
- package/ts/skr.classes.journalentry.ts +78 -3
- package/ts/skr.classes.ledger.ts +4 -0
- package/ts/skr.export.accounts.ts +154 -0
- package/ts/skr.export.balances.ts +270 -0
- package/ts/skr.export.ledger.ts +249 -0
- package/ts/skr.export.pdf.ts +601 -0
- package/ts/skr.export.ts +443 -0
- package/ts/skr.invoice.adapter.ts +581 -0
- package/ts/skr.invoice.booking.ts +760 -0
- package/ts/skr.invoice.entity.ts +351 -0
- package/ts/skr.invoice.mapper.ts +486 -0
- package/ts/skr.invoice.storage.ts +710 -0
- package/ts/skr.postingkeys.ts +252 -0
- package/ts/skr.security.ts +405 -0
- package/ts/skr.types.ts +27 -0
- package/ts/skr03.data.ts +2 -0
- package/ts/skr04.data.ts +2 -0
package/ts/skr.api.ts
CHANGED
|
@@ -1,10 +1,28 @@
|
|
|
1
1
|
import * as plugins from './plugins.js';
|
|
2
|
+
import * as path from 'path';
|
|
2
3
|
import { ChartOfAccounts } from './skr.classes.chartofaccounts.js';
|
|
3
4
|
import { Ledger } from './skr.classes.ledger.js';
|
|
4
5
|
import { Reports } from './skr.classes.reports.js';
|
|
5
6
|
import { Account } from './skr.classes.account.js';
|
|
6
7
|
import { Transaction } from './skr.classes.transaction.js';
|
|
7
8
|
import { JournalEntry } from './skr.classes.journalentry.js';
|
|
9
|
+
import { SkrExport, type IExportOptions } from './skr.export.js';
|
|
10
|
+
import { LedgerExporter } from './skr.export.ledger.js';
|
|
11
|
+
import { AccountsExporter } from './skr.export.accounts.js';
|
|
12
|
+
import { BalancesExporter } from './skr.export.balances.js';
|
|
13
|
+
import { PdfReportGenerator, type IPdfReportOptions } from './skr.export.pdf.js';
|
|
14
|
+
import { SecurityManager, type ISigningOptions } from './skr.security.js';
|
|
15
|
+
import { InvoiceAdapter } from './skr.invoice.adapter.js';
|
|
16
|
+
import { InvoiceStorage } from './skr.invoice.storage.js';
|
|
17
|
+
import { InvoiceBookingEngine, type IBookingOptions, type IBookingResult } from './skr.invoice.booking.js';
|
|
18
|
+
import type {
|
|
19
|
+
IInvoice,
|
|
20
|
+
IInvoiceFilter,
|
|
21
|
+
IInvoiceImportOptions,
|
|
22
|
+
IInvoiceExportOptions,
|
|
23
|
+
IBookingRules,
|
|
24
|
+
TInvoiceDirection,
|
|
25
|
+
} from './skr.invoice.entity.js';
|
|
8
26
|
import type {
|
|
9
27
|
IDatabaseConfig,
|
|
10
28
|
TSKRType,
|
|
@@ -17,6 +35,7 @@ import type {
|
|
|
17
35
|
ITrialBalanceReport,
|
|
18
36
|
IIncomeStatement,
|
|
19
37
|
IBalanceSheet,
|
|
38
|
+
IAccountBalance,
|
|
20
39
|
} from './skr.types.js';
|
|
21
40
|
|
|
22
41
|
/**
|
|
@@ -29,6 +48,9 @@ export class SkrApi {
|
|
|
29
48
|
private logger: plugins.smartlog.Smartlog;
|
|
30
49
|
private initialized: boolean = false;
|
|
31
50
|
private currentSKRType: TSKRType | null = null;
|
|
51
|
+
private invoiceAdapter: InvoiceAdapter | null = null;
|
|
52
|
+
private invoiceStorage: InvoiceStorage | null = null;
|
|
53
|
+
private invoiceBookingEngine: InvoiceBookingEngine | null = null;
|
|
32
54
|
|
|
33
55
|
constructor(private config: IDatabaseConfig) {
|
|
34
56
|
this.chartOfAccounts = new ChartOfAccounts(config);
|
|
@@ -62,6 +84,13 @@ export class SkrApi {
|
|
|
62
84
|
this.currentSKRType = skrType;
|
|
63
85
|
this.ledger = new Ledger(skrType);
|
|
64
86
|
this.reports = new Reports(skrType);
|
|
87
|
+
|
|
88
|
+
// Initialize invoice components
|
|
89
|
+
this.invoiceAdapter = new InvoiceAdapter();
|
|
90
|
+
const invoicePath = this.config.invoiceExportPath || path.resolve(process.cwd(), 'exports', 'invoices');
|
|
91
|
+
this.invoiceStorage = new InvoiceStorage(invoicePath);
|
|
92
|
+
this.invoiceBookingEngine = new InvoiceBookingEngine(skrType);
|
|
93
|
+
|
|
65
94
|
this.initialized = true;
|
|
66
95
|
|
|
67
96
|
this.logger.log('info', 'SKR API initialized successfully');
|
|
@@ -350,6 +379,262 @@ export class SkrApi {
|
|
|
350
379
|
return await this.chartOfAccounts.exportAccountsToCSV();
|
|
351
380
|
}
|
|
352
381
|
|
|
382
|
+
/**
|
|
383
|
+
* Export Jahresabschluss in GoBD-compliant BagIt format
|
|
384
|
+
* Creates a revision-safe export for 10-year archival
|
|
385
|
+
*/
|
|
386
|
+
public async exportJahresabschluss(options: IExportOptions): Promise<string> {
|
|
387
|
+
this.ensureInitialized();
|
|
388
|
+
if (!this.ledger || !this.reports || !this.currentSKRType) {
|
|
389
|
+
throw new Error('API not fully initialized');
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
this.logger.log('info', `Starting Jahresabschluss export for fiscal year ${options.fiscalYear}`);
|
|
393
|
+
|
|
394
|
+
// Create export instance
|
|
395
|
+
const exporter = new SkrExport(options);
|
|
396
|
+
|
|
397
|
+
// Create BagIt structure
|
|
398
|
+
await exporter.createBagItStructure();
|
|
399
|
+
await exporter.createExportMetadata(this.currentSKRType);
|
|
400
|
+
await exporter.createSchemas();
|
|
401
|
+
|
|
402
|
+
// Export accounting data
|
|
403
|
+
await this.exportLedgerData(exporter, options);
|
|
404
|
+
await this.exportAccountData(exporter, options);
|
|
405
|
+
await this.exportBalanceData(exporter, options);
|
|
406
|
+
|
|
407
|
+
// Generate PDF reports if requested
|
|
408
|
+
if (options.generatePdfReports) {
|
|
409
|
+
await this.generatePdfReports(exporter, options);
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
// Sign export if requested
|
|
413
|
+
if (options.signExport) {
|
|
414
|
+
await this.signExport(exporter, options);
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
// Create manifests and validate
|
|
418
|
+
await exporter.writeManifests();
|
|
419
|
+
const merkleRoot = await exporter.createMerkleTree();
|
|
420
|
+
|
|
421
|
+
const isValid = await exporter.validateBagIt();
|
|
422
|
+
if (!isValid) {
|
|
423
|
+
throw new Error('BagIt validation failed');
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
this.logger.log('ok', `Jahresabschluss export completed. Merkle root: ${merkleRoot}`);
|
|
427
|
+
|
|
428
|
+
return options.exportPath;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
/**
|
|
432
|
+
* Export ledger data in NDJSON format
|
|
433
|
+
*/
|
|
434
|
+
private async exportLedgerData(exporter: SkrExport, options: IExportOptions): Promise<void> {
|
|
435
|
+
if (!this.ledger) throw new Error('Ledger not initialized');
|
|
436
|
+
|
|
437
|
+
const ledgerExporter = new LedgerExporter(options.exportPath);
|
|
438
|
+
await ledgerExporter.initialize();
|
|
439
|
+
|
|
440
|
+
// Get all transactions for the period
|
|
441
|
+
const transactions = await this.chartOfAccounts.getTransactions({
|
|
442
|
+
dateFrom: options.dateFrom,
|
|
443
|
+
dateTo: options.dateTo
|
|
444
|
+
});
|
|
445
|
+
|
|
446
|
+
// Export each transaction
|
|
447
|
+
for (const transaction of transactions) {
|
|
448
|
+
const transactionData = transaction;
|
|
449
|
+
await ledgerExporter.exportTransaction(transactionData as any);
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
// Get all journal entries for the period
|
|
453
|
+
// Use MongoDB query syntax for date range
|
|
454
|
+
const journalEntries = await JournalEntry.getInstances({
|
|
455
|
+
date: {
|
|
456
|
+
$gte: options.dateFrom,
|
|
457
|
+
$lte: options.dateTo
|
|
458
|
+
} as any, // SmartData supports MongoDB query operators
|
|
459
|
+
skrType: this.currentSKRType
|
|
460
|
+
});
|
|
461
|
+
|
|
462
|
+
// Export each journal entry
|
|
463
|
+
for (const entry of journalEntries) {
|
|
464
|
+
const entryData = entry;
|
|
465
|
+
await ledgerExporter.exportJournalEntry(entryData as any);
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
const entryCount = await ledgerExporter.close();
|
|
469
|
+
this.logger.log('info', `Exported ${entryCount} ledger entries`);
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
/**
|
|
473
|
+
* Export account data in CSV format
|
|
474
|
+
*/
|
|
475
|
+
private async exportAccountData(exporter: SkrExport, options: IExportOptions): Promise<void> {
|
|
476
|
+
const accountsExporter = new AccountsExporter(options.exportPath);
|
|
477
|
+
|
|
478
|
+
// Get all accounts
|
|
479
|
+
const accounts = await this.chartOfAccounts.getAllAccounts();
|
|
480
|
+
|
|
481
|
+
// Add each account to export
|
|
482
|
+
for (const account of accounts) {
|
|
483
|
+
const accountData = account;
|
|
484
|
+
accountsExporter.addAccount(accountData as any);
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
// Export to CSV and JSON
|
|
488
|
+
await accountsExporter.exportToCSV();
|
|
489
|
+
await accountsExporter.exportToJSON();
|
|
490
|
+
|
|
491
|
+
this.logger.log('info', `Exported ${accountsExporter.getAccountCount()} accounts`);
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
/**
|
|
495
|
+
* Export balance data in CSV format
|
|
496
|
+
*/
|
|
497
|
+
private async exportBalanceData(exporter: SkrExport, options: IExportOptions): Promise<void> {
|
|
498
|
+
if (!this.ledger) throw new Error('Ledger not initialized');
|
|
499
|
+
|
|
500
|
+
const balancesExporter = new BalancesExporter(
|
|
501
|
+
options.exportPath,
|
|
502
|
+
options.fiscalYear
|
|
503
|
+
);
|
|
504
|
+
|
|
505
|
+
// Get all accounts with balances
|
|
506
|
+
const accounts = await this.chartOfAccounts.getAllAccounts();
|
|
507
|
+
|
|
508
|
+
for (const account of accounts) {
|
|
509
|
+
const balance = await this.ledger.getAccountBalance(
|
|
510
|
+
account.accountNumber,
|
|
511
|
+
options.dateTo
|
|
512
|
+
);
|
|
513
|
+
|
|
514
|
+
if (balance) {
|
|
515
|
+
balancesExporter.addBalance(
|
|
516
|
+
account.accountNumber,
|
|
517
|
+
account.accountName,
|
|
518
|
+
balance as IAccountBalance,
|
|
519
|
+
`${options.fiscalYear}`
|
|
520
|
+
);
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
// Export balance reports
|
|
525
|
+
await balancesExporter.exportToCSV();
|
|
526
|
+
await balancesExporter.exportTrialBalance();
|
|
527
|
+
await balancesExporter.exportClassSummary();
|
|
528
|
+
|
|
529
|
+
this.logger.log('info', `Exported ${balancesExporter.getBalanceCount()} account balances`);
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
/**
|
|
533
|
+
* Generate PDF reports for the export
|
|
534
|
+
*/
|
|
535
|
+
private async generatePdfReports(exporter: SkrExport, options: IExportOptions): Promise<void> {
|
|
536
|
+
if (!this.reports) throw new Error('Reports not initialized');
|
|
537
|
+
|
|
538
|
+
const pdfOptions: IPdfReportOptions = {
|
|
539
|
+
companyName: options.companyInfo?.name || 'Unternehmen',
|
|
540
|
+
companyAddress: options.companyInfo?.address,
|
|
541
|
+
taxId: options.companyInfo?.taxId,
|
|
542
|
+
registrationNumber: options.companyInfo?.registrationNumber,
|
|
543
|
+
fiscalYear: options.fiscalYear,
|
|
544
|
+
dateFrom: options.dateFrom,
|
|
545
|
+
dateTo: options.dateTo,
|
|
546
|
+
preparedDate: new Date()
|
|
547
|
+
};
|
|
548
|
+
|
|
549
|
+
const pdfGenerator = new PdfReportGenerator(options.exportPath, pdfOptions);
|
|
550
|
+
await pdfGenerator.initialize();
|
|
551
|
+
|
|
552
|
+
try {
|
|
553
|
+
// Generate reports
|
|
554
|
+
const trialBalance = await this.reports.getTrialBalance({
|
|
555
|
+
dateFrom: options.dateFrom,
|
|
556
|
+
dateTo: options.dateTo,
|
|
557
|
+
skrType: this.currentSKRType
|
|
558
|
+
});
|
|
559
|
+
|
|
560
|
+
const incomeStatement = await this.reports.getIncomeStatement({
|
|
561
|
+
dateFrom: options.dateFrom,
|
|
562
|
+
dateTo: options.dateTo,
|
|
563
|
+
skrType: this.currentSKRType
|
|
564
|
+
});
|
|
565
|
+
|
|
566
|
+
const balanceSheet = await this.reports.getBalanceSheet({
|
|
567
|
+
dateFrom: options.dateFrom,
|
|
568
|
+
dateTo: options.dateTo,
|
|
569
|
+
skrType: this.currentSKRType
|
|
570
|
+
});
|
|
571
|
+
|
|
572
|
+
// Generate PDFs
|
|
573
|
+
const jahresabschlussPdf = await pdfGenerator.generateJahresabschlussPdf(
|
|
574
|
+
trialBalance,
|
|
575
|
+
incomeStatement,
|
|
576
|
+
balanceSheet
|
|
577
|
+
);
|
|
578
|
+
|
|
579
|
+
// Save PDFs
|
|
580
|
+
await pdfGenerator.savePdfReport('jahresabschluss.pdf', jahresabschlussPdf);
|
|
581
|
+
|
|
582
|
+
// Store in BagIt structure
|
|
583
|
+
await exporter.storeDocument(jahresabschlussPdf, 'jahresabschluss.pdf');
|
|
584
|
+
|
|
585
|
+
this.logger.log('info', 'PDF reports generated successfully');
|
|
586
|
+
} finally {
|
|
587
|
+
await pdfGenerator.close();
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
/**
|
|
592
|
+
* Sign the export with CAdES signature
|
|
593
|
+
*/
|
|
594
|
+
private async signExport(exporter: SkrExport, options: IExportOptions): Promise<void> {
|
|
595
|
+
const signingOptions: ISigningOptions = {
|
|
596
|
+
certificatePem: options.signExport ? undefined : undefined, // Use provided cert or generate
|
|
597
|
+
privateKeyPem: options.signExport ? undefined : undefined,
|
|
598
|
+
includeTimestamp: options.timestampExport !== false
|
|
599
|
+
};
|
|
600
|
+
|
|
601
|
+
const security = new SecurityManager(signingOptions);
|
|
602
|
+
|
|
603
|
+
// Generate self-signed certificate if none provided
|
|
604
|
+
let cert: string, key: string;
|
|
605
|
+
if (!signingOptions.certificatePem) {
|
|
606
|
+
const generated = await security.generateSelfSignedCertificate(
|
|
607
|
+
options.companyInfo?.name || 'SKR Export System'
|
|
608
|
+
);
|
|
609
|
+
cert = generated.certificate;
|
|
610
|
+
key = generated.privateKey;
|
|
611
|
+
} else {
|
|
612
|
+
cert = signingOptions.certificatePem;
|
|
613
|
+
key = signingOptions.privateKeyPem!;
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
// Sign the manifest
|
|
617
|
+
const manifestPath = path.resolve(
|
|
618
|
+
options.exportPath,
|
|
619
|
+
`jahresabschluss_${options.fiscalYear}`,
|
|
620
|
+
'manifest-sha256.txt'
|
|
621
|
+
);
|
|
622
|
+
|
|
623
|
+
await security.createDetachedSignature(
|
|
624
|
+
manifestPath,
|
|
625
|
+
path.resolve(
|
|
626
|
+
options.exportPath,
|
|
627
|
+
`jahresabschluss_${options.fiscalYear}`,
|
|
628
|
+
'data',
|
|
629
|
+
'metadata',
|
|
630
|
+
'signatures',
|
|
631
|
+
'manifest.cades'
|
|
632
|
+
)
|
|
633
|
+
);
|
|
634
|
+
|
|
635
|
+
this.logger.log('info', 'Export signed with CAdES signature');
|
|
636
|
+
}
|
|
637
|
+
|
|
353
638
|
// ========== Utility Methods ==========
|
|
354
639
|
|
|
355
640
|
/**
|
|
@@ -532,4 +817,204 @@ export class SkrApi {
|
|
|
532
817
|
totalPages,
|
|
533
818
|
};
|
|
534
819
|
}
|
|
820
|
+
|
|
821
|
+
// ========== Invoice Management ==========
|
|
822
|
+
|
|
823
|
+
/**
|
|
824
|
+
* Import an invoice from file or buffer
|
|
825
|
+
* Parses, validates, and optionally books the invoice
|
|
826
|
+
*/
|
|
827
|
+
public async importInvoice(
|
|
828
|
+
file: Buffer | string,
|
|
829
|
+
direction: TInvoiceDirection,
|
|
830
|
+
options?: IInvoiceImportOptions
|
|
831
|
+
): Promise<IInvoice> {
|
|
832
|
+
this.ensureInitialized();
|
|
833
|
+
if (!this.invoiceAdapter || !this.invoiceStorage || !this.invoiceBookingEngine) {
|
|
834
|
+
throw new Error('Invoice components not initialized');
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
this.logger.log('info', `Importing ${direction} invoice`);
|
|
838
|
+
|
|
839
|
+
// Parse and validate invoice
|
|
840
|
+
const invoice = await this.invoiceAdapter.parseInvoice(file, direction);
|
|
841
|
+
|
|
842
|
+
// Store invoice
|
|
843
|
+
await this.invoiceStorage.initialize();
|
|
844
|
+
const contentHash = await this.invoiceStorage.storeInvoice(invoice);
|
|
845
|
+
invoice.contentHash = contentHash;
|
|
846
|
+
|
|
847
|
+
// Auto-book if requested
|
|
848
|
+
if (options?.autoBook) {
|
|
849
|
+
const bookingResult = await this.bookInvoice(
|
|
850
|
+
invoice,
|
|
851
|
+
options.bookingRules,
|
|
852
|
+
{
|
|
853
|
+
autoBook: true,
|
|
854
|
+
confidenceThreshold: options.confidenceThreshold || 80,
|
|
855
|
+
skipValidation: options.validateOnly
|
|
856
|
+
}
|
|
857
|
+
);
|
|
858
|
+
|
|
859
|
+
if (bookingResult.success && bookingResult.bookingInfo) {
|
|
860
|
+
invoice.bookingInfo = bookingResult.bookingInfo;
|
|
861
|
+
invoice.status = 'posted';
|
|
862
|
+
|
|
863
|
+
// Update stored metadata with booking information
|
|
864
|
+
await this.invoiceStorage.updateMetadata(invoice.contentHash, {
|
|
865
|
+
journalEntryId: bookingResult.bookingInfo.journalEntryId,
|
|
866
|
+
transactionIds: bookingResult.bookingInfo.transactionIds
|
|
867
|
+
});
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
this.logger.log('info', `Invoice imported successfully: ${invoice.invoiceNumber}`);
|
|
872
|
+
return invoice;
|
|
873
|
+
}
|
|
874
|
+
|
|
875
|
+
/**
|
|
876
|
+
* Book an invoice to the ledger
|
|
877
|
+
*/
|
|
878
|
+
public async bookInvoice(
|
|
879
|
+
invoice: IInvoice,
|
|
880
|
+
bookingRules?: Partial<IBookingRules>,
|
|
881
|
+
options?: IBookingOptions
|
|
882
|
+
): Promise<IBookingResult> {
|
|
883
|
+
this.ensureInitialized();
|
|
884
|
+
if (!this.invoiceBookingEngine) {
|
|
885
|
+
throw new Error('Invoice booking engine not initialized');
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
this.logger.log('info', `Booking invoice ${invoice.invoiceNumber}`);
|
|
889
|
+
|
|
890
|
+
const result = await this.invoiceBookingEngine.bookInvoice(
|
|
891
|
+
invoice,
|
|
892
|
+
bookingRules,
|
|
893
|
+
options
|
|
894
|
+
);
|
|
895
|
+
|
|
896
|
+
if (result.success) {
|
|
897
|
+
this.logger.log('info', `Invoice booked successfully with confidence ${result.confidence}%`);
|
|
898
|
+
|
|
899
|
+
// Update stored metadata if invoice has a content hash
|
|
900
|
+
if (invoice.contentHash && result.bookingInfo && this.invoiceStorage) {
|
|
901
|
+
await this.invoiceStorage.updateMetadata(invoice.contentHash, {
|
|
902
|
+
journalEntryId: result.bookingInfo.journalEntryId,
|
|
903
|
+
transactionIds: result.bookingInfo.transactionIds
|
|
904
|
+
});
|
|
905
|
+
}
|
|
906
|
+
} else {
|
|
907
|
+
this.logger.log('error', `Invoice booking failed: ${result.errors?.join(', ')}`);
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
return result;
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
/**
|
|
914
|
+
* Export an invoice in a different format
|
|
915
|
+
*/
|
|
916
|
+
public async exportInvoice(
|
|
917
|
+
invoice: IInvoice,
|
|
918
|
+
options: IInvoiceExportOptions
|
|
919
|
+
): Promise<{ xml: string; pdf?: Buffer }> {
|
|
920
|
+
this.ensureInitialized();
|
|
921
|
+
if (!this.invoiceAdapter) {
|
|
922
|
+
throw new Error('Invoice adapter not initialized');
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
this.logger.log('info', `Exporting invoice ${invoice.invoiceNumber} to ${options.format}`);
|
|
926
|
+
|
|
927
|
+
// Convert format if needed
|
|
928
|
+
const xml = await this.invoiceAdapter.convertFormat(invoice, options.format);
|
|
929
|
+
|
|
930
|
+
// Generate PDF if requested
|
|
931
|
+
let pdf: Buffer | undefined;
|
|
932
|
+
if (options.embedInPdf) {
|
|
933
|
+
const result = await this.invoiceAdapter.generateInvoice(invoice, options.format);
|
|
934
|
+
pdf = result.pdf;
|
|
935
|
+
}
|
|
936
|
+
|
|
937
|
+
return { xml, pdf };
|
|
938
|
+
}
|
|
939
|
+
|
|
940
|
+
/**
|
|
941
|
+
* Search invoices by filter
|
|
942
|
+
*/
|
|
943
|
+
public async searchInvoices(filter: IInvoiceFilter): Promise<IInvoice[]> {
|
|
944
|
+
this.ensureInitialized();
|
|
945
|
+
if (!this.invoiceStorage) {
|
|
946
|
+
throw new Error('Invoice storage not initialized');
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
await this.invoiceStorage.initialize();
|
|
950
|
+
const metadata = await this.invoiceStorage.searchInvoices(filter);
|
|
951
|
+
|
|
952
|
+
const invoices: IInvoice[] = [];
|
|
953
|
+
for (const meta of metadata) {
|
|
954
|
+
const invoice = await this.invoiceStorage.retrieveInvoice(meta.contentHash);
|
|
955
|
+
if (invoice) {
|
|
956
|
+
invoices.push(invoice);
|
|
957
|
+
}
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
return invoices;
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
/**
|
|
964
|
+
* Get invoice by content hash
|
|
965
|
+
*/
|
|
966
|
+
public async getInvoice(contentHash: string): Promise<IInvoice | null> {
|
|
967
|
+
this.ensureInitialized();
|
|
968
|
+
if (!this.invoiceStorage) {
|
|
969
|
+
throw new Error('Invoice storage not initialized');
|
|
970
|
+
}
|
|
971
|
+
|
|
972
|
+
await this.invoiceStorage.initialize();
|
|
973
|
+
return await this.invoiceStorage.retrieveInvoice(contentHash);
|
|
974
|
+
}
|
|
975
|
+
|
|
976
|
+
/**
|
|
977
|
+
* Get invoice storage statistics
|
|
978
|
+
*/
|
|
979
|
+
public async getInvoiceStatistics(): Promise<any> {
|
|
980
|
+
this.ensureInitialized();
|
|
981
|
+
if (!this.invoiceStorage) {
|
|
982
|
+
throw new Error('Invoice storage not initialized');
|
|
983
|
+
}
|
|
984
|
+
|
|
985
|
+
await this.invoiceStorage.initialize();
|
|
986
|
+
return await this.invoiceStorage.getStatistics();
|
|
987
|
+
}
|
|
988
|
+
|
|
989
|
+
/**
|
|
990
|
+
* Create EN16931 compliance report for invoices
|
|
991
|
+
*/
|
|
992
|
+
public async createInvoiceComplianceReport(): Promise<void> {
|
|
993
|
+
this.ensureInitialized();
|
|
994
|
+
if (!this.invoiceStorage) {
|
|
995
|
+
throw new Error('Invoice storage not initialized');
|
|
996
|
+
}
|
|
997
|
+
|
|
998
|
+
await this.invoiceStorage.initialize();
|
|
999
|
+
await this.invoiceStorage.createComplianceReport();
|
|
1000
|
+
|
|
1001
|
+
this.logger.log('info', 'Invoice compliance report created');
|
|
1002
|
+
}
|
|
1003
|
+
|
|
1004
|
+
/**
|
|
1005
|
+
* Generate an invoice from internal data
|
|
1006
|
+
*/
|
|
1007
|
+
public async generateInvoice(
|
|
1008
|
+
invoiceData: Partial<IInvoice>,
|
|
1009
|
+
format: IInvoiceExportOptions['format']
|
|
1010
|
+
): Promise<{ xml: string; pdf?: Buffer }> {
|
|
1011
|
+
this.ensureInitialized();
|
|
1012
|
+
if (!this.invoiceAdapter) {
|
|
1013
|
+
throw new Error('Invoice adapter not initialized');
|
|
1014
|
+
}
|
|
1015
|
+
|
|
1016
|
+
this.logger.log('info', `Generating invoice in ${format} format`);
|
|
1017
|
+
|
|
1018
|
+
return await this.invoiceAdapter.generateInvoice(invoiceData, format);
|
|
1019
|
+
}
|
|
535
1020
|
}
|
|
@@ -56,6 +56,9 @@ export class Account extends SmartDataDbDoc<Account, Account> {
|
|
|
56
56
|
@svDb()
|
|
57
57
|
public isSystemAccount: boolean;
|
|
58
58
|
|
|
59
|
+
@svDb()
|
|
60
|
+
public isAutomaticAccount: boolean;
|
|
61
|
+
|
|
59
62
|
@svDb()
|
|
60
63
|
public createdAt: Date;
|
|
61
64
|
|
|
@@ -90,6 +93,7 @@ export class Account extends SmartDataDbDoc<Account, Account> {
|
|
|
90
93
|
this.debitTotal = 0;
|
|
91
94
|
this.creditTotal = 0;
|
|
92
95
|
this.isSystemAccount = true;
|
|
96
|
+
this.isAutomaticAccount = data.isAutomaticAccount || false;
|
|
93
97
|
this.createdAt = new Date();
|
|
94
98
|
this.updatedAt = new Date();
|
|
95
99
|
}
|
|
@@ -157,6 +161,85 @@ export class Account extends SmartDataDbDoc<Account, Account> {
|
|
|
157
161
|
);
|
|
158
162
|
}
|
|
159
163
|
|
|
164
|
+
/**
|
|
165
|
+
* Check if account number is in debtor range (10000-69999)
|
|
166
|
+
* Debtor accounts (Debitorenkonten) are individual customer accounts
|
|
167
|
+
*/
|
|
168
|
+
public static isInDebtorRange(accountNumber: string): boolean {
|
|
169
|
+
const num = parseInt(accountNumber);
|
|
170
|
+
return num >= 10000 && num <= 69999;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Check if account number is in creditor range (70000-99999)
|
|
175
|
+
* Creditor accounts (Kreditorenkonten) are individual vendor accounts
|
|
176
|
+
*/
|
|
177
|
+
public static isInCreditorRange(accountNumber: string): boolean {
|
|
178
|
+
const num = parseInt(accountNumber);
|
|
179
|
+
return num >= 70000 && num <= 99999;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* Check if account is an automatic account (Automatikkonto)
|
|
184
|
+
* Automatic accounts like 1400/1600 cannot be posted to directly
|
|
185
|
+
*/
|
|
186
|
+
public static isAutomaticAccount(accountNumber: string, skrType: TSKRType): boolean {
|
|
187
|
+
// SKR03: 1400 (Forderungen), 1600 (Verbindlichkeiten)
|
|
188
|
+
// SKR04: 1400 (Forderungen), 1600 (Verbindlichkeiten)
|
|
189
|
+
// Note: In SKR04, 3300 is "Fahrzeugkosten" (vehicle costs), NOT an automatic account
|
|
190
|
+
if (skrType === 'SKR03') {
|
|
191
|
+
return accountNumber === '1400' || accountNumber === '1600';
|
|
192
|
+
} else {
|
|
193
|
+
return accountNumber === '1400' || accountNumber === '1600';
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* Validate account for posting - throws error if account cannot be posted to
|
|
199
|
+
*/
|
|
200
|
+
public static async validateAccountForPosting(
|
|
201
|
+
accountNumber: string,
|
|
202
|
+
skrType: TSKRType,
|
|
203
|
+
): Promise<void> {
|
|
204
|
+
// Check if automatic account
|
|
205
|
+
if (Account.isAutomaticAccount(accountNumber, skrType)) {
|
|
206
|
+
throw new Error(
|
|
207
|
+
`Account ${accountNumber} is an automatic account (Automatikkonto) and cannot be posted to directly. ` +
|
|
208
|
+
`Use debtor accounts (10000-69999) or creditor accounts (70000-99999) instead.`
|
|
209
|
+
);
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// Get account to verify it exists
|
|
213
|
+
const account = await Account.getAccountByNumber(accountNumber, skrType);
|
|
214
|
+
if (!account) {
|
|
215
|
+
throw new Error(
|
|
216
|
+
`Account ${accountNumber} not found in ${skrType}. ` +
|
|
217
|
+
`Please create the account before posting.`
|
|
218
|
+
);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// Check if account is active
|
|
222
|
+
if (!account.isActive) {
|
|
223
|
+
throw new Error(
|
|
224
|
+
`Account ${accountNumber} is inactive and cannot be posted to.`
|
|
225
|
+
);
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* Check if this account instance is a debtor account
|
|
231
|
+
*/
|
|
232
|
+
public isDebtorAccount(): boolean {
|
|
233
|
+
return Account.isInDebtorRange(this.accountNumber);
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Check if this account instance is a creditor account
|
|
238
|
+
*/
|
|
239
|
+
public isCreditorAccount(): boolean {
|
|
240
|
+
return Account.isInCreditorRange(this.accountNumber);
|
|
241
|
+
}
|
|
242
|
+
|
|
160
243
|
public async updateBalance(
|
|
161
244
|
debitAmount: number = 0,
|
|
162
245
|
creditAmount: number = 0,
|
|
@@ -209,19 +292,33 @@ export class Account extends SmartDataDbDoc<Account, Account> {
|
|
|
209
292
|
|
|
210
293
|
public async beforeSave(): Promise<void> {
|
|
211
294
|
// Validate account number format
|
|
212
|
-
|
|
295
|
+
const accountLength = this.accountNumber?.length || 0;
|
|
296
|
+
if (!this.accountNumber || (accountLength !== 4 && accountLength !== 5)) {
|
|
213
297
|
throw new Error(
|
|
214
|
-
`Invalid account number format: ${this.accountNumber}. Must be 4 digits.`,
|
|
298
|
+
`Invalid account number format: ${this.accountNumber}. Must be 4 digits (standard SKR) or 5 digits (debtor/creditor).`,
|
|
215
299
|
);
|
|
216
300
|
}
|
|
217
301
|
|
|
218
302
|
// Validate account number is numeric
|
|
219
|
-
if (!/^\d{4}$/.test(this.accountNumber)) {
|
|
303
|
+
if (!/^\d{4,5}$/.test(this.accountNumber)) {
|
|
220
304
|
throw new Error(
|
|
221
305
|
`Account number must contain only digits: ${this.accountNumber}`,
|
|
222
306
|
);
|
|
223
307
|
}
|
|
224
308
|
|
|
309
|
+
// For 5-digit accounts, validate they are in debtor (10000-69999) or creditor (70000-99999) ranges
|
|
310
|
+
if (accountLength === 5) {
|
|
311
|
+
const accountNum = parseInt(this.accountNumber);
|
|
312
|
+
const isDebtor = accountNum >= 10000 && accountNum <= 69999;
|
|
313
|
+
const isCreditor = accountNum >= 70000 && accountNum <= 99999;
|
|
314
|
+
|
|
315
|
+
if (!isDebtor && !isCreditor) {
|
|
316
|
+
throw new Error(
|
|
317
|
+
`5-digit account number ${this.accountNumber} must be in debtor range (10000-69999) or creditor range (70000-99999).`,
|
|
318
|
+
);
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
|
|
225
322
|
// Validate account class matches first digit
|
|
226
323
|
const firstDigit = parseInt(this.accountNumber[0]);
|
|
227
324
|
if (this.accountClass !== firstDigit) {
|
|
@@ -234,5 +331,11 @@ export class Account extends SmartDataDbDoc<Account, Account> {
|
|
|
234
331
|
if (this.skrType !== 'SKR03' && this.skrType !== 'SKR04') {
|
|
235
332
|
throw new Error(`Invalid SKR type: ${this.skrType}`);
|
|
236
333
|
}
|
|
334
|
+
|
|
335
|
+
// Mark automatic accounts (Automatikkonten)
|
|
336
|
+
// These are summary accounts that cannot be posted to directly
|
|
337
|
+
if (Account.isAutomaticAccount(this.accountNumber, this.skrType)) {
|
|
338
|
+
this.isAutomaticAccount = true;
|
|
339
|
+
}
|
|
237
340
|
}
|
|
238
341
|
}
|