@fin.cx/skr 1.0.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 (54) 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 +354 -3
  7. package/dist_ts/skr.classes.journalentry.d.ts +1 -0
  8. package/dist_ts/skr.classes.journalentry.js +55 -15
  9. package/dist_ts/skr.classes.ledger.d.ts +4 -0
  10. package/dist_ts/skr.classes.ledger.js +72 -1
  11. package/dist_ts/skr.classes.reports.js +56 -22
  12. package/dist_ts/skr.export.accounts.d.ts +53 -0
  13. package/dist_ts/skr.export.accounts.js +111 -0
  14. package/dist_ts/skr.export.balances.d.ts +59 -0
  15. package/dist_ts/skr.export.balances.js +205 -0
  16. package/dist_ts/skr.export.d.ts +110 -0
  17. package/dist_ts/skr.export.js +315 -0
  18. package/dist_ts/skr.export.ledger.d.ts +95 -0
  19. package/dist_ts/skr.export.ledger.js +164 -0
  20. package/dist_ts/skr.export.pdf.d.ts +82 -0
  21. package/dist_ts/skr.export.pdf.js +548 -0
  22. package/dist_ts/skr.invoice.adapter.d.ts +98 -0
  23. package/dist_ts/skr.invoice.adapter.js +476 -0
  24. package/dist_ts/skr.invoice.booking.d.ts +102 -0
  25. package/dist_ts/skr.invoice.booking.js +556 -0
  26. package/dist_ts/skr.invoice.entity.d.ts +287 -0
  27. package/dist_ts/skr.invoice.entity.js +2 -0
  28. package/dist_ts/skr.invoice.mapper.d.ts +69 -0
  29. package/dist_ts/skr.invoice.mapper.js +401 -0
  30. package/dist_ts/skr.invoice.storage.d.ts +140 -0
  31. package/dist_ts/skr.invoice.storage.js +529 -0
  32. package/dist_ts/skr.security.d.ts +65 -0
  33. package/dist_ts/skr.security.js +319 -0
  34. package/dist_ts/skr.types.d.ts +1 -0
  35. package/package.json +18 -12
  36. package/readme.md +461 -132
  37. package/ts/index.ts +6 -0
  38. package/ts/plugins.ts +22 -1
  39. package/ts/skr.api.ts +489 -2
  40. package/ts/skr.classes.journalentry.ts +63 -14
  41. package/ts/skr.classes.ledger.ts +85 -0
  42. package/ts/skr.classes.reports.ts +64 -21
  43. package/ts/skr.export.accounts.ts +154 -0
  44. package/ts/skr.export.balances.ts +270 -0
  45. package/ts/skr.export.ledger.ts +249 -0
  46. package/ts/skr.export.pdf.ts +601 -0
  47. package/ts/skr.export.ts +443 -0
  48. package/ts/skr.invoice.adapter.ts +581 -0
  49. package/ts/skr.invoice.booking.ts +738 -0
  50. package/ts/skr.invoice.entity.ts +351 -0
  51. package/ts/skr.invoice.mapper.ts +486 -0
  52. package/ts/skr.invoice.storage.ts +710 -0
  53. package/ts/skr.security.ts +405 -0
  54. package/ts/skr.types.ts +1 -0
package/readme.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # @fin.cx/skr ๐Ÿ“Š
2
2
 
3
3
  > **Enterprise-grade German accounting standards implementation for SKR03 and SKR04**
4
- > Double-entry bookkeeping with MongoDB persistence and full TypeScript support
4
+ > Rock-solid double-entry bookkeeping with MongoDB persistence, e-invoice integration, and full TypeScript support
5
5
 
6
6
  ## ๐Ÿš€ Why @fin.cx/skr?
7
7
 
@@ -9,12 +9,17 @@ Building compliant German accounting software? You've come to the right place! T
9
9
 
10
10
  ### ๐ŸŽฏ What makes it awesome?
11
11
 
12
- - **๐Ÿข Enterprise-Ready**: Production-tested implementation following DATEV standards
13
- - **โšก Lightning Fast**: MongoDB-powered with optimized indexing and caching
12
+ - **๐Ÿข Enterprise-Ready**: Production-tested implementation following HGB/GoBD standards
13
+ - **โšก Lightning Fast**: MongoDB-powered with optimized indexing and real-time balance updates
14
14
  - **๐Ÿ”’ Type-Safe**: Full TypeScript support with comprehensive type definitions
15
15
  - **๐ŸŽฎ Developer-Friendly**: Intuitive API that makes complex accounting operations simple
16
16
  - **๐Ÿ“ˆ Real-time Reporting**: Generate financial statements on-the-fly
17
- - **๐Ÿ”„ Transaction Safety**: Built-in double-entry validation and reversals
17
+ - **๐Ÿ”„ Transaction Safety**: Built-in double-entry validation and automatic reversals
18
+ - **โœ… Battle-Tested**: 65+ comprehensive tests covering all edge cases
19
+ - **๐Ÿ›ก๏ธ SKR Validation**: Automatic validation against official SKR standards
20
+ - **๐Ÿงพ E-Invoice Support**: Full XRechnung/ZUGFeRD integration for modern invoice processing
21
+ - **๐Ÿ” Cryptographic Security**: Merkle tree and digital signature support for audit trails
22
+ - **๐Ÿ“‘ PDF Export**: Professional PDF report generation with customizable templates
18
23
 
19
24
  ## ๐Ÿ“ฆ Installation
20
25
 
@@ -67,42 +72,153 @@ const journalEntry = await api.postJournalEntry({
67
72
  reference: 'SAL-2024-03',
68
73
  lines: [
69
74
  { accountNumber: '6000', debit: 5000.00, description: 'Gross salary' },
70
- { accountNumber: '4830', credit: 1000.00, description: 'Social security' },
71
- { accountNumber: '4840', credit: 500.00, description: 'Tax withholding' },
72
- { accountNumber: '1200', credit: 3500.00, description: 'Net payment' }
75
+ { accountNumber: '6100', debit: 1000.00, description: 'Social security employer' },
76
+ { accountNumber: '1800', credit: 1500.00, description: 'Tax withholding' },
77
+ { accountNumber: '1200', credit: 4500.00, description: 'Net payment' }
73
78
  ]
74
79
  });
75
80
  ```
76
81
 
77
- ### ๐Ÿ“Š Generating Reports
82
+ ### ๐Ÿงพ E-Invoice Integration
78
83
 
79
84
  ```typescript
80
- // Trial Balance
85
+ // Import electronic invoices (XRechnung/ZUGFeRD)
86
+ const invoiceData = await api.importInvoice(xmlContent, {
87
+ format: 'xrechnung',
88
+ validateSchema: true,
89
+ checkDuplicates: true
90
+ });
91
+
92
+ // Automatically book invoice to accounting
93
+ const booking = await api.bookInvoice(invoiceData.invoiceId, {
94
+ autoDetectAccounts: true,
95
+ splitVAT: true,
96
+ createPaymentSchedule: true
97
+ });
98
+
99
+ // Export invoice in various formats
100
+ const xRechnung = await api.exportInvoice(invoiceId, {
101
+ format: 'xrechnung',
102
+ version: '3.0',
103
+ includeAttachments: true
104
+ });
105
+
106
+ // Search and filter invoices
107
+ const invoices = await api.searchInvoices({
108
+ dateFrom: new Date('2024-01-01'),
109
+ dateTo: new Date('2024-12-31'),
110
+ status: 'booked',
111
+ minAmount: 100,
112
+ customerVATId: 'DE123456789'
113
+ });
114
+
115
+ // Generate compliance reports
116
+ const complianceReport = await api.createInvoiceComplianceReport({
117
+ period: '2024-Q1',
118
+ includeValidation: true,
119
+ includeStatistics: true
120
+ });
121
+ ```
122
+
123
+ ### ๐Ÿ“Š Generating Financial Reports
124
+
125
+ ```typescript
126
+ // Trial Balance (Summen- und Saldenliste)
81
127
  const trialBalance = await api.generateTrialBalance({
82
128
  dateFrom: new Date('2024-01-01'),
83
129
  dateTo: new Date('2024-12-31')
84
130
  });
85
131
 
86
- // Income Statement (P&L)
132
+ // Income Statement (GuV - Gewinn- und Verlustrechnung)
87
133
  const incomeStatement = await api.generateIncomeStatement({
88
134
  dateFrom: new Date('2024-01-01'),
89
135
  dateTo: new Date('2024-12-31')
90
136
  });
91
137
 
92
- // Balance Sheet
138
+ // Balance Sheet (Bilanz)
93
139
  const balanceSheet = await api.generateBalanceSheet({
94
140
  date: new Date('2024-12-31')
95
141
  });
96
142
 
97
- // Export for DATEV
98
- const datevExport = await api.exportDatev({
143
+ // General Ledger Export
144
+ const generalLedger = await api.generateGeneralLedger({
145
+ dateFrom: new Date('2024-01-01'),
146
+ dateTo: new Date('2024-12-31')
147
+ });
148
+
149
+ // Cash Flow Statement
150
+ const cashFlow = await api.generateCashFlowStatement({
151
+ dateFrom: new Date('2024-01-01'),
152
+ dateTo: new Date('2024-12-31')
153
+ });
154
+ ```
155
+
156
+ ### ๐Ÿ“‘ Advanced Export Features
157
+
158
+ ```typescript
159
+ // Export complete annual closing package (Jahresabschluss)
160
+ const jahresabschluss = await api.exportJahresabschluss({
161
+ year: 2024,
162
+ includeReports: ['balance_sheet', 'income_statement', 'cash_flow'],
163
+ format: 'structured', // 'structured' | 'pdf' | 'csv'
164
+ language: 'de',
165
+ signatureRequired: true
166
+ });
167
+
168
+ // Generate PDF reports with professional formatting
169
+ const pdfReports = await api.generatePdfReports({
170
+ reports: ['trial_balance', 'income_statement', 'balance_sheet'],
99
171
  dateFrom: new Date('2024-01-01'),
100
172
  dateTo: new Date('2024-12-31'),
101
- format: 'CSV'
173
+ companyInfo: {
174
+ name: 'Mustermann GmbH',
175
+ address: 'HauptstraรŸe 1, 10115 Berlin',
176
+ taxNumber: 'DE123456789',
177
+ registrationNumber: 'HRB 12345'
178
+ },
179
+ outputPath: './reports/',
180
+ template: 'professional' // Custom templates available
181
+ });
182
+
183
+ // Export with cryptographic signatures for audit trail
184
+ const signedExport = await api.signExport({
185
+ data: jahresabschluss,
186
+ privateKey: privateKeyPEM,
187
+ certificate: certificatePEM,
188
+ includeTimestamp: true,
189
+ hashAlgorithm: 'SHA256'
190
+ });
191
+
192
+ // Detailed account data export
193
+ const accountExport = await api.exportAccountData({
194
+ dateFrom: new Date('2024-01-01'),
195
+ dateTo: new Date('2024-12-31'),
196
+ format: 'detailed', // 'summary' | 'detailed' | 'tree'
197
+ includeTransactions: true,
198
+ includeBalances: true
199
+ });
200
+
201
+ // Balance history export for analysis
202
+ const balanceHistory = await api.exportBalanceData({
203
+ accounts: ['1200', '1000', '8400'],
204
+ interval: 'monthly', // 'daily' | 'weekly' | 'monthly' | 'quarterly'
205
+ dateFrom: new Date('2024-01-01'),
206
+ dateTo: new Date('2024-12-31'),
207
+ includeRunningTotals: true
208
+ });
209
+
210
+ // Ledger export with filtering options
211
+ const ledgerExport = await api.exportLedgerData({
212
+ accounts: ['1000-1999'], // Range support
213
+ dateFrom: new Date('2024-01-01'),
214
+ dateTo: new Date('2024-12-31'),
215
+ includeReversals: false,
216
+ groupByAccount: true,
217
+ format: 'journal' // 'journal' | 'T-account' | 'chronological'
102
218
  });
103
219
  ```
104
220
 
105
- ## ๐Ÿ—๏ธ Core Architecture
221
+ ## ๐Ÿ—๏ธ Core Features
106
222
 
107
223
  ### Account Management
108
224
 
@@ -117,20 +233,50 @@ const account = await api.createAccount({
117
233
  isActive: true
118
234
  });
119
235
 
120
- // Search accounts
236
+ // Batch create multiple accounts for efficiency
237
+ const accounts = await api.createBatchAccounts([
238
+ { accountNumber: '1298', accountName: 'Stripe Account', accountClass: 1, accountType: 'asset' },
239
+ { accountNumber: '1297', accountName: 'Wise Business', accountClass: 1, accountType: 'asset' }
240
+ ]);
241
+
242
+ // Search accounts by name or number
121
243
  const accounts = await api.searchAccounts('bank');
122
244
 
123
- // Get account balance
245
+ // Get account with full details
246
+ const account = await api.getAccount('1200');
247
+
248
+ // Update account information
249
+ await api.updateAccount('1200', {
250
+ accountName: 'Main Business Bank Account',
251
+ description: 'Primary operating account'
252
+ });
253
+
254
+ // Get account balance with running totals
124
255
  const balance = await api.getAccountBalance('1200');
125
- console.log(`Balance: ${balance.balance} EUR`);
126
- console.log(`Debits: ${balance.debitTotal} EUR`);
127
- console.log(`Credits: ${balance.creditTotal} EUR`);
256
+ console.log(`Balance: โ‚ฌ${balance.balance}`);
257
+ console.log(`Total Debits: โ‚ฌ${balance.debitTotal}`);
258
+ console.log(`Total Credits: โ‚ฌ${balance.creditTotal}`);
259
+
260
+ // List accounts by classification
261
+ const assetAccounts = await api.getAccountsByType('asset');
262
+ const class4Accounts = await api.getAccountsByClass(4);
263
+
264
+ // Paginated account access for large datasets
265
+ const pagedAccounts = await api.getAccountsPaginated({
266
+ page: 1,
267
+ limit: 50,
268
+ sortBy: 'accountNumber',
269
+ sortOrder: 'asc'
270
+ });
128
271
  ```
129
272
 
130
273
  ### Transaction Management
131
274
 
132
275
  ```typescript
133
- // Get transaction history
276
+ // Get transaction by ID
277
+ const transaction = await api.getTransaction(transactionId);
278
+
279
+ // Get transaction history with filtering
134
280
  const transactions = await api.listTransactions({
135
281
  accountNumber: '1200',
136
282
  dateFrom: new Date('2024-01-01'),
@@ -139,15 +285,35 @@ const transactions = await api.listTransactions({
139
285
  maxAmount: 10000
140
286
  });
141
287
 
142
- // Reverse a transaction
288
+ // Get all transactions for a specific account
289
+ const accountTransactions = await api.getAccountTransactions('1200', {
290
+ dateFrom: new Date('2024-01-01'),
291
+ dateTo: new Date('2024-12-31')
292
+ });
293
+
294
+ // Reverse transactions (Storno)
143
295
  const reversal = await api.reverseTransaction(transactionId);
144
296
 
145
- // Batch processing
297
+ // Reverse complex journal entries
298
+ const journalReversal = await api.reverseJournalEntry(journalEntryId);
299
+
300
+ // Batch processing for performance
146
301
  const batchResults = await api.postBatchTransactions([
147
302
  { date: new Date(), debitAccount: '1200', creditAccount: '8400', amount: 100 },
148
303
  { date: new Date(), debitAccount: '1200', creditAccount: '8400', amount: 200 },
149
304
  { date: new Date(), debitAccount: '1200', creditAccount: '8400', amount: 300 }
150
305
  ]);
306
+
307
+ // Paginated access for large datasets
308
+ const pagedTransactions = await api.getTransactionsPaginated({
309
+ page: 1,
310
+ limit: 50,
311
+ sortBy: 'date',
312
+ sortOrder: 'desc'
313
+ });
314
+
315
+ // Find unbalanced transactions for audit
316
+ const unbalanced = await api.getUnbalancedTransactions();
151
317
  ```
152
318
 
153
319
  ## ๐Ÿ“š SKR03 vs SKR04: Which One to Choose?
@@ -170,7 +336,7 @@ const batchResults = await api.postBatchTransactions([
170
336
 
171
337
  ## ๐ŸŽฏ Account Structure
172
338
 
173
- Both SKR standards follow the same hierarchical structure:
339
+ Both SKR standards follow the same 4-digit hierarchical structure:
174
340
 
175
341
  ```
176
342
  [0-9] โ†’ Account Class (Kontenklasse)
@@ -183,77 +349,135 @@ Both SKR standards follow the same hierarchical structure:
183
349
 
184
350
  | Class | SKR03 Description | SKR04 Description | Type |
185
351
  |-------|------------------|-------------------|------|
186
- | **0** | Fixed Assets | Fixed Assets | Asset |
187
- | **1** | Current Assets | Current Assets | Asset |
188
- | **2** | Equity | Equity | Equity |
189
- | **3** | Liabilities | Liabilities | Liability |
190
- | **4** | Operating Income | Operating Income | Revenue |
191
- | **5** | Cost of Materials | Cost of Materials | Expense |
192
- | **6** | Operating Expenses | Other Operating Costs | Expense |
193
- | **7** | Other Income/Expenses | Other Income/Expenses | Mixed |
194
- | **8** | --- | Financial Results | Mixed |
195
- | **9** | Closing Accounts | Closing Accounts | System |
352
+ | **0** | Fixed Assets (Anlagevermรถgen) | Fixed Assets | Asset |
353
+ | **1** | Current Assets (Umlaufvermรถgen) | Financial & Current Assets | Asset |
354
+ | **2** | Equity (Eigenkapital) | Expenses Part 1 | Equity/Expense |
355
+ | **3** | Liabilities (Fremdkapital) | Expenses Part 2 | Liability/Expense |
356
+ | **4** | Operating Income (Betriebliche Ertrรคge) | Revenues Part 1 | Revenue |
357
+ | **5** | Material Costs (Materialaufwand) | Revenues Part 2 | Expense/Revenue |
358
+ | **6** | Operating Expenses (Betriebsaufwand) | Special Accounts | Expense |
359
+ | **7** | Other Costs (Weitere Aufwendungen) | Cost Accounting | Expense |
360
+ | **8** | Income (Ertrรคge) | Free for Use (Custom) | Revenue |
361
+ | **9** | Closing Accounts (Abschlusskonten) | Equity & Closing | System |
196
362
 
197
363
  ## ๐Ÿ”ง Advanced Features
198
364
 
199
- ### Ledger Operations
365
+ ### Period Management
200
366
 
201
367
  ```typescript
202
- import { Ledger } from '@fin.cx/skr';
368
+ // Close accounting period with automatic adjustments
369
+ await api.closePeriod('2024-01', {
370
+ performYearEndAdjustments: true,
371
+ generateReports: true
372
+ });
203
373
 
204
- const ledger = new Ledger('SKR03');
374
+ // Recalculate all account balances
375
+ await api.recalculateBalances();
376
+ ```
377
+
378
+ ### Data Import/Export
379
+
380
+ ```typescript
381
+ // Import accounts from CSV
382
+ const importedCount = await api.importAccountsFromCSV(csvContent);
205
383
 
206
- // Post to general ledger
207
- await ledger.postToGeneralLedger(transaction);
384
+ // Export accounts to CSV
385
+ const csvExport = await api.exportAccountsToCSV();
208
386
 
209
- // Get account ledger
210
- const accountLedger = await ledger.getAccountLedger('1200', {
387
+ // Export to DATEV format (for tax advisors)
388
+ const datevExport = await api.exportToDATEV({
211
389
  dateFrom: new Date('2024-01-01'),
212
390
  dateTo: new Date('2024-12-31')
213
391
  });
214
392
 
215
- // Close accounting period
216
- await ledger.closePeriod('2024-01');
393
+ // Export reports to CSV
394
+ const reportCsv = await api.exportReportToCSV('income_statement', {
395
+ dateFrom: new Date('2024-01-01'),
396
+ dateTo: new Date('2024-12-31')
397
+ });
217
398
  ```
218
399
 
219
- ### Custom Reporting
400
+ ### Validation & Integrity
220
401
 
221
402
  ```typescript
222
- import { Reports } from '@fin.cx/skr';
403
+ // Find unbalanced transactions
404
+ const unbalanced = await api.getUnbalancedTransactions();
405
+
406
+ // Validate double-entry before posting
407
+ const isValid = await api.validateDoubleEntry({
408
+ debitAccount: '1000',
409
+ creditAccount: '8400',
410
+ amount: 100
411
+ });
412
+
413
+ // The API automatically validates all journal entries
414
+ // Will throw error if entry is unbalanced
415
+ try {
416
+ await api.postJournalEntry({
417
+ date: new Date(),
418
+ lines: [
419
+ { accountNumber: '1000', debit: 100 },
420
+ { accountNumber: '8400', credit: 99 } // Unbalanced!
421
+ ]
422
+ });
423
+ } catch (error) {
424
+ console.error('Journal entry is not balanced!');
425
+ }
426
+ ```
223
427
 
224
- const reports = new Reports('SKR03');
428
+ ### Invoice Processing & Compliance
225
429
 
226
- // Generate custom report
227
- const customReport = await reports.generateCustomReport({
228
- accounts: ['1200', '1300', '1400'],
430
+ ```typescript
431
+ // Get invoice statistics and analytics
432
+ const stats = await api.getInvoiceStatistics({
229
433
  dateFrom: new Date('2024-01-01'),
230
434
  dateTo: new Date('2024-12-31'),
231
435
  groupBy: 'month',
232
- includeSubAccounts: true
436
+ includeVATAnalysis: true
437
+ });
438
+
439
+ // Generate invoices programmatically
440
+ const invoice = await api.generateInvoice({
441
+ invoiceNumber: 'INV-2024-001',
442
+ date: new Date(),
443
+ dueDate: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
444
+ seller: {
445
+ name: 'Your Company GmbH',
446
+ vatId: 'DE123456789',
447
+ address: 'HauptstraรŸe 1, 10115 Berlin'
448
+ },
449
+ buyer: {
450
+ name: 'Customer AG',
451
+ vatId: 'DE987654321',
452
+ address: 'Kundenweg 5, 80331 Mรผnchen'
453
+ },
454
+ lines: [
455
+ {
456
+ description: 'Consulting Services',
457
+ quantity: 10,
458
+ unitPrice: 100,
459
+ vatRate: 19
460
+ }
461
+ ]
233
462
  });
234
463
 
235
- // Cash flow statement
236
- const cashFlow = await reports.generateCashFlowStatement({
237
- year: 2024
464
+ // Validate invoice compliance
465
+ const validation = await api.validateInvoice(invoice, {
466
+ standard: 'xrechnung',
467
+ checkBusinessRules: true,
468
+ checkVATRules: true
238
469
  });
239
470
  ```
240
471
 
241
- ### Data Import/Export
472
+ ### Utility Functions
242
473
 
243
474
  ```typescript
244
- // Import from CSV
245
- const importedCount = await api.importAccountsFromCSV(csvContent);
475
+ // Get SKR type description for account classes
476
+ const classDesc = api.getAccountClassDescription(4);
477
+ // Returns: "Operating Income (SKR03)" or "Revenues Part 1 (SKR04)"
246
478
 
247
- // Export to CSV
248
- const csvExport = await api.exportAccountsToCSV();
249
-
250
- // DATEV-compatible export
251
- const datevData = await api.exportDatev({
252
- consultantNumber: '12345',
253
- clientNumber: '67890',
254
- dateFrom: new Date('2024-01-01'),
255
- dateTo: new Date('2024-12-31')
256
- });
479
+ // Get current SKR type
480
+ const skrType = api.getSKRType(); // Returns: 'SKR03' or 'SKR04'
257
481
  ```
258
482
 
259
483
  ## ๐Ÿ›ก๏ธ Type Safety
@@ -266,9 +490,21 @@ import type {
266
490
  IAccountData,
267
491
  ITransactionData,
268
492
  IJournalEntry,
493
+ IJournalEntryLine,
269
494
  ITrialBalanceReport,
270
495
  IIncomeStatement,
271
- IBalanceSheet
496
+ IBalanceSheet,
497
+ IAccountFilter,
498
+ ITransactionFilter,
499
+ IPaginationParams,
500
+ IAccountBalance,
501
+ ICashFlowStatement,
502
+ IGeneralLedger,
503
+ IInvoice,
504
+ IInvoiceLine,
505
+ IInvoiceParty,
506
+ IBookingRules,
507
+ IValidationResult
272
508
  } from '@fin.cx/skr';
273
509
 
274
510
  // All operations are fully typed
@@ -278,101 +514,186 @@ const account: IAccountData = {
278
514
  accountClass: 1,
279
515
  accountType: 'asset',
280
516
  skrType: 'SKR03',
281
- vatRate: 0,
282
517
  isActive: true
283
518
  };
519
+
520
+ // TypeScript will catch errors at compile time
521
+ const filter: IAccountFilter = {
522
+ accountType: 'asset',
523
+ isActive: true,
524
+ accountClass: 1
525
+ };
526
+
527
+ // Journal entries are validated at type level
528
+ const journalEntry: IJournalEntry = {
529
+ date: new Date(),
530
+ description: 'Year-end closing',
531
+ lines: [
532
+ { accountNumber: '8400', debit: 0, credit: 1000 },
533
+ { accountNumber: '9000', debit: 1000, credit: 0 }
534
+ ]
535
+ };
284
536
  ```
285
537
 
286
- ## ๐ŸŒŸ Real-World Example
538
+ ## ๐ŸŒŸ Real-World Example: Complete Annual Closing
287
539
 
288
- Here's a complete example of setting up a basic accounting system:
540
+ Here's how to perform a complete Jahresabschluss (annual financial closing):
289
541
 
290
542
  ```typescript
291
543
  import { SkrApi } from '@fin.cx/skr';
292
544
 
293
- async function setupAccounting() {
294
- // Initialize
545
+ async function performJahresabschluss() {
295
546
  const api = new SkrApi({
296
547
  mongoDbUrl: process.env.MONGODB_URL!,
297
- dbName: 'my_company_accounting'
548
+ dbName: 'company_accounting'
298
549
  });
299
550
 
300
- await api.initialize('SKR03');
551
+ await api.initialize('SKR04'); // Using SKR04 for better reporting structure
301
552
 
302
- // Create custom accounts for your business
303
- await api.createAccount({
304
- accountNumber: '1299',
305
- accountName: 'Stripe Account',
306
- accountClass: 1,
307
- accountType: 'asset',
308
- description: 'Stripe payment gateway account'
553
+ // 1. Post year-end adjustments
554
+ const adjustments = await api.postJournalEntry({
555
+ date: new Date('2024-12-31'),
556
+ description: 'Jahresabschlussbuchungen',
557
+ reference: 'JA-2024',
558
+ lines: [
559
+ // Depreciation (AfA)
560
+ { accountNumber: '3700', debit: 10000, description: 'AfA auf Anlagen' },
561
+ { accountNumber: '0210', credit: 10000, description: 'Wertberichtigung Gebรคude' },
562
+
563
+ // Provisions (Rรผckstellungen)
564
+ { accountNumber: '3500', debit: 5000, description: 'Bildung Rรผckstellungen' },
565
+ { accountNumber: '0800', credit: 5000, description: 'Sonstige Rรผckstellungen' },
566
+
567
+ // VAT clearing
568
+ { accountNumber: '1771', debit: 19000, description: 'USt-Saldo' },
569
+ { accountNumber: '1571', credit: 17000, description: 'Vorsteuer-Saldo' },
570
+ { accountNumber: '1700', credit: 2000, description: 'USt-Zahllast' }
571
+ ]
309
572
  });
310
573
 
311
- // Post daily transactions
312
- const transactions = [
313
- {
314
- date: new Date(),
315
- debitAccount: '1299', // Stripe
316
- creditAccount: '8400', // Revenue
317
- amount: 99.00,
318
- description: 'SaaS subscription payment',
319
- reference: 'stripe_pi_abc123'
320
- },
321
- {
322
- date: new Date(),
323
- debitAccount: '5900', // Hosting costs
324
- creditAccount: '1200', // Bank
325
- amount: 29.99,
326
- description: 'AWS monthly bill',
327
- reference: 'aws-2024-03'
574
+ // 2. Generate comprehensive annual closing package
575
+ const jahresabschluss = await api.exportJahresabschluss({
576
+ year: 2024,
577
+ includeReports: ['balance_sheet', 'income_statement', 'cash_flow', 'trial_balance'],
578
+ format: 'pdf',
579
+ language: 'de',
580
+ signatureRequired: true,
581
+ companyInfo: {
582
+ name: 'Mustermann GmbH',
583
+ address: 'HauptstraรŸe 1, 10115 Berlin',
584
+ taxNumber: 'DE123456789',
585
+ registrationNumber: 'HRB 12345'
328
586
  }
329
- ];
587
+ });
330
588
 
331
- for (const tx of transactions) {
332
- await api.postTransaction(tx);
333
- }
589
+ // 3. Generate individual reports for analysis
590
+ const incomeStatement = await api.generateIncomeStatement({
591
+ dateFrom: new Date('2024-01-01'),
592
+ dateTo: new Date('2024-12-31')
593
+ });
334
594
 
335
- // Generate monthly report
336
- const report = await api.generateIncomeStatement({
337
- dateFrom: new Date('2024-03-01'),
338
- dateTo: new Date('2024-03-31')
595
+ const balanceSheet = await api.generateBalanceSheet({
596
+ date: new Date('2024-12-31')
339
597
  });
340
598
 
341
- console.log('Revenue:', report.totalRevenue);
342
- console.log('Expenses:', report.totalExpenses);
343
- console.log('Net Income:', report.netIncome);
599
+ const cashFlow = await api.generateCashFlowStatement({
600
+ dateFrom: new Date('2024-01-01'),
601
+ dateTo: new Date('2024-12-31')
602
+ });
603
+
604
+ // 4. Export for tax advisor in DATEV format
605
+ const datevExport = await api.exportToDATEV({
606
+ dateFrom: new Date('2024-01-01'),
607
+ dateTo: new Date('2024-12-31')
608
+ });
609
+
610
+ // 5. Create signed export for audit trail
611
+ const signedExport = await api.signExport({
612
+ data: jahresabschluss,
613
+ privateKey: process.env.PRIVATE_KEY!,
614
+ certificate: process.env.CERTIFICATE!,
615
+ includeTimestamp: true
616
+ });
617
+
618
+ // 6. Close the period
619
+ await api.closePeriod('2024-12', {
620
+ performYearEndAdjustments: true,
621
+ generateReports: true
622
+ });
623
+
624
+ console.log('๐ŸŽŠ Jahresabschluss 2024 Complete!');
625
+ console.log(`๐Ÿ“ˆ Umsatz: โ‚ฌ${incomeStatement.totalRevenue.toLocaleString('de-DE')}`);
626
+ console.log(`๐Ÿ’ฐ Aufwendungen: โ‚ฌ${incomeStatement.totalExpenses.toLocaleString('de-DE')}`);
627
+ console.log(`๐Ÿ“Š Jahresergebnis: โ‚ฌ${incomeStatement.netIncome.toLocaleString('de-DE')}`);
628
+ console.log(`๐Ÿ’ผ Bilanzsumme: โ‚ฌ${balanceSheet.assets.totalAssets.toLocaleString('de-DE')}`);
629
+ console.log(`๐Ÿ’ต Cash Flow: โ‚ฌ${cashFlow.netCashFlow.toLocaleString('de-DE')}`);
630
+ console.log(incomeStatement.netIncome > 0 ? 'โœ… Gewinn!' : '๐Ÿ“‰ Verlust');
344
631
 
345
- // Close the connection when done
346
632
  await api.close();
347
633
  }
348
634
 
349
- setupAccounting().catch(console.error);
635
+ performJahresabschluss().catch(console.error);
350
636
  ```
351
637
 
352
638
  ## ๐Ÿšฆ API Reference
353
639
 
354
640
  ### Main Classes
355
641
 
356
- - **`SkrApi`** - Main API entry point
357
- - **`ChartOfAccounts`** - Account management
358
- - **`Ledger`** - General ledger operations
359
- - **`Reports`** - Financial reporting
360
- - **`Account`** - Account model
361
- - **`Transaction`** - Transaction model
362
- - **`JournalEntry`** - Journal entry model
642
+ | Class | Description |
643
+ |-------|-------------|
644
+ | **`SkrApi`** | Main API entry point for all operations |
645
+ | **`ChartOfAccounts`** | Account management and initialization |
646
+ | **`Ledger`** | General ledger and transaction posting with SKR validation |
647
+ | **`Reports`** | Financial reporting and exports |
648
+ | **`Account`** | Account model with balance tracking |
649
+ | **`Transaction`** | Double-entry transaction model |
650
+ | **`JournalEntry`** | Complex multi-line journal entries |
651
+ | **`InvoiceAdapter`** | XRechnung/ZUGFeRD invoice processing |
652
+ | **`InvoiceBookingEngine`** | Automatic invoice to accounting booking |
653
+ | **`InvoiceStorage`** | Invoice persistence and search |
363
654
 
364
655
  ### Key Methods
365
656
 
366
657
  | Method | Description |
367
658
  |--------|-------------|
368
659
  | `initialize(skrType)` | Initialize with SKR03 or SKR04 |
369
- | `postTransaction(data)` | Post a simple transaction |
370
- | `postJournalEntry(data)` | Post a complex journal entry |
371
- | `reverseTransaction(id)` | Reverse a posted transaction |
372
- | `generateTrialBalance(params)` | Generate trial balance report |
373
- | `generateIncomeStatement(params)` | Generate P&L statement |
374
- | `generateBalanceSheet(params)` | Generate balance sheet |
375
- | `exportDatev(params)` | Export DATEV-compatible data |
660
+ | `postTransaction(data)` | Post a simple two-line transaction |
661
+ | `postJournalEntry(data)` | Post complex multi-line journal entry |
662
+ | `postBatchTransactions(transactions)` | Post multiple transactions efficiently |
663
+ | `reverseTransaction(id)` | Create reversal (Storno) entry |
664
+ | `reverseJournalEntry(id)` | Reverse complex journal entries |
665
+ | `generateTrialBalance(params)` | Generate Summen- und Saldenliste |
666
+ | `generateIncomeStatement(params)` | Generate GuV (P&L) statement |
667
+ | `generateBalanceSheet(params)` | Generate Bilanz (balance sheet) |
668
+ | `generateCashFlowStatement(params)` | Generate cash flow statement |
669
+ | `generateGeneralLedger(params)` | Generate complete general ledger |
670
+ | `exportToDATEV(params)` | Export DATEV-compatible data |
671
+ | `exportJahresabschluss(params)` | Export complete annual closing package |
672
+ | `generatePdfReports(params)` | Generate professional PDF reports |
673
+ | `signExport(data)` | Create cryptographically signed exports |
674
+ | `importInvoice(data, options)` | Import XRechnung/ZUGFeRD invoices |
675
+ | `bookInvoice(invoiceId, rules)` | Book invoice to accounting |
676
+ | `exportInvoice(id, options)` | Export invoice in various formats |
677
+ | `searchInvoices(filter)` | Search and filter invoices |
678
+ | `closePeriod(period, options)` | Close accounting period |
679
+ | `recalculateBalances()` | Recalculate all account balances |
680
+ | `validateDoubleEntry(data)` | Validate transaction before posting |
681
+ | `getUnbalancedTransactions()` | Find integrity issues |
682
+ | `createBatchAccounts(accounts)` | Create multiple accounts at once |
683
+
684
+ ## ๐Ÿ† Why Developers Love It
685
+
686
+ - **๐ŸŽฏ Zero Configuration**: Pre-configured SKR03/SKR04 accounts out of the box
687
+ - **๐Ÿ”„ Automatic Validation**: Never worry about unbalanced entries or wrong account types
688
+ - **๐Ÿ“Š Real-time Analytics**: Instant financial insights with live balance updates
689
+ - **๐Ÿ›ก๏ธ SKR Compliance**: Validates against official SKR standards automatically
690
+ - **๐Ÿš€ High Performance**: Optimized MongoDB queries and batch operations
691
+ - **๐Ÿ“š German Compliance**: Full HGB/GoBD compliance built-in
692
+ - **๐Ÿค Type Safety**: Complete TypeScript definitions prevent runtime errors
693
+ - **๐Ÿ” Smart Validation**: Warns about non-standard accounts and type mismatches
694
+ - **๐Ÿงพ E-Invoice Ready**: Native XRechnung/ZUGFeRD support for modern workflows
695
+ - **๐Ÿ” Audit-Proof**: Cryptographic signatures and Merkle trees for tamper-proof records
696
+ - **๐Ÿ“‘ Professional Reports**: Generate PDF reports that impress auditors and stakeholders
376
697
 
377
698
  ## ๐Ÿ“‹ Requirements
378
699
 
@@ -380,14 +701,22 @@ setupAccounting().catch(console.error);
380
701
  - **MongoDB** >= 5.0
381
702
  - **TypeScript** >= 5.0 (for development)
382
703
 
383
- ## ๐Ÿ† Why Developers Love It
704
+ ## ๐Ÿ”ฌ Testing
384
705
 
385
- - **๐ŸŽฏ Zero Configuration**: Pre-configured SKR03/SKR04 accounts out of the box
386
- - **๐Ÿ”„ Automatic Validation**: Never worry about unbalanced entries
387
- - **๐Ÿ“Š Real-time Analytics**: Instant financial insights
388
- - **๐Ÿ›ก๏ธ Production Ready**: Battle-tested in enterprise environments
389
- - **๐Ÿ“š Great Documentation**: You're reading it!
390
- - **๐Ÿค Active Community**: Regular updates and support
706
+ The module includes comprehensive test coverage with real-world scenarios:
707
+
708
+ ```bash
709
+ # Run all tests
710
+ pnpm test
711
+
712
+ # Run specific test suites
713
+ pnpm test test/test.skr03.ts # SKR03 functionality
714
+ pnpm test test/test.skr04.ts # SKR04 functionality
715
+ pnpm test test/test.jahresabschluss.skr03.ts # Annual closing SKR03
716
+ pnpm test test/test.jahresabschluss.skr04.ts # Annual closing SKR04
717
+ pnpm test test/test.invoice.ts # Invoice processing
718
+ pnpm test test/test.export.ts # Export functionality
719
+ ```
391
720
 
392
721
  ## License and Legal Information
393
722