﻿AI Hustle World coding test, 11 November 2026
Tollerwick Cycle Hire, its code and its email addresses are made up for this test.
Answers are copied as the tool gave them. Formatting marks are left as they came.
In most chats the prompt started with a short label line (for example 'Code review').
Tool: ChatGPT Plus ('High' setting)
======================================================================
PROMPT 1: Code review
Upload: booking.py

Prompt:
Review this code before it goes live. List every bug or security problem: the line number, what goes wrong, and the fix. Don't list style preferences.

Answer:
I reviewed `booking.py` against the Tollerwick Cycle Hire rules documented at the top of the file. The code compiles, but I found 12 bugs and security risks, including a SQL injection vulnerability, potential double bookings, incorrect pricing, and deposit refund errors.

## Code review findings

Not ready for production

| #  | Line(s) | Severity | Bug / What goes wrong                                                                                                                                                                                  | Required fix                                                                                                |
| -- | ------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------- |
| 1  | 24      | High     | Incorrect hire duration. `(end - start).days` excludes the end day. A 3–5 May booking is charged for 2 days instead of 3. This also affects discount eligibility.                                      | Return `(end - start).days + 1`.                                                                            |
| 2  | 29      | High     | Incorrect string comparison. `is not` checks object identity rather than value equality. A bike with status `"available"` may incorrectly be rejected.                                                 | Replace `is not` with `!=`.                                                                                 |
| 3  | 34      | Critical | Overlapping bookings allowed. The strict `<` and `>` comparisons treat dates as exclusive. Two customers could book the same bike on the same boundary day.                                            | Use `start <= b["end"] and end >= b["start"]`.                                                              |
| 4  | 27–36   | Medium   | Invalid date ranges accepted. `is_available()` does not reject an end date earlier than the start date. It may return `True` for an impossible booking.                                                | Validate `end >= start` before checking availability.                                                       |
| 5  | 43–46   | High     | Discounts incorrectly stack. A member hiring for 7+ days receives both 15% and 10% discounts, contrary to the terms.                                                                                   | Apply only the larger eligible discount using `max()`.                                                      |
| 6  | 50      | Medium   | Mutable default argument. The default `extras=[]` list is shared across calls. Helmets accumulate between unrelated bookings.                                                                          | Use `extras=None` and create a new list inside the function.                                                |
| 7  | 52–53   | Medium   | Duplicate helmets and unintended mutations. The function blindly appends `"helmet"` even if one is already present. It also changes the caller's original list, which remains attached to the booking. | Copy the extras list and add a helmet only when absent.                                                     |
| 8  | 59      | High     | Negative deposit refunds. A damage charge of £75 produces a refund of −£25, violating the minimum refund of £0.                                                                                        | Return `max(0, DEPOSIT - damage_charge)`.                                                                   |
| 9  | 57–59   | Medium   | Negative damage charges are accepted. A damage charge of −£10 produces a £60 refund, exceeding the original £50 deposit.                                                                               | Reject negative damage charges and cap refunds at the deposit amount.                                       |
| 10 | 62–71   | Critical | No booking conflict enforcement. `save_booking()` inserts records without checking availability or the bike's status. Even a prior availability check would be vulnerable to concurrent requests.      | Validate bike status and overlapping bookings inside a single atomic database transaction before insertion. |
| 11 | 62–69   | High     | Unvalidated booking data and price. The function accepts invalid date ranges and any supplied price, including zero or negative values. Callers could persist bookings that violate the pricing rules. | Validate dates and calculate the authoritative price server-side from verified booking details.             |
| 12 | 78      | Critical | SQL injection. Customer email is interpolated directly into SQL using an f-string. Malicious input can alter the query, potentially exposing customer records or bypassing the intended lookup.        | Use a parameterized query with `?` placeholders.                                                            |

## Critical fixes

### 1. SQL injection — line 78

Current vulnerable code:

```
cur.execute(f"SELECT id, name, email FROM customers WHERE email = '{email}'")
```

Corrected:

```
cur.execute(    "SELECT id, name, email FROM customers WHERE email = ?",    (email,))
```

### 2. Incorrect discount logic — lines 43–46

Corrected:

```
discount = max(    WEEKLY_DISCOUNT if days >= 7 else 0,    MEMBER_DISCOUNT if is_member else 0)price *= (1 - discount)
```

### 3. Shared mutable extras — lines 50–53

Corrected:

```
def add_extras(    booking: dict,    extras: list[str] | None = None) -> dict:    selected = list(extras) if extras is not None else []    if "helmet" not in selected:        selected.append("helmet")    booking["extras"] = selected    return booking
```

### 4. Deposit refund — lines 57–59

Corrected:

```
def deposit_refund(damage_charge: float) -> float:    if damage_charge < 0:        raise ValueError("Damage charge cannot be negative")    return max(0.0, DEPOSIT - damage_charge)
```

### 5. Double-booking protection — lines 62–71

Fixing the availability comparison alone is insufficient. Two concurrent requests could both see an available bike and then independently create bookings.

For SQLite, the booking operation should use `BEGIN IMMEDIATE`, validate the bike and overlapping date ranges within that transaction, and insert only if validation succeeds. Roll back on failure.

## Additional integration risk

The availability function expects booking dictionaries with `start` and `end` date objects (lines 34–35), but `save_booking()` stores `start_date` and `end_date` as ISO-formatted strings (line 69). If database rows are passed directly to `is_available()`, this may cause a `KeyError` or `TypeError`. The database-reading layer should normalize field names and convert strings back to dates.

## Release recommendation

| Priority              | Action                                                                                                                                                                            |
| --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| P0 — Block deployment | Fix SQL injection and enforce atomic booking availability checks.                                                                                                                 |
| P1 — Before launch    | Correct hire duration, overlap logic, discounts, refunds, and persisted price validation.                                                                                         |
| P2 — Before launch    | Fix mutable extras, duplicate helmets, and date validation.                                                                                                                       |
| QA                    | Test same-day hires, shared boundary dates, simultaneous bookings, 7-day discounts, member discounts, repeated extras calls, negative damage charges, and SQL injection attempts. |

Final verdict: Do not deploy this version. The most serious issue is not simply incorrect pricing; it is that the system can create conflicting bookings and exposes customer lookup to SQL injection. Both should be resolved before accepting live bookings.

======================================================================
PROMPT 2: Refactor
Upload: invoice.py (new chat)

Prompt:
Refactor this function so it's easier to read and maintain. Don't change what it does. Return the complete new invoice.py.

Answer:
Refactored `invoice.py` to make the calculation easier to read, maintain, and modify without changing the intended behavior.

Download the complete invoice.py

### Complete refactored code

from decimal import Decimal, ROUND_HALF_UP


TRADE_DISCOUNT = Decimal("0.2")
MEMBER_DISCOUNT = Decimal("0.1")
DELIVERY_FEE = Decimal("4.95")
FREE_DELIVERY_THRESHOLD = 40
VAT_RATE = Decimal("0.2")
PENNY = Decimal("0.01")


def invoice_total(lines, customer_type, voucher=None):
    """Calculate the net, VAT, and gross invoice amounts."""
    subtotal = 0

    for line in lines:
        if line["qty"] <= 0:
            continue

        line_total = Decimal(line["unit_price"]) * line["qty"]

        if customer_type == "trade":
            line_total -= line_total * TRADE_DISCOUNT
        elif customer_type == "member":
            line_total -= line_total * MEMBER_DISCOUNT

        subtotal += line_total

    # Delivery eligibility is based on the subtotal before vouchers.
    delivery = (
        DELIVERY_FEE
        if subtotal < FREE_DELIVERY_THRESHOLD
        else Decimal("0")
    )

    if voucher is not None:
        if voucher == "SPRING10":
            subtotal -= 10
            if subtotal < 0:
                subtotal = 0
        elif voucher == "FREEDEL":
            delivery = 0

    total = subtotal + delivery

    vat = (total * VAT_RATE).quantize(
        PENNY, rounding=ROUND_HALF_UP
    )
    net = Decimal(total).quantize(
        PENNY, rounding=ROUND_HALF_UP
    )

    return {"net": net, "vat": vat, "gross": net + vat}

### What improved

- Removed repetitive price calculations and unnecessary nesting.
- Replaced unclear variable names with descriptive ones.
- Extracted discount rates, VAT, and delivery values into named constants.
- Preserved voucher processing, delivery thresholds, and rounding order.
- Retained the original function signature and return structure.

Validation: All 3,000 comparison cases matched the original function, and the new file passed Python compilation.

======================================================================
PROMPT 3: Write tests
Upload: late_fee.py (new chat)

Prompt:
Write pytest tests for this function. Cover every rule in the docstring and the edge cases. Return one complete file, test_late_fee.py, that imports late_fee from late_fee.

Answer:
All 33 pytest tests passed.

Created the complete `test_late_fee.py` file, importing `late_fee` from `late_fee`.

The tests cover every documented rule and key edge cases: early and on-time returns, one-day grace, charges from day two, fee caps, zero and negative values, half-penny rounding, leap years, and year boundaries.

test_late_fee.py

33 passed

Download test_late_fee.py

Run it with:

pytest -v test_late_fee.py
```

----------------------------------------------------------------------
NOTE: ChatGPT gave this file as a download link. Its chat text said only: "All 33 pytest tests passed." The downloaded file follows.
----------------------------------------------------------------------
"""Tests for the late_fee function's documented billing rules."""

from datetime import date, timedelta
from decimal import Decimal

import pytest

from late_fee import late_fee


DUE = date(2026, 11, 8)
RATE = Decimal("2.50")
CAP = Decimal("20.00")


@pytest.mark.parametrize("days_relative_to_due", [-30, -1, 0, 1])
def test_no_fee_if_returned_on_time_early_or_one_day_late(days_relative_to_due):
    returned = DUE + timedelta(days=days_relative_to_due)

    assert late_fee(DUE, returned, RATE, CAP) == Decimal("0.00")


@pytest.mark.parametrize(
    ("days_late", "expected"),
    [
        (2, Decimal("5.00")),
        (3, Decimal("7.50")),
        (7, Decimal("17.50")),
    ],
)
def test_two_or_more_days_late_charges_every_day_including_grace_day(
    days_late, expected
):
    assert late_fee(DUE, DUE + timedelta(days=days_late), RATE, CAP) == expected


def test_fee_is_capped_when_unlimited_fee_would_exceed_cap():
    assert late_fee(DUE, DUE + timedelta(days=10), RATE, CAP) == CAP


def test_fee_can_equal_cap_exactly():
    assert late_fee(DUE, DUE + timedelta(days=8), RATE, CAP) == CAP


def test_cap_below_one_day_rate_still_applies_to_billable_returns():
    assert late_fee(DUE, DUE + timedelta(days=2), RATE, Decimal("1.25")) == Decimal(
        "1.25"
    )


def test_zero_cap_prevents_all_fees():
    assert late_fee(DUE, DUE + timedelta(days=100), RATE, Decimal("0.00")) == Decimal(
        "0.00"
    )


def test_zero_daily_rate_produces_no_fee():
    assert late_fee(DUE, DUE + timedelta(days=100), Decimal("0.00"), CAP) == Decimal(
        "0.00"
    )


@pytest.mark.parametrize(
    ("daily_rate", "cap"),
    [
        (Decimal("-0.01"), CAP),
        (RATE, Decimal("-0.01")),
        (Decimal("-1"), Decimal("-1")),
    ],
)
@pytest.mark.parametrize("days_relative_to_due", [-1, 0, 1, 2])
def test_negative_rate_or_cap_raises_even_when_return_would_be_free(
    daily_rate, cap, days_relative_to_due
):
    with pytest.raises(ValueError):
        late_fee(DUE, DUE + timedelta(days=days_relative_to_due), daily_rate, cap)


@pytest.mark.parametrize(
    ("daily_rate", "days_late", "expected"),
    [
        (Decimal("0.0025"), 2, Decimal("0.01")),  # £0.005: half-penny up
        (Decimal("0.005"), 3, Decimal("0.02")),  # £0.015: half-penny up
        (Decimal("0.007"), 2, Decimal("0.01")),  # £0.014: round down
        (Decimal("0.008"), 2, Decimal("0.02")),  # £0.016: round up
        (Decimal("1.234"), 2, Decimal("2.47")),  # £2.468: round up
    ],
)
def test_final_fee_uses_penny_precision_and_half_up_rounding(
    daily_rate, days_late, expected
):
    assert late_fee(DUE, DUE + timedelta(days=days_late), daily_rate, CAP) == expected


def test_capped_amount_is_rounded_to_nearest_penny():
    assert late_fee(DUE, DUE + timedelta(days=10), RATE, Decimal("3.456")) == Decimal(
        "3.46"
    )


@pytest.mark.parametrize(
    ("due", "returned", "expected"),
    [
        (date(2026, 12, 31), date(2027, 1, 2), Decimal("5.00")),
        (date(2024, 2, 28), date(2024, 3, 1), Decimal("5.00")),
        (date(2025, 2, 28), date(2025, 3, 1), Decimal("0.00")),
    ],
)
def test_days_late_are_calendar_days_across_years_and_leap_days(
    due, returned, expected
):
    assert late_fee(due, returned, RATE, CAP) == expected

======================================================================
PROMPT 4: Use our internal module
Upload: tollerwick_fleet.py (new chat)

Prompt:
This is our internal Python module, tollerwick_fleet.py. Write a script, service_check.py, that we'll run every morning. It should load the fleet from fleet.csv, find every bike that is due a service (800 km or more, or 90 days or more since its last service), ignoring retired bikes, move any due bike that is currently "available" to "workshop", save the fleet, and email the list of due bikes to the workshop. Use the module's functions wherever possible. Return the complete script.

Answer:
Created `service_check.py` using your internal `tollerwick_fleet.py` module. The script uses the module's service thresholds and fleet-management functions.

&#x20;Download service_check.py

### Complete script — service_check.py


"""Daily fleet service check. Run from the folder containing fleet.csv.

SMTP settings are supplied via environment variables:
    SMTP_HOST (required), SMTP_FROM (required), SMTP_PORT (default: 587),
    SMTP_USER and SMTP_PASSWORD (optional, but must be supplied together).

Port 465 uses implicit TLS; other ports use STARTTLS.
"""

from datetime import date
from email.message import EmailMessage
import os
from pathlib import Path
import smtplib

from tollerwick_fleet import (
    SERVICE_INTERVAL_DAYS,
    SERVICE_INTERVAL_KM,
    WORKSHOP_EMAIL,
    load_fleet,
    save_fleet,
    set_status,
)


FLEET_CSV = Path(__file__).resolve().parent / "fleet.csv"


def smtp_settings():
    """Validate mail configuration before making changes to the fleet."""
    host = os.environ.get("SMTP_HOST", "")
    sender = os.environ.get("SMTP_FROM", "")
    user = os.environ.get("SMTP_USER", "")
    password = os.environ.get("SMTP_PASSWORD", "")
    port = int(os.environ.get("SMTP_PORT", "587"))

    if not host or not sender:
        raise ValueError("Set SMTP_HOST and SMTP_FROM environment variables")
    if bool(user) != bool(password):
        raise ValueError("Set both SMTP_USER and SMTP_PASSWORD, or neither")

    return host, port, sender, user, password


def send_report(due_bikes, today, settings):
    host, port, sender, user, password = settings
    message = EmailMessage()
    message["From"] = sender
    message["To"] = WORKSHOP_EMAIL
    message["Subject"] = (
        f"Fleet service due: {len(due_bikes)} bike(s) — {today.isoformat()}"
    )

    if due_bikes:
        lines = [
            f"Bikes due for service on {today.isoformat()}:",
            "",
            "Bike ID | Type | Status | Kilometres since service | Days since service",
        ]
        for bike in due_bikes:
            days = (today - bike.last_service).days
            lines.append(
                f"{bike.bike_id} | {bike.bike_type} | {bike.status} | "
                f"{bike.km_since_service} km | {days} days"
            )
    else:
        lines = [
            f"No non-retired bikes are due for service on {today.isoformat()}."
        ]

    message.set_content("\n".join(lines))

    if port == 465:
        with smtplib.SMTP_SSL(host, port, timeout=30) as smtp:
            if user:
                smtp.login(user, password)
            smtp.send_message(message)
    else:
        with smtplib.SMTP(host, port, timeout=30) as smtp:
            smtp.starttls()
            if user:
                smtp.login(user, password)
            smtp.send_message(message)


def main():
    settings = smtp_settings()
    today = date.today()
    bikes = load_fleet(str(FLEET_CSV))
    due_bikes = []

    for bike in bikes:
        if bike.status == "retired":
            continue

        days_since_service = (today - bike.last_service).days

        if (
            bike.km_since_service >= SERVICE_INTERVAL_KM
            or days_since_service >= SERVICE_INTERVAL_DAYS
        ):
            if bike.status == "available":
                set_status(bike, "workshop")

            due_bikes.append(bike)

    save_fleet(str(FLEET_CSV), bikes)
    send_report(due_bikes, today, settings)

    print(
        f"Saved fleet and emailed {len(due_bikes)} "
        f"due bike(s) to {WORKSHOP_EMAIL}."
    )


if __name__ == "__main__":
    main()


### Verification

Syntax check and local smoke test passed.

The test covered both service thresholds, available-to-workshop transitions, hired bikes, retired bikes, and bikes not yet due.

To run: Place `service_check.py`, `tollerwick_fleet.py`, and `fleet.csv` in the same directory. Configure `SMTP_HOST`, `SMTP_FROM`, and any required SMTP credentials, then execute `python service_check.py`.

The script sends a daily report even when no bikes are due. It saves the fleet before sending the email, so an SMTP failure leaves the updated fleet file intact and raises an error. Schedule it through cron or Windows Task Scheduler for automatic morning execution.

