bettersight-statement-extra.../backend/services/xero_csv_service.py

101 lines
5.2 KiB
Python

# Builds a Xero-compatible statement CSV export of an extraction result - callers decide where it ends up (an in-memory buffer streamed to the client, see routes/extraction.py's /api/export/xero-csv).
"""
Xero statement import CSV - the second accounting-software integration
this app supports, after QBO's own export (qbo_service.py). Researched
directly (Xero's own documented import requirements) rather than assumed
to match QBO's shape - and genuinely simpler in one real way: Xero's CSV
import has NO equivalent of OFX's <BANKACCTFROM> block at all. Which bank
account a statement gets imported INTO is chosen inside Xero's own UI at
import time, not embedded in the file - so, unlike QBO, this needs no
bankAccountProfiles lookup and no "bank_account" input at all. Confirmed
across multiple independent sources before building, not assumed from one.
Two sources disagreed on whether Xero maps CSV columns by NAME or by
POSITION - rather than picking one and risking the other being right,
this writes a real header row in the documented recommended order
(Date, Amount, Payee, Description), which is correct under either
reading.
Reuses this pipeline's own existing data entirely - no new extraction
logic, same `result["transactions"]` list excel_service.py/qbo_service.py
already consume.
"""
import csv
import io
import re
_DESC_SANITIZE_RE = re.compile(r"[\r\n]+")
def _clean_description(text):
"""A transaction description, with any embedded newline collapsed to
a space - Python's csv module would technically quote a multi-line
field correctly per RFC 4180, but Xero's own importer isn't
guaranteed to parse an embedded raw newline the same way (its own
documentation doesn't say either way) - same conservative choice
qbo_service.py's own _escape() already makes for the identical
reason, rather than trusting a downstream parser's own leniency."""
return _DESC_SANITIZE_RE.sub(" ", text or "").strip()
def build_csv(result, title="Statement Extraction"):
"""
Builds the Xero statement-import CSV as a plain string - never
touches disk, same discipline as excel_service.build_workbook/
qbo_service.build_qbo.
Data flow:
result (dict) - a pipeline_service.run()/recheck() result:
transactions, etc. (title is accepted for
signature symmetry with build_qbo, but Xero's
own CSV format has nowhere to put a statement
title - there's no header/metadata block at all,
just the data rows)
returns (str) - the complete CSV text, UTF-8, comma-delimited,
one header row + one row per transaction
Column choices, not arbitrary:
Date - this pipeline's own existing "DD Mon YYYY" text
(e.g. "03 Jan 2027") is ALREADY one of Xero's own
documented accepted date formats, unchanged - a
genuine fit, not a coincidence worth re-deriving:
it sidesteps the #1 documented Xero CSV failure mode
(locale-ambiguous numeric dates like "03/04/2026"
parsing differently depending on the importing
org's own regional settings) for free, since this
format is never ambiguous in any locale.
Amount - a single signed value (Xero's own CSV format has no
separate debit/credit columns, unlike this app's own
Excel export) - already exactly what this pipeline's
own `amount` field already is; formatted to 2
decimals with no currency symbol/thousands separator/
parentheses, all of which Xero's own documentation
flags as real, silent-failure-prone formats to avoid.
Payee/ - this pipeline has no separate payee-name extraction
Description (would mean guessing a clean counterparty name out
of noisy bank text, which this app's own "never
silently correct" rule prohibits) - so both columns
carry the same real transaction description, the
identical NAME/MEMO duality qbo_service.py's own
build_qbo() already uses for the exact same reason,
kept consistent across both export formats rather
than inventing a second, different judgment call.
"""
buffer = io.StringIO()
writer = csv.writer(buffer)
writer.writerow(["Date", "Amount", "Payee", "Description"])
for t in result.get("transactions") or []:
date_text = (t.get("date") or "").strip()
amount = t.get("amount")
if not date_text or amount is None:
# Never silently invent a date/amount this pipeline itself
# never resolved - skip it from the export the same way
# qbo_service.py's own build_qbo() does, rather than writing
# a row Xero would import with a blank/wrong value.
continue
description = _clean_description(t.get("description"))
writer.writerow([date_text, f"{amount:.2f}", description, description])
return buffer.getvalue()