|
| 1 | +from django.core.exceptions import ValidationError |
| 2 | +from django.db import models |
| 3 | +from typing import List, Dict, Any |
| 4 | +from .models import Trip, TripStop |
| 5 | +from orders.models import Stop, Order |
| 6 | + |
| 7 | + |
| 8 | +class TripValidationError(ValidationError): |
| 9 | + """Custom validation error for trip-related violations""" |
| 10 | + pass |
| 11 | + |
| 12 | + |
| 13 | +def validate_trip_stops_completeness(trip: Trip) -> None: |
| 14 | + """ |
| 15 | + Validate that all orders in a trip have both pickup and delivery stops. |
| 16 | +
|
| 17 | + Args: |
| 18 | + trip: The Trip instance to validate |
| 19 | +
|
| 20 | + Raises: |
| 21 | + TripValidationError: If any order is missing its pickup or delivery stop |
| 22 | + """ |
| 23 | + incomplete_orders = get_incomplete_orders(trip) |
| 24 | + if incomplete_orders: |
| 25 | + order_numbers = [order.order_number for order in incomplete_orders] |
| 26 | + raise TripValidationError( |
| 27 | + f"Trip '{trip.name}' contains incomplete orders. " |
| 28 | + f"Orders {order_numbers} are missing either pickup or delivery stops. " |
| 29 | + f"All orders must have both pickup and delivery stops in the trip." |
| 30 | + ) |
| 31 | + |
| 32 | + |
| 33 | +def validate_new_trip_stop(trip: Trip, stop: Stop) -> None: |
| 34 | + """ |
| 35 | + Validate that adding a new stop to a trip maintains order completeness. |
| 36 | +
|
| 37 | + Args: |
| 38 | + trip: The Trip instance to add the stop to |
| 39 | + stop: The Stop instance to be added |
| 40 | +
|
| 41 | + Raises: |
| 42 | + TripValidationError: If adding this stop would violate the completeness rule |
| 43 | + """ |
| 44 | + if not stop.order: |
| 45 | + # Stops without orders are allowed (legacy or special stops) |
| 46 | + return |
| 47 | + |
| 48 | + order = stop.order |
| 49 | + trip_stops = trip.trip_stops.all() |
| 50 | + existing_stop_ids = set(ts.stop.id for ts in trip_stops) |
| 51 | + |
| 52 | + # Get the paired stop (pickup if this is delivery, delivery if this is pickup) |
| 53 | + paired_stop_type = 'pickup' if stop.stop_type == 'delivery' else 'delivery' |
| 54 | + paired_stop = order.stops.filter(stop_type=paired_stop_type).first() |
| 55 | + |
| 56 | + if not paired_stop: |
| 57 | + raise TripValidationError( |
| 58 | + f"Order {order.order_number} does not have a {paired_stop_type} stop. " |
| 59 | + f"Cannot add {stop.stop_type} stop without its pair." |
| 60 | + ) |
| 61 | + |
| 62 | + # If the paired stop is not in the trip, this would create an incomplete order |
| 63 | + if paired_stop.id not in existing_stop_ids: |
| 64 | + raise TripValidationError( |
| 65 | + f"Cannot add {stop.stop_type} stop for order {order.order_number} " |
| 66 | + f"without also including its {paired_stop_type} stop. " |
| 67 | + f"Trips must contain complete order journeys (both pickup and delivery)." |
| 68 | + ) |
| 69 | + |
| 70 | + |
| 71 | +def get_incomplete_orders(trip: Trip) -> List[Order]: |
| 72 | + """ |
| 73 | + Get a list of orders that have incomplete stop pairs in the trip. |
| 74 | +
|
| 75 | + Args: |
| 76 | + trip: The Trip instance to check |
| 77 | +
|
| 78 | + Returns: |
| 79 | + List of Order instances that are missing either pickup or delivery stops |
| 80 | + """ |
| 81 | + trip_stops = trip.trip_stops.select_related('stop', 'stop__order').all() |
| 82 | + orders_in_trip = {} |
| 83 | + |
| 84 | + # Group stops by order |
| 85 | + for trip_stop in trip_stops: |
| 86 | + if trip_stop.stop.order: |
| 87 | + order = trip_stop.stop.order |
| 88 | + if order.id not in orders_in_trip: |
| 89 | + orders_in_trip[order.id] = {'order': order, 'stops': []} |
| 90 | + orders_in_trip[order.id]['stops'].append(trip_stop.stop) |
| 91 | + |
| 92 | + incomplete_orders = [] |
| 93 | + for order_data in orders_in_trip.values(): |
| 94 | + order = order_data['order'] |
| 95 | + stops = order_data['stops'] |
| 96 | + stop_types = {stop.stop_type for stop in stops} |
| 97 | + |
| 98 | + # Check if both pickup and delivery are present |
| 99 | + if 'pickup' not in stop_types or 'delivery' not in stop_types: |
| 100 | + incomplete_orders.append(order) |
| 101 | + |
| 102 | + return incomplete_orders |
| 103 | + |
| 104 | + |
| 105 | +def ensure_order_pair_in_trip(trip: Trip, order: Order) -> Dict[str, Any]: |
| 106 | + """ |
| 107 | + Ensure both pickup and delivery stops for an order are in the trip. |
| 108 | +
|
| 109 | + Args: |
| 110 | + trip: The Trip instance |
| 111 | + order: The Order instance to ensure completeness for |
| 112 | +
|
| 113 | + Returns: |
| 114 | + Dict with 'pickup_stop' and 'delivery_stop' that should be in the trip |
| 115 | +
|
| 116 | + Raises: |
| 117 | + TripValidationError: If the order doesn't have both pickup and delivery stops |
| 118 | + """ |
| 119 | + pickup_stop = order.stops.filter(stop_type='pickup').first() |
| 120 | + delivery_stop = order.stops.filter(stop_type='delivery').first() |
| 121 | + |
| 122 | + if not pickup_stop: |
| 123 | + raise TripValidationError( |
| 124 | + f"Order {order.order_number} does not have a pickup stop." |
| 125 | + ) |
| 126 | + |
| 127 | + if not delivery_stop: |
| 128 | + raise TripValidationError( |
| 129 | + f"Order {order.order_number} does not have a delivery stop." |
| 130 | + ) |
| 131 | + |
| 132 | + return { |
| 133 | + 'pickup_stop': pickup_stop, |
| 134 | + 'delivery_stop': delivery_stop |
| 135 | + } |
| 136 | + |
| 137 | + |
| 138 | +def add_order_to_trip(trip: Trip, order: Order, pickup_time, delivery_time, notes: str = "") -> Dict[str, Any]: |
| 139 | + """ |
| 140 | + Add both pickup and delivery stops for an order to a trip atomically. |
| 141 | +
|
| 142 | + Args: |
| 143 | + trip: The Trip instance to add stops to |
| 144 | + order: The Order instance to add |
| 145 | + pickup_time: Time for pickup stop |
| 146 | + delivery_time: Time for delivery stop |
| 147 | + notes: Optional notes for both stops |
| 148 | +
|
| 149 | + Returns: |
| 150 | + Dict with 'pickup_trip_stop' and 'delivery_trip_stop' instances |
| 151 | +
|
| 152 | + Raises: |
| 153 | + TripValidationError: If the order doesn't have both pickup and delivery stops |
| 154 | + """ |
| 155 | + from django.db import transaction |
| 156 | + from .models import TripStop |
| 157 | + |
| 158 | + # Validate the order has both stops |
| 159 | + order_stops = ensure_order_pair_in_trip(trip, order) |
| 160 | + pickup_stop = order_stops['pickup_stop'] |
| 161 | + delivery_stop = order_stops['delivery_stop'] |
| 162 | + |
| 163 | + with transaction.atomic(): |
| 164 | + # Get the next available order numbers for the trip |
| 165 | + last_order = trip.trip_stops.aggregate( |
| 166 | + max_order=models.Max('order') |
| 167 | + )['max_order'] or 0 |
| 168 | + |
| 169 | + pickup_order = last_order + 1 |
| 170 | + delivery_order = last_order + 2 |
| 171 | + |
| 172 | + # Create both trip stops with validation disabled |
| 173 | + pickup_trip_stop = TripStop( |
| 174 | + trip=trip, |
| 175 | + stop=pickup_stop, |
| 176 | + order=pickup_order, |
| 177 | + planned_arrival_time=pickup_time, |
| 178 | + notes=notes or f'Pickup for {order.order_number}' |
| 179 | + ) |
| 180 | + pickup_trip_stop.save(skip_validation=True) |
| 181 | + |
| 182 | + delivery_trip_stop = TripStop( |
| 183 | + trip=trip, |
| 184 | + stop=delivery_stop, |
| 185 | + order=delivery_order, |
| 186 | + planned_arrival_time=delivery_time, |
| 187 | + notes=notes or f'Delivery for {order.order_number}' |
| 188 | + ) |
| 189 | + delivery_trip_stop.save(skip_validation=True) |
| 190 | + |
| 191 | + return { |
| 192 | + 'pickup_trip_stop': pickup_trip_stop, |
| 193 | + 'delivery_trip_stop': delivery_trip_stop |
| 194 | + } |
| 195 | + |
| 196 | + |
| 197 | +def get_orders_requiring_both_stops() -> List[Order]: |
| 198 | + """ |
| 199 | + Get all orders that have both pickup and delivery stops defined. |
| 200 | + This is useful for trip planning to ensure we only work with complete orders. |
| 201 | +
|
| 202 | + Returns: |
| 203 | + List of Order instances that have both pickup and delivery stops |
| 204 | + """ |
| 205 | + orders_with_both_stops = [] |
| 206 | + |
| 207 | + for order in Order.objects.prefetch_related('stops').all(): |
| 208 | + stops = order.stops.all() |
| 209 | + stop_types = {stop.stop_type for stop in stops} |
| 210 | + |
| 211 | + if 'pickup' in stop_types and 'delivery' in stop_types: |
| 212 | + orders_with_both_stops.append(order) |
| 213 | + |
| 214 | + return orders_with_both_stops |
0 commit comments