06db2136cf749513a3e31b7b8b552e8c11735aa6
Bernd Wurst In eigenes GIT ausgelagert

Bernd Wurst authored 4 months ago

1) # -*- coding: utf-8 -*-
2) # (C) 2011 by Bernd Wurst <bernd@schokokeks.org>
3) 
4) # This file is part of Bib2011.
5) #
6) # Bib2011 is free software: you can redistribute it and/or modify
7) # it under the terms of the GNU General Public License as published by
8) # the Free Software Foundation, either version 3 of the License, or
9) # (at your option) any later version.
10) #
11) # Bib2011 is distributed in the hope that it will be useful,
12) # but WITHOUT ANY WARRANTY; without even the implied warranty of
13) # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14) # GNU General Public License for more details.
15) #
16) # You should have received a copy of the GNU General Public License
17) # along with Bib2011.  If not, see <http://www.gnu.org/licenses/>.
18) 
19) import os.path, sys
20) from decimal import Decimal
21) 
22) # Search for included submodule python-drafthorse
23) atoms = os.path.abspath(os.path.dirname(__file__)).split('/')
24) dir = ''
25) while atoms:
26)     candidate = os.path.join('/'.join(atoms), 'external/python-drafthorse')
27)     if os.path.exists(candidate):
28)         dir = candidate
29)         break
30)     atoms = atoms[:-1]
31) sys.path.insert(0, dir)
32) from drafthorse.models.document import Document
33) from drafthorse.models.accounting import ApplicableTradeTax
34) from drafthorse.models.tradelines import LineItem
Bernd Wurst Codestyle-Fixes

Bernd Wurst authored 4 months ago

35) from .InvoiceObjects import InvoiceTable, InvoiceText, RECHNUNG, GUTSCHRIFT, KORREKTUR, \
Bernd Wurst WiP

Bernd Wurst authored 4 months ago

36)     VAT_REGULAR, VAT_KLEINUNTERNEHMER, VAT_INNERGEM, PAYMENT_UEBERWEISUNG, PAYMENT_LASTSCHRIFT
Bernd Wurst In eigenes GIT ausgelagert

Bernd Wurst authored 4 months ago

37) from drafthorse.models.party import TaxRegistration, URIUniversalCommunication
38) from drafthorse.models.payment import PaymentTerms
39) from drafthorse.models.note import IncludedNote
40) from drafthorse.pdf import attach_xml
41) 
42) def InvoiceToXML(invoice):
43)     doc = Document()
Bernd Wurst WiP

Bernd Wurst authored 4 months ago

44)     doc.context.guideline_parameter.id = "urn:cen.eu:en16931:2017#conformant#urn:factur-x.eu:1p0:en16931"
Bernd Wurst In eigenes GIT ausgelagert

Bernd Wurst authored 4 months ago

45)     doc.header.id = invoice.id
46)     # Typecodes:
47)     # 380: Handelsrechnungen
48)     # 381: Gutschrift
49)     # 384: Korrekturrechnung
50)     # 389: Eigenrechnung (vom Käufer im Namen des Lieferanten erstellt).
51)     # 261: Selbstverfasste Gutschrift.
52)     # 386: Vorauszahlungsrechnung
53)     # 326: Teilrechnung
54)     # 751: Rechnungsinformation - KEINE RECHNUNG
55)     if invoice.type == RECHNUNG:
56)         doc.header.type_code = "380"
57)     elif invoice.type == GUTSCHRIFT:
58)         doc.header.type_code = "381"
59)     elif invoice.type == KORREKTUR:
60)         doc.header.type_code = "384"
61)     else:
62)         raise TypeError("Unbekannter Rechnungstyp, kann kein XML erstellen")
63)     doc.header.issue_date_time = invoice.date
64) 
65)     # Seller-Address
66)     if invoice.seller['trade_name']:
67)         pass
68)         # FIXME: specified_legal_organization ist in der Library nicht implementiert, pull request ist vorhanden
69)         #doc.trade.agreement.seller.specified_legal_organization.trade_name = invoice.seller['trade_name']
70)     doc.trade.agreement.seller.name = invoice.seller['name']
71)     doc.trade.agreement.seller.address.country_id = invoice.seller['address']['country_id']
72)     doc.trade.agreement.seller.address.postcode = invoice.seller['address']['postcode']
73)     doc.trade.agreement.seller.address.city_name = invoice.seller['address']['city_name']
74)     doc.trade.agreement.seller.address.line_one = invoice.seller['address']['line1']
75)     doc.trade.agreement.seller.address.line_two = invoice.seller['address']['line2']
76)     doc.trade.agreement.seller.address.line_three = invoice.seller['address']['line3']
77)     if invoice.seller_vat_id:
78)         tax_reg = TaxRegistration()
79)         tax_reg.id = ('VA', invoice.seller_vat_id)
80)         doc.trade.agreement.seller.tax_registrations.add(tax_reg)
81)     if invoice.seller['email']:
82)         email = URIUniversalCommunication()
83)         email.uri_ID = ('EM', invoice.seller['email'])
84)         # FIXME: Typo in der Library ("adress")?
85)         doc.trade.agreement.seller.electronic_adress.add(email)
86) 
87)     # Buyer-Address
88)     doc.trade.agreement.buyer.name = invoice.customer['name']
89)     doc.trade.agreement.buyer.address.country_id = invoice.customer['address']['country_id']
90)     doc.trade.agreement.buyer.address.postcode = invoice.customer['address']['postcode']
91)     doc.trade.agreement.buyer.address.city_name = invoice.customer['address']['city_name']
92)     doc.trade.agreement.buyer.address.line_one = invoice.customer['address']['line1']
93)     doc.trade.agreement.buyer.address.line_two = invoice.customer['address']['line2']
94)     doc.trade.agreement.buyer.address.line_three = invoice.customer['address']['line3']
95) 
96)     # Line Items
97)     summe_netto = 0.0
98)     summe_brutto = 0.0
99)     summe_bezahlt = 0.0
100)     summe_ust = 0.0
101)     line_id_count = 0
102)     textparts = []
103)     for part in invoice.parts:
Bernd Wurst Codestyle-Fixes

Bernd Wurst authored 4 months ago

104)         if isinstance(part, InvoiceText):
Bernd Wurst In eigenes GIT ausgelagert

Bernd Wurst authored 4 months ago

105)             textparts += part.paragraphs
Bernd Wurst Codestyle-Fixes

Bernd Wurst authored 4 months ago

106)         if isinstance(part, InvoiceTable):
Bernd Wurst In eigenes GIT ausgelagert

Bernd Wurst authored 4 months ago

107)             for el in part.entries:
108)                 line_id_count += 1
109)                 li = LineItem()
110)                 li.document.line_id = f"{line_id_count}"
111)                 li.product.name = el['subject']
112)                 if 'desc' in el and el['desc'] != '':
113)                     desc = li.product.description = el['desc']
114) 
115)                 if 'period_start' in el and el['period_start']:
116)                     if 'period_end' in el and el['period_end']:
117)                         li.settlement.period.start = el['period_start']
118)                         li.settlement.period.end = el['period_end']
119)                     else:
120)                         li.delivery.event.occurrence = el['period_start']
121) 
122)                 # FIXME: Hier sollte der passende Code benutzt werden (z.B. Monat)
123)                 li.delivery.billed_quantity = (Decimal(el['count']), 'H87')
124)                 # LTR = Liter (1 dm3)
125)                 # MTQ = cubic meter
126)                 # KGM = Kilogram
127)                 # MTR = Meter
128)                 # H87 = Piece
129)                 # TNE = Tonne
130)                 # MON = Month
131) 
132)                 li.settlement.trade_tax.type_code = "VAT"
133)                 if invoice.vat_type == VAT_REGULAR:
134)                     li.settlement.trade_tax.category_code = "S"
135)                 elif invoice.vat_type == VAT_KLEINUNTERNEHMER:
136)                     li.settlement.trade_tax.category_code = "E"
137)                 elif invoice.vat_type == VAT_INNERGEM:
138)                     li.settlement.trade_tax.category_code = "K"
139)                 # FIXME: Typ bei uns nur global gesetzt, nicht pro Artikel
140)                 # S = Standard VAT rate
141)                 # Z = Zero rated goods
142)                 # E = VAT exempt
143)                 # AE = Reverse charge
144)                 # K = Intra-Community supply (specific reverse charge)
145)                 # G = Exempt VAT for Export outside EU
146)                 # O = Outside VAT scope
147)                 li.settlement.trade_tax.rate_applicable_percent = Decimal(f"{el['vat']*100:.1f}")
148) 
149)                 nettopreis = el['price']
150)                 if part.vatType == 'gross':
151)                     nettopreis = el['price'] / (1 + el['vat'])
152)                 li.agreement.net.amount = Decimal(f"{nettopreis:.2f}")
153) 
154)                 nettosumme = el['total']
155)                 if part.vatType == 'gross':
156)                     nettosumme = el['total'] / (1 + el['vat'])
157)                 li.settlement.monetary_summation.total_amount = Decimal(f"{nettosumme:.2f}")
158) 
159)                 summe_netto += nettosumme
160)                 summe_brutto += el['total']
161)                 doc.trade.items.add(li)
162) 
163)             for pay in part.payments:
164)                 summe_bezahlt += pay['amount']
165) 
166)             for vat, vatdata in part.vat.items():
167)                 trade_tax = ApplicableTradeTax()
168)                 # Steuerbetrag dieses Steuersatzes
169)                 trade_tax.calculated_amount = Decimal(f"{(vatdata[0] / (vat + 1)) * vat:.2f}")
170)                 # Nettosumme dieses Steuersatzes
171)                 trade_tax.basis_amount = Decimal(f"{(vatdata[0] / (vat + 1)):.2f}")
172)                 trade_tax.type_code = "VAT"
173)                 if invoice.vat_type == VAT_REGULAR:
174)                     trade_tax.category_code = "S"
175)                 elif invoice.vat_type == VAT_KLEINUNTERNEHMER:
176)                     trade_tax.category_code = "E"
177)                     trade_tax.exemption_reason = 'Als Kleinunternehmer wird gemäß §19 UStG keine USt in Rechnung gestellt.'
178)                 elif invoice.vat_type == VAT_INNERGEM:
179)                     trade_tax.category_code = "K"
180)                 trade_tax.rate_applicable_percent = Decimal(f"{vat*100:.1f}")
181)                 summe_ust += (vatdata[0] / (vat + 1)) * vat
182)                 doc.trade.settlement.trade_tax.add(trade_tax)
183) 
184)     for paragraph in textparts:
185)         note = IncludedNote()
186)         note.content.add(paragraph)
187)         doc.header.notes.add(note)
188) 
189)     rest = summe_brutto - summe_bezahlt
190) 
191)     if invoice.creditor_reference_id:
192)         # Gläubiger-ID für SEPA
193)         doc.trade.settlement.creditor_reference_id = invoice.creditor_reference_id
194)     doc.trade.settlement.payment_reference = invoice.id
195)     doc.trade.settlement.currency_code = 'EUR'
Bernd Wurst WiP

Bernd Wurst authored 4 months ago

196)     if invoice.payment_type:
197)         doc.trade.settlement.payment_means.type_code = invoice.payment_type
198) 
199)     if invoice.seller_bank_data['iban'] and invoice.payment_type == PAYMENT_UEBERWEISUNG:
Bernd Wurst In eigenes GIT ausgelagert

Bernd Wurst authored 4 months ago

200)         doc.trade.settlement.payment_means.payee_account.iban = invoice.seller_bank_data['iban']
201)         doc.trade.settlement.payment_means.payee_institution.bic = "GENODES1VBK"
202)         # Ist in der Library vorhanden, validiert aber nicht im XML?!
Bernd Wurst WiP

Bernd Wurst authored 4 months ago

203)     if invoice.buyer_bank_data['iban'] and invoice.payment_type == PAYMENT_LASTSCHRIFT:
Bernd Wurst In eigenes GIT ausgelagert

Bernd Wurst authored 4 months ago

204)         # Kunden-Bankverbindung bei Lastschrift
205)         doc.trade.settlement.payment_means.payer_account.iban = invoice.buyer_bank_data['iban']
206) 
207)     terms = PaymentTerms()
Bernd Wurst WiP

Bernd Wurst authored 4 months ago

208)     if invoice.due_date and invoice.payment_type == PAYMENT_UEBERWEISUNG:
Bernd Wurst In eigenes GIT ausgelagert

Bernd Wurst authored 4 months ago

209)         terms.description = f"Bitte begleichen Sie den Betrag bis zum {invoice.due_date.strftime('%d.%m.%Y')} ohne Abzüge."
210)         terms.due = invoice.due_date
Bernd Wurst WiP

Bernd Wurst authored 4 months ago

211)     if invoice.type == GUTSCHRIFT:
212)         terms.description = f"Wir überweisen den Betrag auf Ihr Konto."
213)     elif invoice.debit:
Bernd Wurst In eigenes GIT ausgelagert

Bernd Wurst authored 4 months ago

214)         if invoice.debit_mandate_id:
215)             # Mandatsreferenz für Lastschrift
216)             terms.debit_mandate_id = invoice.debit_mandate_id
217)         terms.description = 'Wir buchen von Ihrem Konto ab.'
218)     doc.trade.settlement.terms.add(terms)
219) 
220) 
221)     doc.trade.settlement.monetary_summation.line_total = Decimal(f"{summe_netto:.2f}")
222)     doc.trade.settlement.monetary_summation.charge_total = Decimal("0.00")
223)     doc.trade.settlement.monetary_summation.allowance_total = Decimal("0.00")
224)     doc.trade.settlement.monetary_summation.tax_basis_total = Decimal(f"{summe_netto:.2f}")
225)     doc.trade.settlement.monetary_summation.tax_total = (Decimal(f"{summe_ust:.2f}"), "EUR")
226)     doc.trade.settlement.monetary_summation.prepaid_total = Decimal(f"{summe_bezahlt:.2f}")
227)     doc.trade.settlement.monetary_summation.grand_total = Decimal(f"{summe_brutto:.2f}")
228)     doc.trade.settlement.monetary_summation.due_amount = Decimal(f"{rest:.2f}")
229) 
230) 
231)     # Generate XML file
Bernd Wurst WiP

Bernd Wurst authored 4 months ago

232)     xml = doc.serialize(schema="FACTUR-X_EN16931")