ifixkart-backend/app/services/ShiprocketService.py

261 lines
11 KiB
Python

"""
@service ShiprocketService (Backend/app/services/ShiprocketService.py)
@purpose Automated 5-step Shiprocket fulfillment engine: order creation, courier auto-selection, AWB generation, printable label/slip retrieval, and pickup scheduling.
"""
import logging
import json
import httpx
from datetime import datetime, timezone, timedelta
from typing import Dict, Any, Optional, List
from app.core.config.Config import settings
logger = logging.getLogger("shiprocket")
class ShiprocketService:
def __init__(self):
self.email = settings.SHIPROCKET_EMAIL
self.password = settings.SHIPROCKET_PASSWORD
self.api_url = settings.SHIPROCKET_API_URL or "https://apiv2.shiprocket.in/v1/external"
self.enabled = settings.SHIPROCKET_ENABLED
self.mode = settings.SHIPROCKET_MODE or "test_label_only"
self.pickup_location = settings.SHIPROCKET_PICKUP_LOCATION or "Primary"
self.pickup_pin = settings.SHIPROCKET_PICKUP_PIN or "110001"
self.token: Optional[str] = None
self.token_expiry: Optional[datetime] = None
def can_call_live_api(self) -> bool:
return bool(self.enabled and self.email and self.password and self.mode != "test_label_only")
async def _authenticate(self) -> str:
"""Authenticate with Shiprocket API and cache the JWT token."""
now = datetime.now(timezone.utc)
if self.token and self.token_expiry and now < self.token_expiry:
return self.token
if not self.email or not self.password:
raise ValueError("Shiprocket email or password not configured")
async with httpx.AsyncClient(timeout=15.0) as client:
resp = await client.post(
f"{self.api_url}/auth/login",
json={"email": self.email, "password": self.password}
)
if resp.status_code != 200:
raise RuntimeError(f"Shiprocket auth failed ({resp.status_code}): {resp.text}")
data = resp.json()
token = data.get("token")
if not token:
raise RuntimeError("Shiprocket auth response missing token")
self.token = token
# Shiprocket token is valid for 10 days, cache for 9 days
self.token_expiry = now + timedelta(days=9)
return self.token
async def book_and_schedule_pickup(
self,
order: Any,
weight_kg: float,
courier_preference: Optional[str] = None,
length_cm: float = 10.0,
breadth_cm: float = 15.0,
height_cm: float = 5.0
) -> Dict[str, Any]:
"""
Executes the automated 5-step fulfillment pipeline:
1. Order Creation
2. Courier Serviceability & Auto Selection
3. AWB Assignment
4. Printable Label Generation
5. Pickup Scheduling
"""
# Parse shipping address
addr = {}
if getattr(order, 'shipping_address_json', None):
try:
addr = json.loads(order.shipping_address_json)
except Exception:
pass
delivery_pin = str(addr.get("pincode") or addr.get("postal_code") or addr.get("pin") or "110001")
customer_name = addr.get("name") or addr.get("full_name") or "Customer"
customer_phone = addr.get("phone") or "9999999999"
customer_email = addr.get("email") or "customer@ifixkart.com"
street_address = addr.get("address_line1") or addr.get("address") or "Street Address"
city = addr.get("city") or "New Delhi"
state = addr.get("state") or "Delhi"
# Check if running in sandbox / test mode
if not self.can_call_live_api():
logger.info("Shiprocket running in sandbox/test mode. Generating mock AWB and printable test label.")
simulated_awb = f"SF{int(datetime.now().timestamp())}"
courier = courier_preference or "BlueDart Surface"
test_label_url = f"/api/v1/shipping/label/preview/{order.order_id}"
return {
"ok": True,
"mode": "sandbox",
"shipment_id": f"sim_ship_{order.order_id[:8]}",
"awb_code": simulated_awb,
"courier_name": courier,
"label_url": test_label_url,
"tracking_url": f"https://shiprocket.co/tracking/{simulated_awb}",
"pickup_scheduled": True,
"message": "Fulfillment created in sandbox mode. Printable label generated."
}
# --- LIVE SHIPROCKET EXECUTION ---
token = await self._authenticate()
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json"
}
# Format items
order_items = []
for item in getattr(order, 'items', []):
order_items.append({
"name": item.product_name or "Component",
"sku": item.sku or str(item.item_id),
"units": item.quantity or 1,
"selling_price": float(item.unit_price or 0.0),
"discount": 0,
"tax": 0
})
if not order_items:
order_items.append({
"name": "Electronics Spare Part",
"sku": f"SKU-{order.order_no}",
"units": 1,
"selling_price": float(order.final_amount or 100.0)
})
async with httpx.AsyncClient(timeout=30.0) as client:
# STEP 1: CREATE ADHOC ORDER
order_payload = {
"order_id": order.order_no,
"order_date": (order.created_at or datetime.now()).strftime("%Y-%m-%d %H:%M"),
"pickup_location": self.pickup_location,
"billing_customer_name": customer_name,
"billing_last_name": "",
"billing_address": street_address,
"billing_address_2": addr.get("address_line2", ""),
"billing_city": city,
"billing_pincode": delivery_pin,
"billing_state": state,
"billing_country": "India",
"billing_email": customer_email,
"billing_phone": customer_phone,
"shipping_is_billing": True,
"order_items": order_items,
"payment_method": "Prepaid" if order.payment_status == "PAYMENT_CAPTURED" else "COD",
"sub_total": float(order.final_amount or 100.0),
"length": length_cm,
"breadth": breadth_cm,
"height": height_cm,
"weight": max(float(weight_kg), 0.1)
}
resp = await client.post(
f"{self.api_url}/orders/create/adhoc",
headers=headers,
json=order_payload
)
if resp.status_code not in (200, 201):
raise RuntimeError(f"Shiprocket order creation failed ({resp.status_code}): {resp.text}")
order_res = resp.json()
shipment_id = order_res.get("shipment_id")
if not shipment_id:
raise RuntimeError("Shiprocket did not return shipment_id")
# STEP 2: CHECK SERVICEABILITY & AUTO-SELECT BEST COURIER
courier_id = None
courier_name = courier_preference or "Shiprocket Courier"
try:
serv_params = {
"pickup_postcode": self.pickup_pin,
"delivery_postcode": delivery_pin,
"weight": weight_kg,
"cod": "0" if order.payment_status == "PAYMENT_CAPTURED" else "1"
}
serv_resp = await client.get(
f"{self.api_url}/courier/serviceability/",
headers=headers,
params=serv_params
)
if serv_resp.status_code == 200:
serv_data = serv_resp.json()
avail = serv_data.get("data", {}).get("available_courier_companies", [])
if avail and isinstance(avail, list):
# Sort by rating descending
avail.sort(key=lambda x: float(x.get("rating", 0) or 0), reverse=True)
courier_id = avail[0].get("courier_company_id")
courier_name = avail[0].get("courier_name", courier_name)
except Exception as e:
logger.warning(f"Could not auto-select courier from serviceability: {e}")
# STEP 3: ASSIGN AWB
awb_payload = {"shipment_id": shipment_id}
if courier_id:
awb_payload["courier_id"] = courier_id
awb_resp = await client.post(
f"{self.api_url}/courier/assign/awb",
headers=headers,
json=awb_payload
)
awb_code = None
if awb_resp.status_code == 200:
awb_data = awb_resp.json()
payload_part = awb_data.get("response", {}).get("data", {}) or awb_data.get("payload", {})
awb_code = payload_part.get("awb_code") or awb_data.get("awb_code")
if payload_part.get("courier_name"):
courier_name = payload_part.get("courier_name")
if not awb_code:
raise RuntimeError(f"Shiprocket AWB assignment failed: {awb_resp.text}")
# STEP 4: GENERATE PRINTABLE LABEL
label_url = None
label_resp = await client.post(
f"{self.api_url}/courier/generate/label",
headers=headers,
json={"shipment_id": [shipment_id]}
)
if label_resp.status_code == 200:
label_data = label_resp.json()
label_url = label_data.get("label_url")
# Fallback preview if label URL delayed
if not label_url:
label_url = f"/api/v1/shipping/label/preview/{order.order_id}"
# STEP 5: SCHEDULE PICKUP
pickup_scheduled = False
try:
pick_resp = await client.post(
f"{self.api_url}/courier/generate/pickup",
headers=headers,
json={"shipment_id": [shipment_id]}
)
if pick_resp.status_code == 200:
pickup_scheduled = True
except Exception as e:
logger.warning(f"Pickup auto-schedule notice: {e}")
return {
"ok": True,
"mode": "live",
"shipment_id": str(shipment_id),
"awb_code": str(awb_code),
"courier_name": courier_name,
"label_url": label_url,
"tracking_url": f"https://shiprocket.co/tracking/{awb_code}",
"pickup_scheduled": pickup_scheduled,
"message": "Fulfillment booked and pickup scheduled."
}
shiprocket_service = ShiprocketService()