11c41343fc41f8a139c2eddac76c988631ab6b4d
Bernd Wurst In eigenes GIT ausgelagert

Bernd Wurst authored 9 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) import datetime
22) 
23) import re
24) 
25) # Search for included submodule python-drafthorse
26) atoms = os.path.abspath(os.path.dirname(__file__)).split('/')
27) dir = ''
28) while atoms:
29)     candidate = os.path.join('/'.join(atoms), 'external/python-drafthorse')
30)     if os.path.exists(candidate):
31)         dir = candidate
32)         break
33)     atoms = atoms[:-1]
34) sys.path.insert(0, dir)
35) from drafthorse.models.document import Document
36) from drafthorse.models.accounting import ApplicableTradeTax
37) from drafthorse.models.tradelines import LineItem
38) from .InvoiceObjects import InvoiceTable, InvoiceText, InvoiceImage, RECHNUNG, GUTSCHRIFT, KORREKTUR, \
Bernd Wurst WiP

Bernd Wurst authored 9 months ago

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

Bernd Wurst authored 9 months ago

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

Bernd Wurst authored 9 months ago

47)     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 9 months ago

48)     doc.header.id = invoice.id
49)     # Typecodes:
50)     # 380: Handelsrechnungen
51)     # 381: Gutschrift
52)     # 384: Korrekturrechnung
53)     # 389: Eigenrechnung (vom Käufer im Namen des Lieferanten erstellt).
54)     # 261: Selbstverfasste Gutschrift.
55)     # 386: Vorauszahlungsrechnung
56)     # 326: Teilrechnung
57)     # 751: Rechnungsinformation - KEINE RECHNUNG
58)     if invoice.type == RECHNUNG:
59)         doc.header.type_code = "380"
60)     elif invoice.type == GUTSCHRIFT:
61)         doc.header.type_code = "381"
62)     elif invoice.type == KORREKTUR:
63)         doc.header.type_code = "384"
64)     else:
65)         raise TypeError("Unbekannter Rechnungstyp, kann kein XML erstellen")
66)     doc.header.issue_date_time = invoice.date
67) 
68)     # Seller-Address
69)     if invoice.seller['trade_name']:
70)         pass
71)         # FIXME: specified_legal_organization ist in der Library nicht implementiert, pull request ist vorhanden
72)         #doc.trade.agreement.seller.specified_legal_organization.trade_name = invoice.seller['trade_name']
73)     doc.trade.agreement.seller.name = invoice.seller['name']
74)     doc.trade.agreement.seller.address.country_id = invoice.seller['address']['country_id']
75)     doc.trade.agreement.seller.address.postcode = invoice.seller['address']['postcode']
76)     doc.trade.agreement.seller.address.city_name = invoice.seller['address']['city_name']
77)     doc.trade.agreement.seller.address.line_one = invoice.seller['address']['line1']
78)     doc.trade.agreement.seller.address.line_two = invoice.seller['address']['line2']
79)     doc.trade.agreement.seller.address.line_three = invoice.seller['address']['line3']
80)     if invoice.seller_vat_id:
81)         tax_reg = TaxRegistration()
82)         tax_reg.id = ('VA', invoice.seller_vat_id)
83)         doc.trade.agreement.seller.tax_registrations.add(tax_reg)
84)     if invoice.seller['email']:
85)         email = URIUniversalCommunication()
86)         email.uri_ID = ('EM', invoice.seller['email'])
87)         # FIXME: Typo in der Library ("adress")?
88)         doc.trade.agreement.seller.electronic_adress.add(email)
89) 
90)     # Buyer-Address
91)     doc.trade.agreement.buyer.name = invoice.customer['name']
92)     doc.trade.agreement.buyer.address.country_id = invoice.customer['address']['country_id']
93)     doc.trade.agreement.buyer.address.postcode = invoice.customer['address']['postcode']
94)     doc.trade.agreement.buyer.address.city_name = invoice.customer['address']['city_name']
95)     doc.trade.agreement.buyer.address.line_one = invoice.customer['address']['line1']
96)     doc.trade.agreement.buyer.address.line_two = invoice.customer['address']['line2']
97)     doc.trade.agreement.buyer.address.line_three = invoice.customer['address']['line3']
98) 
99)     # Line Items
100)     summe_netto = 0.0
101)     summe_brutto = 0.0
102)     summe_bezahlt = 0.0
103)     summe_ust = 0.0
104)     line_id_count = 0
105)     textparts = []
106)     for part in invoice.parts:
107)         if type(part) == InvoiceText:
108)             textparts += part.paragraphs
109)         if type(part) == InvoiceTable:
110)             for el in part.entries:
111)                 line_id_count += 1
112)                 li = LineItem()
113)                 li.document.line_id = f"{line_id_count}"
114)                 li.product.name = el['subject']
115)                 if 'desc' in el and el['desc'] != '':
116)                     desc = li.product.description = el['desc']
117) 
118)                 if 'period_start' in el and el['period_start']:
119)                     if 'period_end' in el and el['period_end']:
120)                         li.settlement.period.start = el['period_start']
121)                         li.settlement.period.end = el['period_end']
122)                     else:
123)                         li.delivery.event.occurrence = el['period_start']
124) 
125)                 # FIXME: Hier sollte der passende Code benutzt werden (z.B. Monat)
126)                 li.delivery.billed_quantity = (Decimal(el['count']), 'H87')
127)                 # LTR = Liter (1 dm3)
128)                 # MTQ = cubic meter
129)                 # KGM = Kilogram
130)                 # MTR = Meter
131)                 # H87 = Piece
132)                 # TNE = Tonne
133)                 # MON = Month
134) 
135)                 li.settlement.trade_tax.type_code = "VAT"
136)                 if invoice.vat_type == VAT_REGULAR:
137)                     li.settlement.trade_tax.category_code = "S"
138)                 elif invoice.vat_type == VAT_KLEINUNTERNEHMER:
139)                     li.settlement.trade_tax.category_code = "E"
140)                 elif invoice.vat_type == VAT_INNERGEM:
141)                     li.settlement.trade_tax.category_code = "K"
142)                 # FIXME: Typ bei uns nur global gesetzt, nicht pro Artikel
143)                 # S = Standard VAT rate
144)                 # Z = Zero rated goods
145)                 # E = VAT exempt
146)                 # AE = Reverse charge
147)                 # K = Intra-Community supply (specific reverse charge)
148)                 # G = Exempt VAT for Export outside EU
149)                 # O = Outside VAT scope
150)                 li.settlement.trade_tax.rate_applicable_percent = Decimal(f"{el['vat']*100:.1f}")
151) 
152)                 nettopreis = el['price']
153)                 if part.vatType == 'gross':
154)                     nettopreis = el['price'] / (1 + el['vat'])
155)                 li.agreement.net.amount = Decimal(f"{nettopreis:.2f}")
156) 
157)                 nettosumme = el['total']
158)                 if part.vatType == 'gross':
159)                     nettosumme = el['total'] / (1 + el['vat'])
160)                 li.settlement.monetary_summation.total_amount = Decimal(f"{nettosumme:.2f}")
161) 
162)                 summe_netto += nettosumme
163)                 summe_brutto += el['total']
164)                 doc.trade.items.add(li)
165) 
166)             for pay in part.payments:
167)                 summe_bezahlt += pay['amount']
168) 
169)             for vat, vatdata in part.vat.items():
170)                 trade_tax = ApplicableTradeTax()
171)                 # Steuerbetrag dieses Steuersatzes
172)                 trade_tax.calculated_amount = Decimal(f"{(vatdata[0] / (vat + 1)) * vat:.2f}")
173)                 # Nettosumme dieses Steuersatzes
174)                 trade_tax.basis_amount = Decimal(f"{(vatdata[0] / (vat + 1)):.2f}")
175)                 trade_tax.type_code = "VAT"
176)                 if invoice.vat_type == VAT_REGULAR:
177)                     trade_tax.category_code = "S"
178)                 elif invoice.vat_type == VAT_KLEINUNTERNEHMER:
179)                     trade_tax.category_code = "E"
180)                     trade_tax.exemption_reason = 'Als Kleinunternehmer wird gemäß §19 UStG keine USt in Rechnung gestellt.'
181)                 elif invoice.vat_type == VAT_INNERGEM:
182)                     trade_tax.category_code = "K"
183)                 trade_tax.rate_applicable_percent = Decimal(f"{vat*100:.1f}")
184)                 summe_ust += (vatdata[0] / (vat + 1)) * vat
185)                 doc.trade.settlement.trade_tax.add(trade_tax)
186) 
187)     for paragraph in textparts:
188)         note = IncludedNote()
189)         note.content.add(paragraph)
190)         doc.header.notes.add(note)
191) 
192)     rest = summe_brutto - summe_bezahlt
193) 
194)     if invoice.creditor_reference_id:
195)         # Gläubiger-ID für SEPA
196)         doc.trade.settlement.creditor_reference_id = invoice.creditor_reference_id
197)     doc.trade.settlement.payment_reference = invoice.id
198)     doc.trade.settlement.currency_code = 'EUR'
Bernd Wurst WiP

Bernd Wurst authored 9 months ago

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

Bernd Wurst authored 9 months ago

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

Bernd Wurst authored 9 months ago

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

Bernd Wurst authored 9 months ago

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

Bernd Wurst authored 9 months ago

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

Bernd Wurst authored 9 months ago

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

Bernd Wurst authored 9 months ago

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

Bernd Wurst authored 9 months ago

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

Bernd Wurst authored 9 months ago

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