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
13 changes: 11 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,16 @@ In a Security Operations Center (SOC), analysts must often parse through massive
- **Automated ingestion:** reads the active sheet of an `.xlsx` workbook with openpyxl, matching columns by header name, so the column order doesn't matter.
- **Row-level validation:** bad rows are skipped and listed with their Excel row number, ticket ID and reason.
- **Exact money math:** prices, discounts and revenue use `Decimal`, rounded to cents.
- **HTML dashboard report (default):** one self-contained file such as `reports/booking_summary_20261031_140211.html` that opens in any browser, offline. It shows the headline numbers first (net revenue, confirmed tickets, cancellation rate, loyalty share), a warning when rows were skipped, bookings by route and by class, net revenue by week, and a table of every booking you can filter by status and search. It has Export CSV and Print / Save PDF buttons, follows the system's light or dark mode, and works on a phone.
- **HTML dashboard report (default):** one self-contained file such as `reports/booking_summary_20261031_140211.html` that opens in any browser. It contains:
- filters for period (all weeks, or the last few weeks), route and class;
- headline numbers (net revenue, confirmed tickets, cancellation rate, loyalty share), each showing its change against the previous period;
- a line saying whether every row was used;
- weekly net revenue, with the compared weeks shaded and the high and low weeks labelled;
- cancellation rate by route, measured against the average;
- bookings by route and by class;
- a bookings table you can sort, search and page through.

It has Export CSV and Print / Save PDF buttons and a light/dark switch, uses the Space Mono font (falling back to the system monospace font offline), and works on a phone.
- **Text report:** `--format txt` (or `both`) writes the same figures as plain text.
- **Skipped rows:** listed in the report and saved next to it as `..._skipped_rows.csv`.
- **Privacy by default:** passenger names are masked (`Maria Gonzalez` becomes `M. G•••••••`) and full names are never written to the file unless you pass `--show-names`. Spreadsheet text is HTML-escaped, and CSV cells that could run as spreadsheet formulas are neutralised.
Expand Down Expand Up @@ -54,7 +63,7 @@ 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.
`app.py` is a small Flask app. The landing page explains the tool, shows a preview built from the sample file, and takes an `.xlsx` upload (up to 4 MB, drag and drop or browse) that returns the HTML dashboard. `/sample` shows the sample report and `/template.xlsx` downloads a blank workbook with the right headers. Upload problems (wrong file type, missing columns, no usable rows) are explained in plain words with how to fix them. The page uses the Space Mono font and has a light/dark switch that remembers your choice. 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
Expand Down
174 changes: 162 additions & 12 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,26 +7,135 @@
from __future__ import annotations

import datetime as dt
import functools
import hashlib
import io
import tempfile
from pathlib import Path

from flask import Flask, Response, render_template, request
from flask import Flask, Response, render_template, request, send_file
from openpyxl import Workbook
from werkzeug.exceptions import RequestEntityTooLarge

from report_tool.charts import weekly_revenue
from report_tool.html_report import render_html
from report_tool.loader import LoadResult, WorkbookError, load_bookings
from report_tool.loader import (
LoadResult,
MissingColumnsError,
NotAWorkbookError,
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__)
# (header, required, example) shown on the landing page and used for the template download.
COLUMNS = [
("TicketID", True, "TB-1042"),
("PassengerName", True, "Maria Gonzalez"),
("Route", True, "Toronto–Montréal"),
("Class", True, "Economy"),
("Price", True, "85.50 or $85.50"),
("Status", True, "Confirmed / Cancelled"),
("Date", False, "2026-09-08"),
("DiscountApplied", False, "10 or 10%"),
("LoyaltyMember", False, "Yes / No"),
]
TEMPLATE_ROWS = [
[
"TB-1042",
"Maria Gonzalez",
"Toronto–Montréal",
"Economy",
85.5,
"Confirmed",
dt.date(2026, 9, 8),
10,
"Yes",
],
[
"TB-1043",
"Sam Patel",
"Ottawa–Québec City",
"Business",
142,
"Cancelled",
dt.date(2026, 9, 9),
0,
"No",
],
]

app = Flask(__name__, template_folder="report_tool/templates")
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
@functools.cache
def sample_preview() -> dict:
"""Figures from the sample workbook for the small dashboard preview on the landing page."""
summary = summarize(load_bookings(SAMPLE).bookings)
top = summary.routes_by_volume()[:3]
widest = max((counts.total for _, counts in top), default=1)
routes = [
{
"name": name,
"confirmed_pct": round(100 * counts.confirmed / widest, 1),
"cancelled_pct": round(100 * counts.cancelled / widest, 1),
"cancelled": counts.cancelled,
}
for name, counts in top
]
series = weekly_revenue(summary.confirmed)
spark = ""
if len(series) > 1:
peak = float(max(value for _, value in series)) or 1
step = 300 / (len(series) - 1)
spark = " ".join(
f"{round(i * step, 1)},{round(64 - 58 * float(value) / peak, 1)}"
for i, (_, value) in enumerate(series)
)
return {
"source": SAMPLE.name,
"revenue": f"${summary.net_revenue:,.2f}",
"cancel_rate": f"{summary.cancellation_rate:.1%}",
"routes": routes,
"spark": spark,
}


def landing_page(error: dict | None = None, status: int = 200) -> tuple[str, int]:
page = render_template(
"landing.html",
error=error,
max_mb=MAX_UPLOAD_MB,
preview=sample_preview(),
columns=COLUMNS,
)
return page, status


def problem(title: str, text: str, template_link: bool = False) -> dict:
return {"title": title, "text": text, "template_link": template_link}


def explain(exc: WorkbookError, name: str) -> dict:
"""Turn a loader error into a message that says what's wrong and how to fix it."""
if isinstance(exc, NotAWorkbookError):
return problem(
f"{name} isn't a readable Excel file.",
"Open it in Excel and choose Save As › Excel Workbook (.xlsx), then upload it again.",
)
if isinstance(exc, MissingColumnsError):
plural = "s" if len(exc.missing) > 1 else ""
return problem(
f"{name} is missing the {', '.join(exc.missing)} column{plural}.",
f"Its first row has: {', '.join(exc.found) or 'nothing'}. "
"Add the missing header, or start from the template.",
template_link=True,
)
return problem(f"{name} couldn't be read.", str(exc))


def report_response(result: LoadResult, source: str, data: bytes, show_names: bool) -> Response:
Expand All @@ -37,6 +146,7 @@ def report_response(result: LoadResult, source: str, data: bytes, show_names: bo
source_sha256=hashlib.sha256(data).hexdigest(),
generated_at=dt.datetime.now(dt.UTC).replace(tzinfo=None),
show_names=show_names,
upload_url="/",
)
response = Response(html, mimetype="text/html")
response.headers["Cache-Control"] = "no-store"
Expand All @@ -51,26 +161,39 @@ def build_report(data: bytes, source: str, show_names: bool) -> Response | tuple
try:
result = load_bookings(handle.name)
except WorkbookError as exc:
message = str(exc).replace(handle.name, source)
return upload_page(message, 400)
exc.args = (str(exc).replace(handle.name, source),)
return landing_page(explain(exc, source), 400)
if not result.bookings:
return upload_page(f"No valid bookings found in {source}. Check the columns and try again.", 400)
return landing_page(
problem(
f"None of the rows in {source} could be used.",
"Check that Price is a number and Status is Confirmed or Cancelled.",
template_link=True,
),
400,
)
return report_response(result, source, data, show_names)


@app.get("/")
def index():
return upload_page()
return landing_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)
return landing_page(problem("No file chosen.", "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 landing_page(
problem(
f"{name} isn't an .xlsx file.",
"Only Excel .xlsx files are supported. In Excel, choose Save As › Excel Workbook (.xlsx).",
),
400,
)
return build_report(upload.read(), name, show_names=request.form.get("show_names") == "on")


Expand All @@ -80,6 +203,33 @@ def sample():
return report_response(load_bookings(SAMPLE), SAMPLE.name, data, show_names=False)


@app.get("/template.xlsx")
def template():
workbook = Workbook()
sheet = workbook.active
sheet.title = "Bookings"
sheet.append([name for name, _, _ in COLUMNS])
for row in TEMPLATE_ROWS:
sheet.append(row)
for cell in sheet["G"][1:]:
cell.number_format = "yyyy-mm-dd"
buffer = io.BytesIO()
workbook.save(buffer)
buffer.seek(0)
return send_file(
buffer,
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
as_attachment=True,
download_name="railstat_template.xlsx",
)


@app.errorhandler(RequestEntityTooLarge)
def too_large(_error):
return upload_page(f"That file is larger than {MAX_UPLOAD_MB} MB.", 413)
return landing_page(
problem(
f"That file is larger than {MAX_UPLOAD_MB} MB.",
"Remove unused sheets or rows and try again.",
),
413,
)
4 changes: 2 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"

[project]
name = "report-tool"
version = "1.1.0"
version = "1.2.0"
description = "Turn a train bookings Excel workbook into a validated HTML or text report."
readme = "README.md"
requires-python = ">=3.11"
Expand All @@ -20,7 +20,7 @@ report-tool = "report_tool.cli:main"
packages = ["report_tool"]

[tool.setuptools.package-data]
report_tool = ["templates/*.j2"]
report_tool = ["templates/*.j2", "templates/*.html"]

[tool.pytest.ini_options]
testpaths = ["tests"]
Expand Down
2 changes: 1 addition & 1 deletion report_tool/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
"""Turn a train bookings Excel workbook into a summary report."""

__version__ = "1.1.0"
__version__ = "1.2.0"
96 changes: 1 addition & 95 deletions report_tool/charts.py
Original file line number Diff line number Diff line change
@@ -1,80 +1,14 @@
"""Chart geometry computed in Python so the HTML report needs no charting library."""
"""Series helpers shared by the web app's preview chart."""

from __future__ import annotations

import datetime as dt
import math
from collections import defaultdict
from dataclasses import dataclass
from decimal import Decimal

from report_tool.loader import Booking


def nice_max(value: float) -> float:
"""Round up to 1, 2, 2.5, 5 or 10 times a power of ten, so axis ticks read cleanly."""
if value <= 0:
return 1
magnitude = 10 ** math.floor(math.log10(value))
for step in (1, 2, 2.5, 5, 10):
if value <= step * magnitude:
return step * magnitude
return 10 * magnitude


def nice_axis(value: float, count: int = 4, integer: bool = False) -> float:
"""Axis maximum whose `count` equal steps are round numbers (whole numbers when `integer`)."""
step = nice_max(value / count) if value > 0 else 1
if integer:
step = max(1, math.ceil(step))
return step * count


def ticks(maximum: float, count: int = 4) -> list[float]:
return [maximum * i / count for i in range(count + 1)]


def percent(value: float, maximum: float) -> float:
return round(100 * value / maximum, 2) if maximum else 0.0


@dataclass(frozen=True)
class WeekPoint:
week_start: dt.date
revenue: Decimal
x: float
y: float
labelled: bool = True


@dataclass(frozen=True)
class LineChart:
points: list[WeekPoint]
y_ticks: list[tuple[float, float]] # (value, y position)
width: int
height: int
left: int
top: int
bottom: int

@property
def polyline(self) -> str:
return " ".join(f"{p.x},{p.y}" for p in self.points)

@property
def area_path(self) -> str:
first, last = self.points[0], self.points[-1]
return (
f"M{first.x} {self.bottom} L"
+ " L".join(f"{p.x} {p.y}" for p in self.points)
+ (f" L{last.x} {self.bottom} Z")
)

@property
def peak(self) -> WeekPoint:
return max(self.points, key=lambda p: p.revenue)


def weekly_revenue(bookings: list[Booking]) -> list[tuple[dt.date, Decimal]]:
"""Net revenue of confirmed, dated bookings per week (weeks start Monday), gaps filled with zero."""
totals: dict[dt.date, Decimal] = defaultdict(lambda: Decimal("0.00"))
Expand All @@ -89,31 +23,3 @@ def weekly_revenue(bookings: list[Booking]) -> list[tuple[dt.date, Decimal]]:
series.append((week, totals.get(week, Decimal("0.00"))))
week += dt.timedelta(weeks=1)
return series


def line_chart(
series: list[tuple[dt.date, Decimal]], width: int = 640, height: int = 240
) -> LineChart | None:
if len(series) < 2:
return None
left, right, top, bottom = 72, width - 24, 16, height - 44
y_max = nice_axis(float(max(value for _, value in series)))
step = (right - left) / (len(series) - 1)

def y_of(value: float) -> float:
return round(bottom - (bottom - top) * value / y_max, 1)

every = math.ceil(len(series) / 8) # at most 8 date labels on the axis
points = [
WeekPoint(week, value, round(left + i * step, 1), y_of(float(value)), labelled=i % every == 0)
for i, (week, value) in enumerate(series)
]
return LineChart(
points=points,
y_ticks=[(value, y_of(value)) for value in ticks(y_max)],
width=width,
height=height,
left=left,
top=top,
bottom=bottom,
)
Loading
Loading