Skip to content

Ordering Meals

jsem-nerad edited this page Nov 12, 2025 · 4 revisions

Ordering Meals

This guide covers how to order and cancel meals using the strava-cz-python library.

Basic Ordering

Order Single Meal

strava.menu.fetch()

# Order meal with ID 3
strava.menu.order_meals(3)

Order Multiple Meals

# Order meals with IDs 3, 6, and 9
strava.menu.order_meals(3, 6, 9)

Basic Cancellation

Cancel Single Meal

# Cancel meal with ID 3
strava.menu.cancel_meals(3)

Cancel Multiple Meals

# Cancel meals with IDs 3, 6, and 9
strava.menu.cancel_meals(3, 6, 9)

How Ordering Works

The ordering process involves three steps:

  1. Mark meals for ordering - Calls pridejJidloS5 API endpoint for each meal
  2. Save the order - Calls saveOrders API endpoint to commit changes
  3. Refresh menu - Automatically fetches updated menu data

All these steps are handled automatically by order_meals() and cancel_meals().

Advanced Ordering Options

Continue on Error

By default, ordering stops at the first error. Use continue_on_error=True to attempt all meals:

try:
    strava.menu.order_meals(
        3, 6, 9,
        continue_on_error=True  # Try to order all, collect errors
    )
except StravaAPIError as e:
    print(f"Some meals failed: {e}")

Default behavior (continue_on_error=False):

  • Stops at first error
  • Rolls back all changes
  • Raises the exception

With continue_on_error=True:

  • Attempts all meals
  • Tracks which meals succeeded/failed
  • Raises exception with details of all failures after completion

Example: Resilient Ordering

from strava_cz import StravaAPIError

# Get unordered main dishes
meals = strava.menu.get_meals(
    meal_types=[MealType.MAIN],
    ordered=False
)

meal_ids = [m['id'] for m in meals[:5]]

try:
    strava.menu.order_meals(*meal_ids, continue_on_error=True)
    print(f"Successfully ordered meals")
except StravaAPIError as e:
    print(f"Some orders failed: {e}")
    # Menu is still updated with successful orders

Duplicate Detection

The Duplicate Problem

You can only order one meal per day. Attempting to order multiple meals from the same day will cause issues.

Automatic Detection

The library automatically detects duplicate days:

# Assume meal 3 and meal 6 are both from 2025-11-15
strava.menu.order_meals(3, 6)  # Default: warns and orders only meal 3
# Warning: Skipping meal 6 from 2025-11-15 because meal 3 from the same day is already being ordered

Strict Duplicates Mode

Use strict_duplicates=True to throw an error instead of warning:

from strava_cz import DuplicateMealError

try:
    strava.menu.order_meals(
        3, 6,  # Both from the same day
        strict_duplicates=True
    )
except DuplicateMealError as e:
    print(f"Error: {e}")
    # Error: Cannot order multiple meals from the same day (2025-11-15)

Example: Safe Ordering with Duplicate Handling

# Get one meal per day for next 5 days
days = strava.menu.get_days(
    meal_types=[MealType.MAIN],
    ordered=False
)[:5]

# Collect first meal from each day
meal_ids = [day['meals'][0]['id'] for day in days if day['meals']]

# Order safely - no duplicates possible
strava.menu.order_meals(*meal_ids)

Meal Type Restrictions

Only Main Dishes Can Be Ordered

Important: You cannot order or cancel soups!

from strava_cz import InvalidMealTypeError

# Get a soup ID
soups = strava.menu.get_meals(meal_types=[MealType.SOUP])
soup_id = soups[0]['id'] if soups else None

try:
    strava.menu.order_meals(soup_id)
except InvalidMealTypeError as e:
    print(e)
    # Cannot order or cancel Polévka meals. Only main dishes (MAIN) can be ordered or canceled.

Validation Before Ordering

from strava_cz import MealType

def safe_order(strava, meal_id):
    """Order a meal only if it's a main dish."""
    meal = strava.menu.get_by_id(meal_id)
    
    if not meal:
        print(f"Meal {meal_id} not found")
        return False
    
    if meal['type'] != MealType.MAIN:
        print(f"Cannot order {meal['type'].value}")
        return False
    
    if meal['ordered']:
        print(f"Meal already ordered")
        return False
    
    strava.menu.order_meals(meal_id)
    return True

Balance Checking

Automatic Balance Validation

The library checks your balance before ordering:

from strava_cz import InsufficientBalanceError

try:
    strava.menu.order_meals(3, 6, 9)  # Total cost exceeds balance
except InsufficientBalanceError as e:
    print(f"Not enough money: {e}")
    print(f"Current balance: {strava.user.balance} Kč")

Balance Tracking

Your balance is automatically updated after each operation:

print(f"Initial balance: {strava.user.balance} Kč")

strava.menu.order_meals(3)  # Costs 40 Kč

print(f"New balance: {strava.user.balance} Kč")  # Reduced by 40

strava.menu.cancel_meals(3)

print(f"Balance after cancel: {strava.user.balance} Kč")  # Restored

Check Balance Before Ordering

meals = strava.menu.get_meals(
    meal_types=[MealType.MAIN],
    ordered=False
)

# Calculate total cost
total_cost = sum(m['price'] for m in meals[:5])

if total_cost <= strava.user.balance:
    meal_ids = [m['id'] for m in meals[:5]]
    strava.menu.order_meals(*meal_ids)
else:
    print(f"Cannot afford: need {total_cost} Kč, have {strava.user.balance} Kč")

Error Recovery and Rollback

Automatic Rollback

When an error occurs (with continue_on_error=False), all changes are automatically rolled back:

strava.menu.fetch()

# Assume meal 3 can be ordered but meal 999 doesn't exist
try:
    strava.menu.order_meals(3, 999)
except StravaAPIError:
    # Meal 3 was NOT ordered - changes were rolled back
    pass

# Verify meal 3 is still not ordered
print(strava.menu.is_ordered(3))  # False

Manual Recovery

If you need to handle errors manually:

strava.menu.fetch()
initial_balance = strava.user.balance

try:
    strava.menu.order_meals(3, 6, 9, continue_on_error=False)
except StravaAPIError as e:
    print(f"Order failed: {e}")
    
    # Refresh to get current state
    strava.menu.fetch()
    
    # Check what succeeded
    for meal_id in [3, 6, 9]:
        if strava.menu.is_ordered(meal_id):
            print(f"Meal {meal_id} was ordered")

Verification

Automatic Verification

After ordering, the library automatically verifies that meals were ordered:

strava.menu.order_meals(3, 6)
# Internally:
# 1. Orders meals
# 2. Saves order
# 3. Refreshes menu
# 4. Verifies meals are ordered
# 5. Raises exception if verification fails

Manual Verification

strava.menu.order_meals(3, 6)

# Check individual meals
print(f"Meal 3 ordered: {strava.menu.is_ordered(3)}")
print(f"Meal 6 ordered: {strava.menu.is_ordered(6)}")

# Get all ordered meals
ordered = strava.menu.get_meals(ordered=True)
print(f"Total ordered: {len(ordered)} meals")

Cancellation Details

Cancel Works Like Order

Cancellation uses the same mechanisms as ordering:

# Cancel multiple meals with error handling
try:
    strava.menu.cancel_meals(
        3, 6, 9,
        continue_on_error=True
    )
except StravaAPIError as e:
    print(f"Some cancellations failed: {e}")

Cancel All Ordered Meals

# Get all ordered meal IDs
ordered = strava.menu.get_meals(ordered=True)
meal_ids = [m['id'] for m in ordered]

if meal_ids:
    strava.menu.cancel_meals(*meal_ids)
    print(f"Canceled {len(meal_ids)} meals")

Idempotent Cancellation

Canceling an already-canceled meal is safe:

strava.menu.cancel_meals(3)  # Cancels meal 3
strava.menu.cancel_meals(3)  # Does nothing, no error

Complex Examples

Example 1: Order Cheapest Meals for Next Week

from datetime import date, timedelta

# Get next 7 days
days = strava.menu.get_days(
    meal_types=[MealType.MAIN],
    ordered=False
)[:7]

# Find cheapest meal each day
meal_ids = []
for day in days:
    if day['meals']:
        cheapest = min(day['meals'], key=lambda m: m['price'])
        meal_ids.append(cheapest['id'])
        print(f"{day['date']}: {cheapest['name']} - {cheapest['price']} Kč")

# Check total cost
total = sum(m['price'] for day in days for m in day['meals'] 
            if m['id'] in meal_ids)

print(f"\nTotal cost: {total} Kč")
print(f"Your balance: {strava.user.balance} Kč")

if total <= strava.user.balance:
    strava.menu.order_meals(*meal_ids)
    print("All meals ordered!")
else:
    print("Insufficient balance")

Example 2: Bulk Order with Detailed Error Handling

from strava_cz import (
    InvalidMealTypeError,
    InsufficientBalanceError,
    DuplicateMealError,
    StravaAPIError
)

def bulk_order_with_retry(strava, meal_ids, max_retries=2):
    """Order meals with automatic retry on certain errors."""
    
    for attempt in range(max_retries):
        try:
            strava.menu.order_meals(
                *meal_ids,
                continue_on_error=True,
                strict_duplicates=False
            )
            print(f"Successfully ordered {len(meal_ids)} meals")
            return True
            
        except InvalidMealTypeError as e:
            print(f"Invalid meal type: {e}")
            # Remove soups and retry
            valid_ids = [
                mid for mid in meal_ids 
                if strava.menu.get_by_id(mid)['type'] == MealType.MAIN
            ]
            meal_ids = valid_ids
            
        except InsufficientBalanceError as e:
            print(f"Insufficient balance: {e}")
            return False
            
        except StravaAPIError as e:
            if attempt < max_retries - 1:
                print(f"Attempt {attempt + 1} failed, retrying...")
                strava.menu.fetch()  # Refresh and retry
            else:
                print(f"Failed after {max_retries} attempts: {e}")
                return False
    
    return False

# Usage
meal_ids = [3, 6, 9, 12, 15]
bulk_order_with_retry(strava, meal_ids)

Example 3: Replace Ordered Meals

def replace_order(strava, old_date, new_meal_id):
    """Cancel meal from a specific date and order a new one."""
    
    # Get meals from the date
    day = strava.menu.get_by_date(old_date)
    if not day:
        print(f"No menu for {old_date}")
        return False
    
    # Find ordered meal from that day
    ordered = [m for m in day['meals'] if m['ordered']]
    
    if not ordered:
        print(f"No ordered meals on {old_date}")
        return False
    
    old_meal_id = ordered[0]['id']
    
    # Cancel old and order new
    try:
        strava.menu.cancel_meals(old_meal_id)
        strava.menu.order_meals(new_meal_id)
        print(f"Replaced meal {old_meal_id} with {new_meal_id}")
        return True
    except StravaAPIError as e:
        print(f"Failed to replace: {e}")
        return False

# Usage
replace_order(strava, "2025-11-15", 7)

Best Practices

1. Always Validate Before Ordering

# ✅ Good
meals = strava.menu.get_meals(
    meal_types=[MealType.MAIN],
    order_types=[OrderType.NORMAL],
    ordered=False
)
meal_ids = [m['id'] for m in meals]
strava.menu.order_meals(*meal_ids)

# ❌ Bad - no validation
strava.menu.order_meals(1, 2, 3, 4, 5)

2. Handle Errors Appropriately

# ✅ Good
try:
    strava.menu.order_meals(3, 6, 9)
except InsufficientBalanceError:
    print("Not enough money - please add funds")
except InvalidMealTypeError:
    print("Cannot order this meal type")
except StravaAPIError as e:
    print(f"Order failed: {e}")

3. Use continue_on_error for Batch Operations

# ✅ Good for large batches
meal_ids = [m['id'] for m in strava.menu.get_meals()[:20]]
try:
    strava.menu.order_meals(*meal_ids, continue_on_error=True)
except StravaAPIError as e:
    print(f"Some orders failed: {e}")
    # Other orders still succeeded

Common Issues

Issue 1: "Cannot order soup"

Problem: Trying to order a meal with MealType.SOUP

Solution: Filter for main dishes only

meals = strava.menu.get_meals(meal_types=[MealType.MAIN])

Issue 2: "Duplicate meal from same day"

Problem: Multiple meals from same date in one order

Solution: Use one meal per day

days = strava.menu.get_days()
meal_ids = [day['meals'][0]['id'] for day in days]

Issue 3: Insufficient balance

Problem: Not enough money to order

Solution: Check balance first

if total_cost <= strava.user.balance:
    strava.menu.order_meals(*meal_ids)

Next Steps

Clone this wiki locally