Storage and export - Keep books and transactions in SQLite (data/cashbook.db) instead of .ods files; existing .ods books are migrated once at startup - Export a book as the cashbook spreadsheet (.xlsx/.ods, built from the template via LibreOffice) or as CSV - GST rounded per transaction to match the spreadsheet Tax - GST return page with IRD GST101A boxes 5-15 per six-monthly, two-monthly or monthly period, due dates, and a Zero-rated GST type - Income tax page with IR10 (financial statements summary) and IR4 (company return) boxes, from the cashbook plus year-end amounts typed in and saved per book FastAPI and accounts (following led-editor) - Replace the stdlib server with a FastAPI app (src/cashbook_app) run by uvicorn; dependencies in Pipfile - Cookie sessions with bcrypt passwords, first-run admin setup or BOOTSTRAP_ADMIN_*, invites (link or email), sign-in throttling, password change that signs out other sessions - Users page for administrators: rename, reset password, promote or demote, delete, list and revoke invites; last admin is protected - Replaces the shared CASHBOOK_PASSWORD basic auth; AUTH_* settings in .env (see .env.example) - Docker image uses a venv with system site packages for python3-uno - pytest suite for auth, user management, imports, GST and tax figures Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
93 lines
3.4 KiB
Python
93 lines
3.4 KiB
Python
#!/usr/bin/env python3
|
|
"""Export a cashbook from the database as a spreadsheet (.ods / .xlsx) or CSV.
|
|
|
|
The spreadsheet uses the cashbook template's layout: one sheet per month with
|
|
GST and category columns, plus the summary sheet.
|
|
|
|
Usage:
|
|
export.py BOOK OUT.{ods,xlsx,csv} [--data DIR]
|
|
"""
|
|
import argparse
|
|
import csv
|
|
import io
|
|
import os
|
|
import shutil
|
|
import tempfile
|
|
|
|
import ledger
|
|
|
|
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
TEMPLATE = os.path.join(HERE, "template.ods")
|
|
FORMATS = {
|
|
"ods": ("application/vnd.oasis.opendocument.spreadsheet", None),
|
|
"xlsx": ("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Calc MS Excel 2007 XML"),
|
|
"csv": ("text/csv", None),
|
|
}
|
|
|
|
|
|
def export_csv(conn, book):
|
|
out = io.StringIO()
|
|
w = csv.writer(out)
|
|
w.writerow(["Date", "Month", "Reference", "Payment origin", "In", "Out", "GST type",
|
|
"GST", "Net (excl GST)", "Category"])
|
|
for sheet in ledger.FY_ORDER:
|
|
m = ledger.read_month(conn, book, sheet)
|
|
for r in m["rows"]:
|
|
w.writerow([r["date"], m["label"], r["reference"], r["origin"],
|
|
f"{r['income']:.2f}" if r["income"] else "",
|
|
f"{r['expense']:.2f}" if r["expense"] else "",
|
|
r["gst"], f"{r['gst_in'] or r['gst_out']:.2f}", f"{r['net']:.2f}",
|
|
r["category"] or "Unallocated"])
|
|
return out.getvalue().encode("utf-8-sig") # BOM so Excel reads UTF-8
|
|
|
|
|
|
def export_spreadsheet(conn, book, fmt, open_fn):
|
|
"""Fill a copy of the template and return its bytes. `open_fn` opens a document (office.Office.open)."""
|
|
import cashbook # needs LibreOffice's Python bridge
|
|
from office import prop
|
|
months = {s: ledger.read_month(conn, book, s)["rows"] for s in ledger.FY_ORDER}
|
|
tmp = tempfile.mkdtemp(prefix="cashbook_export_")
|
|
try:
|
|
path = os.path.join(tmp, "book.ods")
|
|
shutil.copy(TEMPLATE, path)
|
|
with open_fn(path) as doc:
|
|
cashbook.write_book(doc, book["start_year"], book["opening_cents"] / 100, months)
|
|
if fmt == "ods":
|
|
doc.store()
|
|
else:
|
|
import uno
|
|
path = os.path.join(tmp, f"book.{fmt}")
|
|
doc.storeToURL(uno.systemPathToFileUrl(path), (prop("FilterName", FORMATS[fmt][1]),))
|
|
with open(path, "rb") as f:
|
|
return f.read()
|
|
finally:
|
|
shutil.rmtree(tmp, ignore_errors=True)
|
|
|
|
|
|
def export(conn, book, fmt, open_fn=None):
|
|
if fmt not in FORMATS:
|
|
raise ValueError(f"unknown format {fmt!r}; use ods, xlsx or csv")
|
|
if fmt == "csv":
|
|
return export_csv(conn, book)
|
|
if open_fn is None:
|
|
from office import open_book as open_fn
|
|
return export_spreadsheet(conn, book, fmt, open_fn)
|
|
|
|
|
|
def main():
|
|
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
|
|
ap.add_argument("book", help="book name")
|
|
ap.add_argument("out", help="file to write; the extension picks the format")
|
|
ap.add_argument("--data", default=os.path.join(os.path.dirname(HERE), "data"))
|
|
args = ap.parse_args()
|
|
conn = ledger.connect(os.path.join(args.data, "cashbook.db"))
|
|
fmt = os.path.splitext(args.out)[1].lstrip(".").lower()
|
|
data = export(conn, ledger.get_book(conn, args.book), fmt)
|
|
with open(args.out, "wb") as f:
|
|
f.write(data)
|
|
print(f"Wrote {args.out}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|