fajfield-einvoice 0.1.0__tar.gz

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.
@@ -0,0 +1,14 @@
1
+ *.tgz
2
+ __pycache__/
3
+ dart/.dart_tool/
4
+ dart/pubspec.lock
5
+ dist/
6
+ dotnet/**/bin/
7
+ dotnet/**/obj/
8
+ dotnet/out/
9
+ node_modules/
10
+ python/**/__pycache__/
11
+ python/dist/
12
+ spec/out/
13
+ tools/.phive/
14
+ tools/rules/
@@ -0,0 +1,5 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0
4
+
5
+ First release: UAE (Peppol PINT AE 1.0.4) invoices and credit notes. Build, validate with plain-language errors citing the official rules, calculate, read received invoices, logging with trace ids, explain and masked debug reports. Same results as the JavaScript, Python, .NET and Dart SDKs.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Fajfield
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,146 @@
1
+ Metadata-Version: 2.5
2
+ Name: fajfield-einvoice
3
+ Version: 0.1.0
4
+ Summary: Build, check and read UAE e-invoices (Peppol PINT AE). Clear errors, logging and debug helpers. No dependencies.
5
+ Project-URL: Homepage, https://fajfield.com/e-invoicing/
6
+ Project-URL: Documentation, https://fajfield.com/developers/e-invoicing/
7
+ Project-URL: Source, https://github.com/fajfield/fajfield-einvoice
8
+ Author: Fajfield
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: e-invoicing,einvoice,fta,peppol,pint-ae,uae,ubl,vat
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Topic :: Office/Business :: Financial :: Accounting
15
+ Requires-Python: >=3.8
16
+ Description-Content-Type: text/markdown
17
+
18
+ # fajfield-einvoice
19
+
20
+ Build, check and read **UAE e-invoices** (Peppol **PINT AE**, UBL 2.1) from Python: Django, Flask, FastAPI, Odoo and ERPNext modules, scripts. Plain dicts in, valid PINT AE XML out, with plain-language errors, logging and debugging helpers. **No dependencies**, Python 3.8+.
21
+
22
+ - **Tested against the official rules:** output is checked against the official PINT AE Schematron in CI, and the SDK reads and rebuilds all 31 official PINT AE sample invoices into files that pass those rules.
23
+ - **Same results as every Fajfield SDK:** JavaScript, Python, .NET and Dart produce byte-identical XML and the same issues for the same invoice, checked in CI.
24
+ - **Errors you can act on:** each problem names the field, says what is wrong and how to fix it, and cites the official rule.
25
+ - **All the maths done for you:** line amounts, VAT breakdown, totals, AED amounts for foreign-currency invoices, transaction type flags.
26
+ - **Read received invoices** back into the same model, with a check that their totals add up.
27
+ - **Logging and debugging built in:** trace IDs, timings, pluggable log sinks, a step-by-step explanation, and a masked debug report that is safe to attach to a support ticket.
28
+
29
+ Fajfield is not an accredited service provider (ASP). This SDK produces the invoice file; your ASP sends it on the Peppol network and reports it to the FTA. For connecting any software to any ASP without code, see the [Fajfield e-invoicing gateway](https://fajfield.com/e-invoicing/).
30
+
31
+ ## Install
32
+
33
+ ```sh
34
+ pip install fajfield-einvoice
35
+ ```
36
+
37
+ ## Build an invoice
38
+
39
+ ```python
40
+ from fajfield_einvoice import EInvoicing
41
+
42
+ ei = EInvoicing(log_level='info')
43
+
44
+ result = ei.build({
45
+ 'number': 'INV-2026-0452',
46
+ 'issueDate': '2026-11-30',
47
+ 'dueDate': '2026-12-14',
48
+ 'seller': {
49
+ 'name': 'Harbour Foods Trading LLC',
50
+ 'trn': '100234567800003', # VAT registration number (TRN)
51
+ 'tin': '1002345678', # tax identification number, also the Peppol address
52
+ 'legalId': {'type': 'TL', 'id': 'CN-1234567', 'authority': 'Dubai Department of Economy and Tourism'},
53
+ 'address': {'street': 'Warehouse 14, Al Quoz Industrial 3', 'city': 'Dubai', 'emirate': 'DXB'},
54
+ },
55
+ 'buyer': {
56
+ 'name': 'Fresh Mart Supermarket LLC',
57
+ 'trn': '100987654300003',
58
+ 'tin': '1009876543',
59
+ 'legalId': {'type': 'TL', 'id': 'CN-7654321', 'authority': 'Abu Dhabi Department of Economic Development'},
60
+ 'address': {'street': 'Shop 3, Al Wahda Mall', 'city': 'Abu Dhabi', 'emirate': 'AUH'},
61
+ },
62
+ 'payment': {'means': '30', 'accountId': 'AE070331234567890123456'},
63
+ 'lines': [
64
+ {'name': 'Basmati rice 5 kg', 'quantity': 40, 'price': 18.5, 'vat': {'category': 'S'}, 'itemType': 'G', 'hsCode': '100630'},
65
+ {'name': 'Delivery service', 'quantity': 1, 'price': 75, 'vat': {'category': 'S'}, 'itemType': 'S'},
66
+ ],
67
+ })
68
+
69
+ if result.ok:
70
+ send_to_your_asp(result.xml) # the PINT AE XML
71
+ save_uuid(result.invoice['uuid']) # generated if you did not give one: keep it
72
+ else:
73
+ print(ei.format(result.errors))
74
+ ```
75
+
76
+ The model uses the same camelCase keys as every Fajfield SDK, so the JSON in [`spec/invoices`](../spec/invoices) works as is. `build()` checks first and only writes XML when there are no errors. Use `throw_on_error=True` to get an `EInvoiceError` (with `.code` and `.issues`) instead, or `strict=False` to write it anyway.
77
+
78
+ ## Errors in plain words
79
+
80
+ ```
81
+ ✗ buyer.trn: The buyer's TRN "12345" is not valid.
82
+ → A TRN has 15 digits, starts with 1 and ends with 03, for example 100234567800003. [ibr-132-ae]
83
+ ✗ seller.address.emirate: "Dubai" is not an emirate code.
84
+ → Use one of: AUH (Abu Dhabi), DXB (Dubai), SHJ (Sharjah), UAQ (Umm Al Quwain), FUJ (Fujairah), AJM (Ajman), RAK (Ras Al Khaimah). [ibr-128-ae]
85
+ ✗ lines[0].vat.exemptionCode: Line 1 is exempt, so the exemption reason code is required.
86
+ → For example 'DL8.46.2'. [ibr-167-ae]
87
+ ```
88
+
89
+ Each issue is a dict: `severity`, `code`, `path`, `message`, `hint`, `rule`. Match on `code` (stable) to highlight the right field in your own screens.
90
+
91
+ ## Logging and debugging
92
+
93
+ ```python
94
+ from fajfield_einvoice import EInvoicing, create_logger, json_sink, memory_sink
95
+
96
+ ei = EInvoicing(log_level='debug') # while integrating: everything to the console
97
+
98
+ recent = memory_sink(500) # in production: JSON lines + recent entries for support
99
+ ei = EInvoicing(logger=create_logger('info', [json_sink(), recent]))
100
+
101
+ # or send entries to the standard logging module
102
+ import logging
103
+ log = logging.getLogger('einvoice')
104
+ ei = EInvoicing(log_level='info', sink=lambda e: log.info('%s %s', e['event'], e['message'], extra=e))
105
+ ```
106
+
107
+ Every entry for one invoice carries the same trace ID (`result.trace_id`).
108
+
109
+ ```python
110
+ print(ei.explain(invoice)) # how every amount was calculated
111
+ report = ei.debug_report(invoice, logs=recent.entries, trace_id=result.trace_id) # masked by default
112
+ ```
113
+
114
+ Other helpers: `describe_transaction_type('10000001')` → `['Free zone supply', 'Export']`, `describe('vat', 'AE')` → `'Reverse charge'`, `redact(invoice)`, `mask(value)`, `calculate(invoice)`.
115
+
116
+ ## Read a received invoice
117
+
118
+ ```python
119
+ parsed = ei.parse(xml_from_your_asp)
120
+ if parsed['mismatches']:
121
+ print('Totals do not add up:', parsed['mismatches'])
122
+ book_purchase_invoice(parsed['invoice']) # same model as the invoices you send
123
+ ```
124
+
125
+ ## What's supported
126
+
127
+ | | |
128
+ |---|---|
129
+ | Documents | Tax invoice (380), commercial invoice (480), tax credit note (381), credit note (81) |
130
+ | VAT | Standard 5%, zero-rated, exempt (with reason code), out of scope, reverse charge, additional rate |
131
+ | Special transactions | Free zone, deemed supply, margin scheme, summary, continuous supplies, disclosed agent, e-commerce, exports (the 8 flags of BTAE-02) |
132
+ | Amounts | Line discounts and charges, price discounts, document allowances and charges, prepaid amounts, rounding |
133
+ | Currency | Any currency, with the AED VAT total, AED line amounts and AED total the UAE requires |
134
+ | Parties | TRN, TIN, Peppol address, trade licence / Emirates ID / passport / cabinet decision, addresses, contacts |
135
+ | Items | Goods/services type, HS code, service accounting code (SAC), GTIN, reverse charge type |
136
+ | Payment | Payment means, bank account, card (last 4 digits), payment terms |
137
+
138
+ Coming next: Oman (PINT OM), Saudi Arabia (ZATCA), India (IRP).
139
+
140
+ ## Not tax advice
141
+
142
+ This SDK is software. It follows the published PINT AE specification and validation rules; your accountant or tax adviser decides how each transaction should be invoiced. Always test with your ASP before going live.
143
+
144
+ ## License
145
+
146
+ MIT. Made by [Fajfield](https://fajfield.com): research and development for ERP, warehouse, POS and business data.
@@ -0,0 +1,129 @@
1
+ # fajfield-einvoice
2
+
3
+ Build, check and read **UAE e-invoices** (Peppol **PINT AE**, UBL 2.1) from Python: Django, Flask, FastAPI, Odoo and ERPNext modules, scripts. Plain dicts in, valid PINT AE XML out, with plain-language errors, logging and debugging helpers. **No dependencies**, Python 3.8+.
4
+
5
+ - **Tested against the official rules:** output is checked against the official PINT AE Schematron in CI, and the SDK reads and rebuilds all 31 official PINT AE sample invoices into files that pass those rules.
6
+ - **Same results as every Fajfield SDK:** JavaScript, Python, .NET and Dart produce byte-identical XML and the same issues for the same invoice, checked in CI.
7
+ - **Errors you can act on:** each problem names the field, says what is wrong and how to fix it, and cites the official rule.
8
+ - **All the maths done for you:** line amounts, VAT breakdown, totals, AED amounts for foreign-currency invoices, transaction type flags.
9
+ - **Read received invoices** back into the same model, with a check that their totals add up.
10
+ - **Logging and debugging built in:** trace IDs, timings, pluggable log sinks, a step-by-step explanation, and a masked debug report that is safe to attach to a support ticket.
11
+
12
+ Fajfield is not an accredited service provider (ASP). This SDK produces the invoice file; your ASP sends it on the Peppol network and reports it to the FTA. For connecting any software to any ASP without code, see the [Fajfield e-invoicing gateway](https://fajfield.com/e-invoicing/).
13
+
14
+ ## Install
15
+
16
+ ```sh
17
+ pip install fajfield-einvoice
18
+ ```
19
+
20
+ ## Build an invoice
21
+
22
+ ```python
23
+ from fajfield_einvoice import EInvoicing
24
+
25
+ ei = EInvoicing(log_level='info')
26
+
27
+ result = ei.build({
28
+ 'number': 'INV-2026-0452',
29
+ 'issueDate': '2026-11-30',
30
+ 'dueDate': '2026-12-14',
31
+ 'seller': {
32
+ 'name': 'Harbour Foods Trading LLC',
33
+ 'trn': '100234567800003', # VAT registration number (TRN)
34
+ 'tin': '1002345678', # tax identification number, also the Peppol address
35
+ 'legalId': {'type': 'TL', 'id': 'CN-1234567', 'authority': 'Dubai Department of Economy and Tourism'},
36
+ 'address': {'street': 'Warehouse 14, Al Quoz Industrial 3', 'city': 'Dubai', 'emirate': 'DXB'},
37
+ },
38
+ 'buyer': {
39
+ 'name': 'Fresh Mart Supermarket LLC',
40
+ 'trn': '100987654300003',
41
+ 'tin': '1009876543',
42
+ 'legalId': {'type': 'TL', 'id': 'CN-7654321', 'authority': 'Abu Dhabi Department of Economic Development'},
43
+ 'address': {'street': 'Shop 3, Al Wahda Mall', 'city': 'Abu Dhabi', 'emirate': 'AUH'},
44
+ },
45
+ 'payment': {'means': '30', 'accountId': 'AE070331234567890123456'},
46
+ 'lines': [
47
+ {'name': 'Basmati rice 5 kg', 'quantity': 40, 'price': 18.5, 'vat': {'category': 'S'}, 'itemType': 'G', 'hsCode': '100630'},
48
+ {'name': 'Delivery service', 'quantity': 1, 'price': 75, 'vat': {'category': 'S'}, 'itemType': 'S'},
49
+ ],
50
+ })
51
+
52
+ if result.ok:
53
+ send_to_your_asp(result.xml) # the PINT AE XML
54
+ save_uuid(result.invoice['uuid']) # generated if you did not give one: keep it
55
+ else:
56
+ print(ei.format(result.errors))
57
+ ```
58
+
59
+ The model uses the same camelCase keys as every Fajfield SDK, so the JSON in [`spec/invoices`](../spec/invoices) works as is. `build()` checks first and only writes XML when there are no errors. Use `throw_on_error=True` to get an `EInvoiceError` (with `.code` and `.issues`) instead, or `strict=False` to write it anyway.
60
+
61
+ ## Errors in plain words
62
+
63
+ ```
64
+ ✗ buyer.trn: The buyer's TRN "12345" is not valid.
65
+ → A TRN has 15 digits, starts with 1 and ends with 03, for example 100234567800003. [ibr-132-ae]
66
+ ✗ seller.address.emirate: "Dubai" is not an emirate code.
67
+ → Use one of: AUH (Abu Dhabi), DXB (Dubai), SHJ (Sharjah), UAQ (Umm Al Quwain), FUJ (Fujairah), AJM (Ajman), RAK (Ras Al Khaimah). [ibr-128-ae]
68
+ ✗ lines[0].vat.exemptionCode: Line 1 is exempt, so the exemption reason code is required.
69
+ → For example 'DL8.46.2'. [ibr-167-ae]
70
+ ```
71
+
72
+ Each issue is a dict: `severity`, `code`, `path`, `message`, `hint`, `rule`. Match on `code` (stable) to highlight the right field in your own screens.
73
+
74
+ ## Logging and debugging
75
+
76
+ ```python
77
+ from fajfield_einvoice import EInvoicing, create_logger, json_sink, memory_sink
78
+
79
+ ei = EInvoicing(log_level='debug') # while integrating: everything to the console
80
+
81
+ recent = memory_sink(500) # in production: JSON lines + recent entries for support
82
+ ei = EInvoicing(logger=create_logger('info', [json_sink(), recent]))
83
+
84
+ # or send entries to the standard logging module
85
+ import logging
86
+ log = logging.getLogger('einvoice')
87
+ ei = EInvoicing(log_level='info', sink=lambda e: log.info('%s %s', e['event'], e['message'], extra=e))
88
+ ```
89
+
90
+ Every entry for one invoice carries the same trace ID (`result.trace_id`).
91
+
92
+ ```python
93
+ print(ei.explain(invoice)) # how every amount was calculated
94
+ report = ei.debug_report(invoice, logs=recent.entries, trace_id=result.trace_id) # masked by default
95
+ ```
96
+
97
+ Other helpers: `describe_transaction_type('10000001')` → `['Free zone supply', 'Export']`, `describe('vat', 'AE')` → `'Reverse charge'`, `redact(invoice)`, `mask(value)`, `calculate(invoice)`.
98
+
99
+ ## Read a received invoice
100
+
101
+ ```python
102
+ parsed = ei.parse(xml_from_your_asp)
103
+ if parsed['mismatches']:
104
+ print('Totals do not add up:', parsed['mismatches'])
105
+ book_purchase_invoice(parsed['invoice']) # same model as the invoices you send
106
+ ```
107
+
108
+ ## What's supported
109
+
110
+ | | |
111
+ |---|---|
112
+ | Documents | Tax invoice (380), commercial invoice (480), tax credit note (381), credit note (81) |
113
+ | VAT | Standard 5%, zero-rated, exempt (with reason code), out of scope, reverse charge, additional rate |
114
+ | Special transactions | Free zone, deemed supply, margin scheme, summary, continuous supplies, disclosed agent, e-commerce, exports (the 8 flags of BTAE-02) |
115
+ | Amounts | Line discounts and charges, price discounts, document allowances and charges, prepaid amounts, rounding |
116
+ | Currency | Any currency, with the AED VAT total, AED line amounts and AED total the UAE requires |
117
+ | Parties | TRN, TIN, Peppol address, trade licence / Emirates ID / passport / cabinet decision, addresses, contacts |
118
+ | Items | Goods/services type, HS code, service accounting code (SAC), GTIN, reverse charge type |
119
+ | Payment | Payment means, bank account, card (last 4 digits), payment terms |
120
+
121
+ Coming next: Oman (PINT OM), Saudi Arabia (ZATCA), India (IRP).
122
+
123
+ ## Not tax advice
124
+
125
+ This SDK is software. It follows the published PINT AE specification and validation rules; your accountant or tax adviser decides how each transaction should be invoiced. Always test with your ASP before going live.
126
+
127
+ ## License
128
+
129
+ MIT. Made by [Fajfield](https://fajfield.com): research and development for ERP, warehouse, POS and business data.
@@ -0,0 +1,22 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "fajfield-einvoice"
7
+ version = "0.1.0"
8
+ description = "Build, check and read UAE e-invoices (Peppol PINT AE). Clear errors, logging and debug helpers. No dependencies."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ requires-python = ">=3.8"
12
+ authors = [{ name = "Fajfield" }]
13
+ keywords = ["e-invoicing", "einvoice", "uae", "peppol", "pint-ae", "ubl", "vat", "fta"]
14
+ classifiers = ["Programming Language :: Python :: 3", "Operating System :: OS Independent", "Topic :: Office/Business :: Financial :: Accounting"]
15
+
16
+ [project.urls]
17
+ Homepage = "https://fajfield.com/e-invoicing/"
18
+ Documentation = "https://fajfield.com/developers/e-invoicing/"
19
+ Source = "https://github.com/fajfield/fajfield-einvoice"
20
+
21
+ [tool.hatch.build.targets.wheel]
22
+ packages = ["src/fajfield_einvoice"]
@@ -0,0 +1,103 @@
1
+ """fajfield-einvoice: build, check and read e-invoices. UAE (Peppol PINT AE) first.
2
+ https://fajfield.com/developers/e-invoicing/
3
+
4
+ from fajfield_einvoice import EInvoicing
5
+ ei = EInvoicing(log_level='info')
6
+ r = ei.build(invoice) # checks, then writes PINT AE XML
7
+ if not r.ok: print(ei.format(r.errors))
8
+ """
9
+ import time as _time
10
+ from dataclasses import dataclass, field
11
+ from typing import Optional
12
+
13
+ from .calc import calculate, r2, transaction_type
14
+ from .debug import SDK_VERSION, SPEC, debug_report, describe, describe_transaction_type, explain, format_issues, mask, redact
15
+ from .log import Logger, MemorySink, console_sink, create_logger, json_sink, memory_sink, new_trace_id, silent_logger
16
+ from .model import CREDIT_REASONS, EMIRATES, FREQUENCIES, INVOICE_TYPES, LEGAL_ID_TYPES, PAYMENT_MEANS, REVERSE_CHARGE_TYPES, VAT_CATEGORIES
17
+ from .parse import from_pint_ae
18
+ from .pint_ae import PINT_AE, prepare, to_pint_ae
19
+ from .validate import TIN, TRN, validate
20
+ from .xmlio import XmlWriter, parse_xml
21
+
22
+ __version__ = SDK_VERSION
23
+
24
+
25
+ class EInvoiceError(Exception):
26
+ """Raised by build(throw_on_error=True) when the invoice has errors."""
27
+ def __init__(self, issues, trace_id):
28
+ self.issues, self.trace_id = issues, trace_id
29
+ errs = [i for i in issues if i['severity'] == 'error']
30
+ super().__init__(f'The invoice has {len(errs)} problem(s):\n{format_issues(errs)}')
31
+
32
+ @property
33
+ def code(self):
34
+ """The first error's code, e.g. 'buyer.trn.format'."""
35
+ return next((i['code'] for i in self.issues if i['severity'] == 'error'), None)
36
+
37
+
38
+ @dataclass
39
+ class BuildResult:
40
+ ok: bool
41
+ xml: Optional[str]
42
+ issues: list
43
+ errors: list
44
+ warnings: list
45
+ invoice: dict # as sent, including the generated UUID (store it)
46
+ calculation: dict
47
+ trace_id: str
48
+ ms: float = field(default=0)
49
+
50
+
51
+ class EInvoicing:
52
+ """The main entry point. Silent by default; pass log_level='debug' while integrating, or your own Logger."""
53
+
54
+ def __init__(self, logger: Logger = None, log_level: str = None, sink=None):
55
+ self.logger = logger or (create_logger(log_level, sink) if log_level else silent_logger)
56
+
57
+ def build(self, invoice: dict, strict: bool = True, throw_on_error: bool = False, trace_id: str = None) -> BuildResult:
58
+ """Checks the invoice and, if there are no errors, writes the XML. Never raises unless throw_on_error is set."""
59
+ t0, tid = _time.perf_counter(), trace_id or new_trace_id()
60
+ log = self.logger.child(tid)
61
+ inv = prepare(invoice)
62
+ log.info('build.start', f"Building {'credit note' if inv.get('kind') == 'credit-note' else 'invoice'} {inv.get('number')}",
63
+ {'lines': len(inv.get('lines') or []), 'currency': inv['currency'], 'uuid': inv['uuid']})
64
+ issues = log.time('validate', lambda: validate(inv))
65
+ errors = [i for i in issues if i['severity'] == 'error']
66
+ warnings = [i for i in issues if i['severity'] == 'warning']
67
+ for e in errors: log.warn('validate.error', f"{e['path']}: {e['message']}", {'code': e['code'], 'rule': e.get('rule'), 'hint': e.get('hint')})
68
+ for w in warnings: log.info('validate.warning', f"{w['path']}: {w['message']}", {'code': w['code']})
69
+ try:
70
+ calc = calculate(inv)
71
+ except Exception as e:
72
+ log.error('calculate.failed', str(e)); raise
73
+ log.debug('calculate.done', 'Totals', {**calc['totals'], 'aed': calc['aed'], 'transactionType': calc['transactionType']})
74
+ ms = lambda: round((_time.perf_counter() - t0) * 1000, 1)
75
+ if errors and strict:
76
+ log.warn('build.rejected', f'Not built: {len(errors)} error(s)', {'codes': [e['code'] for e in errors]})
77
+ if throw_on_error:
78
+ raise EInvoiceError(issues, tid)
79
+ return BuildResult(False, None, issues, errors, warnings, inv, calc, tid, ms())
80
+ xml = log.time('xml.write', lambda: to_pint_ae(inv, calc))
81
+ log.info('build.done', f"Built {inv['number']}: {calc['totals']['payable']:g} {calc['currency']} due, {len(xml)} bytes", {'errors': len(errors), 'warnings': len(warnings)})
82
+ return BuildResult(not errors, xml, issues, errors, warnings, inv, calc, tid, ms())
83
+
84
+ def parse(self, xml) -> dict:
85
+ """Reads a received PINT AE invoice or credit note."""
86
+ log = self.logger.child(new_trace_id())
87
+ try:
88
+ p = log.time('parse', lambda: from_pint_ae(xml))
89
+ except Exception as e:
90
+ log.error('parse.failed', str(e)); raise
91
+ log.info('parse.done', f"Read {p['invoice']['kind']} {p['invoice']['number']} from {p['invoice']['seller']['name']}", {'lines': len(p['invoice']['lines']), 'mismatches': len(p['mismatches'])})
92
+ for m in p['mismatches']: log.warn('parse.mismatch', m)
93
+ return p
94
+
95
+ validate = staticmethod(validate)
96
+ calculate = staticmethod(calculate)
97
+ explain = staticmethod(explain)
98
+ debug_report = staticmethod(debug_report)
99
+ format = staticmethod(format_issues)
100
+
101
+
102
+ def create_einvoicing(**kw) -> EInvoicing:
103
+ return EInvoicing(**kw)
@@ -0,0 +1,85 @@
1
+ """All the arithmetic, with PINT rounding: each stated amount is rounded to 2 decimals; totals are sums of stated amounts."""
2
+ from decimal import Decimal, ROUND_HALF_UP
3
+
4
+
5
+ def r2(x) -> float:
6
+ x = float(x)
7
+ if x != x or x in (float('inf'), float('-inf')):
8
+ return x
9
+ return float(Decimal(repr(float(x))).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP))
10
+
11
+
12
+ def amt(x) -> str:
13
+ s = f'{r2(x):.2f}'
14
+ if s.endswith('.00'):
15
+ s = s[:-3]
16
+ elif s.endswith('0') and '.' in s:
17
+ s = s[:-1]
18
+ return '0' if s == '-0' else s
19
+
20
+
21
+ def num(x) -> str:
22
+ x = float(x)
23
+ if x.is_integer():
24
+ return str(int(x))
25
+ return format(round(x, 6), 'f').rstrip('0').rstrip('.')
26
+
27
+
28
+ def rate_of(v: dict):
29
+ c = v.get('category')
30
+ if c in ('E', 'O'):
31
+ return None
32
+ if v.get('rate') is not None:
33
+ return v['rate']
34
+ return 0 if c == 'Z' else 5
35
+
36
+
37
+ def transaction_type(t=None) -> str:
38
+ t = t or {}
39
+ keys = ['freeZone', 'deemedSupply', 'marginScheme', 'summary', 'continuous', 'disclosedAgent', 'eCommerce', 'exports']
40
+ return ''.join('1' if t.get(k) else '0' for k in keys)
41
+
42
+
43
+ def calculate(inv: dict) -> dict:
44
+ cur = (inv.get('currency') or 'AED').upper()
45
+ fx = 1 if cur == 'AED' else (inv.get('exchangeRate') or float('nan'))
46
+ lines = []
47
+ for i, ln in enumerate(inv.get('lines') or []):
48
+ base = ln.get('baseQuantity') or 1
49
+ gross = ln['grossPrice'] if ln.get('grossPrice') is not None else ln['price']
50
+ net = r2(r2(ln['quantity'] * (ln['price'] / base)) - (ln.get('discount') or 0) + (ln.get('charge') or 0))
51
+ rate = rate_of(ln['vat'])
52
+ cat = ln['vat']['category']
53
+ vat = None if cat == 'E' else (r2(net * (rate or 0) / 100) if cat == 'S' else 0)
54
+ lines.append({'line': ln, 'index': i, 'id': ln.get('id') or str(i + 1), 'baseQuantity': base, 'grossPrice': gross,
55
+ 'priceDiscount': r2(gross - ln['price']), 'net': net, 'vat': vat, 'rate': rate,
56
+ 'aedAmount': r2((net + (vat or 0)) * fx), 'aedVat': None if vat is None else r2(vat * fx)})
57
+ groups = {}
58
+
59
+ def add(v, amount):
60
+ rate = rate_of(v)
61
+ key = f"{v['category']}|{'' if rate is None else rate}"
62
+ g = groups.get(key)
63
+ if g is None:
64
+ g = {'category': v['category'], 'rate': rate, 'taxable': 0.0, 'tax': 0.0}
65
+ if v.get('exemptionCode'): g['exemptionCode'] = v['exemptionCode']
66
+ if v.get('exemptionReason'): g['exemptionReason'] = v['exemptionReason']
67
+ groups[key] = g
68
+ g['taxable'] = r2(g['taxable'] + amount)
69
+
70
+ for l in lines: add(l['line']['vat'], l['net'])
71
+ for a in inv.get('allowances') or []: add(a['vat'], -r2(a['amount']))
72
+ for c in inv.get('charges') or []: add(c['vat'], r2(c['amount']))
73
+ breakdown = [{**g, 'tax': r2(g['taxable'] * (g['rate'] or 0) / 100) if g['category'] == 'S' else 0.0} for g in groups.values()]
74
+ s = lambda xs: r2(sum(r2(x['amount']) for x in (xs or [])))
75
+ line_ext = r2(sum(l['net'] for l in lines))
76
+ allow, charges = s(inv.get('allowances')), s(inv.get('charges'))
77
+ tax_excl = r2(line_ext - allow + charges)
78
+ tax = r2(sum(b['tax'] for b in breakdown))
79
+ tax_incl = r2(tax_excl + tax)
80
+ prepaid, rounding = r2(inv.get('prepaid') or 0), r2(inv.get('rounding') or 0)
81
+ return {'currency': cur, 'fx': fx, 'lines': lines, 'breakdown': breakdown,
82
+ 'totals': {'lineExtension': line_ext, 'allowances': allow, 'charges': charges, 'taxExclusive': tax_excl, 'tax': tax,
83
+ 'taxInclusive': tax_incl, 'prepaid': prepaid, 'rounding': rounding, 'payable': r2(tax_incl - prepaid + rounding)},
84
+ 'aed': {'tax': r2(tax * fx), 'totalInclVat': r2(tax_incl * fx)},
85
+ 'transactionType': transaction_type(inv.get('transaction'))}
@@ -0,0 +1,116 @@
1
+ """Debugging helpers: how every amount was calculated, codes in plain words, and a support report with personal data masked."""
2
+ import copy
3
+ import platform
4
+ import re
5
+ import traceback
6
+ from datetime import datetime, timezone
7
+ from .calc import calculate
8
+ from .model import CREDIT_REASONS, INVOICE_TYPES, PAYMENT_MEANS, VAT_CATEGORIES
9
+ from .validate import validate
10
+
11
+ SDK_VERSION = '0.1.0'
12
+ SPEC = {'country': 'AE', 'name': 'Peppol PINT AE', 'version': '1.0.4'}
13
+ FLAGS = ['Free zone supply', 'Deemed supply', 'Margin scheme', 'Summary invoice', 'Continuous supplies', 'Disclosed agent billing', 'E-commerce supply', 'Export']
14
+
15
+
16
+ def describe_transaction_type(code: str) -> list:
17
+ if not re.match(r'^[01]{8}$', code or ''):
18
+ return [f'Not a valid transaction type: "{code}" (must be 8 characters of 0 and 1)']
19
+ return [f for i, f in enumerate(FLAGS) if code[i] == '1'] or ['Standard supply']
20
+
21
+
22
+ def describe(kind: str, code: str) -> str:
23
+ table = {'vat': VAT_CATEGORIES, 'type': INVOICE_TYPES, 'payment': PAYMENT_MEANS, 'creditReason': CREDIT_REASONS}[kind]
24
+ return table.get(code, f'Unknown {kind} code "{code}"')
25
+
26
+
27
+ def _g(x):
28
+ return f'{x:g}' if isinstance(x, float) else str(x)
29
+
30
+
31
+ def explain(inv: dict, c: dict = None) -> str:
32
+ c = c or calculate(inv)
33
+ cur = c['currency']
34
+ f = lambda x: '-' if x is None else f'{x:.2f}'
35
+ fx = f" (1 {cur} = {_g(c['fx'])} AED)" if cur != 'AED' else ''
36
+ kind = 'Credit note' if inv.get('kind') == 'credit-note' else 'Invoice'
37
+ out = [f"{kind} {inv.get('number')} {inv.get('issueDate')} {cur}{fx}",
38
+ f"Transaction: {', '.join(describe_transaction_type(c['transactionType']))} [{c['transactionType']}]", '', 'Lines']
39
+ for l in c['lines']:
40
+ ln = l['line']
41
+ per = f" per {_g(l['baseQuantity'])}" if l['baseQuantity'] != 1 else ''
42
+ was = f" (was {_g(l['grossPrice'])})" if l['priceDiscount'] else ''
43
+ disc = f" − discount {_g(ln['discount'])}" if ln.get('discount') else ''
44
+ out.append(f" {l['id']}. {ln['name']}")
45
+ out.append(f" {_g(ln['quantity'])} × {_g(ln['price'])}{per}{was}{disc} = {f(l['net'])} {cur}")
46
+ rate = f" {_g(l['rate'])}%" if l['rate'] is not None else ''
47
+ out.append(f" VAT {ln['vat']['category']} {describe('vat', ln['vat']['category'])}{rate}: {f(l['vat'])} in AED: amount {f(l['aedAmount'])}, VAT {f(l['aedVat'])}")
48
+ if inv.get('allowances') or inv.get('charges'):
49
+ out += ['', 'Document allowances and charges']
50
+ for a in inv.get('allowances') or []: out.append(f" − {f(a['amount'])} {a.get('reason') or a.get('reasonCode') or 'allowance'} (VAT {a['vat']['category']})")
51
+ for a in inv.get('charges') or []: out.append(f" + {f(a['amount'])} {a.get('reason') or a.get('reasonCode') or 'charge'} (VAT {a['vat']['category']})")
52
+ out += ['', 'VAT breakdown']
53
+ for b in c['breakdown']:
54
+ out.append(f" {b['category']:<2} {(_g(b['rate']) + '%' if b['rate'] is not None else ''):<4} taxable {f(b['taxable']):>12} VAT {f(b['tax']):>10}")
55
+ t = c['totals']
56
+ out += ['', 'Totals', f" Lines {f(t['lineExtension']):>12}"]
57
+ if t['allowances']: out.append(f" − Allowances {f(t['allowances']):>12}")
58
+ if t['charges']: out.append(f" + Charges {f(t['charges']):>12}")
59
+ out += [f" Without VAT {f(t['taxExclusive']):>12}", f" VAT {f(t['tax']):>12}", f" With VAT {f(t['taxInclusive']):>12}"]
60
+ if t['prepaid']: out.append(f" − Prepaid {f(t['prepaid']):>12}")
61
+ out.append(f" Amount due {f(t['payable']):>12} {cur}")
62
+ if cur != 'AED': out.append(f" In AED: VAT {f(c['aed']['tax'])}, total with VAT {f(c['aed']['totalInclVat'])}")
63
+ return '\n'.join(out)
64
+
65
+
66
+ def mask(v):
67
+ """'100234567800003' → '1002•••••••0003'-style: keeps enough to recognise it."""
68
+ if not v:
69
+ return v
70
+ if len(v) <= 4:
71
+ return '•' * len(v)
72
+ keep = min(4, len(v) // 4)
73
+ return v[:keep] + '•' * (len(v) - keep * 2) + v[-keep:]
74
+
75
+
76
+ def redact(inv: dict) -> dict:
77
+ """A copy with names, tax numbers, addresses, contacts and bank details masked. Amounts and codes stay."""
78
+ c = copy.deepcopy(inv)
79
+ def m(d, *keys):
80
+ for k in keys:
81
+ if d.get(k): d[k] = mask(d[k])
82
+ for p in (c.get('seller'), c.get('buyer')):
83
+ if not p: continue
84
+ m(p, 'name', 'tradingName', 'trn', 'tin')
85
+ if p.get('endpoint'): m(p['endpoint'], 'id')
86
+ if p.get('legalId'): m(p['legalId'], 'id')
87
+ if p.get('address'): m(p['address'], 'street', 'street2', 'postalCode')
88
+ if p.get('contact'): m(p['contact'], *list(p['contact']))
89
+ if c.get('payment'): m(c['payment'], 'accountId', 'accountName')
90
+ if (c.get('delivery') or {}).get('address'): m(c['delivery']['address'], 'street')
91
+ m(c, 'principalTrn', 'freeZoneBeneficiaryId')
92
+ return c
93
+
94
+
95
+ def debug_report(inv: dict, redact_data=True, logs=None, trace_id=None, error=None) -> dict:
96
+ """Everything needed to investigate a problem, in one dict. Safe for a support ticket when redact_data is True (default)."""
97
+ calc = expl = None
98
+ try:
99
+ calc = calculate(inv); expl = explain(inv, calc)
100
+ except Exception: # noqa: BLE001 - reported through issues
101
+ pass
102
+ if calc and redact_data:
103
+ calc = {**calc, 'lines': [{**l, 'line': redact({'x': l['line']})['x']} for l in calc['lines']]}
104
+ r = {'sdk': f'fajfield-einvoice {SDK_VERSION}', 'spec': SPEC, 'createdAt': datetime.now(timezone.utc).isoformat(timespec='seconds').replace('+00:00', 'Z'),
105
+ 'runtime': f'python {platform.python_version()}', 'redacted': redact_data, 'invoice': redact(inv) if redact_data else inv,
106
+ 'issues': validate(inv), 'calculation': calc, 'explanation': expl}
107
+ if trace_id: r['traceId'] = trace_id
108
+ if logs: r['logs'] = list(logs)[-200:]
109
+ if error: r['error'] = ''.join(traceback.format_exception(type(error), error, error.__traceback__)) if isinstance(error, BaseException) else str(error)
110
+ return r
111
+
112
+
113
+ def format_issues(issues: list) -> str:
114
+ if not issues:
115
+ return 'No problems found.'
116
+ return '\n'.join(f"{'✗' if i['severity'] == 'error' else '!'} {i['path'] or '(invoice)'}: {i['message']}" + (f"\n → {i['hint']}" if i.get('hint') else '') + (f" [{i['rule']}]" if i.get('rule') else '') for i in issues)