Update BT-Nummern
This commit is contained in:
parent
842f3809f1
commit
0fd600ae46
65
main.py
65
main.py
|
|
@ -98,7 +98,6 @@ class InvoiceMetadata(BaseModel):
|
||||||
recipient_email: str = Field(description="E-Mail-Adresse des Kunden (LEER lassen, wenn nicht explizit im Text!)")
|
recipient_email: str = Field(description="E-Mail-Adresse des Kunden (LEER lassen, wenn nicht explizit im Text!)")
|
||||||
vat_rate_percent: float = Field(description="Der primäre Umsatzsteuersatz in Prozent (z.B. 19.0)")
|
vat_rate_percent: float = Field(description="Der primäre Umsatzsteuersatz in Prozent (z.B. 19.0)")
|
||||||
|
|
||||||
# Neue strukturierte Felder für jegliche Daten VOR Position 1
|
|
||||||
delivery_note_id: str = Field(default="", description="Gefundene Lieferscheinnummer (z.B. LS26-035) VOR Position 1. Sonst leer lassen.")
|
delivery_note_id: str = Field(default="", description="Gefundene Lieferscheinnummer (z.B. LS26-035) VOR Position 1. Sonst leer lassen.")
|
||||||
order_id: str = Field(default="", description="Gefundene Nummer der Auftragsbestätigung oder Bestellung (z.B. AB26-080) VOR Position 1. Sonst leer lassen.")
|
order_id: str = Field(default="", description="Gefundene Nummer der Auftragsbestätigung oder Bestellung (z.B. AB26-080) VOR Position 1. Sonst leer lassen.")
|
||||||
contract_id: str = Field(default="", description="Gefundene Nummer von Vergabeangebot, Vertrag oder Ausschreibung (z.B. AN26-130) VOR Position 1. Sonst leer lassen.")
|
contract_id: str = Field(default="", description="Gefundene Nummer von Vergabeangebot, Vertrag oder Ausschreibung (z.B. AN26-130) VOR Position 1. Sonst leer lassen.")
|
||||||
|
|
@ -108,7 +107,7 @@ class InvoiceMetadata(BaseModel):
|
||||||
|
|
||||||
|
|
||||||
# ==========================================
|
# ==========================================
|
||||||
# 3. MATHEMATISCHE & PARSING-FUNKTIONEN
|
# 3. MATHEMATISCHE & PARSING-FUNKTIONEN (ERWEITERT FÜR BT-154)
|
||||||
# ==========================================
|
# ==========================================
|
||||||
def kaufmaennisches_runden(betrag, nachkommastellen=2):
|
def kaufmaennisches_runden(betrag, nachkommastellen=2):
|
||||||
if not betrag:
|
if not betrag:
|
||||||
|
|
@ -165,18 +164,19 @@ def extract_invoice_items_pure_python(text):
|
||||||
if any(prev_lower.startswith(w) for w in ["zwischensumme", "endbetrag", "gesamtbetrag", "umsatzsteuer"]):
|
if any(prev_lower.startswith(w) for w in ["zwischensumme", "endbetrag", "gesamtbetrag", "umsatzsteuer"]):
|
||||||
break
|
break
|
||||||
|
|
||||||
# REPARATUR: Wenn eine reine Positionsnummer (z.B. "1") erreicht wird, MUSS abgebrochen werden,
|
|
||||||
# um nicht in den globalen Kopf- und Vorlauftext darüber hineinzulaufen!
|
|
||||||
if prev_line.isdigit() and len(prev_line) <= 2:
|
if prev_line.isdigit() and len(prev_line) <= 2:
|
||||||
break
|
break
|
||||||
|
|
||||||
desc_lines.insert(0, prev_line)
|
desc_lines.insert(0, prev_line)
|
||||||
|
|
||||||
description = " ".join(desc_lines).strip()
|
|
||||||
|
|
||||||
if description:
|
# REPARATUR & OPTIMIERUNG FÜR BT-153 UND BT-154:
|
||||||
|
if desc_lines:
|
||||||
|
item_name = desc_lines[0].strip() # Die erste Zeile wird der prägnante Artikelname (BT-153)
|
||||||
|
item_description = "\n".join(desc_lines[1:]).strip() if len(desc_lines) > 1 else "" # Restliche Zeilen werden Zusatzbeschreibung (BT-154)
|
||||||
|
|
||||||
items.append({
|
items.append({
|
||||||
"description": description,
|
"name": item_name,
|
||||||
|
"description": item_description,
|
||||||
"quantity": clean_german_float(raw_qty),
|
"quantity": clean_german_float(raw_qty),
|
||||||
"unit": raw_unit,
|
"unit": raw_unit,
|
||||||
"unit_price": clean_german_float(raw_price)
|
"unit_price": clean_german_float(raw_price)
|
||||||
|
|
@ -210,7 +210,6 @@ def generate_compliant_xrechnung(data):
|
||||||
|
|
||||||
root = ET.Element(f"{{{INVOICE_NS}}}Invoice")
|
root = ET.Element(f"{{{INVOICE_NS}}}Invoice")
|
||||||
|
|
||||||
# Kopfdaten Definitionen nach Kosit-Vorgabe (XRechnung 3.0)
|
|
||||||
ET.SubElement(root, f"{{{CBC}}}CustomizationID").text = "urn:cen.eu:en16931:2017#compliant#urn:xeinkauf.de:kosit:xrechnung_3.0"
|
ET.SubElement(root, f"{{{CBC}}}CustomizationID").text = "urn:cen.eu:en16931:2017#compliant#urn:xeinkauf.de:kosit:xrechnung_3.0"
|
||||||
ET.SubElement(root, f"{{{CBC}}}ProfileID").text = "urn:fdc:peppol.eu:2017:poacc:billing:01:1.0"
|
ET.SubElement(root, f"{{{CBC}}}ProfileID").text = "urn:fdc:peppol.eu:2017:poacc:billing:01:1.0"
|
||||||
|
|
||||||
|
|
@ -224,32 +223,28 @@ def generate_compliant_xrechnung(data):
|
||||||
computed_due = (datetime.today() + timedelta(days=14)).strftime("%Y-%m-%d")
|
computed_due = (datetime.today() + timedelta(days=14)).strftime("%Y-%m-%d")
|
||||||
ET.SubElement(root, f"{{{CBC}}}DueDate").text = computed_due
|
ET.SubElement(root, f"{{{CBC}}}DueDate").text = computed_due
|
||||||
|
|
||||||
ET.SubElement(root, f"{{{CBC}}}InvoiceTypeCode").text = "380"
|
# ERWEITERT: Nutzt nun den flexiblen Code aus dem Dropdown-Menü (BT-3)
|
||||||
|
ET.SubElement(root, f"{{{CBC}}}InvoiceTypeCode").text = str(data.get("invoice_type_code", "380"))
|
||||||
|
|
||||||
# Globales Freitextfeld BT-22 (Rechnungserläuterung) für unstrukturierte Vorlauftexte / Vodafone-Klauseln
|
|
||||||
if data.get("invoice_note") and str(data["invoice_note"]).strip() != "":
|
if data.get("invoice_note") and str(data["invoice_note"]).strip() != "":
|
||||||
ET.SubElement(root, f"{{{CBC}}}Note").text = str(data["invoice_note"]).strip()
|
ET.SubElement(root, f"{{{CBC}}}Note").text = str(data["invoice_note"]).strip()
|
||||||
|
|
||||||
ET.SubElement(root, f"{{{CBC}}}DocumentCurrencyCode").text = "EUR"
|
ET.SubElement(root, f"{{{CBC}}}DocumentCurrencyCode").text = "EUR"
|
||||||
ET.SubElement(root, f"{{{CBC}}}BuyerReference").text = str(data["buyer_reference"])
|
ET.SubElement(root, f"{{{CBC}}}BuyerReference").text = str(data["buyer_reference"])
|
||||||
|
|
||||||
# Globaler Leistungszeitraum (BG-14)
|
|
||||||
if data.get("service_start_date") and data.get("service_end_date"):
|
if data.get("service_start_date") and data.get("service_end_date"):
|
||||||
period_elem = ET.SubElement(root, f"{{{CAC}}}InvoicePeriod")
|
period_elem = ET.SubElement(root, f"{{{CAC}}}InvoicePeriod")
|
||||||
ET.SubElement(period_elem, f"{{{CBC}}}StartDate").text = parse_to_strict_xml_date(data["service_start_date"])
|
ET.SubElement(period_elem, f"{{{CBC}}}StartDate").text = parse_to_strict_xml_date(data["service_start_date"])
|
||||||
ET.SubElement(period_elem, f"{{{CBC}}}EndDate").text = parse_to_strict_xml_date(data["service_end_date"])
|
ET.SubElement(period_elem, f"{{{CBC}}}EndDate").text = parse_to_strict_xml_date(data["service_end_date"])
|
||||||
|
|
||||||
# Auftragsbestätigung / Bestellungs-Referenz (BT-13)
|
|
||||||
if data.get("order_id") and str(data["order_id"]).strip() != "":
|
if data.get("order_id") and str(data["order_id"]).strip() != "":
|
||||||
order_ref = ET.SubElement(root, f"{{{CAC}}}OrderReference")
|
order_ref = ET.SubElement(root, f"{{{CAC}}}OrderReference")
|
||||||
ET.SubElement(order_ref, f"{{{CBC}}}ID").text = str(data["order_id"]).strip()
|
ET.SubElement(order_ref, f"{{{CBC}}}ID").text = str(data["order_id"]).strip()
|
||||||
|
|
||||||
# Lieferschein-Referenz (BT-16)
|
|
||||||
if data.get("delivery_note_id") and str(data["delivery_note_id"]).strip() != "":
|
if data.get("delivery_note_id") and str(data["delivery_note_id"]).strip() != "":
|
||||||
despatch_ref = ET.SubElement(root, f"{{{CAC}}}DespatchDocumentReference")
|
despatch_ref = ET.SubElement(root, f"{{{CAC}}}DespatchDocumentReference")
|
||||||
ET.SubElement(despatch_ref, f"{{{CBC}}}ID").text = str(data["delivery_note_id"]).strip()
|
ET.SubElement(despatch_ref, f"{{{CBC}}}ID").text = str(data["delivery_note_id"]).strip()
|
||||||
|
|
||||||
# Vertrags- / Ausschreibungsreferenz (BT-12)
|
|
||||||
if data.get("contract_id") and str(data["contract_id"]).strip() != "":
|
if data.get("contract_id") and str(data["contract_id"]).strip() != "":
|
||||||
contract_ref = ET.SubElement(root, f"{{{CAC}}}ContractDocumentReference")
|
contract_ref = ET.SubElement(root, f"{{{CAC}}}ContractDocumentReference")
|
||||||
ET.SubElement(contract_ref, f"{{{CBC}}}ID").text = str(data["contract_id"]).strip()
|
ET.SubElement(contract_ref, f"{{{CBC}}}ID").text = str(data["contract_id"]).strip()
|
||||||
|
|
@ -325,6 +320,7 @@ def generate_compliant_xrechnung(data):
|
||||||
ET.SubElement(monetary_total, f"{{{CBC}}}TaxInclusiveAmount", {"currencyID": "EUR"}).text = f"{data['total_gross_amount']:.2f}"
|
ET.SubElement(monetary_total, f"{{{CBC}}}TaxInclusiveAmount", {"currencyID": "EUR"}).text = f"{data['total_gross_amount']:.2f}"
|
||||||
ET.SubElement(monetary_total, f"{{{CBC}}}PayableAmount", {"currencyID": "EUR"}).text = f"{data['total_gross_amount']:.2f}"
|
ET.SubElement(monetary_total, f"{{{CBC}}}PayableAmount", {"currencyID": "EUR"}).text = f"{data['total_gross_amount']:.2f}"
|
||||||
|
|
||||||
|
# --- POSITIONEN SCHLEIFE (UMGEBAUT FÜR BT-153 & BT-154) ---
|
||||||
for index, item in enumerate(data["items"], start=1):
|
for index, item in enumerate(data["items"], start=1):
|
||||||
line = ET.SubElement(root, f"{{{CAC}}}InvoiceLine")
|
line = ET.SubElement(root, f"{{{CAC}}}InvoiceLine")
|
||||||
ET.SubElement(line, f"{{{CBC}}}ID").text = str(index)
|
ET.SubElement(line, f"{{{CBC}}}ID").text = str(index)
|
||||||
|
|
@ -338,7 +334,13 @@ def generate_compliant_xrechnung(data):
|
||||||
ET.SubElement(line, f"{{{CBC}}}LineExtensionAmount", {"currencyID": "EUR"}).text = f"{item['total_amount']:.2f}"
|
ET.SubElement(line, f"{{{CBC}}}LineExtensionAmount", {"currencyID": "EUR"}).text = f"{item['total_amount']:.2f}"
|
||||||
|
|
||||||
item_elem = ET.SubElement(line, f"{{{CAC}}}Item")
|
item_elem = ET.SubElement(line, f"{{{CAC}}}Item")
|
||||||
ET.SubElement(item_elem, f"{{{CBC}}}Name").text = str(item["description"])
|
|
||||||
|
# BT-153: Der prägnante Name der Dienstleistung/Ware (Erste Zeile)
|
||||||
|
ET.SubElement(item_elem, f"{{{CBC}}}Name").text = str(item.get("name", "Dienstleistung"))
|
||||||
|
|
||||||
|
# BT-154: Die detaillierte Zusatzbeschreibung (Seriennummern, Laufzeiten etc., falls vorhanden)
|
||||||
|
if item.get("description") and str(item["description"]).strip() != "":
|
||||||
|
ET.SubElement(item_elem, f"{{{CBC}}}Description").text = str(item["description"]).strip()
|
||||||
|
|
||||||
item_tax = ET.SubElement(item_elem, f"{{{CAC}}}ClassifiedTaxCategory")
|
item_tax = ET.SubElement(item_elem, f"{{{CAC}}}ClassifiedTaxCategory")
|
||||||
ET.SubElement(item_tax, f"{{{CBC}}}ID").text = vat_category
|
ET.SubElement(item_tax, f"{{{CBC}}}ID").text = vat_category
|
||||||
|
|
@ -409,12 +411,12 @@ with col2:
|
||||||
"- recipient_city\n"
|
"- recipient_city\n"
|
||||||
"- recipient_email\n"
|
"- recipient_email\n"
|
||||||
"- vat_rate_percent (als Zahl, z.B. 19.0)\n"
|
"- vat_rate_percent (als Zahl, z.B. 19.0)\n"
|
||||||
"- delivery_note_id (Lieferscheinnummer vor Position 1, falls vorhanden)\n"
|
"- delivery_note_id\n"
|
||||||
"- order_id (Auftragsbestätigung/Bestellnummer vor Position 1, falls vorhanden)\n"
|
"- order_id\n"
|
||||||
"- contract_id (Vergabeangebot/Vertragsreferenz vor Position 1, falls vorhanden)\n"
|
"- contract_id\n"
|
||||||
"- service_start_date (Leistungszeitraum Start vor Position 1, Format YYYY-MM-DD)\n"
|
"- service_start_date\n"
|
||||||
"- service_end_date (Leistungszeitraum Ende vor Position 1, Format YYYY-MM-DD)\n"
|
"- service_end_date\n"
|
||||||
"- invoice_note (Sämtlicher unstrukturierter Freitext, Projektbeschreibungen oder Abnahmekriterien vor Position 1)\n\n"
|
"- invoice_note\n\n"
|
||||||
"WICHTIGE REGEL: Analysiere den Text direkt VOR der ersten Tabellenposition '1'. "
|
"WICHTIGE REGEL: Analysiere den Text direkt VOR der ersten Tabellenposition '1'. "
|
||||||
"Sortiere alle dort vorlaufenden Zeilen vollständig in die dafür vorgesehenen ID-, Datums- und Freitext-Felder ein. "
|
"Sortiere alle dort vorlaufenden Zeilen vollständig in die dafür vorgesehenen ID-, Datums- und Freitext-Felder ein. "
|
||||||
"Schreibe diese vorlaufenden Metadaten NIEMALS in die Beschreibung der ersten Position hinein!\n\n"
|
"Schreibe diese vorlaufenden Metadaten NIEMALS in die Beschreibung der ersten Position hinein!\n\n"
|
||||||
|
|
@ -449,20 +451,27 @@ with col2:
|
||||||
if final_data.get("recipient_email") == "office@scitech-gmbh.de":
|
if final_data.get("recipient_email") == "office@scitech-gmbh.de":
|
||||||
final_data["recipient_email"] = ""
|
final_data["recipient_email"] = ""
|
||||||
|
|
||||||
# Zeilenbasiertes Python-Parsing für die Tabelle (stoppt nun korrekt dank 'break' bei Positionsnummern)
|
|
||||||
final_data["items"] = extract_invoice_items_pure_python(pdf_text)
|
final_data["items"] = extract_invoice_items_pure_python(pdf_text)
|
||||||
st.session_state.extracted_data = final_data
|
st.session_state.extracted_data = final_data
|
||||||
|
|
||||||
if st.session_state.extracted_data:
|
if st.session_state.extracted_data:
|
||||||
data = st.session_state.extracted_data
|
data = st.session_state.extracted_data
|
||||||
|
|
||||||
# Standard Rechnungsdaten
|
# --- NEU: BT-3 RECHNUNGSTYP DROPDOWN-MENÜ ---
|
||||||
|
inv_type_ui = st.selectbox(
|
||||||
|
"Rechnungstyp (BT-3)",
|
||||||
|
options=["380 (Handelsrechnung)", "381 (Gutschrift)", "384 (Korrekturrechnung)"],
|
||||||
|
index=0,
|
||||||
|
help="Bestimmt den steuerrechtlichen Belegtyp im XML-Header."
|
||||||
|
)
|
||||||
|
selected_type_code = inv_type_ui.split(" ")[0] # Filtert die reine Code-Nummer heraus
|
||||||
|
|
||||||
inv_num = st.text_input("Rechnungsnummer", value=data.get("invoice_number", ""))
|
inv_num = st.text_input("Rechnungsnummer", value=data.get("invoice_number", ""))
|
||||||
inv_date = st.text_input("Rechnungsdatum (YYYY-MM-DD)", value=data.get("invoice_date", ""))
|
inv_date = st.text_input("Rechnungsdatum (YYYY-MM-DD)", value=data.get("invoice_date", ""))
|
||||||
inv_delivery = st.text_input("Lieferdatum (YYYY-MM-DD)", value=data.get("delivery_date", ""))
|
inv_delivery = st.text_input("Lieferdatum (YYYY-MM-DD)", value=data.get("delivery_date", ""))
|
||||||
buyer_ref = st.text_input("Ihr Auftrag / Referenz", value=data.get("buyer_reference", ""))
|
buyer_ref = st.text_input("Ihr Auftrag / Referenz", value=data.get("buyer_reference", ""))
|
||||||
|
|
||||||
# NEU: UI-Eingabefelder für die Daten vor Position 1
|
# UI-Eingabefelder für die Daten vor Position 1 (BT-22 etc.)
|
||||||
st.markdown("---")
|
st.markdown("---")
|
||||||
st.markdown("🔗 **Globale Referenzen & Vorlauftexte (Vor Position 1):**")
|
st.markdown("🔗 **Globale Referenzen & Vorlauftexte (Vor Position 1):**")
|
||||||
c_ref1, c_ref2, c_ref3 = st.columns(3)
|
c_ref1, c_ref2, c_ref3 = st.columns(3)
|
||||||
|
|
@ -501,6 +510,7 @@ with col2:
|
||||||
r_city = st.text_input("Stadt (Kunde)", value=data.get("recipient_city", ""))
|
r_city = st.text_input("Stadt (Kunde)", value=data.get("recipient_city", ""))
|
||||||
|
|
||||||
st.markdown("**3. Positionen:**")
|
st.markdown("**3. Positionen:**")
|
||||||
|
# NEU: Der Dateneditor zeigt nun getrennte Spalten für Artikelname (BT-153) und Zusatzbeschreibung (BT-154)
|
||||||
edited_items = st.data_editor(data.get("items", []), num_rows="dynamic", width="stretch")
|
edited_items = st.data_editor(data.get("items", []), num_rows="dynamic", width="stretch")
|
||||||
vat_rate = st.number_input("Steuersatz (%)", value=float(data.get("vat_rate_percent") or 19.0))
|
vat_rate = st.number_input("Steuersatz (%)", value=float(data.get("vat_rate_percent") or 19.0))
|
||||||
|
|
||||||
|
|
@ -522,12 +532,12 @@ with col2:
|
||||||
st.markdown("---")
|
st.markdown("---")
|
||||||
if st.button("🔒 XRechnung exportieren", type="primary", width="stretch"):
|
if st.button("🔒 XRechnung exportieren", type="primary", width="stretch"):
|
||||||
final_invoice_dict = {
|
final_invoice_dict = {
|
||||||
|
"invoice_type_code": selected_type_code, # Übergabe der ausgewählten BT-3 ID
|
||||||
"invoice_number": inv_num, "invoice_date": inv_date, "delivery_date": inv_delivery,
|
"invoice_number": inv_num, "invoice_date": inv_date, "delivery_date": inv_delivery,
|
||||||
"buyer_reference": buyer_ref, "recipient_name": r_name, "recipient_email": r_email,
|
"buyer_reference": buyer_ref, "recipient_name": r_name, "recipient_email": r_email,
|
||||||
"recipient_street": r_street, "recipient_zip": r_zip, "recipient_city": r_city,
|
"recipient_street": r_street, "recipient_zip": r_zip, "recipient_city": r_city,
|
||||||
"items": edited_items, "total_net_amount": computed_net_amount, "total_vat_amount": computed_vat_amount,
|
"items": edited_items, "total_net_amount": computed_net_amount, "total_vat_amount": computed_vat_amount,
|
||||||
"vat_rate_percent": vat_rate, "total_gross_amount": computed_gross_amount, "iban": "DE06120700240456207000",
|
"vat_rate_percent": vat_rate, "total_gross_amount": computed_gross_amount, "iban": "DE06120700240456207000",
|
||||||
# Neue Felder für den XML-Builder anhängen
|
|
||||||
"delivery_note_id": dn_id,
|
"delivery_note_id": dn_id,
|
||||||
"order_id": o_id,
|
"order_id": o_id,
|
||||||
"contract_id": c_id,
|
"contract_id": c_id,
|
||||||
|
|
@ -545,9 +555,8 @@ st.caption(
|
||||||
"📝 **Hinweise:**\n\n"
|
"📝 **Hinweise:**\n\n"
|
||||||
"**Human-in-the-Loop:** "
|
"**Human-in-the-Loop:** "
|
||||||
"Das Tool dient als Automations-Assistent. Vor dem finalen XML-Export ist eine visuelle Endkontrolle der extrahierten Daten "
|
"Das Tool dient als Automations-Assistent. Vor dem finalen XML-Export ist eine visuelle Endkontrolle der extrahierten Daten "
|
||||||
"(insbesondere Rechnungsnummer und Empfängeradresse) durch den Sachbearbeiter zwingend erforderlich, um KI-Fehlinterpretationen auszuschließen.\n\n"
|
"(insbesondere Rechnungsnummer und Empfängeradresse) durch den Sachbearbeiter zwingend erforderlich.\n\n"
|
||||||
"**GoBD-Konformität:** "
|
"**GoBD-Konformität:** "
|
||||||
"Das Tool generiert ausschließlich das strukturierte XML-Format. Für die Einhaltung der GoBD-Richtlinien "
|
"Das Tool generiert ausschließlich das strukturierte XML-Format. Für die Einhaltung der GoBD-Richtlinien "
|
||||||
"(u. a. die revisionssichere Archivierung der Original-PDF sowie der generierten XML-Datei über den gesetzlichen Zeitraum von 10 Jahren) "
|
|
||||||
"ist der Betreiber der Software selbst verantwortlich. \n\n"
|
"ist der Betreiber der Software selbst verantwortlich. \n\n"
|
||||||
)
|
)
|
||||||
Loading…
Reference in New Issue