From 4f5c9942c68c487825b6894062df5eefd4262d0b Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 7 Nov 2026 02:16:49 +0000 Subject: [PATCH] Add HTML dashboard report with name masking and skipped-rows CSV - New default output: one self-contained HTML file (Jinja2, inline CSS/SVG, no external assets) with KPI tiles, skipped-rows warning, route and class bar charts, weekly net revenue line, and a filterable, searchable table - Export CSV and Print / Save PDF buttons; light and dark mode; phone layout - Passenger names masked by default in HTML and text; --show-names opts in - Skipped rows also saved as ..._skipped_rows.csv; formula-like cells neutralised - --format html|txt|both; source file sha256 shown in the report footer - Tests for escaping, masking, chart geometry and the new CLI options Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016gtNTGbmvq2DdoGC4air5K --- README.md | 15 +- pyproject.toml | 9 +- report_tool/__init__.py | 2 +- report_tool/charts.py | 119 ++++++++++ report_tool/cli.py | 73 +++++- report_tool/html_report.py | 126 ++++++++++ report_tool/privacy.py | 19 ++ report_tool/render.py | 23 +- report_tool/templates/report.html.j2 | 334 +++++++++++++++++++++++++++ tests/test_cli.py | 53 ++++- tests/test_html_report.py | 101 ++++++++ tests/test_privacy.py | 16 ++ 12 files changed, 864 insertions(+), 26 deletions(-) create mode 100644 report_tool/charts.py create mode 100644 report_tool/html_report.py create mode 100644 report_tool/privacy.py create mode 100644 report_tool/templates/report.html.j2 create mode 100644 tests/test_html_report.py create mode 100644 tests/test_privacy.py diff --git a/README.md b/README.md index 7be9646..144c2ff 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/pyproject.toml b/pyproject.toml index 37dbda6..2fa85de 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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"] @@ -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"] diff --git a/report_tool/__init__.py b/report_tool/__init__.py index 3c74c54..6a85f71 100644 --- a/report_tool/__init__.py +++ b/report_tool/__init__.py @@ -1,3 +1,3 @@ """Turn a train bookings Excel workbook into a summary report.""" -__version__ = "1.0.0" +__version__ = "1.1.0" diff --git a/report_tool/charts.py b/report_tool/charts.py new file mode 100644 index 0000000..c9598ad --- /dev/null +++ b/report_tool/charts.py @@ -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, + ) diff --git a/report_tool/cli.py b/report_tool/cli.py index f5f09e3..18cf54a 100644 --- a/report_tool/cli.py +++ b/report_tool/cli.py @@ -3,7 +3,9 @@ from __future__ import annotations import argparse +import csv import datetime as dt +import hashlib import logging import os import subprocess @@ -11,7 +13,8 @@ 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 @@ -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__}") @@ -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 diff --git a/report_tool/html_report.py b/report_tool/html_report.py new file mode 100644 index 0000000..aef2c09 --- /dev/null +++ b/report_tool/html_report.py @@ -0,0 +1,126 @@ +"""Render a BookingSummary as one self-contained HTML file (no server, no external assets).""" + +from __future__ import annotations + +import datetime as dt +from dataclasses import dataclass +from decimal import Decimal + +from jinja2 import Environment, PackageLoader, select_autoescape + +from report_tool import __version__ +from report_tool.charts import line_chart, nice_axis, percent, ticks, weekly_revenue +from report_tool.loader import Booking, SkippedRow +from report_tool.privacy import display_name +from report_tool.render import money +from report_tool.summary import BookingSummary + +_env = Environment( + loader=PackageLoader("report_tool", "templates"), + autoescape=select_autoescape(["html", "j2"]), # spreadsheet text is untrusted: always escape it + trim_blocks=True, + lstrip_blocks=True, +) +_env.filters["money"] = money + + +def _number(value: float) -> str: + return f"{value:,.0f}" if float(value).is_integer() else f"{value:,.1f}" + + +def _short_money(value: float) -> str: + if value >= 1000: + return f"${value / 1000:,.1f}k".replace(".0k", "k") + return f"${value:,.0f}" + + +def _day(value: dt.date) -> str: + return f"{value.day} {value:%b}" + + +_env.filters["number"] = _number +_env.filters["day"] = _day +_env.filters["short_money"] = _short_money + + +@dataclass(frozen=True) +class Row: + ticket_id: str + passenger: str + route: str + ticket_class: str + net_price: Decimal | None + date: dt.date | None + status: str + + +def _rows(bookings: list[Booking], show_names: bool) -> list[Row]: + ordered = sorted(bookings, key=lambda b: (b.date or dt.date.max, b.row)) + return [ + Row( + ticket_id=b.ticket_id, + passenger=display_name(b.passenger, show_names), + route=b.route, + ticket_class=b.ticket_class, + net_price=b.net_price if b.status == "confirmed" else None, + date=b.date, + status=b.status, + ) + for b in ordered + ] + + +def render_html( + summary: BookingSummary, + skipped: list[SkippedRow], + source: str, + source_sha256: str, + generated_at: dt.datetime, + show_names: bool = False, + skipped_csv_name: str | None = None, +) -> str: + routes = summary.routes_by_volume() + route_max = nice_axis(max((counts.total for _, counts in routes), default=0), integer=True) + route_bars = [ + { + "name": name, + "confirmed": counts.confirmed, + "cancelled": counts.cancelled, + "confirmed_pct": percent(counts.confirmed, route_max), + "cancelled_pct": percent(counts.cancelled, route_max), + } + for name, counts in routes + ] + classes = summary.by_class.most_common() + class_max = nice_axis(max((count for _, count in classes), default=0), integer=True) + class_bars = [{"name": name, "count": count, "pct": percent(count, class_max)} for name, count in classes] + + loyalty_known = summary.loyalty_members + summary.non_loyalty_members + template = _env.get_template("report.html.j2") + return template.render( + s=summary, + skipped=skipped, + skipped_reasons=_reason_counts(skipped), + skipped_csv_name=skipped_csv_name, + source=source, + source_hash=f"{source_sha256[:4]}…{source_sha256[-4:]}", + generated_at=generated_at, + rows_read=summary.valid_bookings + len(skipped), + loyalty_pct=percent(summary.loyalty_members, loyalty_known), + loyalty_known=loyalty_known, + route_bars=route_bars, + route_ticks=ticks(route_max), + class_bars=class_bars, + class_ticks=ticks(class_max), + line=line_chart(weekly_revenue(summary.confirmed)), + rows=_rows(summary.confirmed + summary.cancelled, show_names), + show_names=show_names, + version=__version__, + ) + + +def _reason_counts(skipped: list[SkippedRow]) -> list[tuple[str, int]]: + counts: dict[str, int] = {} + for item in skipped: + counts[item.reason] = counts.get(item.reason, 0) + 1 + return sorted(counts.items(), key=lambda item: -item[1]) diff --git a/report_tool/privacy.py b/report_tool/privacy.py new file mode 100644 index 0000000..9c14917 --- /dev/null +++ b/report_tool/privacy.py @@ -0,0 +1,19 @@ +"""Masking for personal data that reports don't need in full.""" + +MASK = "•" + + +def mask_name(name: str) -> str: + """'Maria Gonzalez' -> 'M. G••••••'; 'Cher' -> 'C•••'. Keeps initials only.""" + parts = name.split() + if not parts: + return "" + if len(parts) == 1: + word = parts[0] + return word[0] + MASK * (len(word) - 1) + last = parts[-1] + return f"{parts[0][0]}. {last[0]}{MASK * (len(last) - 1)}" + + +def display_name(name: str, show_names: bool) -> str: + return name if show_names else mask_name(name) diff --git a/report_tool/render.py b/report_tool/render.py index 77d3a60..9428b35 100644 --- a/report_tool/render.py +++ b/report_tool/render.py @@ -1,4 +1,4 @@ -"""Render a BookingSummary as a plain-text report.""" +"""Render a BookingSummary as a plain-text report. Passenger names are masked unless show_names.""" from __future__ import annotations @@ -6,6 +6,7 @@ from decimal import Decimal from report_tool.loader import Booking, SkippedRow +from report_tool.privacy import display_name from report_tool.summary import BookingSummary @@ -21,8 +22,13 @@ def _loyalty(value: bool | None) -> str: return {True: "Yes", False: "No", None: "Unknown"}[value] -def _booking_line(booking: Booking, with_price: bool) -> str: - parts = [booking.ticket_id, booking.passenger, booking.route, booking.ticket_class] +def _booking_line(booking: Booking, with_price: bool, show_names: bool) -> str: + parts = [ + booking.ticket_id, + display_name(booking.passenger, show_names), + booking.route, + booking.ticket_class, + ] if with_price: parts.append(money(booking.net_price)) parts.append(_date(booking.date)) @@ -36,6 +42,7 @@ def render_text( skipped: list[SkippedRow], source: str, generated_at: dt.datetime, + show_names: bool = False, ) -> str: lines: list[str] = [ "TRAIN BOOKINGS SUMMARY", @@ -76,11 +83,17 @@ def render_text( lines.append("") lines.append("CONFIRMED BOOKINGS") - lines += [f"{i}. {_booking_line(b, with_price=True)}" for i, b in enumerate(summary.confirmed, 1)] + lines += [ + f"{i}. {_booking_line(b, with_price=True, show_names=show_names)}" + for i, b in enumerate(summary.confirmed, 1) + ] lines.append("") lines.append("CANCELLED BOOKINGS") - lines += [f"{i}. {_booking_line(b, with_price=False)}" for i, b in enumerate(summary.cancelled, 1)] + lines += [ + f"{i}. {_booking_line(b, with_price=False, show_names=show_names)}" + for i, b in enumerate(summary.cancelled, 1) + ] if skipped: lines += ["", "SKIPPED ROWS"] diff --git a/report_tool/templates/report.html.j2 b/report_tool/templates/report.html.j2 new file mode 100644 index 0000000..bd4027d --- /dev/null +++ b/report_tool/templates/report.html.j2 @@ -0,0 +1,334 @@ + + + + + + +Train bookings report · {{ source }} + + + +
+ +
+
+

Train bookings report

+

{{ source }} · {{ rows_read | number }} rows read · Generated {{ generated_at.strftime("%d %b %Y, %H:%M") }}

+
+
+ + +
+
+ +{% if skipped %} +
+ +
+ Warning: {{ skipped | length }} row{{ "s were" if skipped | length != 1 else " was" }} skipped and {{ "are" if skipped | length != 1 else "is" }} not in these totals + {% for reason, count in skipped_reasons %}{{ count }} × {{ reason }}{{ " · " if not loop.last }}{% endfor %} +
+ Review skipped rows +
+{% endif %} + +
+
+ Net revenue + {{ s.net_revenue | money }} + after {{ s.total_discount | money }} in discounts +
+
+ Confirmed tickets + {{ s.confirmed_tickets | number }} + of {{ s.valid_bookings | number }} valid bookings · avg {{ s.average_net_ticket | money }} +
+
+ Cancellation rate + {{ "%.1f" | format(s.cancellation_rate * 100) }}% + {{ s.cancellations | number }} booking{{ "s" if s.cancellations != 1 }} cancelled +
+
+ Loyalty members + {% if loyalty_known %} + {{ "%.0f" | format(loyalty_pct) }}% + {{ s.loyalty_members | number }} of {{ loyalty_known | number }} confirmed tickets{% if s.loyalty_unknown %} · {{ s.loyalty_unknown }} unknown{% endif %} + {% else %} + n/a + no loyalty data in the file + {% endif %} +
+
+ +
+
+
+

Bookings by route

+
ConfirmedCancelled
+
+

Busiest first. Labels show confirmed · cancelled.

+
+ {% for r in route_bars %} + {{ r.name }} +
+
+
+
+ {{ r.confirmed }} · {{ r.cancelled }} + {% endfor %} + + + +
+
+ +
+

Confirmed tickets by class

+

{{ s.confirmed_tickets | number }} tickets

+
+ {% for c in class_bars %} + {{ c.name }} +
+ {{ c.count }} + {% endfor %} + + + +
+
+
+ +
+
+

Net revenue by week

+ {% if line %}Highest: week of {{ line.peak.week_start | day }}, {{ line.peak.revenue | money }}{% endif %} +
+ {% if line %} + + {% for value, y in line.y_ticks %} + + {{ value | short_money }} + {% endfor %} + + + {% for p in line.points %} + Week of {{ p.week_start | day }}: {{ p.revenue | money }} + {% if p.labelled %}{{ p.week_start | day }}{% endif %} + {% endfor %} + + {% else %} +

Not enough dated bookings to show a trend (needs at least two weeks).

+ {% endif %} +
+ +
+

All bookings

+
+
+ + + +
+ + +
+
+ + + + + + + {% for r in rows %} + + + + + + + {% endfor %} + +
TicketPassengerRouteClassNet priceDateStatus
{{ r.ticket_id }}{{ r.passenger }}{{ r.route }}{{ r.ticket_class }}{{ r.net_price | money if r.net_price is not none else "—" }}{{ r.date.isoformat() if r.date else "—" }}{{ r.status | capitalize }}
+
+

Showing {{ rows | length }} of {{ rows | length }} bookings.{% if not show_names %} Passenger names are masked; run with --show-names to include them.{% endif %}

+
+ +{% if skipped %} +
+

Skipped rows ({{ skipped | length }})

+
+ + + + {% for item in skipped %} + + {% endfor %} + +
Excel rowTicketReasonValue found
{{ item.row }}{{ item.ticket_id or "—" }}{{ item.reason }}{{ item.value }}
+
+ {% if skipped_csv_name %}

The same list is saved as {{ skipped_csv_name }} next to this report.

{% endif %} +
+{% endif %} + +
+ One file, opens in any browser and works offline. + report-tool {{ version }} · source sha256 {{ source_hash }} +
+
+ + + + diff --git a/tests/test_cli.py b/tests/test_cli.py index b11a497..cfa5ea9 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -28,17 +28,17 @@ Toronto-Montreal: 1 confirmed, 1 cancelled CONFIRMED BOOKINGS -1. TB-1 | Ann Lee | Toronto-Montreal | First | $1,080.00 | 2026-09-08 | Loyalty: Yes +1. TB-1 | A. L•• | Toronto-Montreal | First | $1,080.00 | 2026-09-08 | Loyalty: Yes CANCELLED BOOKINGS -1. TB-2 | Bo Chan | Toronto-Montreal | Economy | no date +1. TB-2 | B. C••• | Toronto-Montreal | Economy | no date SKIPPED ROWS Row 4 (TB-3): Price is not a number, found '$5O' """ -def test_writes_timestamped_report(make_workbook, tmp_path): +def test_writes_timestamped_text_report(make_workbook, tmp_path): path = make_workbook( [ [ @@ -57,7 +57,7 @@ def test_writes_timestamped_report(make_workbook, tmp_path): ] ) out = tmp_path / "out" - assert main([str(path), "--out", str(out)], now=NOW) == EXIT_OK + assert main([str(path), "--out", str(out), "--format", "txt"], now=NOW) == EXIT_OK report = out / "booking_summary_20261031_140211.txt" assert report.read_text(encoding="utf-8") == EXPECTED_REPORT @@ -77,3 +77,48 @@ def test_prompts_for_path_when_not_given(make_workbook, tmp_path, monkeypatch): path = make_workbook([["TB-1", "Ann", "A-B", "Economy", 10, "Confirmed", None, 0, "Yes"]]) monkeypatch.setattr("builtins.input", lambda _prompt: f'"{path}"') assert main(["--out", str(tmp_path / "out")], now=NOW) == EXIT_OK + + +def three_rows(make_workbook): + return make_workbook( + [ + [ + "TB-1", + "Ann Lee", + "Toronto-Montreal", + "First", + 1200, + "Confirmed", + dt.datetime(2026, 9, 8), + 10, + "Yes", + ], + ["TB-2", "Bo Chan", "Toronto-Montreal", "Economy", 80, "Cancelled", None, 0, "No"], + ["@TB-3", "Cy Diaz", "Toronto-Montreal", "Economy", "TBD", "Confirmed", None, 0, "No"], + ] + ) + + +def test_html_is_the_default_and_skipped_rows_csv_is_written(make_workbook, tmp_path): + out = tmp_path / "out" + assert main([str(three_rows(make_workbook)), "--out", str(out)], now=NOW) == EXIT_OK + assert sorted(p.name for p in out.iterdir()) == [ + "booking_summary_20261031_140211.html", + "booking_summary_20261031_140211_skipped_rows.csv", + ] + html = (out / "booking_summary_20261031_140211.html").read_text(encoding="utf-8") + assert "1 row was skipped" in html + assert "A. L••" in html and "Ann Lee" not in html + csv_text = (out / "booking_summary_20261031_140211_skipped_rows.csv").read_text(encoding="utf-8") + assert csv_text.splitlines() == [ + "excel_row,ticket_id,reason,value_found", + "4,'@TB-3,Price is not a number,'TBD'", + ] + + +def test_both_formats_and_show_names(make_workbook, tmp_path): + out = tmp_path / "out" + args = [str(three_rows(make_workbook)), "--out", str(out), "--format", "both", "--show-names"] + assert main(args, now=NOW) == EXIT_OK + for suffix in (".txt", ".html"): + assert "Ann Lee" in (out / f"booking_summary_20261031_140211{suffix}").read_text(encoding="utf-8") diff --git a/tests/test_html_report.py b/tests/test_html_report.py new file mode 100644 index 0000000..32c4d5a --- /dev/null +++ b/tests/test_html_report.py @@ -0,0 +1,101 @@ +import datetime as dt +from decimal import Decimal + +from report_tool.charts import line_chart, nice_axis, nice_max, weekly_revenue +from report_tool.html_report import render_html +from report_tool.loader import Booking, SkippedRow +from report_tool.summary import summarize + +NOW = dt.datetime(2026, 10, 31, 14, 2) + + +def booking( + ticket, status="confirmed", price="100", date=dt.date(2026, 9, 8), passenger="Ann Lee", route="A-B" +): + return Booking( + row=2, + ticket_id=ticket, + passenger=passenger, + route=route, + ticket_class="Economy", + price=Decimal(price), + status=status, + date=date, + discount_pct=Decimal("0"), + loyalty=True, + ) + + +def render(bookings, skipped=(), **kwargs): + return render_html( + summarize(list(bookings)), + list(skipped), + source="bookings.xlsx", + source_sha256="ab" * 32, + generated_at=NOW, + **kwargs, + ) + + +def test_spreadsheet_text_is_escaped(): + html = render([booking("", route="A")], show_names=True) + assert "" not in html + assert "<script>alert(1)</script>" in html + assert "<b>A</b>" in html + + +def test_kpis_and_masking(): + html = render([booking("1", price="1200"), booking("2", status="cancelled")]) + assert "$1,200.00" in html + assert "50.0%" in html + assert "A. L••" in html and "Ann Lee" not in html + assert "run with --show-names" in html + assert "abab…abab" in html + + +def test_skipped_banner_only_when_rows_were_skipped(): + assert "skipped and" not in render([booking("1")]) + html = render([booking("1")], [SkippedRow(5, "TB-9", "Unknown status", "'Pending'")]) + assert "Warning: 1 row was skipped and is not in these totals" in html + assert "1 × Unknown status" in html + assert 'id="skipped"' in html + + +def test_trend_needs_two_weeks(): + assert "Not enough dated bookings" in render([booking("1")]) + html = render([booking("1"), booking("2", date=dt.date(2026, 9, 22))]) + assert "