diff --git a/orders/views.py b/orders/views.py index 07411a4..3f3ccf0 100644 --- a/orders/views.py +++ b/orders/views.py @@ -687,9 +687,12 @@ class OrderCancelView(APIView): if not order: return Response({'error': f'Order {raw_order_id} not found'}, status=status.HTTP_404_NOT_FOUND) - if order.status.lower() in ['shipped', 'delivered']: + st_low = str(order.status or '').lower() + ship_st_low = str(getattr(order, 'shipping_status', '') or '').lower() + in_transit_states = ['shipped', 'delivered', 'in transit', 'in_transit', 'out for delivery'] + if st_low in in_transit_states or ship_st_low in in_transit_states: return Response({ - 'error': 'Order has already been shipped and cannot be cancelled directly. Please initiate a return request instead.' + 'error': 'Order has already been scanned and is in transit with courier. Cancellation is not permitted.' }, status=status.HTTP_400_BAD_REQUEST) if order.status.lower() == 'cancelled': @@ -707,7 +710,7 @@ class OrderCancelView(APIView): Q(order_id=str(raw_order_id)) )) - # 2. Cancel pickups with Shadowfax production API for each registered seller order / AWB + # 2. Cancel pickups with courier API for each registered seller order / AWB cancel_awbs = set() if order.awb_number: cancel_awbs.add((f"{order.id}", order.awb_number)) @@ -727,6 +730,14 @@ class OrderCancelView(APIView): for c_id, awb_val in cancel_awbs: try: + # Delhivery cancellation if numerical / Delhivery format + if awb_val and (str(awb_val).isdigit() or str(awb_val).startswith(('698', 'DELHI', '14', '12'))): + try: + dlh_token = "e70dfd63665335ee6e0a1094f6d34e17a126f5a6" + dlh_url = "https://track.delhivery.com/api/p/edit" + requests.post(dlh_url, json={"waybill": str(awb_val), "cancellation": "true"}, headers={'Authorization': f'Token {dlh_token}', 'Content-Type': 'application/json'}, timeout=6) + except Exception as dlh_err: + audit_logger.warning(f"Delhivery cancel API warning for order {c_id}: {dlh_err}") # Also try microservice endpoint first try: url = f"{SHIPPING_SERVICE_URL.rstrip('/')}/api/v1/forward/cancel/"