@fin.cx/skr 1.2.1 โ†’ 1.2.2

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/{npmextra.json โ†’ .smartconfig.json} +12 -6
  2. package/dist_ts/00_commitinfo_data.js +1 -1
  3. package/dist_ts/index.d.ts +21 -15
  4. package/dist_ts/index.js +16 -16
  5. package/dist_ts/plugins.d.ts +15 -5
  6. package/dist_ts/plugins.js +42 -6
  7. package/dist_ts/skr.api.js +20 -13
  8. package/dist_ts/skr.classes.account.d.ts +8 -3
  9. package/dist_ts/skr.classes.account.js +358 -285
  10. package/dist_ts/skr.classes.chartofaccounts.d.ts +1 -1
  11. package/dist_ts/skr.classes.chartofaccounts.js +13 -6
  12. package/dist_ts/skr.classes.journalentry.d.ts +9 -4
  13. package/dist_ts/skr.classes.journalentry.js +424 -355
  14. package/dist_ts/skr.classes.ledger.js +3 -1
  15. package/dist_ts/skr.classes.reports.js +4 -1
  16. package/dist_ts/skr.classes.transaction.d.ts +9 -4
  17. package/dist_ts/skr.classes.transaction.js +315 -244
  18. package/dist_ts/skr.export.accounts.js +3 -2
  19. package/dist_ts/skr.export.balances.js +4 -2
  20. package/dist_ts/skr.export.js +6 -3
  21. package/dist_ts/skr.export.ledger.js +4 -3
  22. package/dist_ts/skr.export.pdf.js +6 -3
  23. package/dist_ts/skr.invoice.adapter.d.ts +2 -0
  24. package/dist_ts/skr.invoice.adapter.js +22 -10
  25. package/dist_ts/skr.invoice.booking.js +8 -3
  26. package/dist_ts/skr.invoice.mapper.js +84 -82
  27. package/dist_ts/skr.invoice.storage.js +10 -5
  28. package/dist_ts/skr.security.js +24 -21
  29. package/license.md +21 -0
  30. package/package.json +31 -23
  31. package/readme.md +215 -632
  32. package/readme.plan.md +1 -1
  33. package/ts/00_commitinfo_data.ts +1 -1
  34. package/ts/index.ts +43 -15
  35. package/ts/plugins.ts +52 -15
  36. package/ts/skr.api.ts +9 -5
  37. package/ts/skr.classes.account.ts +39 -21
  38. package/ts/skr.classes.chartofaccounts.ts +8 -3
  39. package/ts/skr.classes.journalentry.ts +40 -22
  40. package/ts/skr.classes.reports.ts +22 -2
  41. package/ts/skr.classes.transaction.ts +40 -22
  42. package/ts/skr.export.pdf.ts +4 -3
  43. package/ts/skr.invoice.adapter.ts +31 -11
  44. package/ts/skr.invoice.booking.ts +5 -3
  45. package/ts/skr.invoice.storage.ts +3 -2
  46. package/ts/skr.security.ts +23 -22
package/readme.md CHANGED
@@ -1,738 +1,321 @@
1
- # @fin.cx/skr ๐Ÿ“Š
1
+ # @fin.cx/skr
2
2
 
3
- > **Enterprise-grade German accounting standards implementation for SKR03 and SKR04**
4
- > Rock-solid double-entry bookkeeping with MongoDB persistence, e-invoice integration, and full TypeScript support
3
+ `@fin.cx/skr` is a TypeScript library for German double-entry bookkeeping with built-in SKR03 and SKR04 chart initialization, MongoDB-backed persistence, reporting, DATEV export, GoBD-oriented Jahresabschluss export, and e-invoice workflows.
5
4
 
6
- ## ๐Ÿš€ Why @fin.cx/skr?
5
+ It is built for developers who need a programmable accounting core instead of a pile of CSV glue code: initialize a chart of accounts, post validated transactions and journal entries, generate reports, and archive year-end data in a structured export format.
7
6
 
8
- Building compliant German accounting software? You've come to the right place! This module provides a **complete, type-safe implementation** of the German standard charts of accounts (Standardkontenrahmen) SKR03 and SKR04, the backbone of professional accounting in Germany.
7
+ ## Issue Reporting and Security
9
8
 
10
- ### ๐ŸŽฏ What makes it awesome?
9
+ 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.
11
10
 
12
- - **๐Ÿข Enterprise-Ready**: Production-tested implementation following HGB/GoBD standards
13
- - **โšก Lightning Fast**: MongoDB-powered with optimized indexing and real-time balance updates
14
- - **๐Ÿ”’ Type-Safe**: Full TypeScript support with comprehensive type definitions
15
- - **๐ŸŽฎ Developer-Friendly**: Intuitive API that makes complex accounting operations simple
16
- - **๐Ÿ“ˆ Real-time Reporting**: Generate financial statements on-the-fly
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
11
+ ## What This Library Does
23
12
 
24
- ## ๐Ÿ“ฆ Installation
13
+ - Initializes SKR03 or SKR04 account sets in MongoDB
14
+ - Enforces double-entry bookkeeping rules for transactions and journal entries
15
+ - Supports DATEV posting keys and VAT-aware journal lines
16
+ - Prevents direct posting to automatic accounts that require personal accounts
17
+ - Generates trial balance, income statement, balance sheet, general ledger, and cash flow reports
18
+ - Exports accounting data as CSV, DATEV, and GoBD-style Jahresabschluss packages
19
+ - Imports, stores, searches, books, and exports EN16931-style e-invoices
20
+ - Adds signing and timestamp helpers for audit-oriented export workflows
25
21
 
26
- ```bash
27
- # Using npm
28
- npm install @fin.cx/skr
22
+ ## Why It Is Useful
29
23
 
30
- # Using pnpm (recommended)
31
- pnpm add @fin.cx/skr
24
+ - You get a real accounting domain model, not just account lists
25
+ - SKR03 and SKR04 are both supported behind one API
26
+ - Tests cover initialization, posting, reversals, reports, pagination, DATEV export, and full year-end flows
27
+ - The package exports the lower-level classes too, so you can stay high-level with `SkrApi` or build around the primitives
32
28
 
33
- # Using yarn
34
- yarn add @fin.cx/skr
35
- ```
29
+ ## Requirements
30
+
31
+ - Node.js 20+ with ESM support
32
+ - A reachable MongoDB instance
33
+ - `pnpm`
36
34
 
37
- ## ๐ŸŽ“ Quick Start
35
+ The test setup reads MongoDB connection details from `.nogit/` via `@push.rocks/qenv`, but the runtime API only needs a `mongoDbUrl` and an optional `dbName`.
38
36
 
39
- ### Basic Setup
37
+ ## Installation
38
+
39
+ ```bash
40
+ pnpm add @fin.cx/skr
41
+ ```
40
42
 
41
- ```typescript
43
+ ## Quick Start
44
+
45
+ ```ts
42
46
  import { SkrApi } from '@fin.cx/skr';
43
47
 
44
- // Initialize the API
45
48
  const api = new SkrApi({
46
49
  mongoDbUrl: 'mongodb://localhost:27017',
47
- dbName: 'accounting' // optional, defaults to 'skr_accounting'
50
+ dbName: 'accounting_demo',
48
51
  });
49
52
 
50
- // Choose your SKR standard (SKR03 or SKR04)
51
53
  await api.initialize('SKR03');
52
- ```
53
54
 
54
- ### ๐Ÿ’ฐ Posting Transactions
55
-
56
- ```typescript
57
- // Simple transaction posting
58
- const transaction = await api.postTransaction({
55
+ await api.postTransaction({
59
56
  date: new Date(),
60
- debitAccount: '1200', // Bank account
61
- creditAccount: '8400', // Revenue account
62
- amount: 1190.00,
63
- description: 'Invoice #2024-001 payment received',
64
- reference: 'INV-2024-001',
65
- vatAmount: 190.00
66
- });
67
-
68
- // Complex journal entry with multiple lines
69
- const journalEntry = await api.postJournalEntry({
70
- date: new Date(),
71
- description: 'Monthly salary payments',
72
- reference: 'SAL-2024-03',
73
- lines: [
74
- { accountNumber: '6000', debit: 5000.00, description: 'Gross salary' },
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' }
78
- ]
57
+ debitAccount: '1200',
58
+ creditAccount: '4000',
59
+ amount: 1000,
60
+ description: 'Test sale',
61
+ reference: 'INV-001',
62
+ skrType: 'SKR03',
79
63
  });
80
- ```
81
64
 
82
- ### ๐Ÿงพ E-Invoice Integration
83
-
84
- ```typescript
85
- // Import electronic invoices (XRechnung/ZUGFeRD)
86
- const invoiceData = await api.importInvoice(xmlContent, {
87
- format: 'xrechnung',
88
- validateSchema: true,
89
- checkDuplicates: true
90
- });
65
+ const trialBalance = await api.generateTrialBalance();
91
66
 
92
- // Automatically book invoice to accounting
93
- const booking = await api.bookInvoice(invoiceData.invoiceId, {
94
- autoDetectAccounts: true,
95
- splitVAT: true,
96
- createPaymentSchedule: true
97
- });
67
+ console.log(trialBalance.isBalanced);
98
68
 
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
- });
69
+ await api.close();
121
70
  ```
122
71
 
123
- ### ๐Ÿ“Š Generating Financial Reports
72
+ ## SKR03 vs SKR04
124
73
 
125
- ```typescript
126
- // Trial Balance (Summen- und Saldenliste)
127
- const trialBalance = await api.generateTrialBalance({
128
- dateFrom: new Date('2024-01-01'),
129
- dateTo: new Date('2024-12-31')
130
- });
74
+ `initialize('SKR03')` loads the process-oriented chart.
131
75
 
132
- // Income Statement (GuV - Gewinn- und Verlustrechnung)
133
- const incomeStatement = await api.generateIncomeStatement({
134
- dateFrom: new Date('2024-01-01'),
135
- dateTo: new Date('2024-12-31')
136
- });
76
+ - Class 4: operating income
77
+ - Class 5: material costs
78
+ - Class 6: personnel costs
79
+ - Class 7: other operating expenses
137
80
 
138
- // Balance Sheet (Bilanz)
139
- const balanceSheet = await api.generateBalanceSheet({
140
- date: new Date('2024-12-31')
141
- });
81
+ `initialize('SKR04')` loads the financial-statement-oriented chart.
142
82
 
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
- });
83
+ - Class 2 and 3: expenses
84
+ - Class 4 and 5: revenues
85
+ - Class 8: reserved as `frei` for custom use
148
86
 
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
- ```
87
+ The test suite exercises both variants and includes full Jahresabschluss scenarios for each.
155
88
 
156
- ### ๐Ÿ“‘ Advanced Export Features
89
+ ## Posting Model
157
90
 
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
- });
91
+ Simple postings use `postTransaction()`.
167
92
 
168
- // Generate PDF reports with professional formatting
169
- const pdfReports = await api.generatePdfReports({
170
- reports: ['trial_balance', 'income_statement', 'balance_sheet'],
171
- dateFrom: new Date('2024-01-01'),
172
- dateTo: new Date('2024-12-31'),
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'
93
+ ```ts
94
+ await api.postTransaction({
95
+ date: new Date(),
96
+ debitAccount: '5400',
97
+ creditAccount: '70001',
98
+ amount: 119,
99
+ description: 'Purchase including VAT',
100
+ skrType: 'SKR03',
101
+ vatAmount: 19,
102
+ reference: 'VAT-001',
218
103
  });
219
104
  ```
220
105
 
221
- ## ๐Ÿ—๏ธ Core Features
222
-
223
- ### Account Management
106
+ Complex bookings use `postJournalEntry()` with explicit DATEV posting keys.
224
107
 
225
- ```typescript
226
- // Create custom accounts
227
- const account = await api.createAccount({
228
- accountNumber: '1299',
229
- accountName: 'PayPal Business',
230
- accountClass: 1,
231
- accountType: 'asset',
232
- description: 'PayPal business account for online payments',
233
- isActive: true
108
+ ```ts
109
+ await api.postJournalEntry({
110
+ date: new Date(),
111
+ description: 'Complex distribution',
112
+ reference: 'COMPLEX-001',
113
+ lines: [
114
+ { accountNumber: '5000', debit: 500, description: 'Materials', postingKey: 40 },
115
+ { accountNumber: '6000', debit: 300, description: 'Wages', postingKey: 40 },
116
+ { accountNumber: '7100', debit: 200, description: 'Rent', postingKey: 40 },
117
+ { accountNumber: '1200', credit: 1000, description: 'Bank payment', postingKey: 40 },
118
+ ],
119
+ skrType: 'SKR03',
234
120
  });
121
+ ```
235
122
 
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
- ]);
123
+ Important behavior from the code and tests:
241
124
 
242
- // Search accounts by name or number
243
- const accounts = await api.searchAccounts('bank');
125
+ - debit and credit totals must balance
126
+ - debit and credit account cannot be the same in a simple transaction
127
+ - inactive accounts cannot be posted to
128
+ - automatic accounts such as debtor or creditor control accounts are meant to be replaced by personal accounts for direct postings
244
129
 
245
- // Get account with full details
246
- const account = await api.getAccount('1200');
130
+ ## Common Workflows
247
131
 
248
- // Update account information
249
- await api.updateAccount('1200', {
250
- accountName: 'Main Business Bank Account',
251
- description: 'Primary operating account'
252
- });
132
+ Create custom accounts:
253
133
 
254
- // Get account balance with running totals
255
- const balance = await api.getAccountBalance('1200');
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'
134
+ ```ts
135
+ await api.createAccount({
136
+ accountNumber: '4999',
137
+ accountName: 'Custom Revenue Account',
138
+ accountClass: 4,
139
+ accountType: 'revenue',
140
+ description: 'Test custom account',
270
141
  });
271
142
  ```
272
143
 
273
- ### Transaction Management
274
-
275
- ```typescript
276
- // Get transaction by ID
277
- const transaction = await api.getTransaction(transactionId);
278
-
279
- // Get transaction history with filtering
280
- const transactions = await api.listTransactions({
281
- accountNumber: '1200',
282
- dateFrom: new Date('2024-01-01'),
283
- dateTo: new Date('2024-12-31'),
284
- minAmount: 100,
285
- maxAmount: 10000
286
- });
287
-
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)
295
- const reversal = await api.reverseTransaction(transactionId);
144
+ Batch operations:
296
145
 
297
- // Reverse complex journal entries
298
- const journalReversal = await api.reverseJournalEntry(journalEntryId);
299
-
300
- // Batch processing for performance
301
- const batchResults = await api.postBatchTransactions([
302
- { date: new Date(), debitAccount: '1200', creditAccount: '8400', amount: 100 },
303
- { date: new Date(), debitAccount: '1200', creditAccount: '8400', amount: 200 },
304
- { date: new Date(), debitAccount: '1200', creditAccount: '8400', amount: 300 }
146
+ ```ts
147
+ await api.createBatchAccounts([
148
+ {
149
+ accountNumber: '10001',
150
+ accountName: 'Kunde Mustermann GmbH',
151
+ accountClass: 1,
152
+ accountType: 'asset',
153
+ skrType: 'SKR03',
154
+ },
155
+ {
156
+ accountNumber: '70001',
157
+ accountName: 'Lieferant Test GmbH',
158
+ accountClass: 7,
159
+ accountType: 'liability',
160
+ skrType: 'SKR03',
161
+ },
305
162
  ]);
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();
317
163
  ```
318
164
 
319
- ## ๐Ÿ“š SKR03 vs SKR04: Which One to Choose?
165
+ Pagination:
320
166
 
321
- ### SKR03 - Process Structure Principle (Prozessgliederungsprinzip)
322
- **Best for:** ๐Ÿ›๏ธ Trading companies, ๐Ÿ’ผ Service providers, ๐Ÿช Retail businesses
167
+ ```ts
168
+ const page1 = await api.getAccountsPaginated(1, 10);
169
+ console.log(page1.total, page1.totalPages, page1.data.length);
170
+ ```
323
171
 
324
- - Accounts organized by **business process flow**
325
- - Easier mapping to operational workflows
326
- - Natural progression from purchasing โ†’ inventory โ†’ sales
327
- - Popular with small to medium enterprises
172
+ Reversals and validation:
328
173
 
329
- ### SKR04 - Financial Classification Principle (Abschlussgliederungsprinzip)
330
- **Best for:** ๐Ÿญ Manufacturing companies, ๐Ÿ—๏ธ Large corporations, ๐Ÿ“ˆ Public companies
174
+ ```ts
175
+ const ok = api.validateDoubleEntry(100, 100);
176
+ const reversed = await api.reverseTransaction(transactionId);
177
+ ```
331
178
 
332
- - Accounts organized by **financial statement structure**
333
- - Direct mapping to balance sheet and P&L positions
334
- - Simplified financial reporting and analysis
335
- - Preferred by auditors and financial institutions
179
+ ## Reports And Exports
336
180
 
337
- ## ๐ŸŽฏ Account Structure
181
+ Available reporting methods on `SkrApi`:
338
182
 
339
- Both SKR standards follow the same 4-digit hierarchical structure:
183
+ - `generateTrialBalance()`
184
+ - `generateIncomeStatement()`
185
+ - `generateBalanceSheet()`
186
+ - `generateGeneralLedger()`
187
+ - `generateCashFlowStatement()`
188
+ - `exportReportToCSV()`
189
+ - `exportToDATEV()`
340
190
 
341
- ```
342
- [0-9] โ†’ Account Class (Kontenklasse)
343
- [0-9] โ†’ Account Group (Kontengruppe)
344
- [0-9] โ†’ Account Subgroup (Kontenuntergruppe)
345
- [0-9] โ†’ Individual Account (Einzelkonto)
346
- ```
191
+ Year-end archival export:
347
192
 
348
- ### Account Classes Overview
349
-
350
- | Class | SKR03 Description | SKR04 Description | Type |
351
- |-------|------------------|-------------------|------|
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 |
362
-
363
- ## ๐Ÿ”ง Advanced Features
364
-
365
- ### Period Management
366
-
367
- ```typescript
368
- // Close accounting period with automatic adjustments
369
- await api.closePeriod('2024-01', {
370
- performYearEndAdjustments: true,
371
- generateReports: true
193
+ ```ts
194
+ const exportPath = await api.exportJahresabschluss({
195
+ exportPath: './exports',
196
+ fiscalYear: 2024,
197
+ dateFrom: new Date('2024-01-01'),
198
+ dateTo: new Date('2024-12-31'),
199
+ includeDocuments: true,
200
+ generatePdfReports: true,
201
+ signExport: false,
202
+ timestampExport: false,
203
+ companyInfo: {
204
+ name: 'Example GmbH',
205
+ taxId: 'DE123456789',
206
+ registrationNumber: 'HRB 12345',
207
+ address: 'Example Street 1, 28195 Bremen',
208
+ },
372
209
  });
373
210
 
374
- // Recalculate all account balances
375
- await api.recalculateBalances();
211
+ console.log(exportPath);
376
212
  ```
377
213
 
378
- ### Data Import/Export
214
+ The export code creates a BagIt-style folder structure with metadata, accounting data, report output, document storage, and manifest hashes.
379
215
 
380
- ```typescript
381
- // Import accounts from CSV
382
- const importedCount = await api.importAccountsFromCSV(csvContent);
216
+ ## E-Invoice Workflows
383
217
 
384
- // Export accounts to CSV
385
- const csvExport = await api.exportAccountsToCSV();
218
+ The package includes invoice types and API helpers for importing, storing, booking, searching, exporting, and generating e-invoices.
386
219
 
387
- // Export to DATEV format (for tax advisors)
388
- const datevExport = await api.exportToDATEV({
389
- dateFrom: new Date('2024-01-01'),
390
- dateTo: new Date('2024-12-31')
391
- });
220
+ Supported invoice directions:
392
221
 
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
- });
398
- ```
222
+ - `inbound`
223
+ - `outbound`
399
224
 
400
- ### Validation & Integrity
225
+ Supported formats in the invoice model:
401
226
 
402
- ```typescript
403
- // Find unbalanced transactions
404
- const unbalanced = await api.getUnbalancedTransactions();
227
+ - `xrechnung`
228
+ - `zugferd`
229
+ - `facturx`
230
+ - `peppol`
231
+ - `ubl`
405
232
 
406
- // Validate double-entry before posting
407
- const isValid = await api.validateDoubleEntry({
408
- debitAccount: '1000',
409
- creditAccount: '8400',
410
- amount: 100
411
- });
233
+ Example import and booking flow:
412
234
 
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
- ```
427
-
428
- ### Invoice Processing & Compliance
429
-
430
- ```typescript
431
- // Get invoice statistics and analytics
432
- const stats = await api.getInvoiceStatistics({
433
- dateFrom: new Date('2024-01-01'),
434
- dateTo: new Date('2024-12-31'),
435
- groupBy: 'month',
436
- includeVATAnalysis: true
235
+ ```ts
236
+ const invoice = await api.importInvoice('./fixtures/invoice.xml', 'inbound', {
237
+ autoBook: true,
238
+ confidenceThreshold: 80,
437
239
  });
438
240
 
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
- ]
241
+ const hits = await api.searchInvoices({
242
+ invoiceNumber: invoice.invoiceNumber,
462
243
  });
463
244
 
464
- // Validate invoice compliance
465
- const validation = await api.validateInvoice(invoice, {
466
- standard: 'xrechnung',
467
- checkBusinessRules: true,
468
- checkVATRules: true
245
+ const exported = await api.exportInvoice(invoice, {
246
+ format: 'xrechnung',
247
+ embedInPdf: true,
469
248
  });
470
249
  ```
471
250
 
472
- ### Utility Functions
251
+ The API also exposes:
473
252
 
474
- ```typescript
475
- // Get SKR type description for account classes
476
- const classDesc = api.getAccountClassDescription(4);
477
- // Returns: "Operating Income (SKR03)" or "Revenues Part 1 (SKR04)"
253
+ - `bookInvoice()`
254
+ - `getInvoice()`
255
+ - `getInvoiceStatistics()`
256
+ - `createInvoiceComplianceReport()`
257
+ - `generateInvoice()`
478
258
 
479
- // Get current SKR type
480
- const skrType = api.getSKRType(); // Returns: 'SKR03' or 'SKR04'
481
- ```
259
+ ## Public Exports
482
260
 
483
- ## ๐Ÿ›ก๏ธ Type Safety
484
-
485
- Full TypeScript support with comprehensive type definitions:
486
-
487
- ```typescript
488
- import type {
489
- TSKRType,
490
- IAccountData,
491
- ITransactionData,
492
- IJournalEntry,
493
- IJournalEntryLine,
494
- ITrialBalanceReport,
495
- IIncomeStatement,
496
- IBalanceSheet,
497
- IAccountFilter,
498
- ITransactionFilter,
499
- IPaginationParams,
500
- IAccountBalance,
501
- ICashFlowStatement,
502
- IGeneralLedger,
503
- IInvoice,
504
- IInvoiceLine,
505
- IInvoiceParty,
506
- IBookingRules,
507
- IValidationResult
508
- } from '@fin.cx/skr';
509
-
510
- // All operations are fully typed
511
- const account: IAccountData = {
512
- accountNumber: '1200',
513
- accountName: 'Bank Account',
514
- accountClass: 1,
515
- accountType: 'asset',
516
- skrType: 'SKR03',
517
- isActive: true
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
- };
536
- ```
261
+ Top-level exports include:
537
262
 
538
- ## ๐ŸŒŸ Real-World Example: Complete Annual Closing
263
+ - `SkrApi`
264
+ - `Account`
265
+ - `Transaction`
266
+ - `JournalEntry`
267
+ - `ChartOfAccounts`
268
+ - `Ledger`
269
+ - `Reports`
270
+ - `SkrExport`
271
+ - `LedgerExporter`
272
+ - `AccountsExporter`
273
+ - `BalancesExporter`
274
+ - `PdfReportGenerator`
275
+ - `SecurityManager`
276
+ - `SKR03_ACCOUNTS`, `SKR04_ACCOUNTS`
539
277
 
540
- Here's how to perform a complete Jahresabschluss (annual financial closing):
278
+ This makes the package usable as both an application-facing API and a toolkit for custom accounting workflows.
541
279
 
542
- ```typescript
543
- import { SkrApi } from '@fin.cx/skr';
280
+ ## Development
281
+
282
+ Build:
544
283
 
545
- async function performJahresabschluss() {
546
- const api = new SkrApi({
547
- mongoDbUrl: process.env.MONGODB_URL!,
548
- dbName: 'company_accounting'
549
- });
550
-
551
- await api.initialize('SKR04'); // Using SKR04 for better reporting structure
552
-
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
- ]
572
- });
573
-
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'
586
- }
587
- });
588
-
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
- });
594
-
595
- const balanceSheet = await api.generateBalanceSheet({
596
- date: new Date('2024-12-31')
597
- });
598
-
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');
631
-
632
- await api.close();
633
- }
634
-
635
- performJahresabschluss().catch(console.error);
284
+ ```bash
285
+ pnpm build
636
286
  ```
637
287
 
638
- ## ๐Ÿšฆ API Reference
639
-
640
- ### Main Classes
641
-
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 |
654
-
655
- ### Key Methods
656
-
657
- | Method | Description |
658
- |--------|-------------|
659
- | `initialize(skrType)` | Initialize with SKR03 or SKR04 |
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
697
-
698
- ## ๐Ÿ“‹ Requirements
699
-
700
- - **Node.js** >= 18.0.0
701
- - **MongoDB** >= 5.0
702
- - **TypeScript** >= 5.0 (for development)
703
-
704
- ## ๐Ÿ”ฌ Testing
705
-
706
- The module includes comprehensive test coverage with real-world scenarios:
288
+ Test:
707
289
 
708
290
  ```bash
709
- # Run all tests
710
291
  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
292
  ```
720
293
 
294
+ Current project checks include:
295
+
296
+ - runtime tests for SKR03 and SKR04 flows
297
+ - transaction and journal validation
298
+ - report generation
299
+ - DATEV export
300
+ - published type consumption through `test/fixtures/strict-consumer`
301
+
721
302
  ## License and Legal Information
722
303
 
723
- 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.
304
+ This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the [license](./license.md) file.
724
305
 
725
306
  **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.
726
307
 
727
308
  ### Trademarks
728
309
 
729
- 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.
310
+ 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.
311
+
312
+ 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.
730
313
 
731
314
  ### Company Information
732
315
 
733
316
  Task Venture Capital GmbH
734
- Registered at District court Bremen HRB 35230 HB, Germany
317
+ Registered at District Court Bremen HRB 35230 HB, Germany
735
318
 
736
- For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
319
+ For any legal inquiries or further information, please contact us via email at hello@task.vc.
737
320
 
738
- 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.
321
+ 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.