Files
saura_shakti_website/backend/app/routes/quotations.py
T
Shubhankar45 53dbfa976b -
2026-11-13 12:14:55 +00:00

189 lines
6.6 KiB
Python

from datetime import datetime
from typing import Literal
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.concurrency import run_in_threadpool
from fastapi.responses import Response
from pydantic import BaseModel, EmailStr, Field, field_validator
from sqlalchemy import func, select
from app.core.config import settings
from app.core.deps import AnyAdmin, DbSession, ManagerAdmin
from app.middleware.rate_limit import RateLimiter
from app.models import Enquiry, PropertyType, Subscriber
from app.schemas.common import InputModel, MessageResponse, OrmModel, Page
from app.services.email import send_email
from app.services.quotation import calculate_quote, format_inr, load_quote_settings, render_quote_pdf
from app.utils.helpers import paginate
router = APIRouter(tags=["Quotation & newsletter"])
quote_limiter = RateLimiter("quotation", settings.PUBLIC_FORM_RATE_LIMIT_PER_MINUTE)
subscribe_limiter = RateLimiter("subscribe", settings.PUBLIC_FORM_RATE_LIMIT_PER_MINUTE)
class QuoteRequest(InputModel):
property_type: Literal["residential", "commercial"] = "residential"
roof_area_sqft: int = Field(ge=1, le=1_000_000)
location: str = Field(default="", max_length=120)
class EmailQuoteRequest(QuoteRequest):
email: EmailStr
name: str | None = Field(default=None, max_length=150)
website: str | None = Field(default=None, max_length=200) # honeypot
@field_validator("name", "website", mode="before")
@classmethod
def _blank(cls, v):
return None if isinstance(v, str) and not v.strip() else v
class QuoteOut(BaseModel):
property_type: str
roof_area_sqft: int
location: str
capacity_kw: float
panel_cost: int
installation_cost: int
subsidy: int
total_after_subsidy: int
disclaimer: str
@router.get("/quotations/settings", summary="Rates used by the website calculator")
async def quote_settings(db: DbSession) -> dict:
return await load_quote_settings(db)
@router.post("/quotations/calculate", response_model=QuoteOut)
async def calculate(body: QuoteRequest, db: DbSession):
cfg = await load_quote_settings(db)
return calculate_quote(cfg, body.property_type, body.roof_area_sqft, body.location).as_dict()
@router.post(
"/quotations/pdf",
response_class=Response,
responses={200: {"content": {"application/pdf": {}}}},
summary="Download the quotation as PDF",
)
async def quote_pdf(body: QuoteRequest, db: DbSession):
cfg = await load_quote_settings(db)
q = calculate_quote(cfg, body.property_type, body.roof_area_sqft, body.location)
pdf = await run_in_threadpool(render_quote_pdf, q)
return Response(
pdf,
media_type="application/pdf",
headers={"Content-Disposition": 'attachment; filename="saura-shakti-quotation.pdf"'},
)
@router.post(
"/quotations/email",
response_model=MessageResponse,
dependencies=[Depends(quote_limiter)],
summary="Email the quotation (also saved as an enquiry for the sales team)",
)
async def email_quote(body: EmailQuoteRequest, db: DbSession):
success = MessageResponse(message="Your quotation has also been sent to your email.")
if body.website:
return success
cfg = await load_quote_settings(db)
q = calculate_quote(cfg, body.property_type, body.roof_area_sqft, body.location)
db.add(
Enquiry(
name=body.name or body.email.split("@")[0],
email=body.email,
city=body.location or None,
property_type=PropertyType(body.property_type),
required_capacity_kw=q.capacity_kw,
source="quote_calculator",
message=(
f"Quotation requested: {q.capacity_kw:g} kW for {q.roof_area_sqft} sq ft, "
f"estimated {format_inr(q.total_after_subsidy)} after subsidy."
),
)
)
await db.commit()
pdf = await run_in_threadpool(render_quote_pdf, q, body.name)
text = (
f"Hello{(' ' + body.name) if body.name else ''},\n\n"
f"Thank you for using the Saura Shakti solar calculator.\n\n"
f"Recommended system: {q.capacity_kw:g} kW\n"
f"Solar panel & equipment: {format_inr(q.panel_cost)}\n"
f"Installation & setup: {format_inr(q.installation_cost)}\n"
f"Estimated subsidy / incentive: {format_inr(q.subsidy)}\n"
f"Estimated cost after subsidy: {format_inr(q.total_after_subsidy)}\n\n"
f"{q.disclaimer}\n\nOur team will contact you shortly.\n\nSaura Shakti"
)
try:
await run_in_threadpool(
send_email,
body.email,
"Your Saura Shakti solar quotation",
text,
[("saura-shakti-quotation.pdf", pdf, "application/pdf")],
)
except Exception:
raise HTTPException(
status.HTTP_502_BAD_GATEWAY,
"We saved your request but could not send the email right now. Our team will contact you.",
) from None
return success
# ------------------------------------------------------------------ newsletter
class SubscribeRequest(InputModel):
email: EmailStr
website: str | None = Field(default=None, max_length=200)
class SubscriberOut(OrmModel):
id: int
email: str
is_active: bool
created_at: datetime
@router.post(
"/subscribe",
response_model=MessageResponse,
status_code=status.HTTP_201_CREATED,
dependencies=[Depends(subscribe_limiter)],
)
async def subscribe(body: SubscribeRequest, db: DbSession):
msg = MessageResponse(message="Thanks for subscribing!")
if body.website:
return msg
email = body.email.lower()
existing = await db.scalar(select(Subscriber).where(func.lower(Subscriber.email) == email))
if existing:
existing.is_active = True
else:
db.add(Subscriber(email=email))
await db.commit()
return msg
@router.get("/admin/subscribers", response_model=Page[SubscriberOut], tags=["Admin: subscribers"])
async def list_subscribers(_: AnyAdmin, db: DbSession, page: int = 1, page_size: int = 50):
page, page_size = max(page, 1), min(max(page_size, 1), 200)
stmt = select(Subscriber).order_by(Subscriber.created_at.desc(), Subscriber.id.desc())
rows, total = await paginate(db, stmt, page, page_size)
return Page(items=rows, total=total, page=page, page_size=page_size)
@router.delete(
"/admin/subscribers/{sub_id}", status_code=status.HTTP_204_NO_CONTENT, tags=["Admin: subscribers"]
)
async def delete_subscriber(sub_id: int, _: ManagerAdmin, db: DbSession):
sub = await db.get(Subscriber, sub_id)
if not sub:
raise HTTPException(status.HTTP_404_NOT_FOUND, "Subscriber not found")
await db.delete(sub)
await db.commit()