fajfield-einvoice 0.1.0__py3-none-any.whl
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.
- fajfield_einvoice/__init__.py +103 -0
- fajfield_einvoice/calc.py +85 -0
- fajfield_einvoice/debug.py +116 -0
- fajfield_einvoice/log.py +90 -0
- fajfield_einvoice/model.py +12 -0
- fajfield_einvoice/parse.py +144 -0
- fajfield_einvoice/pint_ae.py +178 -0
- fajfield_einvoice/validate.py +172 -0
- fajfield_einvoice/xmlio.py +63 -0
- fajfield_einvoice-0.1.0.dist-info/METADATA +146 -0
- fajfield_einvoice-0.1.0.dist-info/RECORD +13 -0
- fajfield_einvoice-0.1.0.dist-info/WHEEL +4 -0
- fajfield_einvoice-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -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)
|
fajfield_einvoice/log.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""Logging and tracing: every operation gets a trace id, a duration and structured fields. Plug in any sink."""
|
|
2
|
+
import json
|
|
3
|
+
import secrets
|
|
4
|
+
import sys
|
|
5
|
+
import time as _time
|
|
6
|
+
from datetime import datetime, timezone
|
|
7
|
+
|
|
8
|
+
ORDER = {'debug': 10, 'info': 20, 'warn': 30, 'error': 40, 'silent': 99}
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def console_sink(e: dict):
|
|
12
|
+
"""Human-readable lines: `12:01:22.351 INFO build.done [tr_8f2a] Built INV-1 4 ms`."""
|
|
13
|
+
head = f"{e['time'][11:23]} {e['level'].upper():<5} {e['event']}{' [' + e['traceId'] + ']' if e.get('traceId') else ''} {e['message']}{' ' + str(e['ms']) + ' ms' if e.get('ms') is not None else ''}"
|
|
14
|
+
if e.get('data'):
|
|
15
|
+
head += ' ' + json.dumps(e['data'], default=str)
|
|
16
|
+
print(head, file=sys.stderr if e['level'] in ('warn', 'error') else sys.stdout)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def json_sink(write=print):
|
|
20
|
+
"""One JSON object per line, for log collectors."""
|
|
21
|
+
return lambda e: write(json.dumps(e, default=str))
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class MemorySink:
|
|
25
|
+
"""Keeps entries in memory: handy in tests and for attaching to a support report."""
|
|
26
|
+
def __init__(self, max_entries=1000):
|
|
27
|
+
self.entries, self.max = [], max_entries
|
|
28
|
+
|
|
29
|
+
def __call__(self, e):
|
|
30
|
+
self.entries.append(e)
|
|
31
|
+
if len(self.entries) > self.max:
|
|
32
|
+
self.entries.pop(0)
|
|
33
|
+
|
|
34
|
+
def clear(self):
|
|
35
|
+
self.entries.clear()
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def memory_sink(max_entries=1000):
|
|
39
|
+
return MemorySink(max_entries)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def new_trace_id():
|
|
43
|
+
return 'tr_' + secrets.token_hex(4)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class Logger:
|
|
47
|
+
def __init__(self, level='warn', sink=None, trace_id=None):
|
|
48
|
+
self.level = level
|
|
49
|
+
self.sinks = sink if isinstance(sink, list) else ([sink] if sink else [console_sink])
|
|
50
|
+
self.trace_id = trace_id
|
|
51
|
+
|
|
52
|
+
def _emit(self, level, event, message, data=None, ms=None):
|
|
53
|
+
if ORDER[level] < ORDER[self.level]:
|
|
54
|
+
return
|
|
55
|
+
e = {'time': datetime.now(timezone.utc).isoformat(timespec='milliseconds').replace('+00:00', 'Z'), 'level': level, 'event': event, 'message': message}
|
|
56
|
+
if self.trace_id: e['traceId'] = self.trace_id
|
|
57
|
+
if ms is not None: e['ms'] = ms
|
|
58
|
+
if data: e['data'] = data
|
|
59
|
+
for s in self.sinks:
|
|
60
|
+
try:
|
|
61
|
+
s(e)
|
|
62
|
+
except Exception: # noqa: BLE001 - a broken sink must never break invoicing
|
|
63
|
+
pass
|
|
64
|
+
|
|
65
|
+
def debug(self, event, message, data=None): self._emit('debug', event, message, data)
|
|
66
|
+
def info(self, event, message, data=None): self._emit('info', event, message, data)
|
|
67
|
+
def warn(self, event, message, data=None): self._emit('warn', event, message, data)
|
|
68
|
+
def error(self, event, message, data=None): self._emit('error', event, message, data)
|
|
69
|
+
|
|
70
|
+
def child(self, trace_id):
|
|
71
|
+
"""A logger whose entries all carry this trace id."""
|
|
72
|
+
return Logger(self.level, self.sinks, trace_id)
|
|
73
|
+
|
|
74
|
+
def time(self, event, fn):
|
|
75
|
+
"""Runs fn, logging how long it took (and the error, if it raises)."""
|
|
76
|
+
t0 = _time.perf_counter()
|
|
77
|
+
try:
|
|
78
|
+
r = fn()
|
|
79
|
+
self._emit('debug', event, 'done', None, round((_time.perf_counter() - t0) * 1000, 1))
|
|
80
|
+
return r
|
|
81
|
+
except Exception as err:
|
|
82
|
+
self._emit('error', event, str(err), None, round((_time.perf_counter() - t0) * 1000, 1))
|
|
83
|
+
raise
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def create_logger(level='warn', sink=None, trace_id=None):
|
|
87
|
+
return Logger(level, sink, trace_id)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
silent_logger = Logger('silent', [lambda e: None])
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""The invoice model is plain JSON (dicts), identical to the other Fajfield SDKs: see spec/invoices for examples.
|
|
2
|
+
Keys are camelCase so the same JSON works everywhere. Code lists below."""
|
|
3
|
+
|
|
4
|
+
EMIRATES = {'AUH': 'Abu Dhabi', 'DXB': 'Dubai', 'SHJ': 'Sharjah', 'UAQ': 'Umm Al Quwain', 'FUJ': 'Fujairah', 'AJM': 'Ajman', 'RAK': 'Ras Al Khaimah'}
|
|
5
|
+
VAT_CATEGORIES = {'S': 'Standard rate', 'Z': 'Zero rated', 'E': 'Exempt from VAT', 'O': 'Out of scope of VAT', 'AE': 'Reverse charge', 'N': 'Standard rate additional VAT'}
|
|
6
|
+
INVOICE_TYPES = {'380': 'Tax invoice', '480': 'Commercial invoice (out of scope of VAT)', '381': 'Tax credit note', '81': 'Credit note related to goods or services'}
|
|
7
|
+
PAYMENT_MEANS = {'1': 'Not defined', '10': 'Cash', '30': 'Credit transfer', '48': 'Bank card', '49': 'Direct debit', '54': 'Credit card', '55': 'Debit card', '58': 'SEPA credit transfer', '68': 'Online payment service'}
|
|
8
|
+
# Cases of Article 61(1) of the UAE VAT Decree-Law, and volume discounts. Check the official code list for exact wording.
|
|
9
|
+
CREDIT_REASONS = {'DL8.61.1.A': 'Article 61(1)(a)', 'DL8.61.1.B': 'Article 61(1)(b)', 'DL8.61.1.C': 'Article 61(1)(c)', 'DL8.61.1.D': 'Article 61(1)(d)', 'DL8.61.1.E': 'Article 61(1)(e)', 'VD': 'Volume discount'}
|
|
10
|
+
LEGAL_ID_TYPES = {'TL': 'Commercial / trade licence', 'EID': 'Emirates ID', 'PAS': 'Passport', 'CD': 'Cabinet decision'}
|
|
11
|
+
REVERSE_CHARGE_TYPES = ['DL8.48.3.1', 'DL8.48.3.2', 'DL8.48.3.3', 'DL8.48.8.1', 'DL8.48.8.2', 'DL8.48.8.3']
|
|
12
|
+
FREQUENCIES = {'DLY': 'Daily', 'WKY': 'Weekly', 'Q15': 'Every 15 days', 'MTH': 'Monthly', 'Q45': 'Every 45 days', 'Q60': 'Every 60 days', 'QTR': 'Quarterly', 'YRL': 'Yearly', 'HYR': 'Half-yearly', 'OTH': 'Other'}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"""Reads a PINT AE invoice or credit note back into the invoice model, and reports where the stated totals differ from a fresh calculation."""
|
|
2
|
+
import re
|
|
3
|
+
from .calc import calculate, r2
|
|
4
|
+
from .xmlio import find, find_all, local, parse_xml, text
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def _n(s):
|
|
8
|
+
if s is None or s == '':
|
|
9
|
+
return None
|
|
10
|
+
f = float(s)
|
|
11
|
+
return int(f) if f.is_integer() else f
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _clean(d):
|
|
15
|
+
return {k: v for k, v in d.items() if v is not None}
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _txt(n):
|
|
19
|
+
return (n.text or '').strip() if n is not None else None
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def from_pint_ae(xml) -> dict:
|
|
23
|
+
"""Returns {'invoice', 'stated', 'mismatches', 'customizationId'}."""
|
|
24
|
+
doc = parse_xml(xml)
|
|
25
|
+
root = local(doc.tag)
|
|
26
|
+
if root not in ('Invoice', 'CreditNote'):
|
|
27
|
+
raise ValueError(f'Not a UBL invoice or credit note (root element is <{root}>).')
|
|
28
|
+
credit = root == 'CreditNote'
|
|
29
|
+
flags = text(doc, 'ProfileExecutionID') or '00000000'
|
|
30
|
+
keys = ['freeZone', 'deemedSupply', 'marginScheme', 'summary', 'continuous', 'disclosedAgent', 'eCommerce', 'exports']
|
|
31
|
+
transaction = {k: True for i, k in enumerate(keys) if i < len(flags) and flags[i] == '1'}
|
|
32
|
+
pm, period, dl = find(doc, 'PaymentMeans'), find(doc, 'InvoicePeriod'), find(doc, 'Delivery')
|
|
33
|
+
billing = find(doc, 'BillingReference', 'InvoiceDocumentReference')
|
|
34
|
+
|
|
35
|
+
def addr(a):
|
|
36
|
+
if a is None:
|
|
37
|
+
return None
|
|
38
|
+
return _clean({'street': text(a, 'StreetName') or '', 'street2': text(a, 'AdditionalStreetName'), 'city': text(a, 'CityName') or '',
|
|
39
|
+
'postalCode': text(a, 'PostalZone'), 'emirate': text(a, 'CountrySubentity'), 'country': text(a, 'Country', 'IdentificationCode')})
|
|
40
|
+
|
|
41
|
+
def party(p):
|
|
42
|
+
ep = find(p, 'EndpointID')
|
|
43
|
+
schemes = find_all(p, 'PartyTaxScheme')
|
|
44
|
+
trn = next((s for s in schemes if text(s, 'TaxScheme', 'ID') == 'VAT'), None)
|
|
45
|
+
tax = next((s for s in schemes if text(s, 'TaxScheme', 'ID') == 'TAX'), None)
|
|
46
|
+
le = find(p, 'PartyLegalEntity')
|
|
47
|
+
cid = find(le, 'CompanyID')
|
|
48
|
+
ep_id = _txt(ep)
|
|
49
|
+
ep_scheme = ep.get('schemeID') if ep is not None else None
|
|
50
|
+
tin = text(tax, 'CompanyID') or (ep_id if ep_scheme == '0235' and re.match(r'^1\d{9}$', ep_id or '') else None)
|
|
51
|
+
legal = None
|
|
52
|
+
if cid is not None:
|
|
53
|
+
ty = cid.get('schemeAgencyID')
|
|
54
|
+
legal = _clean({'type': ty, 'id': _txt(cid), ('passportCountry' if ty == 'PAS' else 'authority'): cid.get('schemeAgencyName')})
|
|
55
|
+
ct = find(p, 'Contact')
|
|
56
|
+
return _clean({
|
|
57
|
+
'name': text(le, 'RegistrationName') or text(p, 'PartyName', 'Name') or '',
|
|
58
|
+
'tradingName': text(p, 'PartyName', 'Name'),
|
|
59
|
+
'trn': text(trn, 'CompanyID'),
|
|
60
|
+
'tin': tin,
|
|
61
|
+
'endpoint': {'scheme': ep_scheme or '', 'id': ep_id} if ep_id and not (ep_scheme == '0235' and ep_id == tin) else None,
|
|
62
|
+
'legalId': legal,
|
|
63
|
+
'address': addr(find(p, 'PostalAddress')) or {'street': '', 'city': ''},
|
|
64
|
+
'contact': _clean({'name': text(ct, 'Name'), 'phone': text(ct, 'Telephone'), 'email': text(ct, 'ElectronicMail')}) if ct is not None else None,
|
|
65
|
+
})
|
|
66
|
+
|
|
67
|
+
def vat_of(t):
|
|
68
|
+
return _clean({'category': text(t, 'ID') or 'S', 'rate': _n(text(t, 'Percent')), 'exemptionCode': text(t, 'TaxExemptionReasonCode'), 'exemptionReason': text(t, 'TaxExemptionReason')})
|
|
69
|
+
|
|
70
|
+
def line(l):
|
|
71
|
+
item, price = find(l, 'Item'), find(l, 'Price')
|
|
72
|
+
cc = find_all(item, 'CommodityClassification')
|
|
73
|
+
pick = lambda name: next((v for v in (text(c, name) for c in cc) if v), None)
|
|
74
|
+
hs = next((x for x in (find(c, 'ItemClassificationCode') for c in cc) if x is not None and x.get('listID') in ('HS', None)), None)
|
|
75
|
+
qty = find(l, 'CreditedQuantity' if credit else 'InvoicedQuantity')
|
|
76
|
+
acs = lambda charge: [a for a in find_all(l, 'AllowanceCharge') if text(a, 'ChargeIndicator') == ('true' if charge else 'false')]
|
|
77
|
+
total = lambda xs: r2(sum(_n(text(a, 'Amount')) or 0 for a in xs))
|
|
78
|
+
disc, chg = total(acs(False)), total(acs(True))
|
|
79
|
+
reasons = lambda xs: '; '.join(r for r in (text(a, 'AllowanceChargeReason') for a in xs) if r) or None
|
|
80
|
+
pac, sid = find(price, 'AllowanceCharge'), find(item, 'StandardItemIdentification', 'ID')
|
|
81
|
+
sac = next((x for x in (find(a, 'ID') for a in find_all(item, 'AdditionalItemIdentification')) if x is not None and x.get('schemeID') == 'SAC'), None)
|
|
82
|
+
q = _n(_txt(qty))
|
|
83
|
+
p = _n(text(price, 'PriceAmount'))
|
|
84
|
+
return _clean({
|
|
85
|
+
'id': text(l, 'ID'), 'name': text(item, 'Name') or '', 'description': text(item, 'Description'),
|
|
86
|
+
'quantity': 0 if q is None else q, 'unit': qty.get('unitCode') if qty is not None else None,
|
|
87
|
+
'price': 0 if p is None else p, 'baseQuantity': _n(text(price, 'BaseQuantity')), 'grossPrice': _n(text(pac, 'BaseAmount')),
|
|
88
|
+
'discount': _int(disc) or None, 'discountReason': reasons(acs(False)) if disc else None,
|
|
89
|
+
'charge': _int(chg) or None, 'chargeReason': reasons(acs(True)) if chg else None,
|
|
90
|
+
'vat': vat_of(find(item, 'ClassifiedTaxCategory')), 'itemType': pick('CommodityCode'),
|
|
91
|
+
'hsCode': _txt(hs), 'serviceCode': _txt(sac), 'reverseChargeType': pick('NatureCode'),
|
|
92
|
+
'sellerItemId': text(item, 'SellersItemIdentification', 'ID'),
|
|
93
|
+
'standardItemId': {'scheme': sid.get('schemeID') or '', 'id': _txt(sid)} if sid is not None else None,
|
|
94
|
+
})
|
|
95
|
+
|
|
96
|
+
def ac(charge):
|
|
97
|
+
xs = [_clean({'amount': _n(text(a, 'Amount')) or 0, 'reason': text(a, 'AllowanceChargeReason'), 'reasonCode': text(a, 'AllowanceChargeReasonCode'), 'vat': vat_of(find(a, 'TaxCategory'))})
|
|
98
|
+
for a in find_all(doc, 'AllowanceCharge') if text(a, 'ChargeIndicator') == ('true' if charge else 'false')]
|
|
99
|
+
return xs or None
|
|
100
|
+
|
|
101
|
+
inv = _clean({
|
|
102
|
+
'kind': 'credit-note' if credit else 'invoice',
|
|
103
|
+
'number': text(doc, 'ID') or '', 'uuid': text(doc, 'UUID'), 'issueDate': text(doc, 'IssueDate') or '', 'issueTime': text(doc, 'IssueTime'),
|
|
104
|
+
'dueDate': text(doc, 'DueDate') or text(pm, 'PaymentDueDate'),
|
|
105
|
+
'typeCode': text(doc, 'CreditNoteTypeCode' if credit else 'InvoiceTypeCode'),
|
|
106
|
+
'currency': text(doc, 'DocumentCurrencyCode'), 'exchangeRate': _n(text(doc, 'TaxExchangeRate', 'CalculationRate')),
|
|
107
|
+
'transaction': transaction or None,
|
|
108
|
+
'freeZoneBeneficiaryId': text(doc, 'BuyerCustomerParty', 'Party', 'PartyIdentification', 'ID'),
|
|
109
|
+
'principalTrn': text(doc, 'SellerSupplierParty', 'Party', 'PartyIdentification', 'ID'),
|
|
110
|
+
'period': _clean({'start': text(period, 'StartDate') or '', 'end': text(period, 'EndDate') or '', 'frequency': text(period, 'DescriptionCode')}) if period is not None else None,
|
|
111
|
+
'seller': party(find(doc, 'AccountingSupplierParty', 'Party')),
|
|
112
|
+
'buyer': party(find(doc, 'AccountingCustomerParty', 'Party')),
|
|
113
|
+
'delivery': _clean({'date': text(dl, 'ActualDeliveryDate'), 'address': addr(find(dl, 'DeliveryLocation', 'Address')), 'partyName': text(dl, 'DeliveryParty', 'PartyName', 'Name'),
|
|
114
|
+
'incoterms': text(doc, 'DeliveryTerms', 'ID')}) if dl is not None or find(doc, 'DeliveryTerms') is not None else None,
|
|
115
|
+
'payment': _clean({'means': text(pm, 'PaymentMeansCode') or '', 'accountId': text(pm, 'PayeeFinancialAccount', 'ID'), 'accountName': text(pm, 'PayeeFinancialAccount', 'Name'),
|
|
116
|
+
'terms': text(doc, 'PaymentTerms', 'Note')}) if pm is not None else None,
|
|
117
|
+
'note': text(doc, 'Note'), 'buyerReference': text(doc, 'BuyerReference'), 'orderReference': text(doc, 'OrderReference', 'ID'),
|
|
118
|
+
'creditNote': _clean({'reason': text(doc, 'DiscrepancyResponse', 'ResponseCode'), 'invoiceNumber': text(billing, 'ID') or '', 'invoiceDate': text(billing, 'IssueDate')}) if credit or billing is not None else None,
|
|
119
|
+
'lines': [line(l) for l in find_all(doc, 'CreditNoteLine' if credit else 'InvoiceLine')],
|
|
120
|
+
'allowances': ac(False), 'charges': ac(True),
|
|
121
|
+
'prepaid': _n(text(doc, 'LegalMonetaryTotal', 'PrepaidAmount')), 'rounding': _n(text(doc, 'LegalMonetaryTotal', 'PayableRoundingAmount')),
|
|
122
|
+
})
|
|
123
|
+
lmt = find(doc, 'LegalMonetaryTotal')
|
|
124
|
+
want = inv.get('currency') or 'AED'
|
|
125
|
+
doc_tax = next((t for t in find_all(doc, 'TaxTotal') if ((find(t, 'TaxAmount').get('currencyID') if find(t, 'TaxAmount') is not None else None) or inv.get('currency')) == want), None)
|
|
126
|
+
stated = _clean({'lineExtension': _n(text(lmt, 'LineExtensionAmount')), 'taxExclusive': _n(text(lmt, 'TaxExclusiveAmount')), 'tax': _n(text(doc_tax, 'TaxAmount')),
|
|
127
|
+
'taxInclusive': _n(text(lmt, 'TaxInclusiveAmount')), 'payable': _n(text(lmt, 'PayableAmount'))})
|
|
128
|
+
mismatches = []
|
|
129
|
+
try:
|
|
130
|
+
c = calculate(inv)['totals']
|
|
131
|
+
for k, v in stated.items():
|
|
132
|
+
if abs(r2(v) - c[k]) > 0.01:
|
|
133
|
+
mismatches.append(f'{k}: the file says {v:g}, the lines add up to {c[k]:g}')
|
|
134
|
+
except Exception as e: # noqa: BLE001
|
|
135
|
+
mismatches.append(f'Could not recalculate: {e}')
|
|
136
|
+
out = {'invoice': inv, 'stated': stated, 'mismatches': mismatches}
|
|
137
|
+
cz = text(doc, 'CustomizationID')
|
|
138
|
+
if cz is not None:
|
|
139
|
+
out['customizationId'] = cz
|
|
140
|
+
return out
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _int(x):
|
|
144
|
+
return int(x) if isinstance(x, float) and x.is_integer() else x
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
"""Writes the UAE e-invoice: Peppol PINT AE, UBL 2.1 XML (invoice or credit note)."""
|
|
2
|
+
import uuid as _uuid
|
|
3
|
+
from .calc import amt, calculate, num, rate_of
|
|
4
|
+
from .xmlio import XmlWriter
|
|
5
|
+
|
|
6
|
+
PINT_AE = {
|
|
7
|
+
'customizationId': 'urn:peppol:pint:billing-1@ae-1',
|
|
8
|
+
'profileId': 'urn:peppol:bis:billing',
|
|
9
|
+
'ns': {'invoice': 'urn:oasis:names:specification:ubl:schema:xsd:Invoice-2', 'creditNote': 'urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2',
|
|
10
|
+
'cac': 'urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2', 'cbc': 'urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2'},
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def prepare(inv: dict) -> dict:
|
|
15
|
+
"""Fills in what the SDK decides itself (UUID, default type code) on a copy."""
|
|
16
|
+
credit = inv.get('kind') == 'credit-note'
|
|
17
|
+
return {**inv, 'uuid': inv.get('uuid') or str(_uuid.uuid4()), 'typeCode': inv.get('typeCode') or ('381' if credit else '380'),
|
|
18
|
+
'currency': (inv.get('currency') or 'AED').upper()}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def to_pint_ae(inp: dict, computed: dict = None) -> str:
|
|
22
|
+
inv = prepare(inp)
|
|
23
|
+
c = computed or calculate(inv)
|
|
24
|
+
cur = c['currency']
|
|
25
|
+
credit = inv.get('kind') == 'credit-note'
|
|
26
|
+
root = 'CreditNote' if credit else 'Invoice'
|
|
27
|
+
w = XmlWriter()
|
|
28
|
+
M = lambda name, x, currency=cur: w.el(name, amt(x), {'currencyID': currency})
|
|
29
|
+
g = lambda d, *ks: _get(d, *ks)
|
|
30
|
+
w.open(root, {'xmlns': PINT_AE['ns']['creditNote' if credit else 'invoice'], 'xmlns:cac': PINT_AE['ns']['cac'], 'xmlns:cbc': PINT_AE['ns']['cbc']})
|
|
31
|
+
w.el('cbc:CustomizationID', PINT_AE['customizationId']).el('cbc:ProfileID', PINT_AE['profileId']).el('cbc:ProfileExecutionID', c['transactionType'])
|
|
32
|
+
w.el('cbc:ID', inv['number']).el('cbc:UUID', inv['uuid']).el('cbc:IssueDate', inv['issueDate']).el('cbc:IssueTime', inv.get('issueTime'))
|
|
33
|
+
if not credit:
|
|
34
|
+
w.el('cbc:DueDate', inv.get('dueDate'))
|
|
35
|
+
w.el('cbc:CreditNoteTypeCode' if credit else 'cbc:InvoiceTypeCode', inv['typeCode']).el('cbc:Note', inv.get('note'))
|
|
36
|
+
w.el('cbc:DocumentCurrencyCode', cur)
|
|
37
|
+
if cur != 'AED':
|
|
38
|
+
w.el('cbc:TaxCurrencyCode', 'AED')
|
|
39
|
+
w.el('cbc:BuyerReference', inv.get('buyerReference'))
|
|
40
|
+
per = inv.get('period')
|
|
41
|
+
w.group('cac:InvoicePeriod', lambda: w.el('cbc:StartDate', per['start']).el('cbc:EndDate', per['end']).el('cbc:DescriptionCode', per.get('frequency')), bool(per))
|
|
42
|
+
cn = inv.get('creditNote') or {}
|
|
43
|
+
if credit:
|
|
44
|
+
w.group('cac:DiscrepancyResponse', lambda: w.el('cbc:ResponseCode', cn.get('reason')), bool(cn.get('reason')))
|
|
45
|
+
w.group('cac:OrderReference', lambda: w.el('cbc:ID', inv.get('orderReference')), bool(inv.get('orderReference')))
|
|
46
|
+
w.group('cac:BillingReference', lambda: w.group('cac:InvoiceDocumentReference', lambda: w.el('cbc:ID', cn['invoiceNumber']).el('cbc:IssueDate', cn.get('invoiceDate'))), bool(cn.get('invoiceNumber')))
|
|
47
|
+
if cur != 'AED':
|
|
48
|
+
w.group('cac:AdditionalDocumentReference', lambda: w.el('cbc:ID', 'AED').el('cbc:DocumentTypeCode', 'aedtotal-incl-vat').el('cbc:DocumentDescription', amt(c['aed']['totalInclVat'])))
|
|
49
|
+
w.group('cac:AccountingSupplierParty', lambda: _party(w, inv['seller'], True))
|
|
50
|
+
w.group('cac:AccountingCustomerParty', lambda: _party(w, inv['buyer'], False))
|
|
51
|
+
fz, pr = inv.get('freeZoneBeneficiaryId'), inv.get('principalTrn')
|
|
52
|
+
w.group('cac:BuyerCustomerParty', lambda: w.group('cac:Party', lambda: w.group('cac:PartyIdentification', lambda: w.el('cbc:ID', fz))), bool(fz))
|
|
53
|
+
w.group('cac:SellerSupplierParty', lambda: w.group('cac:Party', lambda: w.group('cac:PartyIdentification', lambda: w.el('cbc:ID', pr))), bool(pr))
|
|
54
|
+
d = inv.get('delivery') or {}
|
|
55
|
+
def delivery():
|
|
56
|
+
w.el('cbc:ActualDeliveryDate', d.get('date'))
|
|
57
|
+
w.group('cac:DeliveryLocation', lambda: w.group('cac:Address', lambda: _address(w, d['address'])), bool(d.get('address')))
|
|
58
|
+
w.group('cac:DeliveryParty', lambda: w.group('cac:PartyName', lambda: w.el('cbc:Name', d.get('partyName'))), bool(d.get('partyName')))
|
|
59
|
+
w.group('cac:Delivery', delivery, bool(d.get('date') or d.get('address') or d.get('partyName')))
|
|
60
|
+
w.group('cac:DeliveryTerms', lambda: w.el('cbc:ID', d.get('incoterms'), {'schemeID': 'Incoterms'}), bool(d.get('incoterms')))
|
|
61
|
+
p = inv.get('payment') or {}
|
|
62
|
+
def payment():
|
|
63
|
+
w.el('cbc:PaymentMeansCode', p['means'])
|
|
64
|
+
card = p.get('card')
|
|
65
|
+
w.group('cac:CardAccount', lambda: w.el('cbc:PrimaryAccountNumberID', 'XXXXXXXXXXXX' + card['last4']).el('cbc:NetworkID', card.get('network') or 'NA').el('cbc:HolderName', card.get('holder')), bool(card))
|
|
66
|
+
w.group('cac:PayeeFinancialAccount', lambda: w.el('cbc:ID', p['accountId']).el('cbc:Name', p.get('accountName')), bool(p.get('accountId')))
|
|
67
|
+
w.group('cac:PaymentMeans', payment, bool(p.get('means')))
|
|
68
|
+
w.group('cac:PaymentTerms', lambda: w.el('cbc:Note', p['terms']), bool(p.get('terms')))
|
|
69
|
+
for a in inv.get('allowances') or []: _allowance_charge(w, a, False, cur)
|
|
70
|
+
for a in inv.get('charges') or []: _allowance_charge(w, a, True, cur)
|
|
71
|
+
if cur != 'AED':
|
|
72
|
+
w.group('cac:TaxExchangeRate', lambda: w.el('cbc:SourceCurrencyCode', cur).el('cbc:TargetCurrencyCode', 'AED').el('cbc:CalculationRate', num(c['fx'])))
|
|
73
|
+
def tax_total():
|
|
74
|
+
M('cbc:TaxAmount', c['totals']['tax'])
|
|
75
|
+
for b in c['breakdown']:
|
|
76
|
+
def sub(b=b):
|
|
77
|
+
M('cbc:TaxableAmount', b['taxable']); M('cbc:TaxAmount', b['tax'])
|
|
78
|
+
_tax_category(w, 'cac:TaxCategory', {'category': b['category'], 'rate': b['rate']}, False)
|
|
79
|
+
w.group('cac:TaxSubtotal', sub)
|
|
80
|
+
w.group('cac:TaxTotal', tax_total)
|
|
81
|
+
if cur != 'AED':
|
|
82
|
+
w.group('cac:TaxTotal', lambda: M('cbc:TaxAmount', c['aed']['tax'], 'AED'))
|
|
83
|
+
t = c['totals']
|
|
84
|
+
def lmt():
|
|
85
|
+
M('cbc:LineExtensionAmount', t['lineExtension']); M('cbc:TaxExclusiveAmount', t['taxExclusive']); M('cbc:TaxInclusiveAmount', t['taxInclusive'])
|
|
86
|
+
if inv.get('allowances'): M('cbc:AllowanceTotalAmount', t['allowances'])
|
|
87
|
+
if inv.get('charges'): M('cbc:ChargeTotalAmount', t['charges'])
|
|
88
|
+
if t['prepaid']: M('cbc:PrepaidAmount', t['prepaid'])
|
|
89
|
+
if t['rounding']: M('cbc:PayableRoundingAmount', t['rounding'])
|
|
90
|
+
M('cbc:PayableAmount', t['payable'])
|
|
91
|
+
w.group('cac:LegalMonetaryTotal', lmt)
|
|
92
|
+
for l in c['lines']:
|
|
93
|
+
ln = l['line']
|
|
94
|
+
def line(l=l, ln=ln):
|
|
95
|
+
w.el('cbc:ID', l['id'])
|
|
96
|
+
w.el('cbc:CreditedQuantity' if credit else 'cbc:InvoicedQuantity', num(ln['quantity']), {'unitCode': ln.get('unit') or 'H87'})
|
|
97
|
+
M('cbc:LineExtensionAmount', l['net'])
|
|
98
|
+
if ln.get('discount'):
|
|
99
|
+
w.group('cac:AllowanceCharge', lambda: (w.el('cbc:ChargeIndicator', 'false').el('cbc:AllowanceChargeReasonCode', '95').el('cbc:AllowanceChargeReason', ln.get('discountReason') or 'Discount'), M('cbc:Amount', ln['discount'])))
|
|
100
|
+
if ln.get('charge'):
|
|
101
|
+
w.group('cac:AllowanceCharge', lambda: (w.el('cbc:ChargeIndicator', 'true').el('cbc:AllowanceChargeReason', ln.get('chargeReason') or 'Charge'), M('cbc:Amount', ln['charge'])))
|
|
102
|
+
def item():
|
|
103
|
+
w.el('cbc:Description', ln.get('description') or ln['name']).el('cbc:Name', ln['name'])
|
|
104
|
+
w.group('cac:SellersItemIdentification', lambda: w.el('cbc:ID', ln.get('sellerItemId')), bool(ln.get('sellerItemId')))
|
|
105
|
+
sid = ln.get('standardItemId')
|
|
106
|
+
w.group('cac:StandardItemIdentification', lambda: w.el('cbc:ID', sid['id'], {'schemeID': sid['scheme']}), bool(sid))
|
|
107
|
+
w.group('cac:AdditionalItemIdentification', lambda: w.el('cbc:ID', ln.get('serviceCode'), {'schemeID': 'SAC'}), bool(ln.get('serviceCode')))
|
|
108
|
+
w.group('cac:CommodityClassification', lambda: w.el('cbc:NatureCode', ln.get('reverseChargeType')).el('cbc:CommodityCode', ln.get('itemType')).el('cbc:ItemClassificationCode', ln.get('hsCode'), {'listID': 'HS'}),
|
|
109
|
+
bool(ln.get('itemType') or ln.get('hsCode') or ln.get('reverseChargeType')))
|
|
110
|
+
_tax_category(w, 'cac:ClassifiedTaxCategory', ln['vat'], True)
|
|
111
|
+
w.group('cac:Item', item)
|
|
112
|
+
def price():
|
|
113
|
+
M('cbc:PriceAmount', ln['price'])
|
|
114
|
+
w.el('cbc:BaseQuantity', num(l['baseQuantity']), {'unitCode': ln.get('unit') or 'H87'})
|
|
115
|
+
w.group('cac:AllowanceCharge', lambda: (w.el('cbc:ChargeIndicator', 'false'), M('cbc:Amount', l['priceDiscount']), M('cbc:BaseAmount', l['grossPrice'])))
|
|
116
|
+
w.group('cac:Price', price)
|
|
117
|
+
def ext():
|
|
118
|
+
M('cbc:Amount', l['aedAmount'], 'AED')
|
|
119
|
+
if l['aedVat'] is not None:
|
|
120
|
+
w.group('cac:TaxTotal', lambda: M('cbc:TaxAmount', l['aedVat'], 'AED'))
|
|
121
|
+
w.group('cac:ItemPriceExtension', ext)
|
|
122
|
+
w.group('cac:CreditNoteLine' if credit else 'cac:InvoiceLine', line)
|
|
123
|
+
w.close(root)
|
|
124
|
+
return str(w)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _get(d, *ks):
|
|
128
|
+
for k in ks:
|
|
129
|
+
d = (d or {}).get(k)
|
|
130
|
+
return d
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _party(w, p, seller):
|
|
134
|
+
def body():
|
|
135
|
+
ep = p.get('endpoint') or ({'scheme': '0235', 'id': p['tin']} if p.get('tin') else None)
|
|
136
|
+
w.el('cbc:EndpointID', ep and ep['id'], {'schemeID': ep and ep['scheme']})
|
|
137
|
+
w.group('cac:PartyName', lambda: w.el('cbc:Name', p.get('tradingName')), bool(p.get('tradingName')))
|
|
138
|
+
w.group('cac:PostalAddress', lambda: _address(w, p['address']))
|
|
139
|
+
w.group('cac:PartyTaxScheme', lambda: (w.el('cbc:CompanyID', p.get('trn')), w.group('cac:TaxScheme', lambda: w.el('cbc:ID', 'VAT'))), bool(p.get('trn')))
|
|
140
|
+
w.group('cac:PartyTaxScheme', lambda: (w.el('cbc:CompanyID', p.get('tin')), w.group('cac:TaxScheme', lambda: w.el('cbc:ID', 'TAX'))), seller and not p.get('trn') and bool(p.get('tin')))
|
|
141
|
+
def legal():
|
|
142
|
+
w.el('cbc:RegistrationName', p['name'])
|
|
143
|
+
l = p.get('legalId')
|
|
144
|
+
if l:
|
|
145
|
+
w.el('cbc:CompanyID', l['id'], {'schemeAgencyID': l.get('type'), 'schemeAgencyName': l.get('passportCountry') if l.get('type') == 'PAS' else l.get('authority')})
|
|
146
|
+
w.group('cac:PartyLegalEntity', legal)
|
|
147
|
+
ct = p.get('contact') or {}
|
|
148
|
+
w.group('cac:Contact', lambda: w.el('cbc:Name', ct.get('name')).el('cbc:Telephone', ct.get('phone')).el('cbc:ElectronicMail', ct.get('email')), bool(ct.get('name') or ct.get('phone') or ct.get('email')))
|
|
149
|
+
w.group('cac:Party', body)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _address(w, a):
|
|
153
|
+
w.el('cbc:StreetName', a.get('street')).el('cbc:AdditionalStreetName', a.get('street2')).el('cbc:CityName', a.get('city')).el('cbc:PostalZone', a.get('postalCode')).el('cbc:CountrySubentity', a.get('emirate'))
|
|
154
|
+
w.group('cac:Country', lambda: w.el('cbc:IdentificationCode', (a.get('country') or 'AE').upper()))
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _tax_category(w, tag, v, with_exemption):
|
|
158
|
+
rate = rate_of(v)
|
|
159
|
+
def body():
|
|
160
|
+
w.el('cbc:ID', v['category']).el('cbc:Percent', None if rate is None else num(rate))
|
|
161
|
+
if with_exemption and v['category'] == 'E':
|
|
162
|
+
w.el('cbc:TaxExemptionReasonCode', v.get('exemptionCode')).el('cbc:TaxExemptionReason', v.get('exemptionReason'))
|
|
163
|
+
w.group('cac:TaxScheme', lambda: w.el('cbc:ID', 'VAT'))
|
|
164
|
+
w.group(tag, body)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _allowance_charge(w, a, charge, cur):
|
|
168
|
+
def body():
|
|
169
|
+
w.el('cbc:ChargeIndicator', 'true' if charge else 'false').el('cbc:AllowanceChargeReasonCode', a.get('reasonCode')).el('cbc:AllowanceChargeReason', a.get('reason'))
|
|
170
|
+
w.el('cbc:Amount', amt(a['amount']), {'currencyID': cur})
|
|
171
|
+
v, rate = a['vat'], rate_of(a['vat'])
|
|
172
|
+
def cat():
|
|
173
|
+
w.el('cbc:ID', v['category']).el('cbc:Percent', ('0' if v['category'] == 'E' else None) if rate is None else num(rate))
|
|
174
|
+
if v['category'] == 'E':
|
|
175
|
+
w.el('cbc:TaxExemptionReasonCode', v.get('exemptionCode')).el('cbc:TaxExemptionReason', v.get('exemptionReason'))
|
|
176
|
+
w.group('cac:TaxScheme', lambda: w.el('cbc:ID', 'VAT'))
|
|
177
|
+
w.group('cac:TaxCategory', cat)
|
|
178
|
+
w.group('cac:AllowanceCharge', body)
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
"""Checks an invoice against the UAE rules and explains every problem: field, what is wrong, how to fix it, official rule."""
|
|
2
|
+
import re
|
|
3
|
+
from datetime import date
|
|
4
|
+
from .calc import calculate, rate_of
|
|
5
|
+
from .model import CREDIT_REASONS, EMIRATES, INVOICE_TYPES, LEGAL_ID_TYPES, REVERSE_CHARGE_TYPES, VAT_CATEGORIES
|
|
6
|
+
|
|
7
|
+
TRN = re.compile(r'^1\d{12}03$')
|
|
8
|
+
TIN = re.compile(r'^1\d{9}$')
|
|
9
|
+
TRN_HINT = 'A TRN has 15 digits, starts with 1 and ends with 03, for example 100234567800003.'
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _valid_date(s):
|
|
13
|
+
if not isinstance(s, str) or not re.match(r'^\d{4}-\d{2}-\d{2}$', s):
|
|
14
|
+
return False
|
|
15
|
+
try:
|
|
16
|
+
date.fromisoformat(s); return True
|
|
17
|
+
except ValueError:
|
|
18
|
+
return False
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _endpoint(p):
|
|
22
|
+
if not p:
|
|
23
|
+
return None
|
|
24
|
+
return p.get('endpoint') or ({'scheme': '0235', 'id': p['tin']} if p.get('tin') else None)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def validate(inv: dict) -> list:
|
|
28
|
+
out = []
|
|
29
|
+
def issue(sev, code, path, message, hint=None, rule=None):
|
|
30
|
+
i = {'severity': sev, 'code': code, 'path': path, 'message': message}
|
|
31
|
+
if hint: i['hint'] = hint
|
|
32
|
+
if rule: i['rule'] = rule
|
|
33
|
+
out.append(i)
|
|
34
|
+
err = lambda *a: issue('error', *a)
|
|
35
|
+
warn = lambda *a: issue('warning', *a)
|
|
36
|
+
if not isinstance(inv, dict):
|
|
37
|
+
err('invoice.missing', '', 'No invoice was given.'); return out
|
|
38
|
+
credit = inv.get('kind') == 'credit-note'
|
|
39
|
+
typ = inv.get('typeCode') or ('381' if credit else '380')
|
|
40
|
+
out_of_scope = typ in ('480', '81')
|
|
41
|
+
t = inv.get('transaction') or {}
|
|
42
|
+
if not (inv.get('number') or '').strip(): err('number.missing', 'number', 'The invoice number is missing.')
|
|
43
|
+
if not _valid_date(inv.get('issueDate')): err('issueDate.format', 'issueDate', f"The issue date \"{inv.get('issueDate') or ''}\" is not a valid date.", "Use 'YYYY-MM-DD', for example '2026-11-30'.")
|
|
44
|
+
if inv.get('dueDate') and not _valid_date(inv['dueDate']): err('dueDate.format', 'dueDate', f"The due date \"{inv['dueDate']}\" is not a valid date.", "Use 'YYYY-MM-DD'.")
|
|
45
|
+
if inv.get('dueDate') and _valid_date(inv.get('issueDate')) and _valid_date(inv['dueDate']) and inv['dueDate'] < inv['issueDate']: warn('dueDate.beforeIssue', 'dueDate', 'The due date is before the issue date.')
|
|
46
|
+
if typ not in INVOICE_TYPES: err('typeCode.unknown', 'typeCode', f'Type code "{typ}" is not used in the UAE.', f"Use one of: {', '.join(INVOICE_TYPES)}.")
|
|
47
|
+
if credit and typ not in ('381', '81'): err('typeCode.notCredit', 'typeCode', f'A credit note cannot use type code {typ}.', "Use '381' (tax credit note) or '81'.")
|
|
48
|
+
if not credit and typ in ('381', '81'): err('typeCode.credit', 'typeCode', f'Type code {typ} is a credit note.', "Set kind: 'credit-note'.")
|
|
49
|
+
cur = (inv.get('currency') or 'AED').upper()
|
|
50
|
+
if not re.match(r'^[A-Z]{3}$', cur): err('currency.format', 'currency', f"\"{inv.get('currency')}\" is not a currency code.", "Use a 3-letter ISO code such as 'AED' or 'USD'.")
|
|
51
|
+
if cur != 'AED':
|
|
52
|
+
fx = inv.get('exchangeRate')
|
|
53
|
+
if not (isinstance(fx, (int, float)) and fx > 0): err('exchangeRate.missing', 'exchangeRate', f'The invoice is in {cur}, so the exchange rate to AED is required.', 'Set exchangeRate: how many AED one unit of the currency is worth, e.g. 3.6725 for USD.', 'ibr-159-ae')
|
|
54
|
+
elif not re.match(r'^\d+(\.\d{1,6})?$', repr(float(fx)).rstrip('0').rstrip('.') if not float(fx).is_integer() else str(int(fx))): err('exchangeRate.decimals', 'exchangeRate', 'The exchange rate has more than 6 decimal places.', None, 'ibr-002-ae')
|
|
55
|
+
cn = inv.get('creditNote') or {}
|
|
56
|
+
if credit:
|
|
57
|
+
reasons = ', '.join(CREDIT_REASONS)
|
|
58
|
+
if not cn.get('reason'): err('creditNote.reason.missing', 'creditNote.reason', 'A credit note needs a reason.', f'Use one of: {reasons}.', 'ibr-055-ae')
|
|
59
|
+
elif cn['reason'] not in CREDIT_REASONS: err('creditNote.reason.unknown', 'creditNote.reason', f"\"{cn['reason']}\" is not a credit note reason code.", f'Use one of: {reasons}.', 'ibr-001-ae')
|
|
60
|
+
if not cn.get('invoiceNumber'): warn('creditNote.invoice.missing', 'creditNote.invoiceNumber', 'The credit note does not say which invoice it corrects.')
|
|
61
|
+
if t.get('summary') or t.get('deemedSupply') or t.get('marginScheme'): err('transaction.credit', 'transaction', 'A credit note cannot be a summary invoice, deemed supply or margin scheme.', None, 'ibr-157-ae')
|
|
62
|
+
if t.get('freeZone') and not inv.get('freeZoneBeneficiaryId'): err('freeZone.beneficiary', 'freeZoneBeneficiaryId', 'A free zone supply needs the beneficiary ID.', None, 'ibr-007-ae')
|
|
63
|
+
if t.get('disclosedAgent'):
|
|
64
|
+
pt = inv.get('principalTrn')
|
|
65
|
+
if not pt: err('disclosedAgent.principal', 'principalTrn', "Disclosed agent billing needs the principal's TRN.", None, 'ibr-137-ae')
|
|
66
|
+
elif pt == (inv.get('seller') or {}).get('trn'): err('disclosedAgent.sameTrn', 'principalTrn', "The principal's TRN must be different from the seller's TRN.", None, 'ibr-176-ae')
|
|
67
|
+
elif not TRN.match(pt): err('principalTrn.format', 'principalTrn', f'The principal\'s TRN "{pt}" is not valid.', TRN_HINT, 'ibr-132-ae')
|
|
68
|
+
per = inv.get('period')
|
|
69
|
+
if t.get('summary') and not per: err('summary.period', 'period', 'A summary invoice needs the invoicing period (start and end dates).', None, 'ibr-138-ae')
|
|
70
|
+
if per:
|
|
71
|
+
if not _valid_date(per.get('start')) or not _valid_date(per.get('end')): err('period.format', 'period', 'The invoicing period dates are not valid.', "Use 'YYYY-MM-DD'.")
|
|
72
|
+
if per.get('frequency') == 'OTH' and not inv.get('note'): err('period.frequency.note', 'note', "Billing frequency is 'Other', so explain it in the note.", None, 'ibr-160-ae')
|
|
73
|
+
|
|
74
|
+
def address(a, path, rule=None):
|
|
75
|
+
if not (a.get('street') or '').strip(): err('address.street.missing', f'{path}.street', f'Address line 1 is missing ({path}).', None, rule)
|
|
76
|
+
if not (a.get('city') or '').strip(): err('address.city.missing', f'{path}.city', f'The city is missing ({path}).', None, rule)
|
|
77
|
+
country = (a.get('country') or 'AE').upper()
|
|
78
|
+
if not re.match(r'^[A-Z]{2}$', country): err('address.country.format', f'{path}.country', f"\"{a.get('country')}\" is not a 2-letter country code.")
|
|
79
|
+
em = a.get('emirate')
|
|
80
|
+
if not em:
|
|
81
|
+
err('address.emirate.missing', f'{path}.emirate', f'The emirate is missing ({path}).' if country == 'AE' else f'The state or region is missing ({path}).',
|
|
82
|
+
f"Use one of: {', '.join(EMIRATES)}." if country == 'AE' else None, rule)
|
|
83
|
+
elif country == 'AE' and em not in EMIRATES:
|
|
84
|
+
err('address.emirate.unknown', f'{path}.emirate', f'"{em}" is not an emirate code.', 'Use one of: ' + ', '.join(f'{k} ({v})' for k, v in EMIRATES.items()) + '.', 'ibr-128-ae')
|
|
85
|
+
|
|
86
|
+
def party(p, who, seller):
|
|
87
|
+
if not p:
|
|
88
|
+
err(f'{who}.missing', who, f'The {who} is missing.'); return
|
|
89
|
+
if not (p.get('name') or '').strip(): err(f'{who}.name.missing', f'{who}.name', f"The {who}'s legal name is missing.")
|
|
90
|
+
if p.get('trn') and not TRN.match(p['trn']): err(f'{who}.trn.format', f'{who}.trn', f"The {who}'s TRN \"{p['trn']}\" is not valid.", TRN_HINT, 'ibr-132-ae')
|
|
91
|
+
if p.get('tin') and not TIN.match(p['tin']): err(f'{who}.tin.format', f'{who}.tin', f"The {who}'s TIN \"{p['tin']}\" is not valid.", 'A TIN has 10 digits and starts with 1. It is usually the first 10 digits of the TRN.', 'ibr-148-ae')
|
|
92
|
+
if p.get('trn') and p.get('tin') and TRN.match(p['trn']) and TIN.match(p['tin']) and not p['trn'].startswith(p['tin']): warn(f'{who}.tin.mismatch', f'{who}.tin', f"The {who}'s TIN is not the start of its TRN. Check both numbers.")
|
|
93
|
+
ep = _endpoint(p)
|
|
94
|
+
if not ep: err(f'{who}.endpoint.missing', f'{who}.tin', f'The {who} needs a Peppol address: give its TIN, or set endpoint.',
|
|
95
|
+
"For a buyer abroad without a UAE TIN, the official samples use endpoint { scheme: '0235', id: '9900000099' }." if who == 'buyer' else None)
|
|
96
|
+
if seller and ep and ep['scheme'] == '0235' and not p.get('legalId'): err('seller.legalId.missing', 'seller.legalId', "The seller's legal registration (for example the trade licence) is required.", None, 'ibr-150-ae')
|
|
97
|
+
l = p.get('legalId')
|
|
98
|
+
if l:
|
|
99
|
+
lp, uae = f'{who}.legalId', bool(ep and ep['scheme'] == '0235')
|
|
100
|
+
if uae and not l.get('type'): err(f'{who}.legalId.type.missing', f'{lp}.type', f"The type of the {who}'s legal registration is required.", 'Use one of: ' + ', '.join(f'{k} ({v})' for k, v in LEGAL_ID_TYPES.items()) + '.', 'ibr-181-ae' if seller else 'ibr-180-ae')
|
|
101
|
+
if l.get('type') and l['type'] not in LEGAL_ID_TYPES: err(f'{who}.legalId.type', f'{lp}.type', f"\"{l['type']}\" is not a legal registration type.", f"Use one of: {', '.join(LEGAL_ID_TYPES)}.", 'ibr-173-ae' if seller else 'ibr-183-ae')
|
|
102
|
+
if not (l.get('id') or '').strip(): err(f'{who}.legalId.id', f'{lp}.id', f"The {who}'s legal registration number is missing.")
|
|
103
|
+
if uae and l.get('type') == 'TL' and not l.get('authority'): err(f'{who}.legalId.authority', f'{lp}.authority', 'For a trade licence, the issuing authority is required.', "For example 'Dubai Department of Economy and Tourism'.", 'ibr-172-ae' if seller else 'ibr-101-ae')
|
|
104
|
+
if l.get('type') == 'PAS' and not re.match(r'^[A-Z]{2}$', l.get('passportCountry') or ''): err(f'{who}.legalId.passportCountry', f'{lp}.passportCountry', 'For a passport, the issuing country is required as a 2-letter code.', "For example 'IN' or 'GB'.", 'ibr-012-ae' if seller else 'ibr-010-ae')
|
|
105
|
+
if not p.get('address'): err(f'{who}.address.missing', f'{who}.address', f"The {who}'s address is missing.", None, 'ibr-143-ae' if seller else 'ibr-144-ae')
|
|
106
|
+
else: address(p['address'], f'{who}.address', 'ibr-143-ae' if seller else 'ibr-144-ae')
|
|
107
|
+
|
|
108
|
+
seller, buyer = inv.get('seller'), inv.get('buyer')
|
|
109
|
+
party(seller, 'seller', True); party(buyer, 'buyer', False)
|
|
110
|
+
if seller and not out_of_scope and not seller.get('trn'): err('seller.trn.missing', 'seller.trn', "The seller's TRN is required on a tax invoice.", TRN_HINT, 'ibr-134-ae')
|
|
111
|
+
if seller and not seller.get('trn') and not seller.get('tin'): err('seller.taxId.missing', 'seller', 'The seller needs a TRN or a TIN.', None, 'ibr-177-ae')
|
|
112
|
+
bep = _endpoint(buyer)
|
|
113
|
+
if buyer and bep and bep['scheme'] == '0235' and not re.match(r'^[19]\d{9}$', bep['id']) and not buyer.get('legalId'): err('buyer.legalId.missing', 'buyer.legalId', "The buyer's legal registration (for example the trade licence) is required.", None, 'ibr-149-ae')
|
|
114
|
+
if buyer and out_of_scope and not buyer.get('legalId'): err('buyer.legalId.outOfScope', 'buyer.legalId', "This document type needs the buyer's legal registration.", None, 'ibr-136-ae')
|
|
115
|
+
if buyer and not t.get('exports') and bep and bep['scheme'] == '0235' and not re.match(r'^1\d{9}$', bep['id']) and not buyer.get('trn'): err('buyer.trn.required', 'buyer.trn', "The buyer's TRN is required unless the buyer has a UAE TIN as its Peppol address, or this is an export.", None, 'ibr-135-ae')
|
|
116
|
+
pay = inv.get('payment') or {}
|
|
117
|
+
if not credit and not out_of_scope and not t.get('deemedSupply') and not pay.get('means'): err('payment.means.missing', 'payment.means', 'How the buyer pays is missing.', "Set payment.means, e.g. '30' credit transfer, '10' cash, '55' debit card.", 'ibr-191-ae')
|
|
118
|
+
if pay.get('means') == '30' and not pay.get('accountId'): err('payment.account.missing', 'payment.accountId', 'For a credit transfer, the bank account (IBAN) to pay into is required.', None, 'ibr-192-ae')
|
|
119
|
+
dl = inv.get('delivery')
|
|
120
|
+
if t.get('exports') and dl and not ((dl.get('address') or {}).get('street') and dl['address'].get('city') and dl['address'].get('emirate')): err('delivery.address.export', 'delivery.address', 'For an export, the delivery address needs street, city and state or emirate.', None, 'ibr-152-ae')
|
|
121
|
+
if dl and dl.get('address'): address(dl['address'], 'delivery.address')
|
|
122
|
+
|
|
123
|
+
def vat(v, path, label, exempt_rule):
|
|
124
|
+
rate = rate_of(v)
|
|
125
|
+
if v['category'] == 'S' and rate != 5: err('vat.rate.standard', f'{path}.rate', f'{label}: the standard VAT rate in the UAE is 5%, not {rate:g}%.', None, 'ibr-190-ae')
|
|
126
|
+
if v['category'] == 'Z' and rate != 0: err('vat.rate.zero', f'{path}.rate', f'{label}: a zero-rated supply must have rate 0.', None, 'ibr-120-ae')
|
|
127
|
+
if v['category'] == 'E' and not v.get('exemptionCode'): err('vat.exemption.missing', f'{path}.exemptionCode', f'{label} is exempt, so the exemption reason code is required.', "For example 'DL8.46.2'.", exempt_rule)
|
|
128
|
+
|
|
129
|
+
lines = inv.get('lines') or []
|
|
130
|
+
if not lines: err('lines.missing', 'lines', 'The invoice has no lines.')
|
|
131
|
+
cats = set()
|
|
132
|
+
rc_types = ', '.join(REVERSE_CHARGE_TYPES)
|
|
133
|
+
for i, l in enumerate(lines):
|
|
134
|
+
p, n = f'lines[{i}]', i + 1
|
|
135
|
+
if not (l.get('name') or '').strip(): err('line.name.missing', f'{p}.name', f'Line {n} has no item name.')
|
|
136
|
+
q = l.get('quantity')
|
|
137
|
+
if not isinstance(q, (int, float)) or isinstance(q, bool): err('line.quantity.invalid', f'{p}.quantity', f'Line {n}: the quantity is not a number.')
|
|
138
|
+
pr = l.get('price')
|
|
139
|
+
if not isinstance(pr, (int, float)) or pr < 0: err('line.price.invalid', f'{p}.price', f'Line {n}: the price must be a number of 0 or more.')
|
|
140
|
+
if l.get('baseQuantity') is not None and not l['baseQuantity'] > 0: err('line.baseQuantity.invalid', f'{p}.baseQuantity', f'Line {n}: the base quantity must be more than 0.')
|
|
141
|
+
if l.get('grossPrice') is not None and isinstance(pr, (int, float)) and l['grossPrice'] < pr: err('line.grossPrice.low', f'{p}.grossPrice', f'Line {n}: the price before discount is lower than the price.')
|
|
142
|
+
v = l.get('vat') or {}
|
|
143
|
+
if v.get('category') not in VAT_CATEGORIES:
|
|
144
|
+
err('line.vat.category', f'{p}.vat.category', f"Line {n}: unknown VAT category \"{v.get('category') or ''}\".", f"Use one of: {', '.join(VAT_CATEGORIES)}.", 'ibr-139-ae'); continue
|
|
145
|
+
cats.add(v['category'])
|
|
146
|
+
vat(v, f'{p}.vat', f'Line {n}', 'ibr-167-ae')
|
|
147
|
+
if v['category'] == 'AE':
|
|
148
|
+
rt = l.get('reverseChargeType')
|
|
149
|
+
if not rt: err('line.reverseCharge.type', f'{p}.reverseChargeType', f'Line {n} is reverse charge, so the type of goods or services is required.', f'Use one of: {rc_types}.', 'ibr-166-ae')
|
|
150
|
+
elif rt not in REVERSE_CHARGE_TYPES: err('line.reverseCharge.unknown', f'{p}.reverseChargeType', f'Line {n}: "{rt}" is not a reverse charge type.', f'Use one of: {rc_types}.', 'ibr-006-ae')
|
|
151
|
+
if (l.get('standardItemId') or {}).get('scheme') != '0160': err('line.reverseCharge.gtin', f'{p}.standardItemId', f"Line {n} is reverse charge, so the item's standard identifier (GTIN, scheme 0160) is required.", None, 'ibr-174-ae')
|
|
152
|
+
if buyer and not buyer.get('trn'): err('buyer.trn.reverseCharge', 'buyer.trn', "Reverse charge lines need the buyer's TRN.", None, 'ibr-103-ae')
|
|
153
|
+
if l.get('itemType') in ('G', 'B') and not l.get('hsCode'): err('line.hsCode.missing', f'{p}.hsCode', f'Line {n} is goods, so the HS code is required.', None, 'ibr-184-ae')
|
|
154
|
+
if not l.get('itemType'): warn('line.itemType.missing', f'{p}.itemType', f"Line {n}: say whether it is goods ('G'), services ('S') or both ('B').")
|
|
155
|
+
if l.get('hsCode') and not re.match(r'^\d+$', l['hsCode']): warn('line.hsCode.format', f'{p}.hsCode', f"Line {n}: the HS code \"{l['hsCode']}\" should be digits only.")
|
|
156
|
+
if typ in ('380', '381') and cats and all(c in ('E', 'O') for c in cats): err('lines.onlyExempt', 'lines', 'A tax invoice or tax credit note needs at least one line that is not exempt or out of scope.', "If nothing on it is taxable, use typeCode '480' (commercial invoice).", 'ibr-151-ae')
|
|
157
|
+
|
|
158
|
+
def ac(a, path, what, n_rule, e_rule):
|
|
159
|
+
if not (isinstance(a.get('amount'), (int, float)) and a['amount'] > 0): err(f'{what}.amount', f'{path}.amount', f'The {what} amount must be more than 0.')
|
|
160
|
+
v = a.get('vat') or {}
|
|
161
|
+
if v.get('category') not in VAT_CATEGORIES:
|
|
162
|
+
err(f'{what}.vat', f'{path}.vat.category', f'The {what} needs a VAT category.', None, 'ibr-139-ae'); return
|
|
163
|
+
if v['category'] == 'N': err(f'{what}.vat.additional', f'{path}.vat.category', f"A document {what} cannot use 'Standard rate additional VAT'.", None, n_rule)
|
|
164
|
+
vat(v, f'{path}.vat', f'The {what}', e_rule)
|
|
165
|
+
if not a.get('reason') and not a.get('reasonCode'): warn(f'{what}.reason', f'{path}.reason', f'Say why the {what} applies.')
|
|
166
|
+
for i, a in enumerate(inv.get('allowances') or []): ac(a, f'allowances[{i}]', 'allowance', 'ibr-115-ae', 'ibr-168-ae')
|
|
167
|
+
for i, a in enumerate(inv.get('charges') or []): ac(a, f'charges[{i}]', 'charge', 'ibr-114-ae', 'ibr-169-ae')
|
|
168
|
+
if not any(x['severity'] == 'error' for x in out):
|
|
169
|
+
c = calculate(inv)
|
|
170
|
+
if not credit and not t.get('deemedSupply') and c['totals']['payable'] > 0 and not inv.get('dueDate'): err('dueDate.missing', 'dueDate', 'An amount is due, so the payment due date is required.', None, 'ibr-127-ae')
|
|
171
|
+
if c['totals']['payable'] < 0: warn('totals.negative', 'lines', f"The amount due is negative ({c['totals']['payable']:g}). Use a credit note instead.")
|
|
172
|
+
return out
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""A tiny XML writer and reader, enough for UBL. Standard library only."""
|
|
2
|
+
import xml.etree.ElementTree as ET
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def esc(s: str) -> str:
|
|
6
|
+
return str(s).replace('&', '&').replace('<', '<').replace('>', '>').replace('"', '"')
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class XmlWriter:
|
|
10
|
+
def __init__(self):
|
|
11
|
+
self.out = ['<?xml version="1.0" encoding="UTF-8"?>']
|
|
12
|
+
self.depth = 0
|
|
13
|
+
|
|
14
|
+
def _attrs(self, a):
|
|
15
|
+
return ''.join(f' {k}="{esc(v)}"' for k, v in (a or {}).items() if v not in (None, ''))
|
|
16
|
+
|
|
17
|
+
def open(self, name, a=None):
|
|
18
|
+
self.out.append(f"{' ' * self.depth}<{name}{self._attrs(a)}>"); self.depth += 1; return self
|
|
19
|
+
|
|
20
|
+
def close(self, name):
|
|
21
|
+
self.depth -= 1; self.out.append(f"{' ' * self.depth}</{name}>"); return self
|
|
22
|
+
|
|
23
|
+
def el(self, name, value, a=None):
|
|
24
|
+
if value is None or value == '':
|
|
25
|
+
return self
|
|
26
|
+
self.out.append(f"{' ' * self.depth}<{name}{self._attrs(a)}>{esc(value)}</{name}>"); return self
|
|
27
|
+
|
|
28
|
+
def group(self, name, body, when=True, a=None):
|
|
29
|
+
if not when:
|
|
30
|
+
return self
|
|
31
|
+
self.open(name, a); body(); return self.close(name)
|
|
32
|
+
|
|
33
|
+
def __str__(self):
|
|
34
|
+
return '\n'.join(self.out) + '\n'
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def local(tag: str) -> str:
|
|
38
|
+
return tag.split('}', 1)[1] if '}' in tag else tag
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def parse_xml(src: str):
|
|
42
|
+
try:
|
|
43
|
+
return ET.fromstring(src.encode('utf-8') if isinstance(src, str) else src)
|
|
44
|
+
except ET.ParseError as e:
|
|
45
|
+
raise ValueError(f'XML error at line {e.position[0]}: {e}') from None
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def find(n, *path):
|
|
49
|
+
cur = n
|
|
50
|
+
for p in path:
|
|
51
|
+
if cur is None:
|
|
52
|
+
return None
|
|
53
|
+
cur = next((c for c in cur if local(c.tag) == p), None)
|
|
54
|
+
return cur
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def find_all(n, name):
|
|
58
|
+
return [] if n is None else [c for c in n if local(c.tag) == name]
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def text(n, *path):
|
|
62
|
+
f = find(n, *path)
|
|
63
|
+
return (f.text or '').strip() if f is not None else None
|
|
@@ -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,13 @@
|
|
|
1
|
+
fajfield_einvoice/__init__.py,sha256=1LiZ2vv-gXFCbgp3kHlDa3FwcyFDeGHWqdhTi3BJTtk,5103
|
|
2
|
+
fajfield_einvoice/calc.py,sha256=DALgMLiX3YxpkhsuCg9Vpg0ir6ikAbVxJR9ALGjtV_A,3812
|
|
3
|
+
fajfield_einvoice/debug.py,sha256=HE2tKEhXvajsO1Mgd-AB72Z3mzKNrhfIs0AQYAROLIY,6371
|
|
4
|
+
fajfield_einvoice/log.py,sha256=ZiPoHUBMEvfYoQnLZpsoPaRCgSBW6rS8fgR34GoHgFQ,3371
|
|
5
|
+
fajfield_einvoice/model.py,sha256=qaf2GqmjSdUn8elvpe1IoOHOUqC9zBcjfR3e8wGc41M,1675
|
|
6
|
+
fajfield_einvoice/parse.py,sha256=ASqZEbFazE0is_IqQAEnSdQ82doxTeROcE_aUNYuRPY,9323
|
|
7
|
+
fajfield_einvoice/pint_ae.py,sha256=_5dZUwepaMkQhmGtuAIF2-Nks6t4cbiwXPYTOExLPMI,11942
|
|
8
|
+
fajfield_einvoice/validate.py,sha256=23mNAGAYg3qXAFMfMu2ollxHuo-d4fvcnu59mEcwBak,17210
|
|
9
|
+
fajfield_einvoice/xmlio.py,sha256=iLm3W-7KvDmKd46W9XkPpkjMH0Z0q3vUGzA6lQnIp0w,1873
|
|
10
|
+
fajfield_einvoice-0.1.0.dist-info/METADATA,sha256=eTsrlNtUrQQHQj5y8MvU_qISRCdcnkxuQhCk2wPLHBg,7561
|
|
11
|
+
fajfield_einvoice-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
12
|
+
fajfield_einvoice-0.1.0.dist-info/licenses/LICENSE,sha256=C0-DIzD6EUX6-6BtCBrh4P59YT0Vw7oJNq-X8lvownA,1065
|
|
13
|
+
fajfield_einvoice-0.1.0.dist-info/RECORD,,
|
|
@@ -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.
|