From f5c40ee04336b4b7260d99468446c35339a13d48 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 7 Nov 2026 02:07:58 +0000 Subject: [PATCH] Package the reporting tool, fix crashes on messy rows, add tests and CI - Move the notebook logic into a report_tool package with a report-tool CLI - Validate each row: blank Status, non-numeric Price, unknown status and out-of-range discounts are skipped and listed with a reason, not fatal - Match columns by header name; clear errors for missing columns and bad files - Use Decimal for money; write time-stamped reports; cross-platform --open - Drop pyinputplus and the fixed 5-second sleep - Add pytest suite, pyproject.toml, ruff config, GitHub Actions CI, sample workbook - Update README to match the code Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016gtNTGbmvq2DdoGC4air5K --- .github/workflows/ci.yml | 22 ++++ .gitignore | 10 ++ README.md | 63 +++++----- pyproject.toml | 31 +++++ report_tool/__init__.py | 3 + report_tool/__main__.py | 5 + report_tool/cli.py | 82 ++++++++++++ report_tool/loader.py | 235 +++++++++++++++++++++++++++++++++++ report_tool/render.py | 91 ++++++++++++++ report_tool/summary.py | 75 +++++++++++ samples/bookings_sample.xlsx | Bin 0 -> 8183 bytes samples/make_sample.py | 60 +++++++++ tests/conftest.py | 36 ++++++ tests/test_cli.py | 79 ++++++++++++ tests/test_loader.py | 126 +++++++++++++++++++ tests/test_summary.py | 60 +++++++++ 16 files changed, 947 insertions(+), 31 deletions(-) create mode 100644 .github/workflows/ci.yml create mode 100644 .gitignore create mode 100644 pyproject.toml create mode 100644 report_tool/__init__.py create mode 100644 report_tool/__main__.py create mode 100644 report_tool/cli.py create mode 100644 report_tool/loader.py create mode 100644 report_tool/render.py create mode 100644 report_tool/summary.py create mode 100644 samples/bookings_sample.xlsx create mode 100644 samples/make_sample.py create mode 100644 tests/conftest.py create mode 100644 tests/test_cli.py create mode 100644 tests/test_loader.py create mode 100644 tests/test_summary.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..3e09ae8 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,22 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + +jobs: + test: + runs-on: ubuntu-latest + strategy: + matrix: + python-version: ["3.11", "3.12", "3.13"] + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version }} + - run: pip install -e ".[dev]" + - run: ruff check . + - run: ruff format --check . + - run: pytest diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..add7d17 --- /dev/null +++ b/.gitignore @@ -0,0 +1,10 @@ +__pycache__/ +*.py[cod] +*.egg-info/ +.venv/ +.pytest_cache/ +.ruff_cache/ +build/ +dist/ +reports/ +.ipynb_checkpoints/ diff --git a/README.md b/README.md index af1a678..7be9646 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,4 @@ -# Train-Booking-Data-Automated-Summarizer -# Data-Analysis & Automated Reporting Tool +# Data Analysis & Automated Reporting Tool ### Project Overview This project is a Python-based automation tool designed to ingest, normalize, and analyze complex datasets from Excel. While currently configured for financial/booking data, the core engine demonstrates the logic required for Security Log Parsing and Incident Reporting. @@ -7,42 +6,44 @@ This project is a Python-based automation tool designed to ingest, normalize, an As a SOC Analyst candidate, I developed this to showcase my ability to handle data integrity, automate repetitive administrative tasks, and generate structured technical reports. ### Cybersecurity Relevance (SOC Context) -In a Security Operations Center (SOC), analysts must often parse through massive amounts of exported CSV/Excel data from SIEMs or Firewalls. This script demonstrates three critical SOC competencies: +In a Security Operations Center (SOC), analysts must often parse through massive amounts of exported CSV/Excel data from SIEMs or Firewalls. This tool demonstrates three critical SOC competencies: -Data Normalization: The script utilizes .strip().lower() and type-casting to ensure that inconsistent data inputs (e.g., "Confirmed " vs "confirmed") are normalized for accurate analysis. +**Data Normalization:** Status, class, loyalty and money values are trimmed, case-normalized and type-checked (for example "Confirmed " and "confirmed" are treated the same, and "$1,200" is read as 1200.00), so inconsistent inputs are analyzed accurately. -Defensive Programming: Implements robust try-except blocks and pyinputplus validation to handle malformed files and user input errors, ensuring the tool doesn't crash during critical operations. +**Defensive Programming:** Every row is validated on its own. A malformed row (blank status, a price like "TBD", an unknown status) is set aside with the reason instead of crashing the run, and unreadable files or missing columns stop with a clear message and a non-zero exit code. -Automated Triage & Reporting: The script automatically categorizes records (Confirmed vs. Cancelled) and calculates metrics, mimicking the logic used to triage "True Positives" vs. "False Positives" in an alert queue. +**Automated Triage & Reporting:** Records are categorized (Confirmed vs. Cancelled) and metrics calculated, mimicking the logic used to triage "True Positives" vs. "False Positives" in an alert queue. Rows that couldn't be processed are listed in the report so nothing disappears silently. ### Features -Automated Ingestion: Uses openpyxl to parse multi-column Excel workbooks. +- **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. +- **Cross-platform:** `--open` opens the report with the default app on Windows, macOS or Linux. -Input Validation: Uses pyinputplus to ensure file paths exist before execution. - -Error Handling: Features granular exception handling for FileNotFound and general data corruption. - -Report Generation: Automatically generates a time-stamped bookingSummary.txt and triggers a system process to open the report for immediate review. +### 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 -Language: Python 3.12 - -Libraries: openpyxl (Excel handling), subprocess (System integration), datetime (Timestamping), pyinputplus (Secure input validation). - -### Sample Output -The tool generates a structured report including: - -Total Revenue and Discount Metrics (Financial Integrity) - -Frequency analysis of routes and classes. - -Full audit logs of confirmed and cancelled transactions. +Python 3.11+, openpyxl, pytest and ruff for development, GitHub Actions for CI. ### How to Use -Ensure Python 3.x is installed. - -Install dependencies: pip install openpyxl pyinputplus. - -Run the script: python main.py. - -Enter the path to your .xlsx data file when prompted. +```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 +``` +You can also run it without installing: `python -m report_tool bookings.xlsx`. Use `-v` to log each skipped row in the terminal. + +Exit codes: `0` report written, `1` no valid bookings found, `2` the file couldn't be read or is missing required columns. + +### Development +```bash +pip install -e ".[dev]" +pytest +ruff check . && ruff format --check . +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/`. diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..37dbda6 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,31 @@ +[build-system] +requires = ["setuptools>=69"] +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." +readme = "README.md" +requires-python = ">=3.11" +dependencies = ["openpyxl>=3.1,<4"] + +[project.optional-dependencies] +dev = ["pytest>=8", "ruff>=0.6"] + +[project.scripts] +report-tool = "report_tool.cli:main" + +[tool.setuptools] +packages = ["report_tool"] + +[tool.pytest.ini_options] +testpaths = ["tests"] + +[tool.ruff] +line-length = 110 +target-version = "py311" +extend-exclude = ["*.ipynb"] + +[tool.ruff.lint] +select = ["E", "F", "W", "I", "B", "UP", "SIM"] diff --git a/report_tool/__init__.py b/report_tool/__init__.py new file mode 100644 index 0000000..3c74c54 --- /dev/null +++ b/report_tool/__init__.py @@ -0,0 +1,3 @@ +"""Turn a train bookings Excel workbook into a summary report.""" + +__version__ = "1.0.0" diff --git a/report_tool/__main__.py b/report_tool/__main__.py new file mode 100644 index 0000000..2119ad6 --- /dev/null +++ b/report_tool/__main__.py @@ -0,0 +1,5 @@ +import sys + +from report_tool.cli import main + +sys.exit(main()) diff --git a/report_tool/cli.py b/report_tool/cli.py new file mode 100644 index 0000000..f5f09e3 --- /dev/null +++ b/report_tool/cli.py @@ -0,0 +1,82 @@ +"""Command-line entry point: report-tool bookings.xlsx""" + +from __future__ import annotations + +import argparse +import datetime as dt +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.render import render_text +from report_tool.summary import summarize + +log = logging.getLogger("report_tool") + +EXIT_OK = 0 +EXIT_NO_BOOKINGS = 1 +EXIT_BAD_INPUT = 2 + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + prog="report-tool", + description="Summarise a train bookings Excel workbook into a 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("--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__}") + return parser + + +def open_file(path: Path) -> None: + """Open a file with the system's default app on Windows, macOS or Linux.""" + try: + if sys.platform.startswith("win"): + os.startfile(path) # type: ignore[attr-defined] + elif sys.platform == "darwin": + subprocess.run(["open", str(path)], check=False) + else: + subprocess.run(["xdg-open", str(path)], check=False) + except OSError as exc: + log.warning("Could not open %s: %s", path, exc) + + +def main(argv: list[str] | None = None, now: dt.datetime | None = None) -> int: + args = build_parser().parse_args(argv) + logging.basicConfig(level=logging.DEBUG if args.verbose else logging.INFO, format="%(message)s") + + workbook = args.workbook or input("Path to the train bookings .xlsx file: ").strip().strip('"') + try: + result = load_bookings(workbook) + except WorkbookError as exc: + log.error("Error: %s", exc) + return EXIT_BAD_INPUT + + for item in result.skipped: + log.debug("Skipped row %s: %s (%s)", item.row, item.reason, item.value) + if result.skipped: + log.warning("%d row(s) skipped; details are in the report.", len(result.skipped)) + if not result.bookings: + log.error("No valid bookings found in %s.", workbook) + return EXIT_NO_BOOKINGS + + now = now or dt.datetime.now() + summary = summarize(result.bookings) + report = render_text(summary, result.skipped, source=Path(workbook).name, generated_at=now) + + 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) + + if args.open: + open_file(out_path) + return EXIT_OK diff --git a/report_tool/loader.py b/report_tool/loader.py new file mode 100644 index 0000000..27fbd85 --- /dev/null +++ b/report_tool/loader.py @@ -0,0 +1,235 @@ +"""Read bookings from an Excel workbook and validate each row.""" + +from __future__ import annotations + +import datetime as dt +import zipfile +from dataclasses import dataclass, field +from decimal import Decimal, InvalidOperation +from pathlib import Path + +import openpyxl +from openpyxl.utils.exceptions import InvalidFileException + +# Internal field name -> accepted header spellings (compared case- and space-insensitively). +COLUMNS: dict[str, tuple[str, ...]] = { + "ticket_id": ("ticketid", "ticket id", "ticket"), + "passenger": ("passengername", "passenger name", "passenger"), + "route": ("route",), + "ticket_class": ("class", "ticketclass", "ticket class"), + "price": ("price",), + "status": ("status",), + "date": ("date",), + "discount": ("discountapplied", "discount applied", "discount"), + "loyalty": ("loyaltymember", "loyalty member", "loyalty"), +} +REQUIRED = ("ticket_id", "passenger", "route", "ticket_class", "price", "status") + +STATUSES = {"confirmed": "confirmed", "cancelled": "cancelled", "canceled": "cancelled"} +YES = {"yes", "y", "true", "1"} +NO = {"no", "n", "false", "0"} + + +class WorkbookError(Exception): + """The workbook can't be read, or it's missing required columns.""" + + +@dataclass(frozen=True) +class Booking: + row: int + ticket_id: str + passenger: str + route: str + ticket_class: str + price: Decimal + status: str # "confirmed" or "cancelled" + date: dt.date | None + discount_pct: Decimal + loyalty: bool | None # None when the cell is blank or unrecognised + + @property + def discount_amount(self) -> Decimal: + return (self.price * self.discount_pct / 100).quantize(Decimal("0.01")) + + @property + def net_price(self) -> Decimal: + return self.price - self.discount_amount + + +@dataclass(frozen=True) +class SkippedRow: + row: int + ticket_id: str + reason: str + value: str + + +@dataclass +class LoadResult: + bookings: list[Booking] = field(default_factory=list) + skipped: list[SkippedRow] = field(default_factory=list) + + @property + def rows_read(self) -> int: + return len(self.bookings) + len(self.skipped) + + +def _normalise_header(value: object) -> str: + return " ".join(str(value).split()).lower() if value is not None else "" + + +def map_headers(header_row: tuple[object, ...]) -> dict[str, int]: + """Return {field name: column index}; raise WorkbookError if a required column is missing.""" + found = {_normalise_header(cell): i for i, cell in enumerate(header_row)} + mapping: dict[str, int] = {} + for name, spellings in COLUMNS.items(): + for spelling in spellings: + if spelling in found: + mapping[name] = found[spelling] + break + missing = [COLUMNS[name][0] for name in REQUIRED if name not in mapping] + if missing: + raise WorkbookError( + "Missing required column(s): " + ", ".join(missing) + ". Check the first row of the sheet." + ) + return mapping + + +def parse_money(value: object) -> Decimal: + """Parse 12.5, "12.50", "$1,200.00". Raise ValueError on anything else.""" + if isinstance(value, bool) or value is None: + raise ValueError + text = str(value).strip().replace("$", "").replace(",", "") + try: + amount = Decimal(text) + except InvalidOperation as exc: + raise ValueError from exc + if not amount.is_finite() or amount < 0: + raise ValueError + return amount.quantize(Decimal("0.01")) + + +def parse_discount(value: object) -> Decimal: + """Parse a discount percentage from 0 to 100; a blank cell means no discount.""" + if value is None or (isinstance(value, str) and not value.strip()): + return Decimal("0") + if isinstance(value, bool): + raise ValueError + text = str(value).strip().rstrip("%").strip() + try: + pct = Decimal(text) + except InvalidOperation as exc: + raise ValueError from exc + if not pct.is_finite() or not 0 <= pct <= 100: + raise ValueError + return pct + + +def parse_loyalty(value: object) -> bool | None: + text = str(value).strip().lower() if value is not None else "" + if text in YES: + return True + if text in NO: + return False + return None + + +def parse_date(value: object) -> dt.date | None: + if isinstance(value, dt.datetime): + return value.date() + if isinstance(value, dt.date): + return value + if isinstance(value, str) and value.strip(): + try: + return dt.date.fromisoformat(value.strip()[:10]) + except ValueError: + return None + return None + + +def _text(value: object) -> str: + return "" if value is None else str(value).strip() + + +def parse_row(row_number: int, values: tuple[object, ...], mapping: dict[str, int]) -> Booking | SkippedRow: + def cell(name: str) -> object: + index = mapping.get(name) + if index is None or index >= len(values): + return None + return values[index] + + ticket_id = _text(cell("ticket_id")) + + def skip(reason: str, value: object) -> SkippedRow: + shown = "(blank)" if _text(value) == "" else repr(value) if isinstance(value, str) else str(value) + return SkippedRow(row_number, ticket_id, reason, shown) + + for name, label in ( + ("ticket_id", "TicketID"), + ("passenger", "PassengerName"), + ("route", "Route"), + ("ticket_class", "Class"), + ): + if _text(cell(name)) == "": + return skip(f"{label} is empty", cell(name)) + + raw_status = cell("status") + status_text = _text(raw_status).lower() + if status_text == "": + return skip("Status is empty", raw_status) + if status_text not in STATUSES: + return skip("Unknown status", raw_status) + + try: + price = parse_money(cell("price")) + except ValueError: + return skip("Price is not a number", cell("price")) + + try: + discount = parse_discount(cell("discount")) + except ValueError: + return skip("Discount is not a percentage from 0 to 100", cell("discount")) + + return Booking( + row=row_number, + ticket_id=ticket_id, + passenger=_text(cell("passenger")), + route=_text(cell("route")), + ticket_class=_text(cell("ticket_class")), + price=price, + status=STATUSES[status_text], + date=parse_date(cell("date")), + discount_pct=discount, + loyalty=parse_loyalty(cell("loyalty")), + ) + + +def load_bookings(path: str | Path) -> LoadResult: + """Load the active sheet of an .xlsx file. Bad rows are collected, not fatal.""" + path = Path(path) + if not path.is_file(): + raise WorkbookError(f"File not found: {path}") + try: + workbook = openpyxl.load_workbook(path, read_only=True, data_only=True) + except (InvalidFileException, zipfile.BadZipFile, KeyError, OSError) as exc: + raise WorkbookError(f"Could not open {path} as an Excel .xlsx workbook ({exc}).") from exc + + try: + rows = workbook.active.iter_rows(values_only=True) + header = next(rows, None) + if header is None: + raise WorkbookError(f"{path} is empty.") + mapping = map_headers(header) + + result = LoadResult() + for row_number, values in enumerate(rows, start=2): + if all(_text(v) == "" for v in values): + continue # fully blank row + parsed = parse_row(row_number, values, mapping) + if isinstance(parsed, Booking): + result.bookings.append(parsed) + else: + result.skipped.append(parsed) + return result + finally: + workbook.close() diff --git a/report_tool/render.py b/report_tool/render.py new file mode 100644 index 0000000..77d3a60 --- /dev/null +++ b/report_tool/render.py @@ -0,0 +1,91 @@ +"""Render a BookingSummary as a plain-text report.""" + +from __future__ import annotations + +import datetime as dt +from decimal import Decimal + +from report_tool.loader import Booking, SkippedRow +from report_tool.summary import BookingSummary + + +def money(amount: Decimal) -> str: + return f"${amount:,.2f}" + + +def _date(value: dt.date | None) -> str: + return value.isoformat() if value else "no date" + + +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] + if with_price: + parts.append(money(booking.net_price)) + parts.append(_date(booking.date)) + if with_price: + parts.append(f"Loyalty: {_loyalty(booking.loyalty)}") + return " | ".join(parts) + + +def render_text( + summary: BookingSummary, + skipped: list[SkippedRow], + source: str, + generated_at: dt.datetime, +) -> str: + lines: list[str] = [ + "TRAIN BOOKINGS SUMMARY", + f"Source: {source}", + f"Generated: {generated_at:%Y-%m-%d %H:%M:%S}", + f"Rows read: {summary.valid_bookings + len(skipped)} " + f"({summary.valid_bookings} valid, {len(skipped)} skipped)", + "", + ] + if skipped: + lines += [ + f"WARNING: {len(skipped)} row(s) were skipped and are not in these totals. See SKIPPED ROWS.", + "", + ] + + lines += [ + "OVERVIEW", + f"Net revenue: {money(summary.net_revenue)}", + f"Discounts given: {money(summary.total_discount)}", + f"Confirmed tickets: {summary.confirmed_tickets}", + f"Average net ticket: {money(summary.average_net_ticket)}", + f"Cancellations: {summary.cancellations} ({summary.cancellation_rate:.1%} of valid bookings)", + f"Loyalty members: {summary.loyalty_members}", + f"Non-loyalty members: {summary.non_loyalty_members}", + ] + if summary.loyalty_unknown: + lines.append(f"Loyalty unknown: {summary.loyalty_unknown}") + lines.append("") + + lines.append("CONFIRMED TICKETS BY CLASS") + for ticket_class, count in summary.by_class.most_common(): + lines.append(f"{ticket_class}: {count}") + lines.append("") + + lines.append("BOOKINGS BY ROUTE (busiest first)") + for route, counts in summary.routes_by_volume(): + lines.append(f"{route}: {counts.confirmed} confirmed, {counts.cancelled} cancelled") + lines.append("") + + lines.append("CONFIRMED BOOKINGS") + lines += [f"{i}. {_booking_line(b, with_price=True)}" 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)] + + if skipped: + lines += ["", "SKIPPED ROWS"] + for item in skipped: + ticket = item.ticket_id or "no ticket ID" + lines.append(f"Row {item.row} ({ticket}): {item.reason}, found {item.value}") + + return "\n".join(lines) + "\n" diff --git a/report_tool/summary.py b/report_tool/summary.py new file mode 100644 index 0000000..de6382f --- /dev/null +++ b/report_tool/summary.py @@ -0,0 +1,75 @@ +"""Aggregate validated bookings into report figures.""" + +from __future__ import annotations + +from collections import Counter +from dataclasses import dataclass, field +from decimal import Decimal + +from report_tool.loader import Booking + + +@dataclass +class RouteCounts: + confirmed: int = 0 + cancelled: int = 0 + + @property + def total(self) -> int: + return self.confirmed + self.cancelled + + +@dataclass +class BookingSummary: + confirmed_tickets: int = 0 + cancellations: int = 0 + net_revenue: Decimal = Decimal("0.00") + total_discount: Decimal = Decimal("0.00") + loyalty_members: int = 0 + non_loyalty_members: int = 0 + loyalty_unknown: int = 0 + by_class: Counter[str] = field(default_factory=Counter) + by_route: dict[str, RouteCounts] = field(default_factory=dict) + confirmed: list[Booking] = field(default_factory=list) + cancelled: list[Booking] = field(default_factory=list) + + @property + def valid_bookings(self) -> int: + return self.confirmed_tickets + self.cancellations + + @property + def cancellation_rate(self) -> float: + return self.cancellations / self.valid_bookings if self.valid_bookings else 0.0 + + @property + def average_net_ticket(self) -> Decimal: + if not self.confirmed_tickets: + return Decimal("0.00") + return (self.net_revenue / self.confirmed_tickets).quantize(Decimal("0.01")) + + def routes_by_volume(self) -> list[tuple[str, RouteCounts]]: + return sorted(self.by_route.items(), key=lambda item: (-item[1].total, item[0])) + + +def summarize(bookings: list[Booking]) -> BookingSummary: + summary = BookingSummary() + for booking in bookings: + route = summary.by_route.setdefault(booking.route, RouteCounts()) + if booking.status == "confirmed": + summary.confirmed_tickets += 1 + summary.net_revenue += booking.net_price + summary.total_discount += booking.discount_amount + summary.by_class[booking.ticket_class] += 1 + route.confirmed += 1 + if booking.loyalty is True: + summary.loyalty_members += 1 + elif booking.loyalty is False: + summary.non_loyalty_members += 1 + else: + summary.loyalty_unknown += 1 + summary.confirmed.append(booking) + else: + summary.cancellations += 1 + route.cancelled += 1 + summary.cancelled.append(booking) + return summary diff --git a/samples/bookings_sample.xlsx b/samples/bookings_sample.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..4a725fd8985d3de18142dbffad5407434f4cf996 GIT binary patch literal 8183 zcmZ{J1yodR*ES&CjkLhb08&!Y%^)*00@5N44vk1kNQczW-JKF5C7nZe2-1j1cleFZ zv;OyaAOG*0v(7o|tTop@_rA`)?tR~Tt1CS~Cr3d+!A3bDwlY%aQ&CJnJ|U1NG4eEb zFjIGSaCG5$<><)mZU<8tRl)0gf{(e{uIbj863&oMC@&G7*)q!gCa8hkF7WzbA6?4c z!=s-zmphCZ)Q}85;@+_1=j$Voo?*F`92(3C&)M**i=?KQ2D;`06BCHG!zt)|8~L5!P(-s4~V!9+pZ`0!7nW?Gy5Ug^q@0~ zf+7M;4%iP%SiN9`nb~WA&y9#)8eap}-1x+ST9$MLq3liQ=r~rSIqz~*Qt1eY} z85DqzY>{RPnU6h#w`=$@KLZonUCsw=!EFvl#X&aBC#VtC#3`^SO3_?qMjrP(D(}n4 zWqf{`YPk>zVDTVsaylsZWUk)vf%22ior$-o2-);9U(;>EY9(i7HwZzOIw2x`NKEVS z{PdEq%3w}1_PgNL%K=#hUPkCqy& zo9L*jfZCv!Z<*Rr{>@H`VLA&jCJIVAD+&r3k{x##kE^wXoyFf*-rxM}>l?T%2$R1% zs2X#(I=92?ed^y(N9JPVwpf=ExUb3>M4}r7^DvJM^lg9klz1qSU_VafbDB6h=kCo2 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a(N#ba%b~qikpq z;}J)Vba3>+-+dS{{xTE=IpYsUltl8A`-R?<@>}+?=||4T%Y!kt3>^ z8co@Kyp{gMBERYaG@FznNTuBUYs+Y6Qu)_tlIop|vpG1uhBrByHkPU>J+pgd9g_&; zHno8nS|4vfd@;27UcH0Ny_C%hzBkQZ=j>48zUx7&a;TE>#Z*r`s&m*DN}VSNC7tc* z*kgo$moIK|88fkB=GIjYFAFrhqIdl6B_<73kgJIeGcGVo*r|{f)&JtTur^37w@8B_ zTHLyxNMnXpQuE-E)!w)(uL>yhN#tnr{B4INZvUVPE{RADx^G_w%fPa>Ig6rsVU;^m z?b(kT8C8S#ZLx^;JA50V4S!SJt None: + rng = random.Random(1002) + workbook = openpyxl.Workbook() + sheet = workbook.active + sheet.title = "Bookings" + sheet.append( + [ + "TicketID", + "PassengerName", + "Route", + "Class", + "Price", + "Status", + "Date", + "DiscountApplied", + "LoyaltyMember", + ] + ) + start = dt.datetime(2026, 9, 7) + for n in range(1, 61): + ticket_class, base = rng.choices(CLASSES, weights=[65, 26, 9])[0] + sheet.append( + [ + f"TB-{1000 + n}", + f"{rng.choice(FIRST)} {rng.choice(LAST)}", + rng.choices(ROUTES, weights=[35, 26, 18, 12, 9])[0], + ticket_class, + round(base * rng.uniform(0.9, 1.3), 2), + rng.choices(["Confirmed", "Cancelled"], weights=[86, 14])[0], + start + dt.timedelta(days=rng.randrange(56)), + rng.choice([0, 0, 0, 5, 10, 15]), + rng.choice(["Yes", "No"]), + ] + ) + # Messy rows the report should flag instead of crashing on. + sheet.append(["TB-1061", "Pat Quinn", "Toronto-Ottawa", "Economy", "$5O", "Confirmed", start, 0, "Yes"]) + sheet.append(["TB-1062", "Ria Shah", "Ottawa-Montreal", "Economy", 72.5, None, start, 0, "No"]) + sheet.append(["TB-1063", "Sam Tran", "Toronto-Kingston", "First", 230, "Pending", start, 0, "Yes"]) + workbook.save(Path(__file__).with_name("bookings_sample.xlsx")) + + +if __name__ == "__main__": + main() diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..eb1fbea --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,36 @@ +from pathlib import Path + +import openpyxl +import pytest + +HEADER = [ + "TicketID", + "PassengerName", + "Route", + "Class", + "Price", + "Status", + "Date", + "DiscountApplied", + "LoyaltyMember", +] + + +@pytest.fixture +def make_workbook(tmp_path: Path): + """Write rows (header first) to an .xlsx file and return its path.""" + + def _make( + rows: list[list[object]], header: list[str] | None = HEADER, name: str = "bookings.xlsx" + ) -> Path: + workbook = openpyxl.Workbook() + sheet = workbook.active + if header is not None: + sheet.append(header) + for row in rows: + sheet.append(row) + path = tmp_path / name + workbook.save(path) + return path + + return _make diff --git a/tests/test_cli.py b/tests/test_cli.py new file mode 100644 index 0000000..b11a497 --- /dev/null +++ b/tests/test_cli.py @@ -0,0 +1,79 @@ +import datetime as dt + +from report_tool.cli import EXIT_BAD_INPUT, EXIT_NO_BOOKINGS, EXIT_OK, main + +NOW = dt.datetime(2026, 10, 31, 14, 2, 11) + +EXPECTED_REPORT = """\ +TRAIN BOOKINGS SUMMARY +Source: bookings.xlsx +Generated: 2026-10-31 14:02:11 +Rows read: 3 (2 valid, 1 skipped) + +WARNING: 1 row(s) were skipped and are not in these totals. See SKIPPED ROWS. + +OVERVIEW +Net revenue: $1,080.00 +Discounts given: $120.00 +Confirmed tickets: 1 +Average net ticket: $1,080.00 +Cancellations: 1 (50.0% of valid bookings) +Loyalty members: 1 +Non-loyalty members: 0 + +CONFIRMED TICKETS BY CLASS +First: 1 + +BOOKINGS BY ROUTE (busiest first) +Toronto-Montreal: 1 confirmed, 1 cancelled + +CONFIRMED BOOKINGS +1. TB-1 | Ann Lee | Toronto-Montreal | First | $1,080.00 | 2026-09-08 | Loyalty: Yes + +CANCELLED BOOKINGS +1. TB-2 | Bo Chan | 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): + path = 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", "$5O", "Confirmed", None, 0, "No"], + ] + ) + out = tmp_path / "out" + assert main([str(path), "--out", str(out)], now=NOW) == EXIT_OK + report = out / "booking_summary_20261031_140211.txt" + assert report.read_text(encoding="utf-8") == EXPECTED_REPORT + + +def test_bad_path_exits_with_error(tmp_path, caplog): + assert main([str(tmp_path / "missing.xlsx"), "--out", str(tmp_path)]) == EXIT_BAD_INPUT + assert "File not found" in caplog.text + + +def test_no_valid_rows(make_workbook, tmp_path): + path = make_workbook([["TB-1", "Ann", "A-B", "Economy", "TBD", "Confirmed", None, 0, "No"]]) + assert main([str(path), "--out", str(tmp_path / "out")]) == EXIT_NO_BOOKINGS + assert not (tmp_path / "out").exists() + + +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 diff --git a/tests/test_loader.py b/tests/test_loader.py new file mode 100644 index 0000000..ba79402 --- /dev/null +++ b/tests/test_loader.py @@ -0,0 +1,126 @@ +import datetime as dt +from decimal import Decimal + +import pytest + +from report_tool.loader import ( + WorkbookError, + load_bookings, + parse_discount, + parse_money, +) + + +def test_clean_rows_load(make_workbook): + path = make_workbook( + [ + [ + "TB-1", + "Ann Lee", + "Toronto-Ottawa", + "Economy", + 100, + "Confirmed ", + dt.datetime(2026, 9, 8), + 10, + "Yes", + ], + ["TB-2", "Bo Chan", "Toronto-Ottawa", "First", 200, "cancelled", "2026-09-09", 0, "no"], + ] + ) + result = load_bookings(path) + assert result.skipped == [] + first, second = result.bookings + assert first.status == "confirmed" + assert first.price == Decimal("100.00") + assert first.net_price == Decimal("90.00") + assert first.date == dt.date(2026, 9, 8) + assert first.loyalty is True + assert second.status == "cancelled" + assert second.date == dt.date(2026, 9, 9) + assert second.loyalty is False + + +def test_bad_rows_are_skipped_with_reasons_not_fatal(make_workbook): + path = make_workbook( + [ + ["TB-1", "Ann Lee", "A-B", "Economy", 100, "Confirmed", None, 0, "Yes"], + ["TB-2", "Bo Chan", "A-B", "Economy", 50, None, None, 0, "No"], + ["TB-3", "Cy Diaz", "A-B", "Economy", "TBD", "Confirmed", None, 0, "No"], + ["TB-4", "Di Eng", "A-B", "Economy", 50, "Pending", None, 0, "No"], + ["TB-5", "Ed Fox", "A-B", "Economy", 50, "Confirmed", None, 150, "No"], + ["TB-6", None, "A-B", "Economy", 50, "Confirmed", None, 0, "No"], + ] + ) + result = load_bookings(path) + assert [b.ticket_id for b in result.bookings] == ["TB-1"] + reasons = {s.ticket_id: (s.row, s.reason) for s in result.skipped} + assert reasons == { + "TB-2": (3, "Status is empty"), + "TB-3": (4, "Price is not a number"), + "TB-4": (5, "Unknown status"), + "TB-5": (6, "Discount is not a percentage from 0 to 100"), + "TB-6": (7, "PassengerName is empty"), + } + assert result.rows_read == 6 + + +def test_columns_are_matched_by_header_name_not_position(make_workbook): + header = ["Status", "Price", "Route", "Class", "Passenger Name", "Ticket ID"] + path = make_workbook([["Confirmed", 40, "A-B", "Economy", "Ann Lee", "TB-9"]], header=header) + (booking,) = load_bookings(path).bookings + assert booking.ticket_id == "TB-9" + assert booking.price == Decimal("40.00") + assert booking.discount_pct == 0 + assert booking.loyalty is None + + +def test_missing_required_column_is_a_clear_error(make_workbook): + path = make_workbook( + [["TB-1", "Ann", "A-B", "Economy", 10]], + header=["TicketID", "PassengerName", "Route", "Class", "Price"], + ) + with pytest.raises(WorkbookError, match="status"): + load_bookings(path) + + +def test_blank_rows_are_ignored(make_workbook): + path = make_workbook([[None] * 9, ["TB-1", "Ann", "A-B", "Economy", 10, "Confirmed", None, None, None]]) + result = load_bookings(path) + assert len(result.bookings) == 1 + assert result.skipped == [] + + +def test_empty_sheet_and_missing_file(make_workbook, tmp_path): + with pytest.raises(WorkbookError, match="empty"): + load_bookings(make_workbook([], header=None)) + with pytest.raises(WorkbookError, match="not found"): + load_bookings(tmp_path / "nope.xlsx") + + +def test_non_excel_file_is_a_clear_error(tmp_path): + path = tmp_path / "notes.xlsx" + path.write_text("not a workbook") + with pytest.raises(WorkbookError, match="Could not open"): + load_bookings(path) + + +@pytest.mark.parametrize( + ("value", "expected"), + [(12.5, "12.50"), ("12.50", "12.50"), ("$1,200", "1200.00"), (0, "0.00")], +) +def test_parse_money(value, expected): + assert parse_money(value) == Decimal(expected) + + +@pytest.mark.parametrize("value", ["TBD", "", None, -5, True, "nan"]) +def test_parse_money_rejects(value): + with pytest.raises(ValueError): + parse_money(value) + + +@pytest.mark.parametrize( + ("value", "expected"), [(None, "0"), ("", "0"), (15, "15"), ("15%", "15"), (100, "100")] +) +def test_parse_discount(value, expected): + assert parse_discount(value) == Decimal(expected) diff --git a/tests/test_summary.py b/tests/test_summary.py new file mode 100644 index 0000000..68c2741 --- /dev/null +++ b/tests/test_summary.py @@ -0,0 +1,60 @@ +import datetime as dt +from decimal import Decimal + +from report_tool.loader import Booking +from report_tool.summary import summarize + + +def booking(ticket, route, status, price="100", discount="0", loyalty=True, ticket_class="Economy"): + return Booking( + row=2, + ticket_id=ticket, + passenger="Test Person", + route=route, + ticket_class=ticket_class, + price=Decimal(price), + status=status, + date=dt.date(2026, 9, 8), + discount_pct=Decimal(discount), + loyalty=loyalty, + ) + + +def test_totals_use_exact_money(): + summary = summarize( + [ + booking("1", "A-B", "confirmed", price="0.10", discount="0"), + booking("2", "A-B", "confirmed", price="0.20", discount="0"), + booking("3", "A-B", "confirmed", price="33.33", discount="15"), + ] + ) + # 0.1 + 0.2 is 0.30000000000000004 with floats; Decimal keeps it exact. + assert summary.total_discount == Decimal("5.00") + assert summary.net_revenue == Decimal("28.63") + assert summary.average_net_ticket == Decimal("9.54") + + +def test_counts_routes_classes_and_loyalty(): + summary = summarize( + [ + booking("1", "A-B", "confirmed", ticket_class="First", loyalty=True), + booking("2", "A-B", "cancelled"), + booking("3", "C-D", "confirmed", loyalty=False), + booking("4", "C-D", "confirmed", loyalty=None), + booking("5", "C-D", "confirmed", loyalty=True), + ] + ) + assert summary.confirmed_tickets == 4 + assert summary.cancellations == 1 + assert summary.cancellation_rate == 0.2 + assert summary.by_class == {"First": 1, "Economy": 3} + assert (summary.loyalty_members, summary.non_loyalty_members, summary.loyalty_unknown) == (2, 1, 1) + assert [route for route, _ in summary.routes_by_volume()] == ["C-D", "A-B"] + assert summary.by_route["A-B"].cancelled == 1 + + +def test_empty_input(): + summary = summarize([]) + assert summary.valid_bookings == 0 + assert summary.cancellation_rate == 0.0 + assert summary.average_net_ticket == Decimal("0.00")