Skip to content
Closed
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
25 changes: 13 additions & 12 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -1,12 +1,3 @@
# DEMO TODO (Module 3 - DevOps): this CI workflow is intentionally incomplete.
# Use Copilot to finish the steps so the pipeline installs dependencies and runs pytest.
#
# Suggested goals for the live demo:
# - check out the repository
# - set up Python 3.13
# - install dependencies from requirements-test.txt
# - run pytest with coverage

name: CI

on:
Expand All @@ -15,15 +6,25 @@ on:
pull_request:
branches: [ main ]

permissions:
contents: read

jobs:
test:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4

# TODO: set up Python 3.13 with actions/setup-python
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.13'
cache: pip
cache-dependency-path: requirements-test.txt

# TODO: install dependencies from requirements-test.txt
- name: Install dependencies
run: python -m pip install -r requirements-test.txt

# TODO: run pytest
- name: Run tests
run: python -m pytest
28 changes: 26 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,15 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [Unreleased]

### Added
- Added a top-five merchants-by-spend section to the monthly report, excluding
income and sorting ties deterministically by merchant name.
- Added table workflow and application report/entry-point tests, bringing the
configured total coverage above 90% without changing application behavior.
- Implemented expense forecasting, over-budget checks, transaction sorting,
normalized category spending alerts, and expense totals by merchant.
- Added validated, path-confined atomic CSV export and clear CSV row errors.
- Added regression tests for feature boundaries, CSV validation, and export safety.
- Added security regression tests for path containment and atomic report writes.
- Revamped the repository into **Budget Buddy**, a working Personal Budget & Expense Tracker demo app for GH-300 delivery.
- Added sample transaction data in [data/sample_transactions.csv](data/sample_transactions.csv).
- Added a sparse starter pytest suite designed to begin around 30% coverage.
Expand All @@ -15,6 +24,19 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
- Added reusable Copilot Skills under [.github/skills](.github/skills).

### Changed
- Documented calculator public methods, including existing zero-division behavior;
retained their existing parameter and return type hints without behavior changes.
- Refactored category grouping into a single-pass aggregation with one category
normalization per expense, preserving input data and expense-only totals.
- Completed Docker and GitHub Actions setup, including dependency installation
and the existing pytest coverage gate. CI uses pip caching and read-only
repository permissions; the image copies app/data without local environments
or Git metadata. Updated demo completion notes.
- Confined CSV/JSON reads and report writes to `base_path`, rejecting absolute,
drive-qualified, and escaping paths, including existing symlink/junction targets.
- Write JSON reports through same-directory temporary files with atomic
replacement and cleanup, preserving existing reports when writes fail.
- Updated security demo documentation; unrelated intentional issues remain.
- Simplified console logging to show report messages without timestamp, logger name, or level prefixes.
- Replaced arithmetic-only calculator examples with budget calculation helpers.
- Replaced generic data processing examples with transaction processing helpers.
Expand All @@ -24,6 +46,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).

### Intentional Demo Gaps
- Coverage is intentionally low at the start of the demo.
- Several TODOs and bugs are intentionally present for Copilot-assisted implementation.
- File handling intentionally includes a path traversal risk for security review demos.
- Original code TODOs are complete; unrelated calculator bugs and permissive
transaction-processor validation remain for Copilot-assisted exercises.
- CSV handling and path traversal are now fixed
subject to a trusted filesystem (concurrent link replacement remains a risk).
- Transaction processing intentionally includes O(n^2) logic for refactoring demos.
23 changes: 12 additions & 11 deletions DEMO_SCRIPT.md
Original file line number Diff line number Diff line change
Expand Up @@ -363,7 +363,8 @@ Add concise docstrings and type hints to the public methods in calculator.py.

### 3e. DevOps snippets

The repo ships a `Dockerfile` and a CI workflow with intentional TODOs. Ask:
The Dockerfile and CI workflow are now complete. Review their implementations
using the original exercise prompt:

```text
Complete the Dockerfile to run Budget Buddy, then finish the GitHub Actions workflow to install deps and run pytest.
Expand Down Expand Up @@ -626,21 +627,20 @@ If live generation runs long, implement one narrow slice end to end:

## Annex A — DevOps files (`Dockerfile` and CI workflow)

Module 3e references these two files, but they ship **intentionally incomplete**
so you can complete them live with Copilot. This annex is a self-contained,
Module 3e references these two files, which are now complete. The original
generation prompts below can be used to review the result. This annex is a self-contained,
optional deep-dive you can run any time you want a DevOps beat. Neither file is
exercised by `pytest`, so finishing them won't affect the coverage journey.

### Starting state
### Completed state

| File | What's missing |
| File | What's implemented |
| --- | --- |
| [Dockerfile](Dockerfile) | `WORKDIR`, dependency install, app copy, and the run command are TODO stubs. |
| [.github/workflows/ci.yml](.github/workflows/ci.yml) | Python setup, dependency install, and the pytest step are TODO stubs. |
| [Dockerfile](Dockerfile) | Python 3.13 slim, `WORKDIR`, dependencies, explicit app/data copy, and `python main.py`. |
| [.github/workflows/ci.yml](.github/workflows/ci.yml) | Python 3.13 setup, pip caching, dependency install, and pytest. |

> Talking point: both files carry guiding TODO comments. This mirrors a real
> onboarding task — "finish the pipeline" — and shows Copilot turning intent in
> comments into working DevOps config.
> Talking point: review the completed configuration, manifest-before-source
> Docker layer caching, and the shared local/CI coverage gate in `pytest.ini`.

### A1. Complete the Dockerfile

Expand All @@ -661,7 +661,8 @@ docker build -t budget-buddy .
docker run --rm budget-buddy
```

> Presenter note: if Docker isn't installed, just review the generated file and
> Presenter note: Docker Desktop's Linux engine must be running. If Docker is
> unavailable, just review the generated file and
> explain the layer-caching order (manifest before source). No build required to
> make the teaching point.

Expand Down
19 changes: 6 additions & 13 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,20 +1,13 @@
# Budget Buddy container image
# DEMO TODO (Module 3 - DevOps): this Dockerfile is intentionally incomplete.
# Use Copilot to finish it so the app runs in a container.
#
# Suggested goals for the live demo:
# - choose a slim Python base image
# - set a working directory
# - install dependencies from requirements-test.txt (or a runtime requirements file)
# - copy the application code
# - set the default command to run the app

FROM python:3.13-slim

# TODO: set WORKDIR
WORKDIR /app

# TODO: copy dependency manifests and install them
COPY requirements-test.txt ./
RUN python -m pip install --no-cache-dir -r requirements-test.txt

# TODO: copy the rest of the application
COPY *.py ./
COPY data/ ./data/

# TODO: define the container entrypoint/command, e.g. python main.py
CMD ["python", "main.py"]
8 changes: 4 additions & 4 deletions INTENTIONAL_ISSUES.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,12 @@ Budget Buddy starts from a realistic but incomplete codebase. These issues are d
| 3 | [data_processor.py](data_processor.py) | Category grouping mutates a list while using nested loops | Replace with one-pass aggregation |
| 3 | [data_processor.py](data_processor.py) | Duplicate detection is O(n^2) | Use a tuple key and dictionary/set |

## DevOps TODOs (Module 3)
## Completed DevOps Work (Module 3)

| File | Issue | Suggested Improvement |
| File | Completed behavior | Verification |
| --- | --- | --- |
| [Dockerfile](Dockerfile) | Image build steps are stubbed with TODOs | Complete so `python main.py` runs in a container |
| [.github/workflows/ci.yml](.github/workflows/ci.yml) | CI steps are stubbed with TODOs | Install deps and run pytest on push/PR |
| [Dockerfile](Dockerfile) | Python 3.13 slim image, dependencies, app/data copy, and `python main.py` | Build and run with Docker Desktop's Linux engine running |
| [.github/workflows/ci.yml](.github/workflows/ci.yml) | Python 3.13 setup, dependency install, and pytest with the existing coverage gate | Push or open a PR targeting main |

## TODOs For Feature Generation

Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ Budget Buddy reads sample transactions from [data/sample_transactions.csv](data/
- savings rate
- largest expense
- spending by category
- top five merchants by expense total
- a paginated transaction table

## Main Files
Expand Down
31 changes: 25 additions & 6 deletions calculator.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
Financial calculation helpers for the Budget Buddy demo app.

This module is intentionally starter-quality for GitHub Copilot demos. Some
methods work on the happy path, while selected edge cases and TODOs are left for
methods work on the happy path, while selected edge cases are left for
learners to fix with Copilot.
"""

Expand All @@ -15,51 +15,70 @@
class BudgetCalculator:

def __init__(self) -> None:
"""Initialize an empty calculation history."""
self.history: List[str] = []

def total_income(self, transactions: List[Transaction]) -> float:
"""Return the sum of income transaction amounts."""
total = sum(float(item["amount"]) for item in transactions if item.get("type") == "income")
self.history.append(f"total_income = {total}")
return total

def total_expenses(self, transactions: List[Transaction]) -> float:
"""Return the sum of expense transaction amounts."""
total = sum(float(item["amount"]) for item in transactions if item.get("type") == "expense")
self.history.append(f"total_expenses = {total}")
return total

def net_cash_flow(self, transactions: List[Transaction]) -> float:
"""Return total income minus total expenses."""
result = self.total_income(transactions) - self.total_expenses(transactions)
self.history.append(f"net_cash_flow = {result}")
return result

def remaining_budget(self, monthly_budget: float, transactions: List[Transaction]) -> float:
"""Return the monthly budget minus total expenses."""
result = monthly_budget - self.total_expenses(transactions)
self.history.append(f"remaining_budget({monthly_budget}) = {result}")
return result

def average_expense(self, transactions: List[Transaction]) -> float:
"""Return mean expense amount; raise ZeroDivisionError if no expenses exist."""
expenses = [float(item["amount"]) for item in transactions if item.get("type") == "expense"]
result = sum(expenses) / len(expenses)
self.history.append(f"average_expense = {result}")
return result

def category_percentage(self, category_total: float, total_expenses: float) -> float:
"""Return category share as a percentage; raise ZeroDivisionError for a zero total."""
result = (category_total / total_expenses) * 100
self.history.append(f"category_percentage = {result}")
return result

def savings_rate(self, income: float, expenses: float) -> float:
result = ((income - expenses) / income) * 100
"""Return savings as a percentage of income, or 0.0 for zero income."""
result = 0.0 if income == 0 else ((income - expenses) / income) * 100
self.history.append(f"savings_rate = {result}")
return result

# TODO: Implement forecast_month_end_spend(transactions, days_elapsed, days_in_month)
# It should estimate month-end spending from current month-to-date expenses.
def forecast_month_end_spend(
self, transactions: List[Transaction], days_elapsed: int, days_in_month: int
) -> float:
"""Project month-to-date expenses over a valid elapsed day range."""
if days_in_month <= 0 or not 1 <= days_elapsed <= days_in_month:
raise ValueError("Days must satisfy 1 <= days_elapsed <= days_in_month")
result = self.total_expenses(transactions) / days_elapsed * days_in_month
self.history.append(f"forecast_month_end_spend = {result}")
return result

# TODO: Implement is_over_budget(monthly_budget, transactions)
# It should return True when expenses exceed the monthly budget.
def is_over_budget(self, monthly_budget: float, transactions: List[Transaction]) -> bool:
"""Return whether expenses strictly exceed the monthly budget."""
result = self.total_expenses(transactions) > monthly_budget
self.history.append(f"is_over_budget({monthly_budget}) = {result}")
return result

def get_history(self) -> List[str]:
"""Return a copy of the recorded calculation history."""
return self.history.copy()


Expand Down
76 changes: 54 additions & 22 deletions data_processor.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
"""
Transaction processing helpers for the Budget Buddy demo app.

This starter module intentionally includes inefficient logic, permissive
validation, and TODOs so GitHub Copilot can improve it during the workshop.
This module intentionally retains inefficient logic and permissive validation
so GitHub Copilot can improve it during the workshop.
"""

from collections import defaultdict
Expand Down Expand Up @@ -35,22 +35,14 @@ def expenses_only(self, transactions: List[Transaction]) -> List[Transaction]:
return [item for item in transactions if item.get("type") == "expense"]

def group_expenses_by_category(self, transactions: List[Transaction]) -> Dict[str, float]:
"""Return expense totals grouped by category."""
"""Return normalized expense totals with a single pass over transactions."""
self.processed_count += 1
totals: Dict[str, float] = defaultdict(float)
expenses = self.expenses_only(transactions)

# PERFORMANCE ISSUE: This nested loop is easy to refactor with one pass.
for expense in expenses:
for expense in transactions:
if expense.get("type") != "expense":
continue
category = self.normalize_category(str(expense.get("category", "")))
for candidate in expenses:
candidate_category = self.normalize_category(str(candidate.get("category", "")))
if candidate_category == category:
totals[category] += float(candidate.get("amount", 0))
expenses = [
item for item in expenses
if self.normalize_category(str(item.get("category", ""))) != category
]
totals[category] += float(expense.get("amount", 0))

return dict(totals)

Expand Down Expand Up @@ -86,14 +78,54 @@ def validate_transaction(self, transaction: Transaction) -> bool:

return True

# TODO: Create sort_transactions(transactions, field, descending=False)
# It should sort by date, merchant, category, or amount and reject unknown fields.

# TODO: Create spending_alerts(transactions, category_limits)
# It should return categories where spending is above the configured limit.
def sort_transactions(
self, transactions: List[Transaction], field: str, descending: bool = False
) -> List[Transaction]:
"""Return a sorted copy, using numeric comparison for amounts."""
if field not in ("date", "merchant", "category", "amount"):
raise ValueError(f"Unsupported sort field: {field}")
self.processed_count += 1
if field == "amount":
return sorted(transactions, key=lambda item: float(item[field]), reverse=descending)
return sorted(transactions, key=lambda item: str(item[field]), reverse=descending)

def spending_alerts(
self, transactions: List[Transaction], category_limits: Dict[str, float]
) -> Dict[str, float]:
"""Return normalized categories and spending totals above their limits."""
self.processed_count += 1
totals: Dict[str, float] = defaultdict(float)
for item in self.expenses_only(transactions):
category = self.normalize_category(str(item.get("category", "")))
totals[category] += float(item["amount"])
limits = {self.normalize_category(category): limit
for category, limit in category_limits.items()}
return {category: total for category, total in totals.items()
if category in limits and total > limits[category]}

def summarize_by_merchant(self, transactions: List[Transaction]) -> Dict[str, float]:
"""Return expense totals by merchant, excluding income."""
self.processed_count += 1
totals: Dict[str, float] = defaultdict(float)
for item in self.expenses_only(transactions):
totals[str(item["merchant"])] += float(item["amount"])
return dict(totals)

# TODO: Create summarize_by_merchant(transactions)
# It should return total spending by merchant.
def top_merchants(
self, transactions: List[Transaction], limit: int = 5
) -> List[Transaction]:
"""Return the highest-spend merchants, ordered by spend then name."""
if limit < 0:
raise ValueError("limit must be nonnegative")
merchant_totals = self.summarize_by_merchant(transactions)
ranked = sorted(
merchant_totals.items(),
key=lambda item: (-item[1], item[0].casefold(), item[0]),
)
return [
{"merchant": merchant, "amount": amount}
for merchant, amount in ranked[:limit]
]

def get_processed_count(self) -> int:
"""Return the number of processing operations performed."""
Expand Down
Loading
Loading