From aff1af5e73cd48f50eab3df8106543ec92aea197 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 7 Nov 2026 02:22:13 +0000 Subject: [PATCH 1/2] Deploy the sample report to Vercel as a static page Vercel detected pyproject.toml and built the repo as a Python web app, failing with PYTHON_ENTRYPOINT_NOT_FOUND. vercel.json now sets the framework to "Other", installs the tool into .deps, generates the HTML report from the sample workbook into public/, and serves it as index.html. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016gtNTGbmvq2DdoGC4air5K --- .gitignore | 3 +++ README.md | 3 +++ vercel.json | 7 +++++++ 3 files changed, 13 insertions(+) create mode 100644 vercel.json diff --git a/.gitignore b/.gitignore index add7d17..0a307d7 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,6 @@ build/ dist/ reports/ .ipynb_checkpoints/ +public/ +.deps/ +.vercel/ diff --git a/README.md b/README.md index 144c2ff..3bf2408 100644 --- a/README.md +++ b/README.md @@ -52,3 +52,6 @@ python samples/make_sample.py # regenerate the sample workbook ``` `Project.ipynb` is the original notebook version, kept for reference. The maintained code is in `report_tool/`. + +### Live demo on Vercel +`vercel.json` deploys the report as a static page: the build installs the tool, generates the HTML report from `samples/bookings_sample.xlsx`, and serves it as `index.html`. It sets the framework to "Other", so Vercel doesn't treat the repo as a Python web app. To show your own data, change the workbook path in `buildCommand`. diff --git a/vercel.json b/vercel.json new file mode 100644 index 0000000..75923e8 --- /dev/null +++ b/vercel.json @@ -0,0 +1,7 @@ +{ + "$schema": "https://openapi.vercel.sh/vercel.json", + "framework": null, + "installCommand": "python3 -m pip install --quiet --target .deps .", + "buildCommand": "PYTHONPATH=.deps python3 -m report_tool samples/bookings_sample.xlsx --out public && cp public/booking_summary_*.html public/index.html", + "outputDirectory": "public" +} From 84e3c435bf228983073c1c885f0b26650d4541a7 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 7 Nov 2026 02:25:27 +0000 Subject: [PATCH 2/2] Serve the report as a Flask upload app on Vercel Replaces the static vercel.json build. app.py is a Flask app that Vercel deploys with zero config: upload an .xlsx (up to 4 MB) and get the HTML dashboard back, or open /sample. Uploads go to a temp file that is deleted right after parsing; nothing is stored. Names stay masked unless the user ticks "Show full passenger names". Adds flask to the dependencies and tests for the upload, sample, error and size-limit paths. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016gtNTGbmvq2DdoGC4air5K --- README.md | 10 ++++- app.py | 85 +++++++++++++++++++++++++++++++++++++++++++ pyproject.toml | 3 +- templates/upload.html | 76 ++++++++++++++++++++++++++++++++++++++ tests/test_app.py | 66 +++++++++++++++++++++++++++++++++ vercel.json | 7 ---- 6 files changed, 237 insertions(+), 10 deletions(-) create mode 100644 app.py create mode 100644 templates/upload.html create mode 100644 tests/test_app.py delete mode 100644 vercel.json diff --git a/README.md b/README.md index 3bf2408..20eccb1 100644 --- a/README.md +++ b/README.md @@ -53,5 +53,11 @@ python samples/make_sample.py # regenerate the sample workbook `Project.ipynb` is the original notebook version, kept for reference. The maintained code is in `report_tool/`. -### Live demo on Vercel -`vercel.json` deploys the report as a static page: the build installs the tool, generates the HTML report from `samples/bookings_sample.xlsx`, and serves it as `index.html`. It sets the framework to "Other", so Vercel doesn't treat the repo as a Python web app. To show your own data, change the workbook path in `buildCommand`. +### Web app (Vercel) +`app.py` is a small Flask app: upload an `.xlsx` (up to 4 MB) and it returns the HTML dashboard, or open `/sample` to see the sample report. Uploads are processed in a temporary file that is deleted straight away; nothing is stored. Passenger names stay masked unless the "Show full passenger names" box is ticked. + +```bash +flask --app app run # http://127.0.0.1:5000 +``` + +On Vercel it deploys with no extra configuration: Vercel finds `app.py` and installs the dependencies from `pyproject.toml`. diff --git a/app.py b/app.py new file mode 100644 index 0000000..55210ba --- /dev/null +++ b/app.py @@ -0,0 +1,85 @@ +"""Web front end: upload a bookings workbook, get the HTML dashboard back. + +Runs locally with `flask --app app run` and on Vercel as a Python function. +Uploaded files are processed in memory/temp storage and never kept. +""" + +from __future__ import annotations + +import datetime as dt +import hashlib +import tempfile +from pathlib import Path + +from flask import Flask, Response, render_template, request +from werkzeug.exceptions import RequestEntityTooLarge + +from report_tool.html_report import render_html +from report_tool.loader import LoadResult, WorkbookError, load_bookings +from report_tool.summary import summarize + +SAMPLE = Path(__file__).parent / "samples" / "bookings_sample.xlsx" +MAX_UPLOAD_MB = 4 # Vercel functions accept request bodies up to 4.5 MB + +app = Flask(__name__) +app.config["MAX_CONTENT_LENGTH"] = MAX_UPLOAD_MB * 1024 * 1024 + + +def upload_page(error: str | None = None, status: int = 200) -> tuple[str, int]: + return render_template("upload.html", error=error, max_mb=MAX_UPLOAD_MB), status + + +def report_response(result: LoadResult, source: str, data: bytes, show_names: bool) -> Response: + html = render_html( + summarize(result.bookings), + result.skipped, + source=source, + source_sha256=hashlib.sha256(data).hexdigest(), + generated_at=dt.datetime.now(dt.UTC).replace(tzinfo=None), + show_names=show_names, + ) + response = Response(html, mimetype="text/html") + response.headers["Cache-Control"] = "no-store" + return response + + +def build_report(data: bytes, source: str, show_names: bool) -> Response | tuple[str, int]: + # openpyxl needs a real file; the temp file is deleted as soon as it's read. + with tempfile.NamedTemporaryFile(suffix=".xlsx") as handle: + handle.write(data) + handle.flush() + try: + result = load_bookings(handle.name) + except WorkbookError as exc: + message = str(exc).replace(handle.name, source) + return upload_page(message, 400) + if not result.bookings: + return upload_page(f"No valid bookings found in {source}. Check the columns and try again.", 400) + return report_response(result, source, data, show_names) + + +@app.get("/") +def index(): + return upload_page() + + +@app.post("/report") +def report(): + upload = request.files.get("workbook") + if upload is None or not upload.filename: + return upload_page("Choose an .xlsx file to upload.", 400) + name = Path(upload.filename).name + if not name.lower().endswith(".xlsx"): + return upload_page("Only Excel .xlsx files are supported.", 400) + return build_report(upload.read(), name, show_names=request.form.get("show_names") == "on") + + +@app.get("/sample") +def sample(): + data = SAMPLE.read_bytes() + return report_response(load_bookings(SAMPLE), SAMPLE.name, data, show_names=False) + + +@app.errorhandler(RequestEntityTooLarge) +def too_large(_error): + return upload_page(f"That file is larger than {MAX_UPLOAD_MB} MB.", 413) diff --git a/pyproject.toml b/pyproject.toml index 2fa85de..202c5a9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -8,7 +8,7 @@ version = "1.1.0" description = "Turn a train bookings Excel workbook into a validated HTML or text report." readme = "README.md" requires-python = ">=3.11" -dependencies = ["openpyxl>=3.1,<4", "jinja2>=3.1,<4"] +dependencies = ["openpyxl>=3.1,<4", "jinja2>=3.1,<4", "flask>=3.1,<4"] [project.optional-dependencies] dev = ["pytest>=8", "ruff>=0.6"] @@ -24,6 +24,7 @@ report_tool = ["templates/*.j2"] [tool.pytest.ini_options] testpaths = ["tests"] +pythonpath = ["."] [tool.ruff] line-length = 110 diff --git a/templates/upload.html b/templates/upload.html new file mode 100644 index 0000000..9832edb --- /dev/null +++ b/templates/upload.html @@ -0,0 +1,76 @@ + + + + + +Railstat · Train bookings report + + + +
+
+

Train bookings report

+

Upload a bookings spreadsheet and get a dashboard: revenue, cancellations, routes, weekly trend, and a list of any rows that couldn't be read.

+
+ + {% if error %}{% endif %} + +
+
+ + + Up to {{ max_mb }} MB. The file is processed and discarded; nothing is stored. +
+ +
+ + View sample report +
+
+ +

Required columns: TicketID, PassengerName, Route, Class, Price, Status. Optional: Date, DiscountApplied, LoyaltyMember. Column order doesn't matter.

+

Source on GitHub

+
+ + + diff --git a/tests/test_app.py b/tests/test_app.py new file mode 100644 index 0000000..eeac7cf --- /dev/null +++ b/tests/test_app.py @@ -0,0 +1,66 @@ +import io +from pathlib import Path + +import pytest + +from app import app + +SAMPLE = Path(__file__).parent.parent / "samples" / "bookings_sample.xlsx" + + +@pytest.fixture +def client(): + app.config["TESTING"] = True + return app.test_client() + + +def upload(client, data: bytes, name: str = "bookings.xlsx", **form): + return client.post( + "/report", + data={"workbook": (io.BytesIO(data), name), **form}, + content_type="multipart/form-data", + ) + + +def test_upload_page(client): + response = client.get("/") + assert response.status_code == 200 + assert b'name="workbook"' in response.data + + +def test_sample_report(client): + response = client.get("/sample") + assert response.status_code == 200 + assert b"Train bookings report" in response.data + assert b"3 rows were skipped" in response.data + + +def test_upload_builds_report_with_names_masked(client, make_workbook): + data = make_workbook( + [["TB-1", "Ann Lee", "A-B", "Economy", 10, "Confirmed", None, 0, "Yes"]] + ).read_bytes() + response = upload(client, data) + assert response.status_code == 200 + assert response.headers["Cache-Control"] == "no-store" + assert "A. L••" in response.get_data(as_text=True) + assert b"Ann Lee" not in response.data + assert b"Ann Lee" in upload(client, data, show_names="on").data + + +def test_rejects_missing_wrong_type_and_bad_files(client, make_workbook): + assert client.post("/report", data={}).status_code == 400 + assert b"Only Excel .xlsx" in upload(client, b"a,b", name="bookings.csv").data + response = upload(client, b"not a workbook") + assert response.status_code == 400 + assert b"Could not open bookings.xlsx" in response.data + assert b"/tmp" not in response.data # temp paths aren't leaked + no_rows = make_workbook( + [["TB-1", "Ann", "A-B", "Economy", "TBD", "Confirmed", None, 0, "No"]] + ).read_bytes() + assert b"No valid bookings" in upload(client, no_rows).data + + +def test_too_large(client, monkeypatch): + monkeypatch.setitem(app.config, "MAX_CONTENT_LENGTH", 10) + response = upload(client, b"x" * 100) + assert response.status_code == 413 diff --git a/vercel.json b/vercel.json deleted file mode 100644 index 75923e8..0000000 --- a/vercel.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "$schema": "https://openapi.vercel.sh/vercel.json", - "framework": null, - "installCommand": "python3 -m pip install --quiet --target .deps .", - "buildCommand": "PYTHONPATH=.deps python3 -m report_tool samples/bookings_sample.xlsx --out public && cp public/booking_summary_*.html public/index.html", - "outputDirectory": "public" -}