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

221 lines
9.9 KiB
Python

# Builds a QBO (QuickBooks Web Connect) 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/qbo).
"""
QBO export - the first of two accounting-software integrations this app
supports (Xero's own CSV import is the second - see xero_csv_service.py
and CLAUDE.md's own "Xero export" entry). QBO (QuickBooks "Web Connect")
is Intuit's own OFX 1.x SGML variant - it writes that shape directly, not
a generic XML library, since OFX 1.x isn't well-formed XML at all.
Renamed from this module's own earlier "qfx_service.py"/build_qfx 2026-11-19
after aggressive requirements research (see CLAUDE.md's own ".qbo export"
entry) found the file this module used to produce was never actually a
real QFX - it was missing the one field, <INTU.BID>, that distinguishes
Intuit's own variants from plain generic OFX. QuickBooks Online's own
official upload UI lists .qbo (not .qfx) as a supported extension, and
QuickBooks Desktop's Web Connect import also expects .qbo - so this format
is now built and named correctly for both of this app's actual targets,
with <INTU.BID>3000 (Wells Fargo, Intuit's own documented generic
placeholder - confirmed via ProperSoft's own support documentation)
added to the sign-on block. That value is purely cosmetic: QuickBooks
Desktop uses it only to choose which bank-name label to show during
import, never which real account the transactions land in (the user
picks that manually regardless) - so it's hardcoded here, not something
a bankAccountProfiles record needs to carry.
Reuses this pipeline's own existing data entirely - no new extraction
logic. `result["transactions"]` is the exact same list excel_service.py
already consumes; `bank_account` is the one new input (bankId/accountId/
accountType), resolved from a bankAccountProfiles record the FRONTEND
already fetched from PocketBase - this service never talks to
PocketBase itself, consistent with every other backend service in this
app.
"""
import hashlib
import re
from services import checks_service
_ESCAPE_RE = re.compile(r"[<>&\r\n]")
# Intuit's own documented generic bank-id placeholder (ProperSoft's own
# support docs: "If your bank is not listed, use 3000 (Wells Fargo), which
# allows every account type") - this app has no real registered Intuit
# bank id for an arbitrary source bank, and doesn't need one: the value
# only affects which bank-name label QuickBooks Desktop shows during
# import, never which account the transactions actually import into.
_INTU_BID = "3000"
def _escape(text):
"""Strips/replaces characters that would break OFX 1.x SGML parsing
(there's no closing tag to bound a value, so a stray "<" or a
newline inside one would corrupt every field after it) - not XML
entity-escaping (OFX 1.x isn't XML), just removal, since a
transaction description has no legitimate use for any of these."""
return _ESCAPE_RE.sub(" ", text or "").strip()
def _fitid(t, index):
"""A stable, unique-per-transaction id (OFX FITID) - this pipeline's
own extracted data has no native bank transaction id to reuse (unlike
a real bank's own OFX export), so one is derived from the
transaction's own content. Hashed on date+description+amount+balance
(not the bare list index, which shifts if a row is later inserted/
deleted via the review screen's own structural edits) so the SAME
transaction re-exported after an unrelated edit elsewhere in the
statement still gets the same FITID - the whole point of a stable id
is letting QBO's own dedup logic recognize a re-import of the same
transaction, which a position-based id would defeat the first time
any other row in the statement changed. `index` is still mixed in as
a tie-breaker for the one real edge case content-hashing alone can't
resolve: two genuinely identical transactions (same date/description/
amount/balance) are not that rare on a real statement (e.g. two
identical-amount coffee purchases the same day) - without this, both
would collide onto the same FITID and one would be silently dropped
by QBO's own dedup, exactly the "never silently exclude data" failure
mode this app's own governing rule exists to prevent.
"""
raw = f"{t.get('date')}|{t.get('description')}|{t.get('amount')}|{t.get('balance')}|{index}"
return hashlib.sha1(raw.encode("utf-8")).hexdigest()[:32].upper()
def _dtposted(date_text):
"""DD Mon[ YYYY] -> YYYYMMDD120000 (OFX's own DTSERVER/DTPOSTED
format - date-only precision is all this pipeline has, so every
transaction gets noon as an arbitrary, non-meaningful time-of-day,
just enough to produce a syntactically valid OFX datetime). Reuses
checks_service._parse_date directly rather than re-deriving the same
"DD Mon[ YYYY]" parsing a second time - same precedent
pipeline_service.py's own period-detection code already sets for
calling this "private" helper across module boundaries. A missing
year (see that function's own docstring - some banks print only
day+month per row) falls back to 1900, a syntactically valid but
obviously-wrong placeholder - better than crashing, and
`has_unreliable_dates` on the overall result already warns the user
their own export may need a manual date check in that case.
"""
parsed = checks_service._parse_date(date_text)
if not parsed:
return None
year, month, day = parsed
return f"{year or 1900:04d}{month:02d}{day:02d}120000"
def build_qbo(result, bank_account, title="Statement Extraction"):
"""
Builds the QBO document as a plain string - never touches disk,
same discipline as excel_service.build_workbook.
Data flow:
result (dict) - a pipeline_service.run()/recheck() result:
transactions, closing_balance, etc.
bank_account (dict) - {"bankId", "accountId", "accountType"} from
a bankAccountProfiles record (see
pb_migrations/14's own docstring for why
accountId is deliberately not required to
be a real account number)
title (str) - used only for OFX's own required but
cosmetic <ORG>/<FID> sign-on fields
returns (str) - the complete QBO document text
"""
transactions = result.get("transactions") or []
lines = []
for i, t in enumerate(transactions):
dtposted = _dtposted(t.get("date"))
amount = t.get("amount")
if dtposted is None or amount is None:
# Never silently invent a date/amount this pipeline itself
# never resolved (e.g. a row the user left blank after an
# "Insert row" structural edit) - skip it from the QBO the
# same way a row with no real money value already doesn't
# become a transaction in the FIRST extraction pass either,
# rather than writing a malformed <STMTTRN> QBO might reject
# the whole file over.
continue
trntype = "CREDIT" if amount >= 0 else "DEBIT"
name = _escape(t.get("description") or "Transaction")[:32] # OFX NAME's own conventional length cap
memo = _escape(t.get("description") or "")
lines.append("<STMTTRN>")
lines.append(f"<TRNTYPE>{trntype}")
lines.append(f"<DTPOSTED>{dtposted}")
lines.append(f"<TRNAMT>{amount:.2f}")
lines.append(f"<FITID>{_fitid(t, i)}")
lines.append(f"<NAME>{name}")
if memo:
lines.append(f"<MEMO>{memo}")
lines.append("</STMTTRN>")
txn_block = "\n".join(lines)
# No top-level "closing_balance" key exists on this result shape at
# all (confirmed by reading excel_service.py, which doesn't
# reference one either - the export route's own `result` dict only
# ever carries transactions/page_reports/period/checks/etc, see
# routes/extraction.py's own /api/export) - the last transaction's
# own printed `balance` is the same "final balance" value the
# Transactions sheet's own last row already shows, so it's reused
# here rather than inventing a field this pipeline doesn't produce.
closing_balance = transactions[-1].get("balance") if transactions else None
dtasof = _dtposted(transactions[-1]["date"]) if transactions else None
ledger_block = ""
if closing_balance is not None and dtasof is not None:
ledger_block = (
"<LEDGERBAL>\n"
f"<BALAMT>{closing_balance:.2f}\n"
f"<DTASOF>{dtasof}\n"
"</LEDGERBAL>\n"
)
org = _escape(title)[:32] or "Bettersight"
return (
"OFXHEADER:100\n"
"DATA:OFXSGML\n"
"VERSION:102\n"
"SECURITY:NONE\n"
"ENCODING:USASCII\n"
"CHARSET:1252\n"
"COMPRESSION:NONE\n"
"OLDFILEUID:NONE\n"
"NEWFILEUID:NONE\n"
"\n"
"<OFX>\n"
"<SIGNONMSGSRSV1>\n"
"<SONRS>\n"
"<STATUS>\n"
"<CODE>0\n"
"<SEVERITY>INFO\n"
"</STATUS>\n"
f"<DTSERVER>{_dtposted(transactions[0]['date']) if transactions else '19000101120000'}\n"
"<LANGUAGE>ENG\n"
"<FI>\n"
f"<ORG>{org}\n"
f"<INTU.BID>{_INTU_BID}\n"
"</FI>\n"
"</SONRS>\n"
"</SIGNONMSGSRSV1>\n"
"<BANKMSGSRSV1>\n"
"<STMTTRNRS>\n"
"<TRNUID>1\n"
"<STATUS>\n"
"<CODE>0\n"
"<SEVERITY>INFO\n"
"</STATUS>\n"
"<STMTRS>\n"
"<CURDEF>USD\n"
"<BANKACCTFROM>\n"
f"<BANKID>{_escape(bank_account['bankId'])}\n"
f"<ACCTID>{_escape(bank_account['accountId'])}\n"
f"<ACCTTYPE>{bank_account['accountType']}\n"
"</BANKACCTFROM>\n"
"<BANKTRANLIST>\n"
f"{txn_block}\n"
"</BANKTRANLIST>\n"
f"{ledger_block}"
"</STMTRS>\n"
"</STMTTRNRS>\n"
"</BANKMSGSRSV1>\n"
"</OFX>\n"
)