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
15 changes: 10 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,21 +18,26 @@ 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.
- **Report generation:** writes a time-stamped report such as `reports/booking_summary_20261031_140211.txt` with net revenue, discounts, cancellation rate, average ticket, tickets by class, bookings by route (busiest first), every confirmed and cancelled booking, and the skipped rows.
- **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.
- **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.
- **Cross-platform:** `--open` opens the report with the default app on Windows, macOS or Linux.

### Expected columns
`TicketID`, `PassengerName`, `Route`, `Class`, `Price`, `Status` are required. `Date`, `DiscountApplied` (a percentage from 0 to 100; blank means none) and `LoyaltyMember` (Yes/No) are optional. Header names are matched without regard to case or spacing.

### Technical Stack
Python 3.11+, openpyxl, pytest and ruff for development, GitHub Actions for CI.
Python 3.11+, openpyxl, Jinja2 (HTML report), pytest and ruff for development, GitHub Actions for CI.

### How to Use
```bash
pip install .
report-tool samples/bookings_sample.xlsx # writes to ./reports/
report-tool bookings.xlsx --out my_reports --open # choose a folder and open the report
report-tool # asks for the file path
report-tool samples/bookings_sample.xlsx # HTML report in ./reports/
report-tool bookings.xlsx --out my_reports --open # choose a folder and open the report
report-tool bookings.xlsx --format both # HTML and text
report-tool bookings.xlsx --show-names # include full passenger names
report-tool # asks for the file path
```
You can also run it without installing: `python -m report_tool bookings.xlsx`. Use `-v` to log each skipped row in the terminal.

Expand Down
9 changes: 6 additions & 3 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ build-backend = "setuptools.build_meta"

[project]
name = "report-tool"
version = "1.0.0"
description = "Turn a train bookings Excel workbook into a validated summary report."
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"]
dependencies = ["openpyxl>=3.1,<4", "jinja2>=3.1,<4"]

[project.optional-dependencies]
dev = ["pytest>=8", "ruff>=0.6"]
Expand All @@ -19,6 +19,9 @@ report-tool = "report_tool.cli:main"
[tool.setuptools]
packages = ["report_tool"]

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

[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.0.0"
__version__ = "1.1.0"
119 changes: 119 additions & 0 deletions report_tool/charts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
"""Chart geometry computed in Python so the HTML report needs no charting library."""

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"))
for booking in bookings:
if booking.status == "confirmed" and booking.date:
totals[booking.date - dt.timedelta(days=booking.date.weekday())] += booking.net_price
if not totals:
return []
week, last = min(totals), max(totals)
series = []
while week <= last:
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,
)
73 changes: 65 additions & 8 deletions report_tool/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,18 @@
from __future__ import annotations

import argparse
import csv
import datetime as dt
import hashlib
import logging
import os
import subprocess
import sys
from pathlib import Path

from report_tool import __version__
from report_tool.loader import WorkbookError, load_bookings
from report_tool.html_report import render_html
from report_tool.loader import SkippedRow, WorkbookError, load_bookings
from report_tool.render import render_text
from report_tool.summary import summarize

Expand All @@ -25,10 +28,20 @@
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
prog="report-tool",
description="Summarise a train bookings Excel workbook into a text report.",
description="Summarise a train bookings Excel workbook into an HTML dashboard or text report.",
)
parser.add_argument("workbook", nargs="?", help="path to the .xlsx file (asked for if left out)")
parser.add_argument("-o", "--out", default="reports", help="folder for the report (default: reports)")
parser.add_argument(
"-f",
"--format",
choices=["html", "txt", "both"],
default="html",
help="report format (default: html)",
)
parser.add_argument(
"--show-names", action="store_true", help="include full passenger names (masked by default)"
)
parser.add_argument("--open", action="store_true", help="open the report when it's written")
parser.add_argument("-v", "--verbose", action="store_true", help="log each skipped row")
parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
Expand Down Expand Up @@ -69,14 +82,58 @@ def main(argv: list[str] | None = None, now: dt.datetime | None = None) -> int:

now = now or dt.datetime.now()
summary = summarize(result.bookings)
report = render_text(summary, result.skipped, source=Path(workbook).name, generated_at=now)

source = Path(workbook).name
out_dir = Path(args.out)
out_dir.mkdir(parents=True, exist_ok=True)
out_path = out_dir / f"booking_summary_{now:%Y%m%d_%H%M%S}.txt"
out_path.write_text(report, encoding="utf-8")
log.info("Report saved to %s", out_path)
stem = f"booking_summary_{now:%Y%m%d_%H%M%S}"

skipped_csv = None
if result.skipped:
skipped_csv = out_dir / f"{stem}_skipped_rows.csv"
write_skipped_csv(skipped_csv, result.skipped)
log.info("Skipped rows saved to %s", skipped_csv)

written: list[Path] = []
if args.format in ("txt", "both"):
path = out_dir / f"{stem}.txt"
text = render_text(
summary, result.skipped, source=source, generated_at=now, show_names=args.show_names
)
path.write_text(text, encoding="utf-8")
written.append(path)
if args.format in ("html", "both"):
path = out_dir / f"{stem}.html"
html = render_html(
summary,
result.skipped,
source=source,
source_sha256=sha256_of(Path(workbook)),
generated_at=now,
show_names=args.show_names,
skipped_csv_name=skipped_csv.name if skipped_csv else None,
)
path.write_text(html, encoding="utf-8")
written.append(path)

for path in written:
log.info("Report saved to %s", path)
if args.open:
open_file(out_path)
open_file(written[-1])
return EXIT_OK


def sha256_of(path: Path) -> str:
return hashlib.sha256(path.read_bytes()).hexdigest()


def write_skipped_csv(path: Path, skipped: list[SkippedRow]) -> None:
with path.open("w", newline="", encoding="utf-8") as handle:
writer = csv.writer(handle)
writer.writerow(["excel_row", "ticket_id", "reason", "value_found"])
for item in skipped:
writer.writerow([item.row, _csv_safe(item.ticket_id), item.reason, _csv_safe(item.value)])


def _csv_safe(value: str) -> str:
"""Stop spreadsheet apps from running a cell copied from the input as a formula."""
return "'" + value if value[:1] in ("=", "+", "-", "@", "\t", "\r") else value
Loading
Loading