import os, uuid from datetime import datetime from flask import Blueprint, request, jsonify, render_template, current_app, send_file from werkzeug.utils import secure_filename import openpyxl from common import load_gl_dump from .logic import list_accounts, header_fill_rates, build_account_report, write_account_sheet gl_analyzer_bp = Blueprint("gl_analyzer", __name__, url_prefix="/gl-analyzer") # Single-user/single-session shortcut, same documented pattern as eib's # LAST_RESULT/PROCESS_STATUS: keeps the uploaded GL Dump's saved path # (not the parsed DataFrame) so the later /api/headers and /api/generate # steps of the wizard don't need a re-upload. Not safe for concurrent # multi-user use - not a concern for this internal, single-operator tool. UPLOADED_FILES = {} def _load(upload_id): path = UPLOADED_FILES.get(upload_id) if path is None or not os.path.exists(path): return None return load_gl_dump(path) @gl_analyzer_bp.route("/") def index(): return render_template("gl_analyzer/index.html") @gl_analyzer_bp.route("/api/upload", methods=["POST"]) def api_upload(): f = request.files.get("gl_file") if not f or not f.filename: return jsonify({"error": "Upload a GL extract"}), 400 path = os.path.join(current_app.config["UPLOAD_FOLDER"], f"{uuid.uuid4()}_{secure_filename(f.filename)}") f.save(path) gl_df = load_gl_dump(path) if gl_df is None: os.remove(path) return jsonify({"error": "This doesn't look like a GL Dump export (no header row with " "\"Journal\" and \"Ledger Account\" found)."}), 400 upload_id = str(uuid.uuid4()) UPLOADED_FILES[upload_id] = path return jsonify({ "status": "ok", "upload_id": upload_id, "accounts": list_accounts(gl_df), "line_count": len(gl_df), }), 200 @gl_analyzer_bp.route("/api/headers", methods=["POST"]) def api_headers(): data = request.get_json(silent=True) or {} upload_id = data.get("upload_id") account_codes = data.get("account_codes") or [] if not account_codes: return jsonify({"error": "Select at least one account"}), 400 gl_df = _load(upload_id) if gl_df is None: return jsonify({"error": "Upload expired or not found - upload the GL extract again"}), 400 result = header_fill_rates(gl_df, account_codes) return jsonify({"status": "ok", **result}), 200 @gl_analyzer_bp.route("/api/generate", methods=["POST"]) def api_generate(): data = request.get_json(silent=True) or {} upload_id = data.get("upload_id") account_labels = data.get("accounts") or [] main_header = data.get("main_header") extra_headers = data.get("extra_headers") or [] if not account_labels or not main_header: return jsonify({"error": "Select at least one account and a main header"}), 400 gl_df = _load(upload_id) if gl_df is None: return jsonify({"error": "Upload expired or not found - upload the GL extract again"}), 400 report_date = datetime.now().strftime("%Y-%m-%d") wb = openpyxl.Workbook() wb.remove(wb.active) accounts_out = [] for account in account_labels: schedule_df = build_account_report(gl_df, account, main_header, extra_headers) summary = write_account_sheet(wb, account, schedule_df, main_header, extra_headers, report_date) rows = [] for _, r in schedule_df.iterrows(): row = { "category": r["category"], "orig_total": r["orig_total"] if r["rate"] is not None else None, "orig_currency": r["orig_currency"], "rate": r["rate"], "amt_cad": r["amt_cad"], } for col in extra_headers: value = r[col] row[col] = value if value == value else None # NaN-safe (NaN != NaN) rows.append(row) accounts_out.append({ "account": account, "total": summary["total"], "row_count": summary["row_count"], "rows": rows, }) filename = f"GL_Analysis_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx" out_path = os.path.join(current_app.config["OUTPUT_FOLDER"], filename) wb.save(out_path) return jsonify({ "status": "ok", "accounts": accounts_out, "main_header": main_header, "extra_headers": extra_headers, "download_filename": filename, }), 200 @gl_analyzer_bp.route("/api/download/") 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)