-
This commit is contained in:
@@ -0,0 +1,233 @@
|
||||
"""Solar quotation estimate (single source of truth for the website calculator, PDF and email).
|
||||
|
||||
Defaults reproduce the per-kW figures shown in the Figma design
|
||||
(₹37,000/kW equipment, ₹9,000/kW installation, 100 sq ft per kW).
|
||||
Admins can override any value via site content key ``quote_settings``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
from dataclasses import asdict, dataclass
|
||||
from datetime import date
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.config import settings
|
||||
from app.models import SiteContent
|
||||
|
||||
DEFAULT_QUOTE_SETTINGS: dict[str, Any] = {
|
||||
"sqft_per_kw": 100,
|
||||
"panel_cost_per_kw": 37000,
|
||||
"installation_cost_per_kw": 9000,
|
||||
"min_area_sqft": 100,
|
||||
"max_area_sqft": 2000,
|
||||
# PM Surya Ghar (residential): ₹30,000/kW for the first 2 kW, ₹18,000 for the 3rd kW, max ₹78,000.
|
||||
"subsidy_first_2kw_per_kw": 30000,
|
||||
"subsidy_third_kw": 18000,
|
||||
"subsidy_cap": 78000,
|
||||
"commercial_subsidy": 0,
|
||||
"disclaimer": (
|
||||
"This is an indicative estimate. Final system size and price are confirmed after a site "
|
||||
"assessment. Subsidy depends on eligibility under the PM Surya Ghar scheme."
|
||||
),
|
||||
}
|
||||
|
||||
NUMERIC_KEYS = [k for k, v in DEFAULT_QUOTE_SETTINGS.items() if isinstance(v, int | float)]
|
||||
|
||||
|
||||
@dataclass
|
||||
class QuoteResult:
|
||||
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
|
||||
|
||||
def as_dict(self) -> dict:
|
||||
return asdict(self)
|
||||
|
||||
|
||||
async def load_quote_settings(db: AsyncSession) -> dict[str, Any]:
|
||||
row = await db.get(SiteContent, "quote_settings")
|
||||
merged = dict(DEFAULT_QUOTE_SETTINGS)
|
||||
if row and isinstance(row.value, dict):
|
||||
for k, v in row.value.items():
|
||||
if k in NUMERIC_KEYS:
|
||||
try:
|
||||
num = float(v)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if num >= 0:
|
||||
merged[k] = num
|
||||
elif k == "disclaimer" and isinstance(v, str):
|
||||
merged[k] = v
|
||||
if merged["sqft_per_kw"] <= 0:
|
||||
merged["sqft_per_kw"] = DEFAULT_QUOTE_SETTINGS["sqft_per_kw"]
|
||||
return merged
|
||||
|
||||
|
||||
def calculate_quote(cfg: dict[str, Any], property_type: str, roof_area_sqft: int, location: str) -> QuoteResult:
|
||||
area = int(max(cfg["min_area_sqft"], min(cfg["max_area_sqft"], roof_area_sqft)))
|
||||
capacity = round((area / cfg["sqft_per_kw"]) * 2) / 2 # nearest 0.5 kW
|
||||
capacity = max(0.5, capacity)
|
||||
panel = round(capacity * cfg["panel_cost_per_kw"])
|
||||
install = round(capacity * cfg["installation_cost_per_kw"])
|
||||
if property_type == "residential":
|
||||
subsidy = cfg["subsidy_first_2kw_per_kw"] * min(capacity, 2)
|
||||
if capacity > 2:
|
||||
subsidy += cfg["subsidy_third_kw"] * min(capacity - 2, 1)
|
||||
subsidy = round(min(subsidy, cfg["subsidy_cap"]))
|
||||
else:
|
||||
subsidy = round(cfg["commercial_subsidy"])
|
||||
total = max(0, panel + install - subsidy)
|
||||
return QuoteResult(
|
||||
property_type=property_type,
|
||||
roof_area_sqft=area,
|
||||
location=location,
|
||||
capacity_kw=capacity,
|
||||
panel_cost=panel,
|
||||
installation_cost=install,
|
||||
subsidy=subsidy,
|
||||
total_after_subsidy=total,
|
||||
disclaimer=cfg["disclaimer"],
|
||||
)
|
||||
|
||||
|
||||
def format_inr(amount: int) -> str:
|
||||
"""Indian digit grouping: 197000 -> ₹1,97,000"""
|
||||
s = str(abs(int(amount)))
|
||||
if len(s) > 3:
|
||||
head, tail = s[:-3], s[-3:]
|
||||
groups = []
|
||||
while len(head) > 2:
|
||||
groups.insert(0, head[-2:])
|
||||
head = head[:-2]
|
||||
if head:
|
||||
groups.insert(0, head)
|
||||
s = ",".join(groups) + "," + tail
|
||||
return ("-" if amount < 0 else "") + "₹" + s
|
||||
|
||||
|
||||
def _kw(v: float) -> str:
|
||||
return f"{v:g} kW"
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ PDF
|
||||
|
||||
|
||||
def render_quote_pdf(q: QuoteResult, customer_name: str | None = None) -> bytes:
|
||||
from reportlab.lib import colors
|
||||
from reportlab.lib.pagesizes import A4
|
||||
from reportlab.lib.units import mm
|
||||
from reportlab.lib.utils import ImageReader
|
||||
from reportlab.pdfbase import pdfmetrics
|
||||
from reportlab.pdfbase.ttfonts import TTFont
|
||||
from reportlab.pdfgen import canvas
|
||||
|
||||
font, bold = "Helvetica", "Helvetica-Bold"
|
||||
rupee = "Rs. "
|
||||
try: # DejaVu has the ₹ glyph; fall back to "Rs." if not installed
|
||||
pdfmetrics.registerFont(TTFont("DejaVu", "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"))
|
||||
pdfmetrics.registerFont(TTFont("DejaVu-Bold", "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"))
|
||||
font, bold, rupee = "DejaVu", "DejaVu-Bold", None
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def money(v: int) -> str:
|
||||
return format_inr(v) if rupee is None else format_inr(v).replace("₹", rupee)
|
||||
|
||||
navy, blue, yellow, grey = (colors.HexColor(c) for c in ("#0F172A", "#034C75", "#F2BC20", "#4D5660"))
|
||||
buf = io.BytesIO()
|
||||
W, H = A4
|
||||
c = canvas.Canvas(buf, pagesize=A4)
|
||||
c.setTitle("Saura Shakti - Solar Quotation")
|
||||
|
||||
c.setFillColor(colors.HexColor("#010F1C"))
|
||||
c.rect(0, H - 42 * mm, W, 42 * mm, stroke=0, fill=1)
|
||||
logo = settings.WATERMARK_LOGO_PATH
|
||||
if logo.is_file():
|
||||
c.drawImage(ImageReader(str(logo)), 18 * mm, H - 36 * mm, width=60 * mm, height=24 * mm,
|
||||
preserveAspectRatio=True, mask="auto")
|
||||
c.setFillColor(colors.white)
|
||||
c.setFont(bold, 16)
|
||||
c.drawRightString(W - 18 * mm, H - 20 * mm, "Solar Quotation (Estimate)")
|
||||
c.setFont(font, 10)
|
||||
c.drawRightString(W - 18 * mm, H - 27 * mm, f"Date: {date.today().strftime('%d %b %Y')}")
|
||||
|
||||
y = H - 58 * mm
|
||||
c.setFillColor(navy)
|
||||
c.setFont(bold, 12)
|
||||
if customer_name:
|
||||
c.drawString(18 * mm, y, f"Prepared for: {customer_name}")
|
||||
y -= 8 * mm
|
||||
c.setFont(font, 11)
|
||||
for label, value in [
|
||||
("Property type", q.property_type.title()),
|
||||
("Available roof area", f"{q.roof_area_sqft} sq. ft."),
|
||||
("Location", q.location or "-"),
|
||||
]:
|
||||
c.setFillColor(grey)
|
||||
c.drawString(18 * mm, y, label)
|
||||
c.setFillColor(navy)
|
||||
c.drawString(70 * mm, y, value)
|
||||
y -= 7 * mm
|
||||
|
||||
y -= 6 * mm
|
||||
c.setFillColor(colors.HexColor("#F4F6F8"))
|
||||
c.roundRect(18 * mm, y - 26 * mm, W - 36 * mm, 30 * mm, 4 * mm, stroke=0, fill=1)
|
||||
for x, label, value in [(30 * mm, "RECOMMENDED SYSTEM", _kw(q.capacity_kw)),
|
||||
(W / 2 + 10 * mm, "ESTIMATED COST", money(q.total_after_subsidy))]:
|
||||
c.setFillColor(grey)
|
||||
c.setFont(bold, 9)
|
||||
c.drawString(x, y - 6 * mm, label)
|
||||
c.setFillColor(blue)
|
||||
c.setFont(bold, 22)
|
||||
c.drawString(x, y - 18 * mm, value)
|
||||
y -= 40 * mm
|
||||
|
||||
rows = [
|
||||
("Solar Panel & Equipment", q.panel_cost),
|
||||
("Installation & Setup", q.installation_cost),
|
||||
("Estimated Subsidy / Incentive", -q.subsidy),
|
||||
("Estimated Cost After Subsidy", q.total_after_subsidy),
|
||||
]
|
||||
for i, (label, value) in enumerate(rows):
|
||||
last = i == len(rows) - 1
|
||||
c.setFillColor(yellow)
|
||||
c.circle(21 * mm, y + 1.2 * mm, 2.2 * mm, stroke=0, fill=1)
|
||||
c.setFillColor(navy)
|
||||
c.setFont(bold if last else font, 11)
|
||||
c.drawString(27 * mm, y, label)
|
||||
c.drawRightString(W - 18 * mm, y, money(value))
|
||||
c.setStrokeColor(colors.HexColor("#E2E2E2"))
|
||||
c.line(18 * mm, y - 4 * mm, W - 18 * mm, y - 4 * mm)
|
||||
y -= 12 * mm
|
||||
|
||||
c.setFillColor(grey)
|
||||
c.setFont(font, 9)
|
||||
text = c.beginText(18 * mm, y - 4 * mm)
|
||||
for line in _wrap(q.disclaimer, 105):
|
||||
text.textLine(line)
|
||||
c.drawText(text)
|
||||
c.showPage()
|
||||
c.save()
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def _wrap(s: str, width: int) -> list[str]:
|
||||
words, lines, cur = s.split(), [], ""
|
||||
for w in words:
|
||||
if len(cur) + len(w) + 1 > width:
|
||||
lines.append(cur)
|
||||
cur = w
|
||||
else:
|
||||
cur = f"{cur} {w}".strip()
|
||||
if cur:
|
||||
lines.append(cur)
|
||||
return lines
|
||||
Reference in New Issue
Block a user