﻿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: Gemini free ('Auto')
======================================================================
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:
Here is the review of `booking.py`, detailing every bug and security problem found:

### 1. Line 20 (`hire_days`)

* **What goes wrong:** The calculation `(end - start).days` excludes the end day, resulting in a duration that is one day too short. According to the hire terms, a hire includes both the start and end days (e.g., 3 May to 5 May should be 3 days, but `5 - 3` evaluates to 2).
* **Fix:** Add `+1` to include both days:
```python
return (end - start).days + 1

```



### 2. Line 25 (`is_available`)

* **What goes wrong:** Uses `is not` to compare string literals (`bike["status"] is not "available"`). Identity operators (`is`/`is not`) test object memory address equality rather than value equality, which can lead to unpredictable bugs.
* **Fix:** Change `is not` to the inequality operator `!=`:
```python
if bike["status"] != "available":

```



### 3. Line 30 (`is_available`)

* **What goes wrong:** The date overlap condition (`start < b["end"] and end > b["start"]`) fails to catch conflicts where a new booking starts on the exact day an existing booking ends. Because hire dates are inclusive and bikes cannot be shared on the same day, this allows double-booking on boundary dates.
* **Fix:** Update the check to handle inclusive overlap boundaries:
```python
if start <= b["end"] and end >= b["start"]:

```



### 4. Lines 41–44 (`hire_price`)

* **What goes wrong:** If a customer qualifies for both a weekly discount (7+ days) and a member discount, both discounts are applied sequentially (compounding), violating the rule: *"Discounts don't stack: use the larger one."*
* **Fix:** Calculate which discount is larger and apply only that single discount:
```python
weekly_disc = WEEKLY_DISCOUNT if days >= 7 else 0.0
member_disc = MEMBER_DISCOUNT if is_member else 0.0
discount = max(weekly_disc, member_disc)
price = price * (1 - discount)

```



### 5. Line 47 (`add_extras`)

* **What goes wrong:** Uses a mutable default argument (`extras: list[str] = []`). In Python, default arguments are evaluated only once at definition time, causing the list object to be shared and accumulate items across multiple function calls if `extras` is omitted.
* **Fix:** Use `None` as the default and initialize a new list inside the function:
```python
def add_extras(booking: dict, extras: list[str] = None) -> dict:
    if extras is None:
        extras = []
    extras.append("helmet")
    booking["extras"] = extras
    return booking

```



### 6. Line 56 (`deposit_refund`)

* **What goes wrong:** If `damage_charge` is greater than `DEPOSIT` (GBP 50.00), the function returns a negative value (e.g., `-10.0`), violating the rule: *"...but never less than 0."*
* **Fix:** Clamp the return value using `max()`:
```python
return max(0.0, DEPOSIT - damage_charge)

```



### 7. Lines 78–79 (`find_customer`) — **Security Vulnerability**

* **What goes wrong:** **SQL Injection**. The `email` argument is directly interpolated into the SQL query using an f-string. An attacker can supply malicious input via the `email` parameter to manipulate the query structure and access or modify unauthorized data.
* **Fix:** Use a parameterized query with placeholders (`?`):
```python
cur.execute("SELECT id, name, email FROM customers WHERE email = ?", (email,))

```

======================================================================
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:
Here is the refactored and cleaned-up version of `invoice.py`.

Improvements made:

* **Constants & Lookups:** Replaced nested conditional blocks for customer discounts with a clean dictionary lookup (`DISCOUNTS`).


* **Readability:** Used descriptive variable names (`subtotal`, `delivery_fee`, `net_total`, `gross_total`) instead of single-letter variables (`t`, `d`, `p`).


* **Built-in Functions:** Used `max()` to handle the floor limit for the `SPRING10` voucher cleanly.


* **Preserved Logic:** Maintained the exact calculation order (such as checking delivery fees against the subtotal before vouchers are applied) and rounding behavior.



```python
from decimal import Decimal, ROUND_HALF_UP

# Define constants for discounts and delivery
DISCOUNTS = {
    "trade": Decimal("0.8"),
    "member": Decimal("0.9"),
}
STANDARD_DELIVERY = Decimal("4.95")
ZERO = Decimal("0")


def invoice_total(lines, customer_type, voucher=None):
    """Calculates the net total, VAT, and gross total for an invoice[cite: 1]."""
    subtotal = ZERO
    discount_multiplier = DISCOUNTS.get(customer_type, Decimal("1.0"))

    # Calculate subtotal based on line items and customer type discounts
    for line in lines:
        if line["qty"] > 0:
            item_total = Decimal(line["unit_price"]) * line["qty"]
            subtotal += item_total * discount_multiplier

    # Determine delivery fee based on subtotal before vouchers
    delivery_fee = STANDARD_DELIVERY if subtotal < 40 else ZERO

    # Apply applicable vouchers
    if voucher == "SPRING10":
        subtotal = max(subtotal - 10, ZERO)
    elif voucher == "FREEDEL":
        delivery_fee = ZERO

    # Combine subtotal and delivery for the net amount
    net_total = subtotal + delivery_fee

    # Calculate VAT and quantize monetary values
    vat = (net_total * Decimal("0.2")).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
    net_total = net_total.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
    gross_total = net_total + vat

    return {"net": net_total, "vat": vat, "gross": gross_total}

```

======================================================================
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:
```python
code = '''import pytest
from datetime import date
from decimal import Decimal
from late_fee import late_fee

def test_returned_on_due_date():
    assert late_fee(date(2023, 10, 1), date(2023, 10, 1), Decimal("2.50"), Decimal("10.00")) == Decimal("0.00")

def test_returned_before_due_date():
    assert late_fee(date(2023, 10, 5), date(2023, 10, 1), Decimal("2.50"), Decimal("10.00")) == Decimal("0.00")

def test_grace_period_one_day_late():
    assert late_fee(date(2023, 10, 1), date(2023, 10, 2), Decimal("2.50"), Decimal("10.00")) == Decimal("0.00")

def test_two_days_late():
    # 2 days late includes grace day -> 2 * 2.50 = 5.00
    assert late_fee(date(2023, 10, 1), date(2023, 10, 3), Decimal("2.50"), Decimal("10.00")) == Decimal("5.00")

def test_three_days_late():
    # 3 days late -> 3 * 2.50 = 7.50
    assert late_fee(date(2023, 10, 1), date(2023, 10, 4), Decimal("2.50"), Decimal("10.00")) == Decimal("7.50")

def test_fee_capped():
    # 5 days late * 2.50 = 12.50, but cap is 10.00
    assert late_fee(date(2023, 10, 1), date(2023, 10, 6), Decimal("2.50"), Decimal("10.00")) == Decimal("10.00")

def test_negative_daily_rate_raises_value_error():
    with pytest.raises(ValueError, match="daily_rate and cap must not be negative"):
        late_fee(date(2023, 10, 1), date(2023, 10, 3), Decimal("-1.00"), Decimal("10.00"))

def test_negative_cap_raises_value_error():
    with pytest.raises(ValueError, match="daily_rate and cap must not be negative"):
        late_fee(date(2023, 10, 1), date(2023, 10, 3), Decimal("2.50"), Decimal("-5.00"))

def test_both_negative_raises_value_error():
    with pytest.raises(ValueError, match="daily_rate and cap must not be negative"):
        late_fee(date(2023, 10, 1), date(2023, 10, 3), Decimal("-2.50"), Decimal("-10.00"))

def test_zero_rate_and_cap():
    assert late_fee(date(2023, 10, 1), date(2023, 10, 5), Decimal("0.00"), Decimal("0.00")) == Decimal("0.00")

def test_rounding_half_up():
    # 2 days late * 1.225 = 2.450 -> 2.45
    assert late_fee(date(2023, 10, 1), date(2023, 10, 3), Decimal("1.225"), Decimal("10.00")) == Decimal("2.45")
    # 2 days late * 1.2255 = 2.4510 -> 2.45
    # 2 days late * 1.227 = 2.454 -> 2.45
    # 2 days late * 1.2275 = 2.455 -> 2.46
    assert late_fee(date(2023, 10, 1), date(2023, 10, 3), Decimal("1.2275"), Decimal("10.00")) == Decimal("2.46")

def test_cap_rounding():
    # Cap with fraction needing rounding
    assert late_fee(date(2023, 10, 1), date(2023, 10, 10), Decimal("5.00"), Decimal("10.005")) == Decimal("10.01")
'''

with open("test_late_fee.py", "w") as f:
    f.write(code)

print("test_late_fee.py created successfully")


```

```text
test_late_fee.py created successfully


```

Your Python test file `test_late_fee.py` is ready:


```python
from datetime import date
from decimal import Decimal
import pytest
from late_fee import late_fee


def test_returned_on_due_date():
    """Returned on the due date produces zero fee."""
    assert late_fee(date(2026, 1, 1), date(2026, 1, 1), Decimal("2.50"), Decimal("10.00")) == Decimal("0.00")


def test_returned_before_due_date():
    """Returned prior to the due date produces zero fee."""
    assert late_fee(date(2026, 1, 5), date(2026, 1, 1), Decimal("2.50"), Decimal("10.00")) == Decimal("0.00")


def test_returned_one_day_late_grace_period():
    """1 day late falls within the grace period (0 fee)."""
    assert late_fee(date(2026, 1, 1), date(2026, 1, 2), Decimal("2.50"), Decimal("10.00")) == Decimal("0.00")


def test_returned_two_days_late():
    """2 days late charges daily_rate for both days (2 x rate)."""
    assert late_fee(date(2026, 1, 1), date(2026, 1, 3), Decimal("2.50"), Decimal("10.00")) == Decimal("5.00")


def test_returned_three_days_late():
    """3 days late charges daily_rate for all 3 days."""
    assert late_fee(date(2026, 1, 1), date(2026, 1, 4), Decimal("2.50"), Decimal("10.00")) == Decimal("7.50")


def test_fee_capped_at_maximum():
    """Fee calculation exceeding cap is capped at the maximum cap value."""
    # 5 days late * 2.50 = 12.50, capped at 10.00
    assert late_fee(date(2026, 1, 1), date(2026, 1, 6), Decimal("2.50"), Decimal("10.00")) == Decimal("10.00")


def test_negative_daily_rate_raises_value_error():
    """Negative daily_rate raises ValueError."""
    with pytest.raises(ValueError, match="daily_rate and cap must not be negative"):
        late_fee(date(2026, 1, 1), date(2026, 1, 3), Decimal("-1.00"), Decimal("10.00"))


def test_negative_cap_raises_value_error():
    """Negative cap raises ValueError."""
    with pytest.raises(ValueError, match="daily_rate and cap must not be negative"):
        late_fee(date(2026, 1, 1), date(2026, 1, 3), Decimal("2.50"), Decimal("-5.00"))


def test_both_negative_raises_value_error():
    """Negative daily_rate and cap raise ValueError."""
    with pytest.raises(ValueError, match="daily_rate and cap must not be negative"):
        late_fee(date(2026, 1, 1), date(2026, 1, 3), Decimal("-2.50"), Decimal("-10.00"))


def test_zero_daily_rate_and_cap():
    """Zero values for daily_rate and cap are valid and result in 0.00 fee."""
    assert late_fee(date(2026, 1, 1), date(2026, 1, 5), Decimal("0.00"), Decimal("0.00")) == Decimal("0.00")


def test_rounding_half_up():
    """Verify ROUND_HALF_UP rounding behavior to the nearest penny."""
    # 2 days late * 1.225 = 2.450 -> rounds to 2.45
    assert late_fee(date(2026, 1, 1), date(2026, 1, 3), Decimal("1.225"), Decimal("10.00")) == Decimal("2.45")
    # 2 days late * 1.2275 = 2.455 -> rounds up to 2.46
    assert late_fee(date(2026, 1, 1), date(2026, 1, 3), Decimal("1.2275"), Decimal("10.00")) == Decimal("2.46")


def test_cap_rounding():
    """Verify capping applies rounding correctly if cap has fractional pennies."""
    assert late_fee(date(2026, 1, 1), date(2026, 1, 10), Decimal("5.00"), Decimal("10.005")) == Decimal("10.01")

```

======================================================================
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:
```python
# Write the script code via Python interpreter to ensure syntax correctness if needed, or generate code directly.
script_content = '''from datetime import date
import smtplib
from email.message import EmailMessage
from tollerwick_fleet import (
    load_fleet,
    save_fleet,
    set_status,
    SERVICE_INTERVAL_KM,
    SERVICE_INTERVAL_DAYS,
    WORKSHOP_EMAIL,
)

FLEET_FILE = "fleet.csv"

def is_due_service(bike, today: date) -> bool:
    """Check if a non-retired bike is due for service."""
    if bike.status == "retired":
        return False
    days_since = (today - bike.last_service).days
    return (bike.km_since_service >= SERVICE_INTERVAL_KM) or (days_since >= SERVICE_INTERVAL_DAYS)

def send_workshop_email(due_bikes: list) -> None:
    """Send an email list of due bikes to the workshop."""
    msg = EmailMessage()
    msg["Subject"] = f"Daily Service Check - {date.today().isoformat()}"
    msg["From"] = "system@tollerwick.test"
    msg["To"] = WORKSHOP_EMAIL

    lines = ["The following bikes are due for service:\n"]
    for bike in due_bikes:
        lines.append(
            f"- Bike ID: {bike.bike_id} | Type: {bike.bike_type} | Status: {bike.status} | "
            f"KM since service: {bike.km_since_service} | Last service: {bike.last_service}"
        )
    msg.set_content("\n".join(lines))

    # Connect to local SMTP server to send email
    with smtplib.SMTP("localhost") as s:
        s.send_message(msg)

def main():
    today = date.today()
    fleet = load_fleet(FLEET_FILE)

    due_bikes = []
    for bike in fleet:
        if is_due_service(bike, today):
            due_bikes.append(bike)
            if bike.status == "available":
                set_status(bike, "workshop")

    if due_bikes:
        save_fleet(FLEET_FILE, fleet)
        send_workshop_email(due_bikes)
        print(f"Updated fleet and sent email for {len(due_bikes)} bikes due for service.")
    else:
        print("No bikes are currently due for service.")

if __name__ == "__main__":
    main()
'''
print("Valid standard python script structure created.")


```

```text
Valid standard python script structure created.


```

I will now generate the complete `service_check.py` script based on your specifications and internal `tollerwick_fleet.py` module.

### Key Features of `service_check.py`:

* **Module Integration:** Leverages `tollerwick_fleet` constants (`SERVICE_INTERVAL_KM`, `SERVICE_INTERVAL_DAYS`, `WORKSHOP_EMAIL`) and helper functions (`load_fleet`, `save_fleet`, `set_status`).
* **Service Logic:** Checks for bikes exceeding 800 km or 90 days since their last service, while explicitly skipping `retired` bikes.
* **Status Updates:** Safely transitions due bikes from `available` to `workshop` and updates `fleet.csv` accordingly.
* **Email Notification:** Uses Python standard library `smtplib` and `email.message.EmailMessage` to send a clean report to the workshop email address.

----------------------------------------------------------------------
NOTE: Gemini's final answer was a Canvas panel called "Daily Service Check Script". Its chat text held an earlier draft (shown first); the Canvas file, which was scored, follows.
----------------------------------------------------------------------
#!/usr/bin/env python3
"""service_check.py - Daily fleet check for Tollerwick Cycle Hire.

Identifies bikes due for service, updates available bikes to 'workshop' status,
saves the updated fleet file, and emails the daily service report to the workshop.
"""

from datetime import date
import smtplib
from email.message import EmailMessage

import tollerwick_fleet as fleet


def is_due_for_service(bike: fleet.Bike, today: date) -> bool:
    """Return True if the bike needs service and is not retired."""
    if bike.status == "retired":
        return False
    
    days_since_service = (today - bike.last_service).days
    return (
        bike.km_since_service >= fleet.SERVICE_INTERVAL_KM
        or days_since_service >= fleet.SERVICE_INTERVAL_DAYS
    )


def build_email_body(due_bikes: list[fleet.Bike], today: date) -> str:
    """Format the text body of the workshop email report."""
    lines = [f"Daily Service Check Report - {today.isoformat()}", "=" * 40, ""]
    
    for bike in due_bikes:
        days = (today - bike.last_service).days
        lines.append(
            f"• Bike ID: {bike.bike_id} ({bike.bike_type})"
            f"\n  Status: {bike.status}"
            f"\n  Km since service: {bike.km_since_service} km (Limit: {fleet.SERVICE_INTERVAL_KM} km)"
            f"\n  Days since service: {days} days (Limit: {fleet.SERVICE_INTERVAL_DAYS} days)\n"
        )
    
    return "\n".join(lines)


def send_workshop_email(due_bikes: list[fleet.Bike], today: date) -> None:
    """Send an email notification with the list of due bikes."""
    msg = EmailMessage()
    msg["Subject"] = f"Daily Workshop Service List - {today.isoformat()}"
    msg["From"] = "no-reply@tollerwick.test"
    msg["To"] = fleet.WORKSHOP_EMAIL
    msg.set_content(build_email_body(due_bikes, today))

    # Send via local SMTP server (adjust host/port as needed for your environment)
    with smtplib.SMTP("localhost") as server:
        server.send_message(msg)


def main() -> None:
    fleet_filepath = "fleet.csv"
    today = date.today()

    # 1. Load the fleet
    bikes = fleet.load_fleet(fleet_filepath)

    # 2. Find bikes due for service & update status if available
    due_bikes: list[fleet.Bike] = []
    updated = False

    for bike in bikes:
        if is_due_for_service(bike, today):
            due_bikes.append(bike)
            if bike.status == "available":
                fleet.set_status(bike, "workshop")
                updated = True

    # 3. Save the fleet if any statuses changed
    if updated:
        fleet.save_fleet(fleet_filepath, bikes)

    # 4. Email the report if there are bikes due for service
    if due_bikes:
        send_workshop_email(due_bikes, today)
        print(f"Service check completed: {len(due_bikes)} bike(s) due for service. Report emailed.")
    else:
        print("Service check completed: No bikes due for service today.")


if __name__ == "__main__":
    main()

