Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,6 @@ build/
dist/
reports/
.ipynb_checkpoints/
public/
.deps/
.vercel/
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,12 @@ 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/`.

### 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`.
85 changes: 85 additions & 0 deletions app.py
Original file line number Diff line number Diff line change
@@ -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)
3 changes: 2 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
Expand All @@ -24,6 +24,7 @@ report_tool = ["templates/*.j2"]

[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["."]

[tool.ruff]
line-length = 110
Expand Down
76 changes: 76 additions & 0 deletions templates/upload.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Railstat · Train bookings report</title>
<style>
:root {
color-scheme: light;
--page: #f4f4f1; --surface: #ffffff; --ink: #0b0b0b; --ink-2: #52514e; --line: #e1e0d9; --axis: #c3c2b7;
--accent: #2a78d6; --error-bg: #fdeceb; --error-line: #f0b8b5; --error-ink: #7a1c1a; --focus: #2a78d6;
}
@media (prefers-color-scheme: dark) {
:root {
color-scheme: dark;
--page: #0d0d0d; --surface: #1a1a19; --ink: #f0efec; --ink-2: #c3c2b7; --line: #2c2c2a; --axis: #4a4a46;
--accent: #3987e5; --error-bg: #2d1514; --error-line: #6b2b28; --error-ink: #f5c2bf; --focus: #6da7ec;
}
}
* { box-sizing: border-box; }
body { margin: 0; background: var(--page); color: var(--ink); font: 16px/1.5 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; }
main { max-width: 680px; margin: 0 auto; padding: 56px 20px; display: flex; flex-direction: column; gap: 24px; }
h1 { margin: 0; font-size: 32px; line-height: 1.2; text-wrap: balance; }
p { margin: 0; }
.lead { color: var(--ink-2); max-width: 60ch; }
.card { background: var(--surface); border: 1px solid var(--line); border-radius: 12px; padding: 24px; display: flex; flex-direction: column; gap: 16px; }
.drop { border: 2px dashed var(--axis); border-radius: 10px; padding: 28px 20px; display: flex; flex-direction: column; gap: 10px; align-items: center; text-align: center; }
.drop.over { border-color: var(--accent); }
input[type="file"] { font: inherit; max-width: 100%; }
.check { display: flex; gap: 8px; align-items: center; font-size: 15px; }
.check input { width: 18px; height: 18px; }
.actions { display: flex; flex-wrap: wrap; gap: 12px; align-items: center; }
button, .button { min-height: 44px; padding: 0 18px; font: inherit; font-size: 15px; font-weight: 600; border-radius: 8px; cursor: pointer; text-decoration: none; display: inline-flex; align-items: center; }
button { background: var(--ink); color: var(--page); border: 1px solid var(--ink); }
.button { border: 1px solid var(--axis); color: var(--ink); background: var(--surface); }
button:focus-visible, .button:focus-visible, input:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; }
.error { background: var(--error-bg); border: 1px solid var(--error-line); color: var(--error-ink); border-radius: 10px; padding: 12px 16px; }
.note { color: var(--ink-2); font-size: 14px; }
code { font-family: ui-monospace, "SF Mono", Consolas, monospace; font-size: 0.92em; }
</style>
</head>
<body>
<main>
<div style="display: flex; flex-direction: column; gap: 10px">
<h1>Train bookings report</h1>
<p class="lead">Upload a bookings spreadsheet and get a dashboard: revenue, cancellations, routes, weekly trend, and a list of any rows that couldn't be read.</p>
</div>

{% if error %}<p class="error" role="alert"><strong>Couldn't build the report.</strong> {{ error }}</p>{% endif %}

<form class="card" action="/report" method="post" enctype="multipart/form-data">
<div class="drop" id="drop">
<label for="workbook"><strong>Choose an .xlsx file</strong> or drop it here</label>
<input id="workbook" name="workbook" type="file" accept=".xlsx,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" required>
<span class="note">Up to {{ max_mb }} MB. The file is processed and discarded; nothing is stored.</span>
</div>
<label class="check"><input type="checkbox" name="show_names"> Show full passenger names in the report</label>
<div class="actions">
<button type="submit">Build report</button>
<a class="button" href="/sample">View sample report</a>
</div>
</form>

<p class="note">Required columns: <code>TicketID</code>, <code>PassengerName</code>, <code>Route</code>, <code>Class</code>, <code>Price</code>, <code>Status</code>. Optional: <code>Date</code>, <code>DiscountApplied</code>, <code>LoyaltyMember</code>. Column order doesn't matter.</p>
<p class="note"><a href="https://github.com/royalpriest/Data-Analysis-Automated-Reporting-Tool" style="color: inherit">Source on GitHub</a></p>
</main>
<script>
(function () {
var drop = document.getElementById("drop"), input = document.getElementById("workbook");
["dragenter", "dragover"].forEach(function (t) { drop.addEventListener(t, function (e) { e.preventDefault(); drop.classList.add("over"); }); });
["dragleave", "drop"].forEach(function (t) { drop.addEventListener(t, function (e) { e.preventDefault(); drop.classList.remove("over"); }); });
drop.addEventListener("drop", function (e) { if (e.dataTransfer.files.length) input.files = e.dataTransfer.files; });
})();
</script>
</body>
</html>
66 changes: 66 additions & 0 deletions tests/test_app.py
Original file line number Diff line number Diff line change
@@ -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
Loading