feat(orders): add on-the-fly GST and thermal invoice PDF streaming endpoint
This commit is contained in:
parent
bd1678cfe8
commit
6e0c520780
1 changed files with 81 additions and 1 deletions
|
|
@ -2,7 +2,7 @@
|
|||
@router AdminOrderRouter (Backend/app/api/v1/routers/AdminOrderRouter.py)
|
||||
@purpose CRM Admin endpoint controllers to search, view, and modify storefront customer orders and trigger status transitions.
|
||||
"""
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from fastapi import APIRouter, Depends, HTTPException, status, Query, Response
|
||||
from sqlalchemy.orm import Session
|
||||
from pydantic import BaseModel
|
||||
from typing import List, Optional, Dict
|
||||
|
|
@ -25,6 +25,7 @@ from app.services.WarrantyService import WarrantyService
|
|||
from app.services.CreditService import CreditService
|
||||
from app.services.ShiprocketService import shiprocket_service
|
||||
from app.services.DelhiveryService import delhivery_service
|
||||
from app.core.invoice_generator import generate_invoice_pdf, generate_thermal_invoice_pdf
|
||||
|
||||
router = APIRouter(prefix="/api/v1/admin/orders", tags=["Admin CRM Customer Orders"])
|
||||
|
||||
|
|
@ -73,6 +74,8 @@ class AdminOrderDetailResponse(BaseModel):
|
|||
shipping_label_url: Optional[str] = None
|
||||
package_weight: Optional[float] = None
|
||||
logistics_provider: Optional[str] = None
|
||||
invoice_id: Optional[str] = None
|
||||
invoice_no: Optional[str] = None
|
||||
created_at: datetime
|
||||
items: List[OrderItemDetail]
|
||||
history: List[StatusHistorySchema]
|
||||
|
|
@ -182,6 +185,8 @@ def get_order_details(
|
|||
cust_email = order.customer.email
|
||||
cust_name = f"{order.customer.first_name} {order.customer.last_name}"
|
||||
|
||||
inv = db.query(Invoice).filter(Invoice.order_id == order.order_id).first()
|
||||
|
||||
return AdminOrderDetailResponse(
|
||||
order_id=order.order_id,
|
||||
order_no=order.order_no,
|
||||
|
|
@ -207,6 +212,8 @@ def get_order_details(
|
|||
shipping_label_url=order.shipping_label_url,
|
||||
package_weight=float(order.package_weight) if order.package_weight else None,
|
||||
logistics_provider=order.logistics_provider,
|
||||
invoice_id=inv.invoice_id if inv else None,
|
||||
invoice_no=inv.invoice_no if inv else None,
|
||||
created_at=order.created_at,
|
||||
items=[
|
||||
OrderItemDetail(
|
||||
|
|
@ -232,6 +239,79 @@ def get_order_details(
|
|||
]
|
||||
)
|
||||
|
||||
@router.get("/{order_id}/invoice")
|
||||
def get_order_invoice_pdf(
|
||||
order_id: str,
|
||||
format: str = Query("standard", regex="^(standard|thermal)$"),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""
|
||||
Generate or retrieve and stream PDF GST invoice for any order directly.
|
||||
Accepts format='standard' (A4/Letter) or format='thermal' (80mm).
|
||||
"""
|
||||
order = db.query(Order).filter(Order.order_id == order_id).first()
|
||||
if not order:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Order not found"
|
||||
)
|
||||
|
||||
# Check if invoice already exists
|
||||
invoice = db.query(Invoice).filter(Invoice.order_id == order.order_id).first()
|
||||
if not invoice:
|
||||
subtotal = float(order.total_amount)
|
||||
discount = float(order.discount_amount or 0.0)
|
||||
tax_amount = float(order.tax_amount or 0.0)
|
||||
cgst = round(tax_amount / 2, 2)
|
||||
sgst = round(tax_amount / 2, 2)
|
||||
igst = 0.0
|
||||
total = float(order.final_amount)
|
||||
|
||||
today = datetime.now()
|
||||
fy = today.strftime("%y")
|
||||
last_inv = db.query(Invoice).order_by(Invoice.created_at.desc()).first()
|
||||
try:
|
||||
seq = int(last_inv.invoice_no.split("-")[-1]) + 1 if last_inv else 1
|
||||
except Exception:
|
||||
seq = 1
|
||||
invoice_no = f"C1P1-{fy}-{seq:06d}"
|
||||
|
||||
invoice = Invoice(
|
||||
invoice_id=str(ulid.ULID()),
|
||||
invoice_no=invoice_no,
|
||||
order_id=order.order_id,
|
||||
customer_id=order.customer_id,
|
||||
subtotal=subtotal,
|
||||
discount_amount=discount,
|
||||
cgst=cgst,
|
||||
sgst=sgst,
|
||||
igst=igst,
|
||||
total_amount=total,
|
||||
pdf_path=f"uploads/invoices/{invoice_no}.pdf"
|
||||
)
|
||||
db.add(invoice)
|
||||
db.commit()
|
||||
db.refresh(invoice)
|
||||
|
||||
customer = db.query(EcomCustomer).filter(EcomCustomer.customer_id == order.customer_id).first()
|
||||
order_items = db.query(OrderItem).filter(OrderItem.order_id == order.order_id).all()
|
||||
|
||||
if format == "thermal":
|
||||
pdf_bytes = generate_thermal_invoice_pdf(order, customer, order_items)
|
||||
filename = f"thermal_{invoice.invoice_no}.pdf"
|
||||
else:
|
||||
pdf_bytes = generate_invoice_pdf(order, customer, order_items, db=db)
|
||||
filename = f"{invoice.invoice_no}.pdf"
|
||||
|
||||
return Response(
|
||||
content=pdf_bytes,
|
||||
media_type="application/pdf",
|
||||
headers={
|
||||
"Content-Disposition": f"inline; filename={filename}",
|
||||
"Cache-Control": "no-cache, no-store, must-revalidate"
|
||||
}
|
||||
)
|
||||
|
||||
from fastapi import BackgroundTasks
|
||||
from app.core.events.notification_events import dispatch_internal_notification
|
||||
from app.core.database.db_session import SessionLocal
|
||||
|
|
|
|||
Loading…
Reference in a new issue