Compare commits
No commits in common. "f89497b25d2b3f2fea581edf48da32af30e928ba" and "bdfa244729c7fa1b6c8d60a35aca98d9aa276174" have entirely different histories.
f89497b25d
...
bdfa244729
|
|
@ -6,6 +6,4 @@ __pycache__/
|
||||||
*.xlsx
|
*.xlsx
|
||||||
*.csv
|
*.csv
|
||||||
*.pdf
|
*.pdf
|
||||||
!app/tools/eib/eib_pre_template.xlsx
|
|
||||||
!app/tools/eib/planeterra_equals_cards_transactions_eib_v45.xlsx
|
|
||||||
.claude/settings.local.json
|
.claude/settings.local.json
|
||||||
|
|
|
||||||
14
CLAUDE.md
14
CLAUDE.md
|
|
@ -65,17 +65,9 @@ to lift out shared helpers only once a second tool actually duplicates something
|
||||||
- `parse_pdf_with_docling()` / `extract_balances_from_markdown()` call the self-hosted
|
- `parse_pdf_with_docling()` / `extract_balances_from_markdown()` call the self-hosted
|
||||||
Docling container over HTTP to OCR a PDF statement into markdown and pull the
|
Docling container over HTTP to OCR a PDF statement into markdown and pull the
|
||||||
opening/credits/debits/closing balance table out of it.
|
opening/credits/debits/closing balance table out of it.
|
||||||
- `populate_template()` writes the final `EIB_Processed[_Audited]_<date>.xlsx` by loading
|
- `build_excel()` writes the final `EIB_Processed[_Audited]_<date>.xlsx`, appending the
|
||||||
the finance-owned `app/tools/eib/eib_pre_template.xlsx` (tracked in git despite the
|
audit table 4 columns right of the EIB columns, color-coded MATCHED (green) /
|
||||||
blanket `*.xlsx` gitignore rule — see the `!` exception) and writing into its
|
REVIEW REQUIRED (red).
|
||||||
`Final Sheet`: EIB rows into `A2:I<n+1>` (clearing any previous run's rows first),
|
|
||||||
audit table starting at column `AA` (color-coded MATCHED/REVIEW REQUIRED), saved as a
|
|
||||||
new dated file — the template itself is never mutated. Columns `J:Y` are finance's own
|
|
||||||
corporate-card-ID lookup formulas (against the `Equals Card IDs` sheet) plus a legacy
|
|
||||||
static block and are **never written to**; `_extend_formulas_down()` only fills in a
|
|
||||||
`J:M` formula (translated from row 2's pattern) on rows within the new data range that
|
|
||||||
don't already have one — the template's formula rows are known to be non-contiguous
|
|
||||||
(leftover manual test batches), so gaps get filled but nothing existing is overwritten.
|
|
||||||
- `routes.py` wires uploads and these functions together behind `/eib/...`, including a
|
- `routes.py` wires uploads and these functions together behind `/eib/...`, including a
|
||||||
module-level `PROCESS_STATUS` dict polled by the frontend for live progress — explicitly
|
module-level `PROCESS_STATUS` dict polled by the frontend for live progress — explicitly
|
||||||
a single-job/single-user shortcut, not safe for concurrent runs.
|
a single-job/single-user shortcut, not safe for concurrent runs.
|
||||||
|
|
|
||||||
Binary file not shown.
|
|
@ -1,44 +1,8 @@
|
||||||
import os, re, json, requests
|
import os, re, json, requests
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
import openpyxl
|
|
||||||
from openpyxl.styles import PatternFill, Font, Alignment, Border, Side
|
from openpyxl.styles import PatternFill, Font, Alignment, Border, Side
|
||||||
from openpyxl.utils import get_column_letter
|
from openpyxl.utils import get_column_letter
|
||||||
from openpyxl.formula.translate import Translator
|
|
||||||
|
|
||||||
TEMPLATE_PATH = os.path.join(os.path.dirname(__file__), "eib_pre_template.xlsx")
|
|
||||||
TEMPLATE_SHEET = "Final Sheet"
|
|
||||||
# A:I holds our EIB output; J:Y is finance's own formula/lookup area and is
|
|
||||||
# never touched; the audit table is written starting at column AA.
|
|
||||||
TEMPLATE_DATA_COLS = 9 # A..I
|
|
||||||
TEMPLATE_FORMULA_COLS = (10, 13) # J..M — extended downward only, never cleared
|
|
||||||
TEMPLATE_AUDIT_START_COL = 27 # AA
|
|
||||||
|
|
||||||
CARD_ID_LOOKUP_SHEET = "Equals Card IDs"
|
|
||||||
|
|
||||||
UPLOAD_TEMPLATE_PATH = os.path.join(
|
|
||||||
os.path.dirname(__file__), "planeterra_equals_cards_transactions_eib_v45.xlsx"
|
|
||||||
)
|
|
||||||
UPLOAD_TRANSACTION_SHEET = "Expense Credit Card Transaction"
|
|
||||||
UPLOAD_HEADER_SHEET = "Credit Card Transaction Header"
|
|
||||||
UPLOAD_DATA_START_ROW = 6
|
|
||||||
UPLOAD_HEADER_DATA_ROW = 6
|
|
||||||
# Column indices (1-based) on the "Expense Credit Card Transaction" sheet.
|
|
||||||
UPLOAD_COLS = {
|
|
||||||
"header_key": 2, # B
|
|
||||||
"line_key": 3, # C
|
|
||||||
"transaction_number": 4, # D
|
|
||||||
"transaction_date": 6, # F
|
|
||||||
"amount": 19, # S
|
|
||||||
"source_currency": 22, # V
|
|
||||||
"converted_amount": 24, # X
|
|
||||||
"converted_currency": 26, # Z
|
|
||||||
"charge_description": 32, # AF
|
|
||||||
"expense_credit_card_id": 37, # AK
|
|
||||||
"corporate_account": 39, # AM
|
|
||||||
"cardholder_id": 40, # AN
|
|
||||||
"merchant_name": 45, # AS
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def probe_docling(pdf_path, docling_url, output_folder):
|
def probe_docling(pdf_path, docling_url, output_folder):
|
||||||
|
|
@ -743,46 +707,8 @@ def run_audit_pdf(output_df, included_box_ids, pdf_balances_by_person, raw_df):
|
||||||
})
|
})
|
||||||
return pd.DataFrame(audit_rows)
|
return pd.DataFrame(audit_rows)
|
||||||
|
|
||||||
def _extend_formulas_down(ws, cols, first_row, last_row):
|
def build_excel(output_df, output_folder, audit_df=None):
|
||||||
"""
|
"""Write the EIB output Excel with optional audit table."""
|
||||||
Ensure every row in [first_row, last_row] has a formula in each of
|
|
||||||
`cols`, using row `first_row`'s formula as the canonical pattern
|
|
||||||
(relative-reference translated per row). The template's formula rows
|
|
||||||
are known to be non-contiguous — leftover from earlier manual test
|
|
||||||
batches — so this fills every gap in the current data range rather
|
|
||||||
than just extending past the last existing formula row. Never
|
|
||||||
overwrites a cell that already has a formula.
|
|
||||||
"""
|
|
||||||
for col in cols:
|
|
||||||
source_cell = ws.cell(row=first_row, column=col)
|
|
||||||
if not (isinstance(source_cell.value, str) and source_cell.value.startswith("=")):
|
|
||||||
continue # no canonical formula in this column to propagate
|
|
||||||
source_formula = source_cell.value
|
|
||||||
source_coord = source_cell.coordinate
|
|
||||||
|
|
||||||
for r in range(first_row, last_row + 1):
|
|
||||||
cell = ws.cell(row=r, column=col)
|
|
||||||
if isinstance(cell.value, str) and cell.value.startswith("="):
|
|
||||||
continue # already has a formula, leave it alone
|
|
||||||
cell.value = Translator(source_formula, origin=source_coord).translate_formula(
|
|
||||||
cell.coordinate
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def populate_template(output_df, output_folder, audit_df=None, template_path=TEMPLATE_PATH):
|
|
||||||
"""
|
|
||||||
Populate finance's eib_pre_template.xlsx with this run's output instead
|
|
||||||
of generating a fresh workbook from scratch.
|
|
||||||
|
|
||||||
Writes EIB rows into 'Final Sheet' A2:I<n+1>, clearing any previous
|
|
||||||
data first. Columns J:Y (finance's own card-ID lookup formulas and a
|
|
||||||
legacy mirrored block) are never written to or cleared — the J:M
|
|
||||||
formulas are guarded with IF(A<>"",...) so they resolve to blank on
|
|
||||||
rows with no data, and are only ever extended downward (never
|
|
||||||
overwritten) if a run has more rows than the template currently
|
|
||||||
covers. The audit table, if provided, is written starting at column AA.
|
|
||||||
Saves a dated copy into output_folder; the template itself is untouched.
|
|
||||||
"""
|
|
||||||
final_df = output_df.sort_values(["Balance", "_row_order"]).reset_index(drop=True)
|
final_df = output_df.sort_values(["Balance", "_row_order"]).reset_index(drop=True)
|
||||||
final_df = final_df[
|
final_df = final_df[
|
||||||
[
|
[
|
||||||
|
|
@ -803,26 +729,10 @@ def populate_template(output_df, output_folder, audit_df=None, template_path=TEM
|
||||||
.str.replace("nan", "", regex=False)
|
.str.replace("nan", "", regex=False)
|
||||||
)
|
)
|
||||||
|
|
||||||
wb = openpyxl.load_workbook(template_path)
|
today = datetime.today().strftime("%Y-%m-%d")
|
||||||
ws = wb[TEMPLATE_SHEET]
|
suffix = "_Audited" if audit_df is not None else ""
|
||||||
|
fname = f"EIB_Processed{suffix}_{today}.xlsx"
|
||||||
old_max_row = ws.max_row
|
fpath = os.path.join(output_folder, fname)
|
||||||
|
|
||||||
# Clear any previous run's data out of A:I (header row untouched).
|
|
||||||
for r in range(2, old_max_row + 1):
|
|
||||||
for c in range(1, TEMPLATE_DATA_COLS + 1):
|
|
||||||
ws.cell(row=r, column=c).value = None
|
|
||||||
|
|
||||||
for i, row in enumerate(final_df.itertuples(index=False), start=2):
|
|
||||||
for c, val in enumerate(row, start=1):
|
|
||||||
ws.cell(row=i, column=c, value=val)
|
|
||||||
|
|
||||||
last_data_row = len(final_df) + 1
|
|
||||||
if last_data_row > 1:
|
|
||||||
_extend_formulas_down(
|
|
||||||
ws, range(TEMPLATE_FORMULA_COLS[0], TEMPLATE_FORMULA_COLS[1] + 1),
|
|
||||||
first_row=2, last_row=last_data_row,
|
|
||||||
)
|
|
||||||
|
|
||||||
green_fill = PatternFill("solid", fgColor="C6EFCE")
|
green_fill = PatternFill("solid", fgColor="C6EFCE")
|
||||||
red_fill = PatternFill("solid", fgColor="FFC7CE")
|
red_fill = PatternFill("solid", fgColor="FFC7CE")
|
||||||
|
|
@ -833,152 +743,43 @@ def populate_template(output_df, output_folder, audit_df=None, template_path=TEM
|
||||||
thin = Side(style="thin")
|
thin = Side(style="thin")
|
||||||
border = Border(left=thin, right=thin, top=thin, bottom=thin)
|
border = Border(left=thin, right=thin, top=thin, bottom=thin)
|
||||||
|
|
||||||
if audit_df is not None:
|
with pd.ExcelWriter(fpath, engine="openpyxl") as writer:
|
||||||
audit_start_col = TEMPLATE_AUDIT_START_COL
|
final_df.to_excel(writer, index=False, sheet_name="EIB Output")
|
||||||
audit_headers = list(audit_df.columns)
|
ws = writer.sheets["EIB Output"]
|
||||||
|
|
||||||
for j, h in enumerate(audit_headers):
|
for col in ws.columns:
|
||||||
c = ws.cell(row=1, column=audit_start_col + j, value=h)
|
max_len = max(len(str(cell.value or "")) for cell in col)
|
||||||
c.fill = hdr_fill
|
ws.column_dimensions[col[0].column_letter].width = min(max_len + 4, 50)
|
||||||
c.font = white_font
|
|
||||||
c.border = border
|
|
||||||
c.alignment = Alignment(horizontal="center")
|
|
||||||
|
|
||||||
for i, arow in audit_df.iterrows():
|
if audit_df is not None:
|
||||||
for j, val in enumerate(arow):
|
audit_start_col = len(final_df.columns) + 1 + 4
|
||||||
c = ws.cell(row=i + 2, column=audit_start_col + j, value=val)
|
audit_headers = list(audit_df.columns)
|
||||||
|
|
||||||
|
for j, h in enumerate(audit_headers):
|
||||||
|
c = ws.cell(row=1, column=audit_start_col + j, value=h)
|
||||||
|
c.fill = hdr_fill
|
||||||
|
c.font = white_font
|
||||||
c.border = border
|
c.border = border
|
||||||
c.alignment = Alignment(horizontal="left" if j == 0 else "center")
|
c.alignment = Alignment(horizontal="center")
|
||||||
if audit_headers[j] == "Audit Status":
|
|
||||||
c.fill = green_fill if val == "MATCHED" else red_fill
|
|
||||||
c.font = bold_font
|
|
||||||
elif i % 2 == 1:
|
|
||||||
c.fill = alt_fill
|
|
||||||
|
|
||||||
col_widths = [18, 26, 22, 22, 70, 60]
|
for i, arow in audit_df.iterrows():
|
||||||
for j, w in enumerate(col_widths):
|
for j, val in enumerate(arow):
|
||||||
if j < len(audit_headers):
|
c = ws.cell(row=i + 2, column=audit_start_col + j, value=val)
|
||||||
ws.column_dimensions[get_column_letter(audit_start_col + j)].width = w
|
c.border = border
|
||||||
|
c.alignment = Alignment(
|
||||||
|
horizontal="left" if j == 0 else "center"
|
||||||
|
)
|
||||||
|
if audit_headers[j] == "Audit Status":
|
||||||
|
c.fill = green_fill if val == "MATCHED" else red_fill
|
||||||
|
c.font = bold_font
|
||||||
|
elif i % 2 == 1:
|
||||||
|
c.fill = alt_fill
|
||||||
|
|
||||||
today = datetime.today().strftime("%Y-%m-%d")
|
col_widths = [18, 26, 22, 22, 70, 60]
|
||||||
suffix = "_Audited" if audit_df is not None else ""
|
for j, w in enumerate(col_widths):
|
||||||
fname = f"EIB_Processed{suffix}_{today}.xlsx"
|
if j < len(audit_headers):
|
||||||
fpath = os.path.join(output_folder, fname)
|
ws.column_dimensions[
|
||||||
wb.save(fpath)
|
get_column_letter(audit_start_col + j)
|
||||||
|
].width = w
|
||||||
|
|
||||||
return fname, fpath
|
return fname, fpath
|
||||||
|
|
||||||
|
|
||||||
def _load_card_id_lookup(lookup_path):
|
|
||||||
"""
|
|
||||||
Read the cardholder -> corporate-card-ID mapping straight from
|
|
||||||
eib_pre_template.xlsx's 'Equals Card IDs' sheet (CC Holder, Expense
|
|
||||||
Credit Card ID [formula], ID, Corporate Account, Card Ending) instead
|
|
||||||
of duplicating it here, so both output files always agree with
|
|
||||||
whatever finance currently has on file there. Expense Credit Card ID
|
|
||||||
is recomputed from ID/Corporate Account/Card Ending rather than read
|
|
||||||
from the sheet's own formula, matching that formula's own pattern
|
|
||||||
(Corporate Account & "-" & ID & "-" & Card Ending).
|
|
||||||
"""
|
|
||||||
wb = openpyxl.load_workbook(lookup_path)
|
|
||||||
ws = wb[CARD_ID_LOOKUP_SHEET]
|
|
||||||
lookup = {}
|
|
||||||
for holder, _formula, card_id, corp_account, card_ending in ws.iter_rows(
|
|
||||||
min_row=2, max_col=5, values_only=True
|
|
||||||
):
|
|
||||||
if not holder:
|
|
||||||
continue
|
|
||||||
lookup[str(holder).strip()] = {
|
|
||||||
"expense_credit_card_id": f"{corp_account}-{card_id}-{card_ending}",
|
|
||||||
"corporate_account": corp_account,
|
|
||||||
"cardholder_id": card_id,
|
|
||||||
}
|
|
||||||
return lookup
|
|
||||||
|
|
||||||
|
|
||||||
def _format_period_label(dates):
|
|
||||||
dmin, dmax = min(dates), max(dates)
|
|
||||||
if (dmin.year, dmin.month) == (dmax.year, dmax.month):
|
|
||||||
return f"{dmin.strftime('%B')} {dmin.day} - {dmax.day} {dmin.year} Equals Card Transactions"
|
|
||||||
return f"{dmin.strftime('%B %d, %Y')} - {dmax.strftime('%B %d, %Y')} Equals Card Transactions"
|
|
||||||
|
|
||||||
|
|
||||||
def populate_upload_template(output_df, output_folder,
|
|
||||||
template_path=UPLOAD_TEMPLATE_PATH,
|
|
||||||
lookup_path=TEMPLATE_PATH):
|
|
||||||
"""
|
|
||||||
Populate finance's Workday-ready
|
|
||||||
planeterra_equals_cards_transactions_eib_v45.xlsx from this run's
|
|
||||||
output (a separate, on-demand output from eib_pre_template.xlsx).
|
|
||||||
|
|
||||||
Writes one row per transaction into 'Expense Credit Card Transaction'
|
|
||||||
(Header Key, Line Key, Transaction Number, Transaction Date, Amount,
|
|
||||||
Source/Converted Currency, Converted Amount, Charge Description,
|
|
||||||
Merchant Name, and the three corporate-card-ID fields resolved via
|
|
||||||
_load_card_id_lookup), clearing any previous run's rows first, plus a
|
|
||||||
single per-file metadata row in 'Credit Card Transaction Header'
|
|
||||||
(Header Key, Credit Card Type, a generated File Name covering this
|
|
||||||
run's date range, and today's date as Report Create Date). Saves a
|
|
||||||
dated copy into output_folder; the template itself is never mutated.
|
|
||||||
|
|
||||||
Returns (filename, filepath, unmatched_cardholders) — cardholders with
|
|
||||||
no row in the 'Equals Card IDs' lookup get blank ID fields, and their
|
|
||||||
names are returned so the caller can surface a warning.
|
|
||||||
"""
|
|
||||||
final_df = output_df.sort_values(["Balance", "_row_order"]).reset_index(drop=True)
|
|
||||||
final_df["Transaction Date"] = pd.to_datetime(final_df["Transaction Date"])
|
|
||||||
final_df["Amount"] = final_df["Amount"].round(2)
|
|
||||||
final_df["Converted Amount"] = final_df["Converted Amount"].round(2)
|
|
||||||
|
|
||||||
lookup = _load_card_id_lookup(lookup_path)
|
|
||||||
unmatched_cardholders = set()
|
|
||||||
|
|
||||||
wb = openpyxl.load_workbook(template_path)
|
|
||||||
ws = wb[UPLOAD_TRANSACTION_SHEET]
|
|
||||||
c = UPLOAD_COLS
|
|
||||||
|
|
||||||
old_max_row = ws.max_row
|
|
||||||
for r in range(UPLOAD_DATA_START_ROW, old_max_row + 1):
|
|
||||||
for col in c.values():
|
|
||||||
ws.cell(row=r, column=col).value = None
|
|
||||||
|
|
||||||
for i, (_, row) in enumerate(final_df.iterrows(), start=UPLOAD_DATA_START_ROW):
|
|
||||||
cardholder = row["Balance"]
|
|
||||||
ids = lookup.get(str(cardholder).strip())
|
|
||||||
if ids is None:
|
|
||||||
unmatched_cardholders.add(cardholder)
|
|
||||||
ids = {"expense_credit_card_id": "", "corporate_account": "", "cardholder_id": ""}
|
|
||||||
|
|
||||||
ws.cell(row=i, column=c["header_key"], value=1)
|
|
||||||
ws.cell(row=i, column=c["line_key"], value=i - UPLOAD_DATA_START_ROW + 1)
|
|
||||||
ws.cell(row=i, column=c["transaction_number"], value=row["Transaction Number"])
|
|
||||||
ws.cell(row=i, column=c["transaction_date"], value=row["Transaction Date"].to_pydatetime())
|
|
||||||
ws.cell(row=i, column=c["amount"], value=row["Amount"])
|
|
||||||
ws.cell(row=i, column=c["source_currency"], value=row["Source Currency"])
|
|
||||||
ws.cell(row=i, column=c["converted_amount"], value=row["Converted Amount"])
|
|
||||||
ws.cell(row=i, column=c["converted_currency"], value=row["Converted Currency"])
|
|
||||||
ws.cell(row=i, column=c["charge_description"], value=row["charge description line 1"])
|
|
||||||
ws.cell(row=i, column=c["merchant_name"], value=row["charge description line 1"])
|
|
||||||
ws.cell(row=i, column=c["expense_credit_card_id"], value=ids["expense_credit_card_id"])
|
|
||||||
ws.cell(row=i, column=c["corporate_account"], value=ids["corporate_account"])
|
|
||||||
ws.cell(row=i, column=c["cardholder_id"], value=ids["cardholder_id"])
|
|
||||||
|
|
||||||
hws = wb[UPLOAD_HEADER_SHEET]
|
|
||||||
hws.cell(row=UPLOAD_HEADER_DATA_ROW, column=2, value=1) # Header Key*
|
|
||||||
hws.cell(row=UPLOAD_HEADER_DATA_ROW, column=8, value="Mastercard") # Credit Card Type*
|
|
||||||
if len(final_df) > 0:
|
|
||||||
hws.cell(
|
|
||||||
row=UPLOAD_HEADER_DATA_ROW, column=6,
|
|
||||||
value=_format_period_label(final_df["Transaction Date"].tolist()),
|
|
||||||
) # File Name
|
|
||||||
hws.cell(row=UPLOAD_HEADER_DATA_ROW, column=7, value=datetime.today()) # Report Create Date
|
|
||||||
|
|
||||||
if unmatched_cardholders:
|
|
||||||
print(f"[upload-template] No card-ID match for: {', '.join(sorted(unmatched_cardholders))}")
|
|
||||||
|
|
||||||
today = datetime.today().strftime("%Y-%m-%d")
|
|
||||||
fname = f"EIB_Upload_{today}.xlsx"
|
|
||||||
fpath = os.path.join(output_folder, fname)
|
|
||||||
wb.save(fpath)
|
|
||||||
|
|
||||||
return fname, fpath, sorted(unmatched_cardholders)
|
|
||||||
|
|
|
||||||
Binary file not shown.
|
|
@ -10,8 +10,7 @@ from .logic import (
|
||||||
parse_pdf_with_docling,
|
parse_pdf_with_docling,
|
||||||
extract_balances_from_markdown,
|
extract_balances_from_markdown,
|
||||||
run_audit_pdf,
|
run_audit_pdf,
|
||||||
populate_template,
|
build_excel,
|
||||||
populate_upload_template,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
eib_bp = Blueprint("eib", __name__, url_prefix="/eib")
|
eib_bp = Blueprint("eib", __name__, url_prefix="/eib")
|
||||||
|
|
@ -23,17 +22,11 @@ DOCLING_URL = os.environ.get("DOCLING_URL", "http://localhost:5001")
|
||||||
# status dict is enough. Reset at the start of every /api/process call.
|
# status dict is enough. Reset at the start of every /api/process call.
|
||||||
PROCESS_STATUS = {"active": False, "current": "", "log": []}
|
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():
|
def status_reset():
|
||||||
PROCESS_STATUS["active"] = True
|
PROCESS_STATUS["active"] = True
|
||||||
PROCESS_STATUS["current"] = "Starting..."
|
PROCESS_STATUS["current"] = "Starting..."
|
||||||
PROCESS_STATUS["log"] = []
|
PROCESS_STATUS["log"] = []
|
||||||
LAST_RESULT["output_df"] = None
|
|
||||||
|
|
||||||
|
|
||||||
def status_set(current):
|
def status_set(current):
|
||||||
|
|
@ -127,8 +120,6 @@ def api_process():
|
||||||
"message": f"{len(unmapped)} merchant(s) need clean names before output can be generated.",
|
"message": f"{len(unmapped)} merchant(s) need clean names before output can be generated.",
|
||||||
}), 200
|
}), 200
|
||||||
|
|
||||||
LAST_RESULT["output_df"] = output_df
|
|
||||||
|
|
||||||
audit_df = None
|
audit_df = None
|
||||||
|
|
||||||
if stmt_file and stmt_file.filename:
|
if stmt_file and stmt_file.filename:
|
||||||
|
|
@ -216,7 +207,7 @@ def api_process():
|
||||||
)
|
)
|
||||||
|
|
||||||
status_set("Building EIB output file...")
|
status_set("Building EIB output file...")
|
||||||
fname, fpath = populate_template(output_df, current_app.config["OUTPUT_FOLDER"], audit_df)
|
fname, fpath = build_excel(output_df, current_app.config["OUTPUT_FOLDER"], audit_df)
|
||||||
|
|
||||||
people = sorted(output_df["Balance"].dropna().unique().tolist())
|
people = sorted(output_df["Balance"].dropna().unique().tolist())
|
||||||
summary = {
|
summary = {
|
||||||
|
|
@ -243,29 +234,6 @@ def api_process_status():
|
||||||
return jsonify(PROCESS_STATUS)
|
return jsonify(PROCESS_STATUS)
|
||||||
|
|
||||||
|
|
||||||
@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>")
|
@eib_bp.route("/api/download/<filename>")
|
||||||
def api_download(filename):
|
def api_download(filename):
|
||||||
safe = secure_filename(filename)
|
safe = secure_filename(filename)
|
||||||
|
|
|
||||||
|
|
@ -522,16 +522,6 @@ footer a { color: var(--cyan); text-decoration: none; }
|
||||||
</svg>
|
</svg>
|
||||||
Download EIB File
|
Download EIB File
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
<button class="btn btn-ghost btn-full" id="generateUploadBtn" style="margin-top:10px">
|
|
||||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5">
|
|
||||||
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
|
|
||||||
<polyline points="17,8 12,3 7,8"/>
|
|
||||||
<line x1="12" y1="3" x2="12" y2="15"/>
|
|
||||||
</svg>
|
|
||||||
Generate EIB File (for Upload)
|
|
||||||
</button>
|
|
||||||
<div id="uploadGenNote" style="display:none;font-size:11px;color:var(--w3);margin-top:8px;line-height:1.5"></div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</main>
|
</main>
|
||||||
|
|
@ -725,8 +715,6 @@ $('processBtn').addEventListener('click', async () => {
|
||||||
$('processBtn').disabled = true;
|
$('processBtn').disabled = true;
|
||||||
$('resultPanel').classList.remove('visible');
|
$('resultPanel').classList.remove('visible');
|
||||||
$('unmappedPanel').classList.remove('visible');
|
$('unmappedPanel').classList.remove('visible');
|
||||||
$('uploadGenNote').style.display = 'none';
|
|
||||||
$('generateUploadBtn').disabled = false;
|
|
||||||
startProgress();
|
startProgress();
|
||||||
|
|
||||||
const fd = new FormData();
|
const fd = new FormData();
|
||||||
|
|
@ -795,34 +783,6 @@ $('processBtn').addEventListener('click', async () => {
|
||||||
$('downloadBtn').addEventListener('click', () => {
|
$('downloadBtn').addEventListener('click', () => {
|
||||||
if (lastFilename) window.location.href = '/eib/api/download/' + encodeURIComponent(lastFilename);
|
if (lastFilename) window.location.href = '/eib/api/download/' + encodeURIComponent(lastFilename);
|
||||||
});
|
});
|
||||||
|
|
||||||
// ── Generate EIB file for upload (separate Workday-ready template) ────────────
|
|
||||||
$('generateUploadBtn').addEventListener('click', async () => {
|
|
||||||
const btn = $('generateUploadBtn');
|
|
||||||
const note = $('uploadGenNote');
|
|
||||||
btn.disabled = true;
|
|
||||||
note.style.display = 'none';
|
|
||||||
|
|
||||||
try {
|
|
||||||
const r = await fetch('/eib/api/generate-upload', { method: 'POST' });
|
|
||||||
const d = await r.json();
|
|
||||||
|
|
||||||
if (d.status === 'ok') {
|
|
||||||
note.textContent = d.unmatched_cardholders && d.unmatched_cardholders.length
|
|
||||||
? `⚠ No card-ID match for: ${d.unmatched_cardholders.join(', ')} — those rows were left blank.`
|
|
||||||
: 'Generated. Starting download…';
|
|
||||||
note.style.display = 'block';
|
|
||||||
window.location.href = '/eib/api/download/' + encodeURIComponent(d.filename);
|
|
||||||
} else {
|
|
||||||
note.textContent = d.error || 'Unexpected error';
|
|
||||||
note.style.display = 'block';
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
note.textContent = 'Network error: ' + e.message;
|
|
||||||
note.style.display = 'block';
|
|
||||||
}
|
|
||||||
btn.disabled = false;
|
|
||||||
});
|
|
||||||
</script>
|
</script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
Loading…
Reference in New Issue