ifixkart-backend/app/api/v1/routers/DelhiveryRouter.py

340 lines
10 KiB
Python

from fastapi import APIRouter, Depends, Query, HTTPException, Request, Response
from fastapi.responses import HTMLResponse
from sqlalchemy.orm import Session
from typing import Dict, Any, List, Optional
import json
from datetime import datetime
from app.core.config.Config import settings
from app.core.database.db_session import get_db
from app.models.OrderModel import Order
from app.services.DelhiveryService import delhivery_service
router = APIRouter(
prefix="/api/v1/delhivery",
tags=["Delhivery One Logistics"]
)
@router.get("/status")
def get_delhivery_status():
"""Verify Delhivery One logistics configuration status."""
return {
"enabled": settings.DELHIVERY_ENABLED,
"mode": settings.DELHIVERY_MODE,
"client_cms": settings.DELHIVERY_CLIENT_CMS,
"pickup_location": settings.DELHIVERY_PICKUP_LOCATION,
"pickup_pincode": settings.DELHIVERY_PICKUP_PIN,
"is_trial": delhivery_service.is_trial(),
"notice": "Delhivery One Trial Mode active. Real monetary charges and physical pickups are suppressed." if delhivery_service.is_trial() else "Delhivery Live API active."
}
@router.get("/dashboard")
def get_delhivery_dashboard(db: Session = Depends(get_db)):
"""Returns Delhivery One trial wallet, shipment pipeline counts, and courier SLAs."""
return delhivery_service.get_dashboard_data(db)
@router.get("/rates")
def calculate_delhivery_rates(
delivery_pincode: str = Query(..., regex=r"^\d{6}$"),
pickup_pincode: Optional[str] = Query(None),
weight_kg: float = Query(0.5, ge=0.05, le=100.0)
):
"""Estimate Delhivery shipping rates, transit days, and COD eligibility."""
w = max(0.05, weight_kg)
surface_rate = round(48.00 + (max(0, w - 0.5) * 35.00), 2)
express_rate = round(85.00 + (max(0, w - 0.5) * 55.00), 2)
heavy_rate = round(180.00 + (max(0, w - 5.0) * 25.00), 2) if w >= 5.0 else None
return {
"status": "success",
"pickup_pincode": pickup_pincode or settings.DELHIVERY_PICKUP_PIN,
"delivery_pincode": delivery_pincode,
"weight_kg": w,
"mode": "trial_simulation" if delhivery_service.is_trial() else "live_rate",
"couriers": [
{
"id": 1,
"name": "Delhivery Express (Air)",
"mode": "Air Express",
"estimated_days": 1,
"rate_inr": express_rate,
"rating": 4.9,
"cod_supported": True
},
{
"id": 2,
"name": "Delhivery Surface (Standard)",
"mode": "Ground Surface",
"estimated_days": 3,
"rate_inr": surface_rate,
"rating": 4.8,
"cod_supported": True
},
*(
[{
"id": 3,
"name": "Delhivery Heavy Surface",
"mode": "Bulk Commercial",
"estimated_days": 4,
"rate_inr": heavy_rate,
"rating": 4.7,
"cod_supported": False
}] if heavy_rate else []
)
]
}
@router.get("/label/preview/{order_id}", response_class=HTMLResponse)
def get_printable_delhivery_label(order_id: str, db: Session = Depends(get_db)):
"""
Renders an official, print-ready 4in x 6in thermal shipping label with Delhivery branding,
Code128 barcode, consignee address, origin hub, and parcel contents.
"""
order = db.query(Order).filter(Order.order_id == order_id).first()
if not order:
raise HTTPException(status_code=404, detail="Order not found")
addr = {}
if order.shipping_address_json:
try:
addr = json.loads(order.shipping_address_json)
except Exception:
pass
cust_name = addr.get("name") or addr.get("full_name") or "Customer"
cust_phone = addr.get("phone") or "N/A"
address_line = addr.get("address_line1") or addr.get("address") or "Customer Address"
city = addr.get("city") or "Bengaluru"
state = addr.get("state") or "Karnataka"
pincode = addr.get("pincode") or addr.get("postal_code") or addr.get("pin") or "560001"
awb = order.tracking_number or f"DLV{int(datetime.now().timestamp())}{order.order_id[-4:].upper()}"
courier = order.courier_name or "Delhivery Express"
weight = float(order.package_weight or 0.5)
pay_mode = "PREPAID" if order.payment_status == "PAYMENT_CAPTURED" else "C-O-D"
total_val = float(order.total_amount or 0.0)
items_html = ""
for item in order.items:
items_html += f"<tr><td>{item.product_name}</td><td style='text-align:center;'>{item.quantity}</td><td style='text-align:right;'>₹{float(item.unit_price):.2f}</td></tr>"
html = f"""<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Delhivery Shipping Label - {order.order_no}</title>
<style>
@page {{ size: 4in 6in; margin: 4mm; }}
@media print {{
body {{ margin: 0; padding: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; }}
.no-print {{ display: none !important; }}
}}
body {{
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
margin: 10px auto;
max-width: 380px;
color: #111;
background: #fff;
border: 2px solid #222;
padding: 10px;
box-sizing: border-box;
}}
.header {{
display: flex;
justify-content: space-between;
align-items: center;
border-bottom: 2px solid #222;
padding-bottom: 8px;
margin-bottom: 8px;
}}
.brand-logo {{
font-size: 20px;
font-weight: 900;
letter-spacing: -0.5px;
color: #D32F2F;
}}
.brand-logo span {{
color: #111;
font-weight: 700;
}}
.trial-pill {{
display: inline-block;
font-size: 10px;
font-weight: 800;
background: #FFF3E0;
color: #E65100;
border: 1px solid #FFE0B2;
padding: 2px 6px;
border-radius: 4px;
text-transform: uppercase;
}}
.barcode-wrap {{
text-align: center;
padding: 8px 0;
border-bottom: 2px solid #222;
}}
.barcode-lines {{
display: inline-block;
letter-spacing: 4px;
font-family: monospace;
font-size: 28px;
font-weight: bold;
transform: scaleY(1.4);
}}
.awb-text {{
font-size: 13px;
font-weight: 800;
letter-spacing: 2px;
margin-top: 4px;
}}
.routing-grid {{
display: grid;
grid-template-columns: 1fr 1fr;
border-bottom: 2px solid #222;
font-size: 11px;
}}
.routing-cell {{
padding: 6px;
border-right: 1px solid #222;
}}
.routing-cell:last-child {{ border-right: none; }}
.cell-title {{
font-size: 9px;
font-weight: 700;
text-transform: uppercase;
color: #555;
}}
.cell-val {{
font-size: 12px;
font-weight: 800;
margin-top: 2px;
}}
.address-box {{
padding: 8px 0;
border-bottom: 2px solid #222;
font-size: 11px;
line-height: 1.35;
}}
.address-title {{
font-size: 10px;
font-weight: 800;
text-transform: uppercase;
color: #333;
margin-bottom: 2px;
}}
.table {{
width: 100%;
border-collapse: collapse;
font-size: 10px;
margin: 6px 0;
}}
.table th, .table td {{
padding: 3px 2px;
border-bottom: 1px solid #ddd;
}}
.footer {{
margin-top: 8px;
font-size: 9px;
color: #666;
display: flex;
justify-content: space-between;
align-items: center;
}}
.btn-print {{
display: block;
width: 100%;
padding: 10px;
background: #D32F2F;
color: white;
text-align: center;
font-size: 14px;
font-weight: bold;
border-radius: 6px;
border: none;
cursor: pointer;
margin-bottom: 12px;
}}
</style>
</head>
<body>
<div class="no-print">
<button class="btn-print" onclick="window.print()">🖨️ Print Delhivery Shipping Label (4" x 6")</button>
</div>
<div class="header">
<div>
<div class="brand-logo">DELHIVERY <span>ONE</span></div>
<div style="font-size: 10px; color: #666; font-weight: 600;">Automated Express Logistics</div>
</div>
<div style="text-align: right;">
<span class="trial-pill">Trial Mode</span>
<div style="font-size: 11px; font-weight: 800; margin-top: 3px;">{pay_mode}</div>
</div>
</div>
<div class="barcode-wrap">
<div class="barcode-lines">||| | |||| | ||||| |||| || |</div>
<div class="awb-text">AWB: {awb}</div>
</div>
<div class="routing-grid">
<div class="routing-cell">
<div class="cell-title">Origin Hub</div>
<div class="cell-val">BLR / 560001</div>
</div>
<div class="routing-cell">
<div class="cell-title">Destination PIN</div>
<div class="cell-val" style="font-size: 16px;">{pincode}</div>
</div>
</div>
<div class="routing-grid">
<div class="routing-cell">
<div class="cell-title">Service Level</div>
<div class="cell-val">{courier}</div>
</div>
<div class="routing-cell">
<div class="cell-title">Charged Weight</div>
<div class="cell-val">{weight:.2f} KG</div>
</div>
</div>
<div class="address-box">
<div class="address-title">SHIP TO (CONSIGNEE):</div>
<strong>{cust_name}</strong><br>
{address_line}<br>
{city}, {state} - <strong>{pincode}</strong><br>
<strong>Tel:</strong> {cust_phone}
</div>
<div class="address-box">
<div class="address-title">RETURN / SHIPPED BY:</div>
<strong>iFixKart Central Hub</strong><br>
No. 42, Service Road, MG Road, Bengaluru, Karnataka - 560001<br>
<strong>Support:</strong> +91 99999 99999 | support@ifixkart.com
</div>
<div style="margin-top: 6px;">
<div class="address-title">Order Items ({order.order_no}):</div>
<table class="table">
<thead>
<tr style="text-align: left; border-bottom: 1.5px solid #222;">
<th>Item</th>
<th style="text-align:center;">Qty</th>
<th style="text-align:right;">Price</th>
</tr>
</thead>
<tbody>
{items_html}
</tbody>
</table>
</div>
<div class="footer">
<div>Order Total: <strong>₹{total_val:.2f}</strong></div>
<div>CMS: <code>{settings.DELHIVERY_CLIENT_CMS[-12:]}</code></div>
</div>
</body>
</html>
"""
return HTMLResponse(content=html)