@fin.cx/skr 1.1.0 → 1.2.0

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.
Files changed (46) hide show
  1. package/dist_ts/index.d.ts +6 -0
  2. package/dist_ts/index.js +7 -1
  3. package/dist_ts/plugins.d.ts +8 -1
  4. package/dist_ts/plugins.js +10 -2
  5. package/dist_ts/skr.api.d.ts +70 -0
  6. package/dist_ts/skr.api.js +348 -1
  7. package/dist_ts/skr.export.accounts.d.ts +53 -0
  8. package/dist_ts/skr.export.accounts.js +111 -0
  9. package/dist_ts/skr.export.balances.d.ts +59 -0
  10. package/dist_ts/skr.export.balances.js +205 -0
  11. package/dist_ts/skr.export.d.ts +110 -0
  12. package/dist_ts/skr.export.js +315 -0
  13. package/dist_ts/skr.export.ledger.d.ts +95 -0
  14. package/dist_ts/skr.export.ledger.js +164 -0
  15. package/dist_ts/skr.export.pdf.d.ts +82 -0
  16. package/dist_ts/skr.export.pdf.js +548 -0
  17. package/dist_ts/skr.invoice.adapter.d.ts +98 -0
  18. package/dist_ts/skr.invoice.adapter.js +476 -0
  19. package/dist_ts/skr.invoice.booking.d.ts +102 -0
  20. package/dist_ts/skr.invoice.booking.js +556 -0
  21. package/dist_ts/skr.invoice.entity.d.ts +287 -0
  22. package/dist_ts/skr.invoice.entity.js +2 -0
  23. package/dist_ts/skr.invoice.mapper.d.ts +69 -0
  24. package/dist_ts/skr.invoice.mapper.js +401 -0
  25. package/dist_ts/skr.invoice.storage.d.ts +140 -0
  26. package/dist_ts/skr.invoice.storage.js +529 -0
  27. package/dist_ts/skr.security.d.ts +65 -0
  28. package/dist_ts/skr.security.js +319 -0
  29. package/dist_ts/skr.types.d.ts +1 -0
  30. package/package.json +17 -12
  31. package/readme.md +207 -16
  32. package/ts/index.ts +6 -0
  33. package/ts/plugins.ts +22 -1
  34. package/ts/skr.api.ts +485 -0
  35. package/ts/skr.export.accounts.ts +154 -0
  36. package/ts/skr.export.balances.ts +270 -0
  37. package/ts/skr.export.ledger.ts +249 -0
  38. package/ts/skr.export.pdf.ts +601 -0
  39. package/ts/skr.export.ts +443 -0
  40. package/ts/skr.invoice.adapter.ts +581 -0
  41. package/ts/skr.invoice.booking.ts +738 -0
  42. package/ts/skr.invoice.entity.ts +351 -0
  43. package/ts/skr.invoice.mapper.ts +486 -0
  44. package/ts/skr.invoice.storage.ts +710 -0
  45. package/ts/skr.security.ts +405 -0
  46. package/ts/skr.types.ts +1 -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
  }
@@ -0,0 +1,154 @@
1
+ import * as plugins from './plugins.js';
2
+ import * as path from 'path';
3
+ import type { IAccountData, TSKRType } from './skr.types.js';
4
+
5
+ // Extended interface for export with additional fields
6
+ export interface IAccountDataExport extends IAccountData {
7
+ parentAccount?: string;
8
+ defaultTaxCode?: string;
9
+ activeFrom?: Date | string;
10
+ activeTo?: Date | string;
11
+ }
12
+
13
+ export interface IAccountExportRow {
14
+ account_code: string;
15
+ name: string;
16
+ type: string;
17
+ class: number;
18
+ parent?: string;
19
+ skr_set: TSKRType;
20
+ tax_code_default?: string;
21
+ active_from?: string;
22
+ active_to?: string;
23
+ description?: string;
24
+ is_active: boolean;
25
+ }
26
+
27
+ export class AccountsExporter {
28
+ private exportPath: string;
29
+ private accounts: IAccountExportRow[] = [];
30
+
31
+ constructor(exportPath: string) {
32
+ this.exportPath = exportPath;
33
+ }
34
+
35
+ /**
36
+ * Adds an account to the export
37
+ */
38
+ public addAccount(account: IAccountDataExport): void {
39
+ const exportRow: IAccountExportRow = {
40
+ account_code: account.accountNumber,
41
+ name: account.accountName,
42
+ type: account.accountType,
43
+ class: account.accountClass,
44
+ parent: account.parentAccount,
45
+ skr_set: account.skrType,
46
+ tax_code_default: account.defaultTaxCode,
47
+ active_from: account.activeFrom ? this.formatDate(account.activeFrom) : undefined,
48
+ active_to: account.activeTo ? this.formatDate(account.activeTo) : undefined,
49
+ description: account.description,
50
+ is_active: account.isActive !== false
51
+ };
52
+
53
+ this.accounts.push(exportRow);
54
+ }
55
+
56
+ /**
57
+ * Exports accounts to CSV format
58
+ */
59
+ public async exportToCSV(): Promise<void> {
60
+ const csvPath = path.join(this.exportPath, 'data', 'accounting', 'accounts.csv');
61
+ await plugins.smartfile.fs.ensureDir(path.dirname(csvPath));
62
+
63
+ // Create CSV header
64
+ const headers = [
65
+ 'account_code',
66
+ 'name',
67
+ 'type',
68
+ 'class',
69
+ 'parent',
70
+ 'skr_set',
71
+ 'tax_code_default',
72
+ 'active_from',
73
+ 'active_to',
74
+ 'description',
75
+ 'is_active'
76
+ ];
77
+
78
+ let csvContent = headers.join(',') + '\n';
79
+
80
+ // Add account rows
81
+ for (const account of this.accounts) {
82
+ const row = [
83
+ this.escapeCSV(account.account_code),
84
+ this.escapeCSV(account.name),
85
+ this.escapeCSV(account.type),
86
+ account.class.toString(),
87
+ this.escapeCSV(account.parent || ''),
88
+ this.escapeCSV(account.skr_set),
89
+ this.escapeCSV(account.tax_code_default || ''),
90
+ this.escapeCSV(account.active_from || ''),
91
+ this.escapeCSV(account.active_to || ''),
92
+ this.escapeCSV(account.description || ''),
93
+ account.is_active.toString()
94
+ ];
95
+
96
+ csvContent += row.join(',') + '\n';
97
+ }
98
+
99
+ await plugins.smartfile.memory.toFs(csvContent, csvPath);
100
+ }
101
+
102
+ /**
103
+ * Exports accounts to JSON format (alternative)
104
+ */
105
+ public async exportToJSON(): Promise<void> {
106
+ const jsonPath = path.join(this.exportPath, 'data', 'accounting', 'accounts.json');
107
+ await plugins.smartfile.fs.ensureDir(path.dirname(jsonPath));
108
+
109
+ const jsonData = {
110
+ schema_version: '1.0',
111
+ export_date: new Date().toISOString(),
112
+ accounts: this.accounts
113
+ };
114
+
115
+ await plugins.smartfile.memory.toFs(
116
+ JSON.stringify(jsonData, null, 2),
117
+ jsonPath
118
+ );
119
+ }
120
+
121
+ /**
122
+ * Escapes CSV values
123
+ */
124
+ private escapeCSV(value: string): string {
125
+ if (value.includes(',') || value.includes('"') || value.includes('\n')) {
126
+ return `"${value.replace(/"/g, '""')}"`;
127
+ }
128
+ return value;
129
+ }
130
+
131
+ /**
132
+ * Formats a date to ISO date string
133
+ */
134
+ private formatDate(date: Date | string): string {
135
+ if (typeof date === 'string') {
136
+ return date.split('T')[0];
137
+ }
138
+ return date.toISOString().split('T')[0];
139
+ }
140
+
141
+ /**
142
+ * Gets the number of accounts
143
+ */
144
+ public getAccountCount(): number {
145
+ return this.accounts.length;
146
+ }
147
+
148
+ /**
149
+ * Clears the accounts list
150
+ */
151
+ public clear(): void {
152
+ this.accounts = [];
153
+ }
154
+ }