280 lines
12 KiB
Python
280 lines
12 KiB
Python
import io
|
|
import csv
|
|
from datetime import datetime, timezone
|
|
from typing import Optional, List, Any
|
|
from fastapi import APIRouter, Depends, Query, HTTPException
|
|
from fastapi.responses import Response, StreamingResponse
|
|
from sqlalchemy.orm import Session
|
|
from sqlalchemy import desc
|
|
|
|
import openpyxl
|
|
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
|
|
from reportlab.lib.pagesizes import letter, landscape
|
|
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle
|
|
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
|
|
from reportlab.lib import colors
|
|
|
|
from app.core.database.db_session import get_db
|
|
from app.core.permissions.RoleChecker import RoleChecker
|
|
import app.models.db_base
|
|
from app.models.OrderModel import Order
|
|
from app.models.ProductModel import Product, ProductVariant
|
|
from app.models.RepairErpModel import CrmRepairTicket
|
|
from app.models.UserModel import User
|
|
from app.models.CrmModel import CrmLead, CrmDeal, CrmTask
|
|
|
|
router = APIRouter(
|
|
prefix="/api/v1/reports",
|
|
tags=["Reporting & Data Export Engine"]
|
|
)
|
|
|
|
def create_excel_workbook(title: str, headers: List[str], rows: List[List[Any]]) -> io.BytesIO:
|
|
wb = openpyxl.Workbook()
|
|
ws = wb.active
|
|
ws.title = title[:31]
|
|
|
|
# Title Banner
|
|
ws.merge_cells(start_row=1, start_column=1, end_row=1, end_column=len(headers))
|
|
title_cell = ws.cell(row=1, column=1, value=f"iFixKart Unified Platform - {title}")
|
|
title_cell.font = Font(name="Arial", size=14, bold=True, color="FFFFFF")
|
|
title_cell.fill = PatternFill(start_color="1E293B", end_color="1E293B", fill_type="solid")
|
|
title_cell.alignment = Alignment(horizontal="center", vertical="center")
|
|
ws.row_dimensions[1].height = 35
|
|
|
|
# Header Row
|
|
header_fill = PatternFill(start_color="0EA5E9", end_color="0EA5E9", fill_type="solid")
|
|
header_font = Font(name="Arial", size=10, bold=True, color="FFFFFF")
|
|
thin_border = Border(
|
|
left=Side(style='thin', color='CBD5E1'),
|
|
right=Side(style='thin', color='CBD5E1'),
|
|
top=Side(style='thin', color='CBD5E1'),
|
|
bottom=Side(style='thin', color='CBD5E1')
|
|
)
|
|
|
|
for col_idx, header in enumerate(headers, 1):
|
|
cell = ws.cell(row=2, column=col_idx, value=header)
|
|
cell.fill = header_fill
|
|
cell.font = header_font
|
|
cell.alignment = Alignment(horizontal="center", vertical="center")
|
|
cell.border = thin_border
|
|
ws.row_dimensions[2].height = 25
|
|
|
|
# Data Rows
|
|
row_alt_fill = PatternFill(start_color="F8FAFC", end_color="F8FAFC", fill_type="solid")
|
|
for row_idx, row_data in enumerate(rows, 3):
|
|
is_alt = (row_idx % 2 == 0)
|
|
for col_idx, val in enumerate(row_data, 1):
|
|
cell = ws.cell(row=row_idx, column=col_idx, value=val)
|
|
cell.font = Font(name="Arial", size=9)
|
|
cell.border = thin_border
|
|
if is_alt:
|
|
cell.fill = row_alt_fill
|
|
cell.alignment = Alignment(vertical="center")
|
|
|
|
# Auto-adjust column widths
|
|
for col in ws.columns:
|
|
max_len = max(len(str(cell.value or '')) for cell in col)
|
|
col_letter = openpyxl.utils.get_column_letter(col[0].column)
|
|
ws.column_dimensions[col_letter].width = max(max_len + 3, 12)
|
|
|
|
output = io.BytesIO()
|
|
wb.save(output)
|
|
output.seek(0)
|
|
return output
|
|
|
|
def create_pdf_document(title: str, headers: List[str], rows: List[List[Any]]) -> io.BytesIO:
|
|
output = io.BytesIO()
|
|
doc = SimpleDocTemplate(
|
|
output,
|
|
pagesize=landscape(letter),
|
|
rightMargin=20,
|
|
leftMargin=20,
|
|
topMargin=20,
|
|
bottomMargin=20
|
|
)
|
|
elements = []
|
|
styles = getSampleStyleSheet()
|
|
|
|
# Title
|
|
elements.append(Paragraph(f"<b>iFixKart Enterprise - {title}</b>", styles["Title"]))
|
|
elements.append(Paragraph(f"Generated: {datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S UTC')}", styles["Normal"]))
|
|
elements.append(Spacer(1, 15))
|
|
|
|
# Truncate text for PDF scannability
|
|
pdf_rows = []
|
|
for r in rows[:150]:
|
|
pdf_rows.append([str(c)[:30] for c in r])
|
|
|
|
table_data = [headers] + pdf_rows
|
|
t = Table(table_data, repeatRows=1)
|
|
t.setStyle(TableStyle([
|
|
('BACKGROUND', (0, 0), (-1, 0), colors.HexColor('#0F172A')),
|
|
('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
|
|
('ALIGN', (0, 0), (-1, -1), 'LEFT'),
|
|
('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
|
|
('FONTSIZE', (0, 0), (-1, 0), 8),
|
|
('BOTTOMPADDING', (0, 0), (-1, 0), 6),
|
|
('FONTNAME', (0, 1), (-1, -1), 'Helvetica'),
|
|
('FONTSIZE', (0, 1), (-1, -1), 7),
|
|
('ROWBACKGROUNDS', (0, 1), (-1, -1), [colors.white, colors.HexColor('#F8FAFC')]),
|
|
('GRID', (0, 0), (-1, -1), 0.5, colors.HexColor('#E2E8F0')),
|
|
]))
|
|
elements.append(t)
|
|
doc.build(elements)
|
|
output.seek(0)
|
|
return output
|
|
|
|
@router.get("/export")
|
|
def export_report(
|
|
category: str = Query(..., regex="^(sales|inventory|repairs|logistics|employee_activity)$"),
|
|
format: str = Query("excel", regex="^(excel|csv|pdf)$"),
|
|
days: int = Query(30, ge=1, le=365),
|
|
current_user: User = Depends(RoleChecker(["Super Admin", "Admin", "Manager", "Accountant"])),
|
|
db: Session = Depends(get_db)
|
|
):
|
|
"""Universal multi-category report exporter supporting Excel (.xlsx), CSV, and PDF."""
|
|
now_str = datetime.now().strftime("%Y%m%d_%H%M")
|
|
|
|
if category == "sales":
|
|
title = "Sales and Orders Report"
|
|
headers = ["Order No", "Date", "Items Count", "Subtotal (INR)", "Discount (INR)", "Shipping (INR)", "Total (INR)", "Order Status", "Payment Status"]
|
|
orders = db.query(Order).order_by(desc(Order.created_at)).limit(500).all()
|
|
rows = [
|
|
[
|
|
o.order_no,
|
|
o.created_at.strftime("%Y-%m-%d %H:%M") if o.created_at else "N/A",
|
|
len(o.items) if o.items else 0,
|
|
float(o.total_amount or 0),
|
|
float(o.discount_amount or 0),
|
|
float(o.shipping_cost or 0),
|
|
float(o.final_amount or 0),
|
|
o.status,
|
|
o.payment_status
|
|
]
|
|
for o in orders
|
|
]
|
|
|
|
elif category == "inventory":
|
|
title = "Inventory and Stock Valuation Report"
|
|
headers = ["Product ID", "Product Name", "SKU", "Category", "Brand", "Stock Qty", "Cost Price", "Selling Price", "Valuation (INR)"]
|
|
products = db.query(Product).limit(500).all()
|
|
rows = []
|
|
for p in products:
|
|
total_prod_stock = sum(loc.stock_quantity or 0 for loc in p.location_mappings) if p.location_mappings else 0
|
|
if p.variants:
|
|
for v in p.variants:
|
|
qty = total_prod_stock if len(p.variants) == 1 else (total_prod_stock // len(p.variants))
|
|
price = float(v.price or 0.0)
|
|
cost = float(v.cost_price or (price * 0.7))
|
|
valuation = round(qty * price, 2)
|
|
rows.append([
|
|
p.product_id,
|
|
p.name,
|
|
v.sku or "N/A",
|
|
p.category.name if p.category else "N/A",
|
|
p.brand.name if p.brand else "N/A",
|
|
qty,
|
|
cost,
|
|
price,
|
|
valuation
|
|
])
|
|
else:
|
|
price = float(p.location_mappings[0].selling_price or 0.0) if p.location_mappings else 0.0
|
|
cost = float(p.location_mappings[0].cost_price or 0.0) if p.location_mappings else 0.0
|
|
rows.append([
|
|
p.product_id,
|
|
p.name,
|
|
"N/A",
|
|
p.category.name if p.category else "N/A",
|
|
p.brand.name if p.brand else "N/A",
|
|
total_prod_stock,
|
|
cost,
|
|
price,
|
|
round(total_prod_stock * price, 2)
|
|
])
|
|
|
|
elif category == "repairs":
|
|
title = "Service and Repair Jobs Report"
|
|
headers = ["Ticket No", "Customer Name", "Customer Phone", "Device Model", "Assigned Tech", "Stage", "Type", "Estimated (INR)", "Date"]
|
|
tickets = db.query(CrmRepairTicket).order_by(desc(CrmRepairTicket.created_at)).limit(500).all()
|
|
rows = [
|
|
[
|
|
t.ticket_number,
|
|
t.customer.name if t.customer else "N/A",
|
|
t.customer.phone if t.customer else "N/A",
|
|
f"{t.device.brand} {t.device.model_name}" if t.device else "N/A",
|
|
t.assigned_technician_id or "Unassigned",
|
|
t.stage,
|
|
"Warranty Claim" if t.is_warranty_claim else "Standard Repair",
|
|
float(t.estimate_amount or 0),
|
|
t.created_at.strftime("%Y-%m-%d %H:%M") if t.created_at else "N/A"
|
|
]
|
|
for t in tickets
|
|
]
|
|
|
|
elif category == "logistics":
|
|
title = "Logistics and Delivery Report"
|
|
headers = ["Order No", "Tracking No", "Courier Partner", "Order Status", "Payment Status", "Shipping Fee (INR)", "Date"]
|
|
orders = db.query(Order).filter(Order.courier_name != None).order_by(desc(Order.created_at)).limit(500).all()
|
|
if not orders:
|
|
orders = db.query(Order).order_by(desc(Order.created_at)).limit(100).all()
|
|
rows = [
|
|
[
|
|
o.order_no,
|
|
o.tracking_number or "N/A",
|
|
o.courier_name or "Standard Courier",
|
|
o.status,
|
|
o.payment_status,
|
|
float(o.shipping_cost or 0),
|
|
o.created_at.strftime("%Y-%m-%d") if o.created_at else "N/A"
|
|
]
|
|
for o in orders
|
|
]
|
|
|
|
elif category == "employee_activity":
|
|
title = "Employee Operational Activity Report"
|
|
headers = ["User ID", "Name", "Email", "Role", "Leads Handled", "Deals Managed", "Tasks Completed", "Status"]
|
|
users = db.query(User).filter(User.is_active == True).limit(200).all()
|
|
rows = []
|
|
for u in users:
|
|
leads_cnt = db.query(CrmLead).filter(CrmLead.assigned_user_id == u.user_id).count()
|
|
deals_cnt = db.query(CrmDeal).filter(CrmDeal.assigned_user_id == u.user_id).count()
|
|
todos_cnt = db.query(CrmTask).filter(CrmTask.assignee_id == u.user_id, CrmTask.status == "COMPLETED").count()
|
|
full_name = f"{u.first_name or ''} {u.last_name or ''}".strip() or (u.display_name or "Staff")
|
|
role_name = u.role.role_name if u.role else "Staff"
|
|
rows.append([
|
|
u.user_id[:12],
|
|
full_name,
|
|
u.email or "N/A",
|
|
role_name,
|
|
leads_cnt,
|
|
deals_cnt,
|
|
todos_cnt,
|
|
"Active" if u.is_active else "Inactive"
|
|
])
|
|
|
|
# Format Output
|
|
if format == "excel":
|
|
stream = create_excel_workbook(title, headers, rows)
|
|
return StreamingResponse(
|
|
stream,
|
|
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
|
headers={"Content-Disposition": f"attachment; filename={category}_report_{now_str}.xlsx"}
|
|
)
|
|
elif format == "csv":
|
|
output = io.StringIO()
|
|
writer = csv.writer(output)
|
|
writer.writerow(headers)
|
|
writer.writerows(rows)
|
|
return Response(
|
|
content=output.getvalue(),
|
|
media_type="text/csv",
|
|
headers={"Content-Disposition": f"attachment; filename={category}_report_{now_str}.csv"}
|
|
)
|
|
elif format == "pdf":
|
|
stream = create_pdf_document(title, headers, rows)
|
|
return StreamingResponse(
|
|
stream,
|
|
media_type="application/pdf",
|
|
headers={"Content-Disposition": f"attachment; filename={category}_report_{now_str}.pdf"}
|
|
)
|