304 lines
11 KiB
Python
304 lines
11 KiB
Python
import os, re, uuid, requests
|
|
from flask import Blueprint, request, jsonify, send_file, render_template, current_app
|
|
from werkzeug.utils import secure_filename
|
|
import pandas as pd
|
|
|
|
from .logic import (
|
|
probe_docling,
|
|
process_raw,
|
|
run_audit,
|
|
parse_pdf_with_docling,
|
|
extract_balances_from_markdown,
|
|
run_audit_pdf,
|
|
populate_template,
|
|
populate_upload_template,
|
|
add_merchant_mappings,
|
|
)
|
|
|
|
eib_bp = Blueprint("eib", __name__, url_prefix="/eib")
|
|
|
|
DOCLING_URL = os.environ.get("DOCLING_URL", "http://localhost:5001")
|
|
|
|
# ── Progress tracking for the frontend polling UI ───────────────────────────
|
|
# Single-job assumption: this is a local single-user tool, so one shared
|
|
# status dict is enough. Reset at the start of every /api/process call.
|
|
PROCESS_STATUS = {"active": False, "current": "", "log": []}
|
|
|
|
# Holds the most recently completed run's output_df, so the "Generate EIB
|
|
# File (for Upload)" button can reuse it without re-uploading. Same
|
|
# single-user/local-tool assumption as PROCESS_STATUS.
|
|
LAST_RESULT = {"output_df": None}
|
|
|
|
|
|
def status_reset():
|
|
PROCESS_STATUS["active"] = True
|
|
PROCESS_STATUS["current"] = "Starting..."
|
|
PROCESS_STATUS["log"] = []
|
|
LAST_RESULT["output_df"] = None
|
|
|
|
|
|
def status_set(current):
|
|
PROCESS_STATUS["current"] = current
|
|
|
|
|
|
def status_log(line):
|
|
PROCESS_STATUS["log"].append(line)
|
|
|
|
|
|
def status_done():
|
|
PROCESS_STATUS["active"] = False
|
|
PROCESS_STATUS["current"] = "Done"
|
|
|
|
|
|
@eib_bp.route("/")
|
|
def index():
|
|
return render_template("eib/index.html")
|
|
|
|
|
|
@eib_bp.route("/api/debug/probe-pdf", methods=["POST"])
|
|
def api_probe_pdf():
|
|
"""
|
|
Diagnostic endpoint. Upload one or more PDFs and this calls Docling
|
|
on each, logging the raw response structure to the container logs
|
|
(docker compose logs app) and saving full JSON dumps to
|
|
outputs/_debug_markdown/*.PROBE.json. Does not touch the normal
|
|
processing flow or produce an EIB file.
|
|
"""
|
|
pdf_files = [
|
|
f for key, f in request.files.items()
|
|
if key.startswith("pdf_file") and f.filename
|
|
]
|
|
if not pdf_files:
|
|
return jsonify({"error": "No PDF files uploaded"}), 400
|
|
|
|
results = []
|
|
for pdf_file in pdf_files:
|
|
pdf_path = os.path.join(
|
|
current_app.config["UPLOAD_FOLDER"],
|
|
f"{uuid.uuid4()}_{secure_filename(pdf_file.filename)}",
|
|
)
|
|
pdf_file.save(pdf_path)
|
|
result = probe_docling(pdf_path, DOCLING_URL, current_app.config["OUTPUT_FOLDER"])
|
|
results.append({
|
|
"filename": pdf_file.filename,
|
|
"probed": result is not None,
|
|
})
|
|
|
|
return jsonify({
|
|
"status": "probed",
|
|
"files": results,
|
|
"message": "Check container logs (docker compose logs app) and "
|
|
"outputs/_debug_markdown/*.PROBE.json for full detail.",
|
|
}), 200
|
|
|
|
|
|
@eib_bp.route("/api/process", methods=["POST"])
|
|
def api_process():
|
|
if "raw_file" not in request.files:
|
|
return jsonify({"error": "No raw file uploaded"}), 400
|
|
|
|
status_reset()
|
|
|
|
try:
|
|
raw_file = request.files["raw_file"]
|
|
stmt_file = request.files.get("stmt_file")
|
|
pdf_files = [
|
|
f for key, f in request.files.items()
|
|
if key.startswith("pdf_file") and f.filename
|
|
]
|
|
|
|
status_set("Reading raw file...")
|
|
raw_filename = secure_filename(raw_file.filename)
|
|
raw_path = os.path.join(current_app.config["UPLOAD_FOLDER"], f"{uuid.uuid4()}_{raw_filename}")
|
|
raw_file.save(raw_path)
|
|
|
|
try:
|
|
raw_df = pd.read_excel(raw_path)
|
|
except Exception as e:
|
|
return jsonify({"error": f"Could not read raw file: {e}"}), 400
|
|
|
|
status_set("Classifying transactions...")
|
|
output_df, included_box_ids, unmapped = process_raw(raw_df)
|
|
status_log(f"Processed {len(output_df)} EIB transactions from {len(raw_df)} raw rows")
|
|
|
|
if unmapped:
|
|
return jsonify({
|
|
"status": "unmapped",
|
|
"unmapped": list(unmapped.keys()),
|
|
"message": f"{len(unmapped)} merchant(s) need clean names before output can be generated.",
|
|
}), 200
|
|
|
|
LAST_RESULT["output_df"] = output_df
|
|
|
|
audit_df = None
|
|
|
|
if stmt_file and stmt_file.filename:
|
|
status_set("Reading statement CSV...")
|
|
stmt_path = os.path.join(
|
|
current_app.config["UPLOAD_FOLDER"],
|
|
f"{uuid.uuid4()}_{secure_filename(stmt_file.filename)}",
|
|
)
|
|
stmt_file.save(stmt_path)
|
|
try:
|
|
stmt_df = pd.read_csv(stmt_path)
|
|
status_set("Running CSV audit...")
|
|
audit_df = run_audit(output_df, included_box_ids, stmt_df)
|
|
status_log(f"Audited {len(stmt_df['Balance'].dropna().unique())} cardholder(s)")
|
|
except Exception as e:
|
|
return jsonify({"error": f"Could not read statement CSV: {e}"}), 400
|
|
|
|
elif pdf_files:
|
|
pdf_balances_by_person = {}
|
|
parse_errors = []
|
|
debug_dir = os.path.join(current_app.config["OUTPUT_FOLDER"], "_debug_markdown")
|
|
os.makedirs(debug_dir, exist_ok=True)
|
|
|
|
total = len(pdf_files)
|
|
for i, pdf_file in enumerate(pdf_files, start=1):
|
|
status_set(f"Converting {pdf_file.filename} via Docling ({i} of {total})...")
|
|
|
|
pdf_path = os.path.join(
|
|
current_app.config["UPLOAD_FOLDER"],
|
|
f"{uuid.uuid4()}_{secure_filename(pdf_file.filename)}",
|
|
)
|
|
pdf_file.save(pdf_path)
|
|
markdown = parse_pdf_with_docling(pdf_path, DOCLING_URL, current_app.config["OUTPUT_FOLDER"])
|
|
|
|
if markdown is None:
|
|
parse_errors.append(pdf_file.filename)
|
|
status_log(f"✕ {pdf_file.filename}: Docling conversion failed")
|
|
continue
|
|
|
|
person_match = re.search(
|
|
r"Balances\s*\n+([A-Z][a-z]+(?: [A-Z][a-z]+)+)", markdown
|
|
)
|
|
person_name = (
|
|
person_match.group(1).strip() if person_match
|
|
else os.path.splitext(pdf_file.filename)[0].replace("_", " ").title()
|
|
)
|
|
|
|
status_set(f"Extracting balances from {pdf_file.filename} ({i} of {total})...")
|
|
balances = extract_balances_from_markdown(markdown)
|
|
|
|
debug_path = os.path.join(
|
|
debug_dir, f"{secure_filename(pdf_file.filename)}.md"
|
|
)
|
|
with open(debug_path, "w", encoding="utf-8") as dbg:
|
|
dbg.write(markdown)
|
|
|
|
if balances:
|
|
pdf_balances_by_person[person_name] = balances
|
|
currencies = ", ".join(sorted(balances.keys()))
|
|
status_log(f"✓ {pdf_file.filename} -> {person_name} ({currencies})")
|
|
print(f"[docling] {pdf_file.filename} -> '{person_name}': {balances}")
|
|
else:
|
|
parse_errors.append(pdf_file.filename)
|
|
status_log(f"✕ {pdf_file.filename}: no balance table found")
|
|
print(f"[docling] No balances found in {pdf_file.filename} — "
|
|
f"markdown saved to {debug_path}")
|
|
print(f"[docling] First 1000 chars:\n{markdown[:1000]}")
|
|
|
|
if not pdf_balances_by_person:
|
|
return jsonify({
|
|
"status": "pdf_parse_failed",
|
|
"message": (
|
|
f"Docling converted the PDF(s) but no balance summary table "
|
|
f"could be found in: {', '.join(parse_errors)}. "
|
|
f"Debug files saved to outputs/_debug_markdown/ for review."
|
|
),
|
|
}), 200
|
|
|
|
status_set("Running PDF audit...")
|
|
audit_df = run_audit_pdf(output_df, included_box_ids, pdf_balances_by_person, raw_df)
|
|
|
|
if parse_errors:
|
|
audit_df["Note"] = audit_df["Cardholder"].apply(
|
|
lambda p: "Parse failed" if p in parse_errors else ""
|
|
)
|
|
|
|
status_set("Building EIB output file...")
|
|
fname, fpath = populate_template(output_df, current_app.config["OUTPUT_FOLDER"], audit_df)
|
|
|
|
people = sorted(output_df["Balance"].dropna().unique().tolist())
|
|
summary = {
|
|
"rows": len(output_df),
|
|
"people": people,
|
|
"totals_usd": round(
|
|
output_df[output_df["Converted Currency"] == "USD"]["Converted Amount"].sum(), 2
|
|
),
|
|
"totals_gbp": round(
|
|
output_df[output_df["Converted Currency"] == "GBP"]["Converted Amount"].sum(), 2
|
|
),
|
|
"audit": audit_df.to_dict("records") if audit_df is not None else None,
|
|
"filename": fname,
|
|
}
|
|
status_log("Done.")
|
|
return jsonify({"status": "ok", **summary}), 200
|
|
|
|
finally:
|
|
status_done()
|
|
|
|
|
|
@eib_bp.route("/api/process/status")
|
|
def api_process_status():
|
|
return jsonify(PROCESS_STATUS)
|
|
|
|
|
|
@eib_bp.route("/api/merchant-mappings", methods=["POST"])
|
|
def api_merchant_mappings():
|
|
"""
|
|
Add clean names for previously-unmapped merchants, submitted from the
|
|
"map it now" form in the unmapped-merchant panel. Writes straight to
|
|
merchant_lookup.csv so the very next /api/process run picks them up.
|
|
"""
|
|
data = request.get_json(silent=True) or {}
|
|
mappings = data.get("mappings")
|
|
if not mappings or not isinstance(mappings, dict):
|
|
return jsonify({"error": "No mappings provided"}), 400
|
|
if not all(str(v).strip() for v in mappings.values()):
|
|
return jsonify({"error": "Every merchant needs a clean name"}), 400
|
|
|
|
add_merchant_mappings(mappings)
|
|
return jsonify({"status": "ok", "added": len(mappings)}), 200
|
|
|
|
|
|
@eib_bp.route("/api/generate-upload", methods=["POST"])
|
|
def api_generate_upload():
|
|
"""
|
|
Populate planeterra_equals_cards_transactions_eib_v45.xlsx (the
|
|
Workday-ready upload file) from the most recently completed /api/process
|
|
run, without requiring a re-upload.
|
|
"""
|
|
output_df = LAST_RESULT["output_df"]
|
|
if output_df is None:
|
|
return jsonify({"error": "No processed data available — run Process first."}), 400
|
|
|
|
try:
|
|
fname, fpath, unmatched = populate_upload_template(output_df, current_app.config["OUTPUT_FOLDER"])
|
|
except FileNotFoundError as e:
|
|
return jsonify({"error": f"Upload template file is missing from the server: {e}"}), 500
|
|
|
|
return jsonify({
|
|
"status": "ok",
|
|
"filename": fname,
|
|
"unmatched_cardholders": unmatched,
|
|
}), 200
|
|
|
|
|
|
@eib_bp.route("/api/download/<filename>")
|
|
def api_download(filename):
|
|
safe = secure_filename(filename)
|
|
fpath = os.path.join(current_app.config["OUTPUT_FOLDER"], safe)
|
|
if not os.path.exists(fpath):
|
|
return jsonify({"error": "File not found"}), 404
|
|
return send_file(fpath, as_attachment=True)
|
|
|
|
|
|
@eib_bp.route("/api/docling/status")
|
|
def docling_status():
|
|
try:
|
|
r = requests.get(f"{DOCLING_URL}/health", timeout=5)
|
|
return jsonify({"available": r.status_code == 200})
|
|
except Exception:
|
|
return jsonify({"available": False})
|