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
22 changes: 22 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -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
10 changes: 10 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
__pycache__/
*.py[cod]
*.egg-info/
.venv/
.pytest_cache/
.ruff_cache/
build/
dist/
reports/
.ipynb_checkpoints/
63 changes: 32 additions & 31 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,48 +1,49 @@
# 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.

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/`.
31 changes: 31 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -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"]
3 changes: 3 additions & 0 deletions report_tool/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
"""Turn a train bookings Excel workbook into a summary report."""

__version__ = "1.0.0"
5 changes: 5 additions & 0 deletions report_tool/__main__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import sys

from report_tool.cli import main

sys.exit(main())
82 changes: 82 additions & 0 deletions report_tool/cli.py
Original file line number Diff line number Diff line change
@@ -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
Loading
Loading