-
This commit is contained in:
@@ -0,0 +1,83 @@
|
||||
"""Management commands.
|
||||
|
||||
python -m app.cli create-admin --email you@example.com --name "Your Name" [--role super_admin]
|
||||
|
||||
The password is read from the ADMIN_PASSWORD environment variable if set,
|
||||
otherwise prompted for interactively (never passed on the command line).
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import getpass
|
||||
import os
|
||||
import sys
|
||||
|
||||
from pydantic import TypeAdapter, ValidationError
|
||||
from sqlalchemy import func, select
|
||||
|
||||
from app.core.database import SessionLocal, engine
|
||||
from app.core.security import hash_password
|
||||
from app.models import Admin, AdminRole
|
||||
from app.schemas.auth import AdminCreate
|
||||
|
||||
|
||||
def _read_password() -> str:
|
||||
if pw := os.environ.get("ADMIN_PASSWORD"):
|
||||
return pw
|
||||
if not sys.stdin.isatty():
|
||||
sys.exit("Set ADMIN_PASSWORD or run interactively to enter a password.")
|
||||
pw = getpass.getpass("Password (min 10 chars, letters + numbers): ")
|
||||
if pw != getpass.getpass("Repeat password: "):
|
||||
sys.exit("Passwords do not match.")
|
||||
return pw
|
||||
|
||||
|
||||
async def create_admin(email: str, name: str, role: str, update_existing: bool) -> None:
|
||||
try:
|
||||
data = TypeAdapter(AdminCreate).validate_python(
|
||||
{"email": email, "full_name": name, "password": _read_password(), "role": role}
|
||||
)
|
||||
except ValidationError as exc:
|
||||
sys.exit("Invalid input:\n" + "\n".join(f" - {e['loc'][-1]}: {e['msg']}" for e in exc.errors()))
|
||||
|
||||
async with SessionLocal() as db:
|
||||
existing = await db.scalar(select(Admin).where(func.lower(Admin.email) == data.email.lower()))
|
||||
if existing and not update_existing:
|
||||
sys.exit(f"Admin {data.email} already exists (use --update to reset password/role).")
|
||||
if existing:
|
||||
existing.hashed_password = hash_password(data.password)
|
||||
existing.role = data.role
|
||||
existing.full_name = data.full_name
|
||||
existing.is_active = True
|
||||
action = "Updated"
|
||||
else:
|
||||
db.add(
|
||||
Admin(
|
||||
email=data.email.lower(),
|
||||
full_name=data.full_name,
|
||||
hashed_password=hash_password(data.password),
|
||||
role=data.role,
|
||||
)
|
||||
)
|
||||
action = "Created"
|
||||
await db.commit()
|
||||
await engine.dispose()
|
||||
print(f"{action} {data.role.value} account: {data.email.lower()}")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(prog="python -m app.cli")
|
||||
sub = parser.add_subparsers(dest="command", required=True)
|
||||
ca = sub.add_parser("create-admin", help="Create (or update) an admin account")
|
||||
ca.add_argument("--email", required=True)
|
||||
ca.add_argument("--name", required=True)
|
||||
ca.add_argument("--role", default=AdminRole.SUPER_ADMIN.value, choices=[r.value for r in AdminRole])
|
||||
ca.add_argument("--update", action="store_true", help="Update the account if it already exists")
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.command == "create-admin":
|
||||
asyncio.run(create_admin(args.email, args.name, args.role, args.update))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,86 @@
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
|
||||
from pydantic import Field, field_validator
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
BACKEND_DIR = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
model_config = SettingsConfigDict(
|
||||
env_file=BACKEND_DIR / ".env", env_file_encoding="utf-8", extra="ignore"
|
||||
)
|
||||
|
||||
APP_NAME: str = "Saura Shakti API"
|
||||
ENVIRONMENT: str = "development" # development | test
|
||||
API_PREFIX: str = "/api"
|
||||
|
||||
DATABASE_URL: str
|
||||
DB_ECHO: bool = False
|
||||
|
||||
JWT_SECRET_KEY: str = Field(min_length=32)
|
||||
JWT_ALGORITHM: str = "HS256"
|
||||
JWT_EXPIRE_MINUTES: int = 120
|
||||
|
||||
# Comma-separated list in .env
|
||||
CORS_ORIGINS: str = "http://localhost:5173"
|
||||
|
||||
# Media / uploads
|
||||
UPLOAD_DIR: Path = BACKEND_DIR / "uploads"
|
||||
MEDIA_URL_PATH: str = "/media"
|
||||
MEDIA_BASE_URL: str = "http://localhost:8020/media"
|
||||
MAX_UPLOAD_SIZE_MB: int = 10
|
||||
MAX_FILES_PER_UPLOAD: int = 20
|
||||
MAX_IMAGE_PIXELS: int = 60_000_000 # guards against decompression bombs
|
||||
|
||||
# Watermark
|
||||
WATERMARK_LOGO_PATH: Path = BACKEND_DIR / "assets" / "watermark" / "logo.png"
|
||||
WATERMARK_WIDTH_RATIO: float = 0.18 # logo width relative to image width
|
||||
WATERMARK_MIN_WIDTH: int = 80
|
||||
WATERMARK_MAX_WIDTH: int = 600
|
||||
WATERMARK_MARGIN_RATIO: float = 0.03 # margin relative to the shorter image side
|
||||
WATERMARK_OPACITY: float = 0.75
|
||||
WATERMARK_SHADOW_OPACITY: float = 0.35
|
||||
|
||||
THUMBNAIL_MAX_SIZE: int = 640
|
||||
|
||||
# Email (quotations). If SMTP_HOST is empty, emails are written to OUTBOX_DIR as .eml files.
|
||||
SMTP_HOST: str = ""
|
||||
SMTP_PORT: int = 587
|
||||
SMTP_USER: str = ""
|
||||
SMTP_PASSWORD: str = ""
|
||||
SMTP_STARTTLS: bool = True
|
||||
MAIL_FROM: str = "Saura Shakti <no-reply@localhost>"
|
||||
OUTBOX_DIR: Path = BACKEND_DIR / "outbox"
|
||||
|
||||
# Simple in-memory rate limits (per client IP, per process)
|
||||
LOGIN_RATE_LIMIT_PER_MINUTE: int = 10
|
||||
PUBLIC_FORM_RATE_LIMIT_PER_MINUTE: int = 10
|
||||
|
||||
@field_validator("WATERMARK_OPACITY", "WATERMARK_SHADOW_OPACITY")
|
||||
@classmethod
|
||||
def _opacity_range(cls, v: float) -> float:
|
||||
if not 0 <= v <= 1:
|
||||
raise ValueError("opacity must be between 0 and 1")
|
||||
return v
|
||||
|
||||
@property
|
||||
def cors_origins_list(self) -> list[str]:
|
||||
return [o.strip() for o in self.CORS_ORIGINS.split(",") if o.strip()]
|
||||
|
||||
@property
|
||||
def max_upload_bytes(self) -> int:
|
||||
return self.MAX_UPLOAD_SIZE_MB * 1024 * 1024
|
||||
|
||||
@property
|
||||
def is_test(self) -> bool:
|
||||
return self.ENVIRONMENT == "test"
|
||||
|
||||
|
||||
@lru_cache
|
||||
def get_settings() -> Settings:
|
||||
return Settings() # type: ignore[call-arg]
|
||||
|
||||
|
||||
settings = get_settings()
|
||||
@@ -0,0 +1,19 @@
|
||||
from collections.abc import AsyncIterator
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
||||
from sqlalchemy.pool import NullPool
|
||||
|
||||
from app.core.config import settings
|
||||
|
||||
_engine_kwargs: dict = {"echo": settings.DB_ECHO, "pool_pre_ping": True}
|
||||
if settings.is_test:
|
||||
# Tests run each case in its own event loop; pooled connections can't cross loops.
|
||||
_engine_kwargs["poolclass"] = NullPool
|
||||
|
||||
engine = create_async_engine(settings.DATABASE_URL, **_engine_kwargs)
|
||||
SessionLocal = async_sessionmaker(engine, expire_on_commit=False, autoflush=False)
|
||||
|
||||
|
||||
async def get_db() -> AsyncIterator[AsyncSession]:
|
||||
async with SessionLocal() as session:
|
||||
yield session
|
||||
@@ -0,0 +1,68 @@
|
||||
from typing import Annotated
|
||||
|
||||
import jwt
|
||||
from fastapi import Depends, HTTPException, status
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.database import get_db
|
||||
from app.core.security import decode_access_token
|
||||
from app.models import Admin, AdminRole
|
||||
|
||||
DbSession = Annotated[AsyncSession, Depends(get_db)]
|
||||
|
||||
_bearer = HTTPBearer(auto_error=False, description="JWT from POST /api/auth/login")
|
||||
|
||||
|
||||
def _unauthorized(detail: str) -> HTTPException:
|
||||
return HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail=detail,
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
|
||||
async def get_current_admin(
|
||||
db: DbSession,
|
||||
credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(_bearer)],
|
||||
) -> Admin:
|
||||
if credentials is None or credentials.scheme.lower() != "bearer":
|
||||
raise _unauthorized("Not authenticated")
|
||||
try:
|
||||
payload = decode_access_token(credentials.credentials)
|
||||
admin_id = int(payload["sub"])
|
||||
except jwt.ExpiredSignatureError:
|
||||
raise _unauthorized("Session expired. Please log in again.") from None
|
||||
except (jwt.PyJWTError, KeyError, ValueError):
|
||||
raise _unauthorized("Invalid authentication token") from None
|
||||
|
||||
admin = await db.get(Admin, admin_id)
|
||||
if admin is None or not admin.is_active:
|
||||
raise _unauthorized("Account not found or disabled")
|
||||
return admin
|
||||
|
||||
|
||||
CurrentAdmin = Annotated[Admin, Depends(get_current_admin)]
|
||||
|
||||
|
||||
def require_roles(*roles: AdminRole):
|
||||
allowed = set(roles)
|
||||
|
||||
async def checker(admin: CurrentAdmin) -> Admin:
|
||||
if admin.role not in allowed:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="You do not have permission to perform this action",
|
||||
)
|
||||
return admin
|
||||
|
||||
return checker
|
||||
|
||||
|
||||
# Convenience role groups
|
||||
ALL_ROLES = (AdminRole.SUPER_ADMIN, AdminRole.ADMIN, AdminRole.EDITOR)
|
||||
MANAGERS = (AdminRole.SUPER_ADMIN, AdminRole.ADMIN)
|
||||
|
||||
AnyAdmin = Annotated[Admin, Depends(require_roles(*ALL_ROLES))]
|
||||
ManagerAdmin = Annotated[Admin, Depends(require_roles(*MANAGERS))]
|
||||
SuperAdmin = Annotated[Admin, Depends(require_roles(AdminRole.SUPER_ADMIN))]
|
||||
@@ -0,0 +1,47 @@
|
||||
from datetime import UTC, datetime, timedelta
|
||||
|
||||
import jwt
|
||||
from pwdlib import PasswordHash
|
||||
|
||||
from app.core.config import settings
|
||||
|
||||
_password_hash = PasswordHash.recommended() # Argon2id
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
return _password_hash.hash(password)
|
||||
|
||||
|
||||
def verify_password(password: str, hashed: str) -> bool:
|
||||
return _password_hash.verify(password, hashed)
|
||||
|
||||
|
||||
# Used to keep login timing similar whether or not the email exists.
|
||||
DUMMY_HASH = hash_password("timing-equaliser-not-a-real-password")
|
||||
|
||||
|
||||
def create_access_token(subject: str, role: str) -> tuple[str, int]:
|
||||
expires_in = settings.JWT_EXPIRE_MINUTES * 60
|
||||
now = datetime.now(UTC)
|
||||
payload = {
|
||||
"sub": subject,
|
||||
"role": role,
|
||||
"type": "access",
|
||||
"iat": now,
|
||||
"exp": now + timedelta(seconds=expires_in),
|
||||
}
|
||||
token = jwt.encode(payload, settings.JWT_SECRET_KEY, algorithm=settings.JWT_ALGORITHM)
|
||||
return token, expires_in
|
||||
|
||||
|
||||
def decode_access_token(token: str) -> dict:
|
||||
"""Raises jwt.PyJWTError on invalid/expired tokens."""
|
||||
payload = jwt.decode(
|
||||
token,
|
||||
settings.JWT_SECRET_KEY,
|
||||
algorithms=[settings.JWT_ALGORITHM],
|
||||
options={"require": ["sub", "exp", "iat"]},
|
||||
)
|
||||
if payload.get("type") != "access":
|
||||
raise jwt.InvalidTokenError("wrong token type")
|
||||
return payload
|
||||
@@ -0,0 +1,100 @@
|
||||
import logging
|
||||
|
||||
from fastapi import FastAPI, Request, status
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import JSONResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app.core.config import settings
|
||||
from app.middleware.security_headers import SecurityHeadersMiddleware
|
||||
from app.routes import auth, enquiries, misc, projects, quotations, services
|
||||
from app.services.image_processing import THUMBNAILS, WATERMARKED, ensure_upload_dirs
|
||||
|
||||
logger = logging.getLogger("app")
|
||||
|
||||
ensure_upload_dirs()
|
||||
|
||||
app = FastAPI(
|
||||
title=settings.APP_NAME,
|
||||
version="0.1.0",
|
||||
description=(
|
||||
"Backend for the Saura Shakti solar company website and admin dashboard.\n\n"
|
||||
"**Admin endpoints** require `Authorization: Bearer <token>` from `POST /api/auth/login` "
|
||||
"(use the *Authorize* button)."
|
||||
),
|
||||
docs_url="/docs",
|
||||
redoc_url="/redoc",
|
||||
openapi_url="/openapi.json",
|
||||
)
|
||||
|
||||
app.add_middleware(SecurityHeadersMiddleware)
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=settings.cors_origins_list,
|
||||
allow_credentials=True,
|
||||
allow_methods=["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
|
||||
allow_headers=["Authorization", "Content-Type"],
|
||||
)
|
||||
|
||||
# Only watermarked images and thumbnails are public. Originals are NOT mounted;
|
||||
# admins fetch them through an authenticated endpoint.
|
||||
media_root = settings.UPLOAD_DIR
|
||||
for sub in (WATERMARKED, THUMBNAILS):
|
||||
app.mount(
|
||||
f"{settings.MEDIA_URL_PATH}/{sub}",
|
||||
StaticFiles(directory=media_root / sub),
|
||||
name=f"media-{sub}",
|
||||
)
|
||||
|
||||
for module_router in (
|
||||
auth.router,
|
||||
auth.users_router,
|
||||
enquiries.public_router,
|
||||
enquiries.admin_router,
|
||||
projects.public_router,
|
||||
projects.admin_router,
|
||||
projects.images_router,
|
||||
services.public_router,
|
||||
services.admin_router,
|
||||
misc.router,
|
||||
quotations.router,
|
||||
):
|
||||
app.include_router(module_router, prefix=settings.API_PREFIX)
|
||||
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def validation_error_handler(_: Request, exc: RequestValidationError):
|
||||
"""Uniform validation errors: {detail: str, errors: [{field, message}]} for the frontend."""
|
||||
errors = []
|
||||
for err in exc.errors():
|
||||
loc = [str(p) for p in err.get("loc", []) if p not in ("body", "query", "path")]
|
||||
errors.append({"field": ".".join(loc) or None, "message": err.get("msg", "Invalid value")})
|
||||
return JSONResponse(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
|
||||
content={"detail": "Validation failed", "errors": errors},
|
||||
)
|
||||
|
||||
|
||||
@app.exception_handler(IntegrityError)
|
||||
async def integrity_error_handler(_: Request, exc: IntegrityError):
|
||||
logger.warning("Integrity error: %s", exc.orig)
|
||||
return JSONResponse(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
content={"detail": "The request conflicts with existing data."},
|
||||
)
|
||||
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def unhandled_error_handler(_: Request, exc: Exception):
|
||||
logger.exception("Unhandled error", exc_info=exc)
|
||||
return JSONResponse(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
content={"detail": "Something went wrong. Please try again."},
|
||||
)
|
||||
|
||||
|
||||
@app.get("/", include_in_schema=False)
|
||||
async def root():
|
||||
return {"name": settings.APP_NAME, "docs": "/docs", "health": f"{settings.API_PREFIX}/health"}
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Minimal in-memory sliding-window rate limiter.
|
||||
|
||||
Good enough for a single-process development server. A multi-process deployment
|
||||
would need a shared store (e.g. Redis) instead.
|
||||
"""
|
||||
|
||||
import time
|
||||
from collections import defaultdict, deque
|
||||
|
||||
from fastapi import HTTPException, Request, status
|
||||
|
||||
_registry: list["RateLimiter"] = []
|
||||
|
||||
|
||||
class RateLimiter:
|
||||
def __init__(self, name: str, limit_per_minute: int, window_seconds: float = 60.0):
|
||||
self.name = name
|
||||
self.limit = limit_per_minute
|
||||
self.window = window_seconds
|
||||
self._hits: dict[str, deque[float]] = defaultdict(deque)
|
||||
_registry.append(self)
|
||||
|
||||
async def __call__(self, request: Request) -> None:
|
||||
if self.limit <= 0:
|
||||
return
|
||||
key = request.client.host if request.client else "unknown"
|
||||
now = time.monotonic()
|
||||
hits = self._hits[key]
|
||||
while hits and now - hits[0] > self.window:
|
||||
hits.popleft()
|
||||
if len(hits) >= self.limit:
|
||||
retry_after = max(1, int(self.window - (now - hits[0])))
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
||||
detail="Too many requests. Please try again shortly.",
|
||||
headers={"Retry-After": str(retry_after)},
|
||||
)
|
||||
hits.append(now)
|
||||
|
||||
def reset(self) -> None:
|
||||
self._hits.clear()
|
||||
|
||||
|
||||
def reset_all_limiters() -> None:
|
||||
for limiter in _registry:
|
||||
limiter.reset()
|
||||
@@ -0,0 +1,11 @@
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
from starlette.requests import Request
|
||||
|
||||
|
||||
class SecurityHeadersMiddleware(BaseHTTPMiddleware):
|
||||
async def dispatch(self, request: Request, call_next):
|
||||
response = await call_next(request)
|
||||
response.headers.setdefault("X-Content-Type-Options", "nosniff")
|
||||
response.headers.setdefault("X-Frame-Options", "DENY")
|
||||
response.headers.setdefault("Referrer-Policy", "strict-origin-when-cross-origin")
|
||||
return response
|
||||
@@ -0,0 +1,25 @@
|
||||
from app.models.admin import Admin
|
||||
from app.models.base import Base
|
||||
from app.models.content import ContactMessage, Service, SiteContent, Subscriber, Testimonial
|
||||
from app.models.enquiry import Enquiry, EnquiryNote
|
||||
from app.models.enums import AdminRole, EnquiryStatus, ProjectCategory, ProjectStatus, PropertyType
|
||||
from app.models.project import Project, ProjectImage
|
||||
|
||||
__all__ = [
|
||||
"Admin",
|
||||
"AdminRole",
|
||||
"Base",
|
||||
"ContactMessage",
|
||||
"Enquiry",
|
||||
"EnquiryNote",
|
||||
"EnquiryStatus",
|
||||
"Project",
|
||||
"ProjectCategory",
|
||||
"ProjectImage",
|
||||
"ProjectStatus",
|
||||
"PropertyType",
|
||||
"Service",
|
||||
"SiteContent",
|
||||
"Subscriber",
|
||||
"Testimonial",
|
||||
]
|
||||
@@ -0,0 +1,21 @@
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import Boolean, DateTime, String, true
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.models.base import Base, TimestampMixin
|
||||
from app.models.enums import AdminRole, db_enum
|
||||
|
||||
|
||||
class Admin(TimestampMixin, Base):
|
||||
__tablename__ = "admins"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
email: Mapped[str] = mapped_column(String(255), unique=True, index=True)
|
||||
full_name: Mapped[str] = mapped_column(String(150))
|
||||
hashed_password: Mapped[str] = mapped_column(String(255))
|
||||
role: Mapped[AdminRole] = mapped_column(
|
||||
db_enum(AdminRole, "admin_role"), default=AdminRole.ADMIN, server_default=AdminRole.ADMIN.value
|
||||
)
|
||||
is_active: Mapped[bool] = mapped_column(Boolean, default=True, server_default=true())
|
||||
last_login_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
||||
@@ -0,0 +1,26 @@
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import DateTime, MetaData, func
|
||||
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
|
||||
|
||||
# Deterministic constraint names so Alembic migrations are stable.
|
||||
NAMING_CONVENTION = {
|
||||
"ix": "ix_%(column_0_label)s",
|
||||
"uq": "uq_%(table_name)s_%(column_0_name)s",
|
||||
"ck": "ck_%(table_name)s_%(constraint_name)s",
|
||||
"fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
|
||||
"pk": "pk_%(table_name)s",
|
||||
}
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
metadata = MetaData(naming_convention=NAMING_CONVENTION)
|
||||
|
||||
|
||||
class TimestampMixin:
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), server_default=func.now(), nullable=False
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), server_default=func.now(), onupdate=func.now(), nullable=False
|
||||
)
|
||||
@@ -0,0 +1,92 @@
|
||||
from sqlalchemy import (
|
||||
Boolean,
|
||||
CheckConstraint,
|
||||
ForeignKey,
|
||||
Integer,
|
||||
SmallInteger,
|
||||
String,
|
||||
Text,
|
||||
false,
|
||||
true,
|
||||
)
|
||||
from sqlalchemy.dialects.postgresql import JSONB
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.models.base import Base, TimestampMixin
|
||||
|
||||
|
||||
class Service(TimestampMixin, Base):
|
||||
__tablename__ = "services"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
title: Mapped[str] = mapped_column(String(150))
|
||||
slug: Mapped[str] = mapped_column(String(170), unique=True, index=True)
|
||||
short_description: Mapped[str | None] = mapped_column(String(300))
|
||||
description: Mapped[str | None] = mapped_column(Text)
|
||||
icon: Mapped[str | None] = mapped_column(String(60)) # optional icon name for the frontend
|
||||
sort_order: Mapped[int] = mapped_column(Integer, default=0, server_default="0")
|
||||
is_published: Mapped[bool] = mapped_column(Boolean, default=False, server_default=false())
|
||||
|
||||
# Single watermarked image (paths relative to UPLOAD_DIR)
|
||||
image_original_path: Mapped[str | None] = mapped_column(String(300))
|
||||
image_watermarked_path: Mapped[str | None] = mapped_column(String(300))
|
||||
image_thumbnail_path: Mapped[str | None] = mapped_column(String(300))
|
||||
|
||||
|
||||
class Testimonial(TimestampMixin, Base):
|
||||
__tablename__ = "testimonials"
|
||||
__table_args__ = (CheckConstraint("rating BETWEEN 1 AND 5", name="rating_range"),)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
customer_name: Mapped[str] = mapped_column(String(150))
|
||||
designation: Mapped[str | None] = mapped_column(String(150))
|
||||
location: Mapped[str | None] = mapped_column(String(150))
|
||||
content: Mapped[str | None] = mapped_column(Text) # quote; optional for video-only reviews
|
||||
video_url: Mapped[str | None] = mapped_column(String(500)) # YouTube link or direct .mp4 URL
|
||||
rating: Mapped[int] = mapped_column(SmallInteger, default=5, server_default="5")
|
||||
project_id: Mapped[int | None] = mapped_column(
|
||||
ForeignKey("projects.id", ondelete="SET NULL"), index=True
|
||||
)
|
||||
sort_order: Mapped[int] = mapped_column(Integer, default=0, server_default="0")
|
||||
is_published: Mapped[bool] = mapped_column(Boolean, default=True, server_default=true())
|
||||
|
||||
# Optional video still / customer photo (watermarked like every admin upload)
|
||||
image_original_path: Mapped[str | None] = mapped_column(String(300))
|
||||
image_watermarked_path: Mapped[str | None] = mapped_column(String(300))
|
||||
image_thumbnail_path: Mapped[str | None] = mapped_column(String(300))
|
||||
|
||||
|
||||
class Subscriber(TimestampMixin, Base):
|
||||
"""Footer newsletter sign-ups."""
|
||||
|
||||
__tablename__ = "subscribers"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
email: Mapped[str] = mapped_column(String(255), unique=True, index=True)
|
||||
is_active: Mapped[bool] = mapped_column(Boolean, default=True, server_default=true())
|
||||
|
||||
|
||||
class ContactMessage(TimestampMixin, Base):
|
||||
__tablename__ = "contact_messages"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
name: Mapped[str] = mapped_column(String(150))
|
||||
email: Mapped[str] = mapped_column(String(255), index=True)
|
||||
phone: Mapped[str | None] = mapped_column(String(20))
|
||||
subject: Mapped[str | None] = mapped_column(String(200))
|
||||
message: Mapped[str] = mapped_column(Text)
|
||||
is_read: Mapped[bool] = mapped_column(Boolean, default=False, server_default=false(), index=True)
|
||||
|
||||
|
||||
class SiteContent(TimestampMixin, Base):
|
||||
"""Key/value blocks of editable copy (hero text, about text, stats, contact info...).
|
||||
|
||||
The frontend decides which keys exist; values are JSON so each block can hold
|
||||
the exact fields its Figma section needs without schema changes.
|
||||
"""
|
||||
|
||||
__tablename__ = "site_content"
|
||||
|
||||
key: Mapped[str] = mapped_column(String(80), primary_key=True)
|
||||
value: Mapped[dict] = mapped_column(JSONB)
|
||||
updated_by_id: Mapped[int | None] = mapped_column(ForeignKey("admins.id", ondelete="SET NULL"))
|
||||
@@ -0,0 +1,63 @@
|
||||
from decimal import Decimal
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from sqlalchemy import CheckConstraint, ForeignKey, Index, Numeric, String, Text
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.models.base import Base, TimestampMixin
|
||||
from app.models.enums import EnquiryStatus, PropertyType, db_enum
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from app.models.admin import Admin
|
||||
|
||||
|
||||
class Enquiry(TimestampMixin, Base):
|
||||
__tablename__ = "enquiries"
|
||||
__table_args__ = (
|
||||
CheckConstraint("monthly_bill IS NULL OR monthly_bill >= 0", name="monthly_bill_non_negative"),
|
||||
CheckConstraint(
|
||||
"required_capacity_kw IS NULL OR required_capacity_kw > 0", name="capacity_positive"
|
||||
),
|
||||
Index("ix_enquiries_status_created_at", "status", "created_at"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
name: Mapped[str] = mapped_column(String(150))
|
||||
phone: Mapped[str | None] = mapped_column(String(20), index=True) # null for calculator leads
|
||||
email: Mapped[str | None] = mapped_column(String(255), index=True)
|
||||
city: Mapped[str | None] = mapped_column(String(120))
|
||||
address: Mapped[str | None] = mapped_column(String(500))
|
||||
property_type: Mapped[PropertyType | None] = mapped_column(db_enum(PropertyType, "property_type"))
|
||||
monthly_bill: Mapped[Decimal | None] = mapped_column(Numeric(12, 2))
|
||||
required_capacity_kw: Mapped[Decimal | None] = mapped_column(Numeric(10, 2))
|
||||
message: Mapped[str | None] = mapped_column(Text)
|
||||
source: Mapped[str] = mapped_column(String(50), default="website", server_default="website")
|
||||
status: Mapped[EnquiryStatus] = mapped_column(
|
||||
db_enum(EnquiryStatus, "enquiry_status"),
|
||||
default=EnquiryStatus.NEW,
|
||||
server_default=EnquiryStatus.NEW.value,
|
||||
)
|
||||
|
||||
notes: Mapped[list["EnquiryNote"]] = relationship(
|
||||
back_populates="enquiry",
|
||||
cascade="all, delete-orphan",
|
||||
passive_deletes=True,
|
||||
order_by="EnquiryNote.created_at.desc()",
|
||||
)
|
||||
|
||||
|
||||
class EnquiryNote(TimestampMixin, Base):
|
||||
"""Internal notes added by admins; never exposed publicly."""
|
||||
|
||||
__tablename__ = "enquiry_notes"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
enquiry_id: Mapped[int] = mapped_column(
|
||||
ForeignKey("enquiries.id", ondelete="CASCADE"), index=True
|
||||
)
|
||||
author_id: Mapped[int | None] = mapped_column(ForeignKey("admins.id", ondelete="SET NULL"))
|
||||
content: Mapped[str] = mapped_column(Text)
|
||||
|
||||
enquiry: Mapped[Enquiry] = relationship(back_populates="notes")
|
||||
author: Mapped["Admin | None"] = relationship("Admin", lazy="joined")
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import enum
|
||||
|
||||
from sqlalchemy import Enum as SAEnum
|
||||
|
||||
|
||||
class AdminRole(str, enum.Enum):
|
||||
SUPER_ADMIN = "super_admin" # everything, incl. managing admin accounts
|
||||
ADMIN = "admin" # all content + enquiries, incl. deletes
|
||||
EDITOR = "editor" # content (projects/services/testimonials/site content), read enquiries
|
||||
|
||||
|
||||
class EnquiryStatus(str, enum.Enum):
|
||||
NEW = "new"
|
||||
CONTACTED = "contacted"
|
||||
SITE_VISIT_SCHEDULED = "site_visit_scheduled"
|
||||
QUOTATION_SENT = "quotation_sent"
|
||||
CONVERTED = "converted"
|
||||
REJECTED = "rejected"
|
||||
|
||||
|
||||
class PropertyType(str, enum.Enum):
|
||||
RESIDENTIAL = "residential"
|
||||
COMMERCIAL = "commercial"
|
||||
INDUSTRIAL = "industrial"
|
||||
OTHER = "other"
|
||||
|
||||
|
||||
class ProjectCategory(str, enum.Enum):
|
||||
RESIDENTIAL = "residential"
|
||||
COMMERCIAL = "commercial"
|
||||
|
||||
|
||||
class ProjectStatus(str, enum.Enum):
|
||||
ONGOING = "ongoing"
|
||||
COMPLETED = "completed"
|
||||
|
||||
|
||||
def db_enum(enum_cls: type[enum.Enum], name: str) -> SAEnum:
|
||||
"""Portable enum stored as VARCHAR + CHECK constraint (easy to extend in migrations)."""
|
||||
return SAEnum(
|
||||
enum_cls,
|
||||
name=name,
|
||||
native_enum=False,
|
||||
create_constraint=True,
|
||||
length=32,
|
||||
values_callable=lambda e: [m.value for m in e],
|
||||
validate_strings=True,
|
||||
)
|
||||
@@ -0,0 +1,89 @@
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
|
||||
from sqlalchemy import (
|
||||
Boolean,
|
||||
CheckConstraint,
|
||||
Date,
|
||||
ForeignKey,
|
||||
Index,
|
||||
Integer,
|
||||
Numeric,
|
||||
String,
|
||||
Text,
|
||||
false,
|
||||
text,
|
||||
)
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.models.base import Base, TimestampMixin
|
||||
from app.models.enums import ProjectCategory, ProjectStatus, db_enum
|
||||
|
||||
|
||||
class Project(TimestampMixin, Base):
|
||||
__tablename__ = "projects"
|
||||
__table_args__ = (
|
||||
CheckConstraint("capacity_kw IS NULL OR capacity_kw > 0", name="capacity_positive"),
|
||||
Index("ix_projects_published_category", "is_published", "category"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
title: Mapped[str] = mapped_column(String(200))
|
||||
slug: Mapped[str] = mapped_column(String(220), unique=True, index=True)
|
||||
category: Mapped[ProjectCategory] = mapped_column(db_enum(ProjectCategory, "project_category"))
|
||||
location: Mapped[str | None] = mapped_column(String(200))
|
||||
capacity_kw: Mapped[Decimal | None] = mapped_column(Numeric(10, 2))
|
||||
installation_date: Mapped[date | None] = mapped_column(Date)
|
||||
description: Mapped[str | None] = mapped_column(Text)
|
||||
status: Mapped[ProjectStatus] = mapped_column(
|
||||
db_enum(ProjectStatus, "project_status"),
|
||||
default=ProjectStatus.COMPLETED,
|
||||
server_default=ProjectStatus.COMPLETED.value,
|
||||
)
|
||||
is_published: Mapped[bool] = mapped_column(Boolean, default=False, server_default=false())
|
||||
|
||||
images: Mapped[list["ProjectImage"]] = relationship(
|
||||
back_populates="project",
|
||||
cascade="all, delete-orphan",
|
||||
passive_deletes=True,
|
||||
order_by="(ProjectImage.sort_order, ProjectImage.id)",
|
||||
lazy="selectin",
|
||||
)
|
||||
|
||||
@property
|
||||
def featured_image(self) -> "ProjectImage | None":
|
||||
for img in self.images:
|
||||
if img.is_featured:
|
||||
return img
|
||||
return self.images[0] if self.images else None
|
||||
|
||||
|
||||
class ProjectImage(TimestampMixin, Base):
|
||||
__tablename__ = "project_images"
|
||||
__table_args__ = (
|
||||
# At most one featured image per project.
|
||||
Index(
|
||||
"uq_project_images_one_featured",
|
||||
"project_id",
|
||||
unique=True,
|
||||
postgresql_where=text("is_featured"),
|
||||
),
|
||||
CheckConstraint("file_size > 0", name="file_size_positive"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
project_id: Mapped[int] = mapped_column(ForeignKey("projects.id", ondelete="CASCADE"), index=True)
|
||||
original_filename: Mapped[str] = mapped_column(String(255))
|
||||
# Paths are relative to UPLOAD_DIR, e.g. "watermarked/3f2a....jpg"
|
||||
original_path: Mapped[str] = mapped_column(String(300))
|
||||
watermarked_path: Mapped[str] = mapped_column(String(300))
|
||||
thumbnail_path: Mapped[str] = mapped_column(String(300))
|
||||
mime_type: Mapped[str] = mapped_column(String(50))
|
||||
file_size: Mapped[int] = mapped_column(Integer)
|
||||
width: Mapped[int] = mapped_column(Integer)
|
||||
height: Mapped[int] = mapped_column(Integer)
|
||||
caption: Mapped[str | None] = mapped_column(String(300))
|
||||
sort_order: Mapped[int] = mapped_column(Integer, default=0, server_default="0")
|
||||
is_featured: Mapped[bool] = mapped_column(Boolean, default=False, server_default=false())
|
||||
|
||||
project: Mapped[Project] = relationship(back_populates="images")
|
||||
@@ -0,0 +1,99 @@
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy import func, select
|
||||
|
||||
from app.core.config import settings
|
||||
from app.core.deps import CurrentAdmin, DbSession, SuperAdmin
|
||||
from app.core.security import DUMMY_HASH, create_access_token, hash_password, verify_password
|
||||
from app.middleware.rate_limit import RateLimiter
|
||||
from app.models import Admin, AdminRole
|
||||
from app.schemas.auth import (
|
||||
AdminCreate,
|
||||
AdminOut,
|
||||
AdminUpdate,
|
||||
ChangePasswordRequest,
|
||||
LoginRequest,
|
||||
TokenResponse,
|
||||
)
|
||||
from app.schemas.common import MessageResponse
|
||||
|
||||
router = APIRouter(prefix="/auth", tags=["Authentication"])
|
||||
users_router = APIRouter(prefix="/admin/users", tags=["Admin users"])
|
||||
|
||||
login_limiter = RateLimiter("login", settings.LOGIN_RATE_LIMIT_PER_MINUTE)
|
||||
|
||||
|
||||
@router.post("/login", response_model=TokenResponse, dependencies=[Depends(login_limiter)])
|
||||
async def login(body: LoginRequest, db: DbSession):
|
||||
admin = await db.scalar(select(Admin).where(func.lower(Admin.email) == body.email.lower()))
|
||||
# Always run a hash verification so response time doesn't reveal valid emails.
|
||||
valid = verify_password(body.password, admin.hashed_password if admin else DUMMY_HASH)
|
||||
if not admin or not valid:
|
||||
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Incorrect email or password")
|
||||
if not admin.is_active:
|
||||
raise HTTPException(status.HTTP_403_FORBIDDEN, "This account is disabled")
|
||||
|
||||
admin.last_login_at = datetime.now(UTC)
|
||||
await db.commit()
|
||||
await db.refresh(admin)
|
||||
token, expires_in = create_access_token(str(admin.id), admin.role.value)
|
||||
return TokenResponse(access_token=token, expires_in=expires_in, admin=AdminOut.model_validate(admin))
|
||||
|
||||
|
||||
@router.get("/me", response_model=AdminOut)
|
||||
async def me(admin: CurrentAdmin):
|
||||
return admin
|
||||
|
||||
|
||||
@router.post("/change-password", response_model=MessageResponse)
|
||||
async def change_password(body: ChangePasswordRequest, admin: CurrentAdmin, db: DbSession):
|
||||
if not verify_password(body.current_password, admin.hashed_password):
|
||||
raise HTTPException(status.HTTP_400_BAD_REQUEST, "Current password is incorrect")
|
||||
admin.hashed_password = hash_password(body.new_password)
|
||||
await db.commit()
|
||||
return MessageResponse(message="Password updated")
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ admin accounts (super admin)
|
||||
|
||||
|
||||
@users_router.get("", response_model=list[AdminOut])
|
||||
async def list_admins(_: SuperAdmin, db: DbSession):
|
||||
return (await db.scalars(select(Admin).order_by(Admin.id))).all()
|
||||
|
||||
|
||||
@users_router.post("", response_model=AdminOut, status_code=status.HTTP_201_CREATED)
|
||||
async def create_admin(body: AdminCreate, _: SuperAdmin, db: DbSession):
|
||||
email = body.email.lower()
|
||||
if await db.scalar(select(Admin.id).where(func.lower(Admin.email) == email)):
|
||||
raise HTTPException(status.HTTP_409_CONFLICT, "An admin with this email already exists")
|
||||
admin = Admin(
|
||||
email=email,
|
||||
full_name=body.full_name,
|
||||
hashed_password=hash_password(body.password),
|
||||
role=body.role,
|
||||
)
|
||||
db.add(admin)
|
||||
await db.commit()
|
||||
await db.refresh(admin)
|
||||
return admin
|
||||
|
||||
|
||||
@users_router.patch("/{admin_id}", response_model=AdminOut)
|
||||
async def update_admin(admin_id: int, body: AdminUpdate, current: SuperAdmin, db: DbSession):
|
||||
admin = await db.get(Admin, admin_id)
|
||||
if not admin:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "Admin not found")
|
||||
data = body.model_dump(exclude_unset=True)
|
||||
if admin.id == current.id and (
|
||||
data.get("is_active") is False or data.get("role", AdminRole.SUPER_ADMIN) != AdminRole.SUPER_ADMIN
|
||||
):
|
||||
raise HTTPException(status.HTTP_400_BAD_REQUEST, "You cannot demote or disable your own account")
|
||||
if (password := data.pop("password", None)) is not None:
|
||||
admin.hashed_password = hash_password(password)
|
||||
for key, value in data.items():
|
||||
setattr(admin, key, value)
|
||||
await db.commit()
|
||||
await db.refresh(admin)
|
||||
return admin
|
||||
@@ -0,0 +1,117 @@
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
from sqlalchemy import or_, select
|
||||
from sqlalchemy.orm import selectinload
|
||||
|
||||
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, EnquiryNote, EnquiryStatus
|
||||
from app.schemas.common import MessageResponse, Page
|
||||
from app.schemas.enquiry import (
|
||||
EnquiryCreate,
|
||||
EnquiryDetail,
|
||||
EnquiryListItem,
|
||||
EnquiryNoteOut,
|
||||
EnquiryUpdate,
|
||||
)
|
||||
from app.utils.helpers import escape_like, paginate
|
||||
|
||||
public_router = APIRouter(tags=["Enquiries"])
|
||||
admin_router = APIRouter(prefix="/admin/enquiries", tags=["Admin: enquiries"])
|
||||
|
||||
enquiry_limiter = RateLimiter("enquiry", settings.PUBLIC_FORM_RATE_LIMIT_PER_MINUTE)
|
||||
|
||||
THANK_YOU = "Thank you! Our team will contact you shortly."
|
||||
|
||||
|
||||
def _detail(e: Enquiry) -> EnquiryDetail:
|
||||
data = EnquiryListItem.model_validate(e).model_dump()
|
||||
return EnquiryDetail(
|
||||
**data,
|
||||
address=e.address,
|
||||
monthly_bill=float(e.monthly_bill) if e.monthly_bill is not None else None,
|
||||
message=e.message,
|
||||
notes=[EnquiryNoteOut.from_note(n) for n in e.notes],
|
||||
)
|
||||
|
||||
|
||||
async def _get_enquiry(db, enquiry_id: int) -> Enquiry:
|
||||
enquiry = await db.scalar(
|
||||
select(Enquiry)
|
||||
.where(Enquiry.id == enquiry_id)
|
||||
.options(selectinload(Enquiry.notes).joinedload(EnquiryNote.author))
|
||||
)
|
||||
if not enquiry:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "Enquiry not found")
|
||||
return enquiry
|
||||
|
||||
|
||||
@public_router.post(
|
||||
"/enquiries",
|
||||
response_model=MessageResponse,
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
dependencies=[Depends(enquiry_limiter)],
|
||||
summary="Submit a solar enquiry (public website form)",
|
||||
)
|
||||
async def create_enquiry(body: EnquiryCreate, db: DbSession):
|
||||
if body.website: # honeypot filled -> silently ignore bot submission
|
||||
return MessageResponse(message=THANK_YOU)
|
||||
db.add(Enquiry(**body.model_dump(exclude={"website"})))
|
||||
await db.commit()
|
||||
return MessageResponse(message=THANK_YOU)
|
||||
|
||||
|
||||
@admin_router.get("", response_model=Page[EnquiryListItem])
|
||||
async def list_enquiries(
|
||||
_: AnyAdmin,
|
||||
db: DbSession,
|
||||
search: Annotated[str | None, Query(max_length=100, description="Name, phone, email or city")] = None,
|
||||
status_filter: Annotated[EnquiryStatus | None, Query(alias="status")] = None,
|
||||
page: Annotated[int, Query(ge=1)] = 1,
|
||||
page_size: Annotated[int, Query(ge=1, le=100)] = 20,
|
||||
):
|
||||
stmt = select(Enquiry).order_by(Enquiry.created_at.desc(), Enquiry.id.desc())
|
||||
if status_filter:
|
||||
stmt = stmt.where(Enquiry.status == status_filter)
|
||||
if search and (term := search.strip()):
|
||||
like = f"%{escape_like(term)}%"
|
||||
stmt = stmt.where(
|
||||
or_(
|
||||
Enquiry.name.ilike(like),
|
||||
Enquiry.phone.ilike(like),
|
||||
Enquiry.email.ilike(like),
|
||||
Enquiry.city.ilike(like),
|
||||
)
|
||||
)
|
||||
rows, total = await paginate(db, stmt, page, page_size)
|
||||
return Page(items=rows, total=total, page=page, page_size=page_size)
|
||||
|
||||
|
||||
@admin_router.get("/{enquiry_id}", response_model=EnquiryDetail)
|
||||
async def get_enquiry(enquiry_id: int, _: AnyAdmin, db: DbSession):
|
||||
return _detail(await _get_enquiry(db, enquiry_id))
|
||||
|
||||
|
||||
@admin_router.patch("/{enquiry_id}", response_model=EnquiryDetail)
|
||||
async def update_enquiry(enquiry_id: int, body: EnquiryUpdate, admin: AnyAdmin, db: DbSession):
|
||||
if body.status is None and body.note is None:
|
||||
raise HTTPException(status.HTTP_422_UNPROCESSABLE_CONTENT, "Provide a status and/or a note")
|
||||
enquiry = await _get_enquiry(db, enquiry_id)
|
||||
if body.status is not None:
|
||||
enquiry.status = body.status
|
||||
if body.note:
|
||||
db.add(EnquiryNote(enquiry_id=enquiry.id, author_id=admin.id, content=body.note))
|
||||
await db.commit()
|
||||
db.expire(enquiry)
|
||||
return _detail(await _get_enquiry(db, enquiry_id))
|
||||
|
||||
|
||||
@admin_router.delete("/{enquiry_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
async def delete_enquiry(enquiry_id: int, _: ManagerAdmin, db: DbSession):
|
||||
enquiry = await db.get(Enquiry, enquiry_id)
|
||||
if not enquiry:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "Enquiry not found")
|
||||
await db.delete(enquiry)
|
||||
await db.commit()
|
||||
@@ -0,0 +1,308 @@
|
||||
"""Testimonials, contact messages, editable site content, dashboard stats, health."""
|
||||
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from typing import Annotated, Any
|
||||
|
||||
from fastapi import APIRouter, Depends, File, HTTPException, Path, Query, UploadFile, status
|
||||
from sqlalchemy import func, select, text
|
||||
|
||||
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 (
|
||||
ContactMessage,
|
||||
Enquiry,
|
||||
EnquiryStatus,
|
||||
Project,
|
||||
ProjectStatus,
|
||||
Service,
|
||||
SiteContent,
|
||||
Testimonial,
|
||||
)
|
||||
from app.schemas.common import MessageResponse, Page
|
||||
from app.schemas.content import (
|
||||
ContactCreate,
|
||||
ContactOut,
|
||||
ContactUpdate,
|
||||
DashboardStats,
|
||||
SiteContentOut,
|
||||
SiteContentUpsert,
|
||||
TestimonialAdmin,
|
||||
TestimonialCreate,
|
||||
TestimonialPublic,
|
||||
TestimonialUpdate,
|
||||
)
|
||||
from app.routes.single_image import image_files, remove_image, replace_image
|
||||
from app.schemas.enquiry import EnquiryListItem
|
||||
from app.services.image_processing import delete_media_files
|
||||
from app.utils.helpers import paginate
|
||||
|
||||
router = APIRouter()
|
||||
contact_limiter = RateLimiter("contact", settings.PUBLIC_FORM_RATE_LIMIT_PER_MINUTE)
|
||||
|
||||
ContentKey = Annotated[str, Path(min_length=1, max_length=80, pattern=r"^[a-z0-9][a-z0-9_.-]*$")]
|
||||
|
||||
|
||||
async def _ensure_project(db, project_id: int | None) -> None:
|
||||
if project_id is not None and not await db.get(Project, project_id):
|
||||
raise HTTPException(status.HTTP_422_UNPROCESSABLE_CONTENT, "project_id does not exist")
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ health
|
||||
|
||||
|
||||
@router.get("/health", tags=["Health"], summary="API + database health check")
|
||||
async def health(db: DbSession) -> dict[str, Any]:
|
||||
try:
|
||||
await db.execute(text("SELECT 1"))
|
||||
db_ok = True
|
||||
except Exception:
|
||||
db_ok = False
|
||||
if not db_ok:
|
||||
raise HTTPException(status.HTTP_503_SERVICE_UNAVAILABLE, {"status": "error", "database": "unreachable"})
|
||||
return {
|
||||
"status": "ok",
|
||||
"database": "ok",
|
||||
"watermark_logo_present": settings.WATERMARK_LOGO_PATH.is_file(),
|
||||
"environment": settings.ENVIRONMENT,
|
||||
}
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ testimonials
|
||||
|
||||
|
||||
@router.get("/testimonials", response_model=list[TestimonialPublic], tags=["Testimonials"])
|
||||
async def list_testimonials(db: DbSession):
|
||||
rows = await db.scalars(
|
||||
select(Testimonial)
|
||||
.where(Testimonial.is_published.is_(True))
|
||||
.order_by(Testimonial.sort_order, Testimonial.id.desc())
|
||||
)
|
||||
return [TestimonialPublic.build(t) for t in rows]
|
||||
|
||||
|
||||
@router.get("/admin/testimonials", response_model=list[TestimonialAdmin], tags=["Admin: testimonials"])
|
||||
async def admin_list_testimonials(_: AnyAdmin, db: DbSession):
|
||||
rows = await db.scalars(select(Testimonial).order_by(Testimonial.sort_order, Testimonial.id.desc()))
|
||||
return [TestimonialAdmin.build(t) for t in rows]
|
||||
|
||||
|
||||
@router.post(
|
||||
"/admin/testimonials",
|
||||
response_model=TestimonialAdmin,
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
tags=["Admin: testimonials"],
|
||||
)
|
||||
async def create_testimonial(body: TestimonialCreate, _: AnyAdmin, db: DbSession):
|
||||
await _ensure_project(db, body.project_id)
|
||||
item = Testimonial(**body.model_dump())
|
||||
db.add(item)
|
||||
await db.commit()
|
||||
await db.refresh(item)
|
||||
return TestimonialAdmin.build(item)
|
||||
|
||||
|
||||
@router.put("/admin/testimonials/{item_id}", response_model=TestimonialAdmin, tags=["Admin: testimonials"])
|
||||
async def update_testimonial(item_id: int, body: TestimonialUpdate, _: AnyAdmin, db: DbSession):
|
||||
item = await db.get(Testimonial, item_id)
|
||||
if not item:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "Testimonial not found")
|
||||
data = body.model_dump(exclude_unset=True)
|
||||
for required in ("customer_name", "rating", "sort_order", "is_published"):
|
||||
if required in data and data[required] is None:
|
||||
raise HTTPException(status.HTTP_422_UNPROCESSABLE_CONTENT, f"'{required}' cannot be null")
|
||||
if "project_id" in data:
|
||||
await _ensure_project(db, data["project_id"])
|
||||
for key, value in data.items():
|
||||
setattr(item, key, value)
|
||||
await db.commit()
|
||||
await db.refresh(item)
|
||||
return TestimonialAdmin.build(item)
|
||||
|
||||
|
||||
async def _get_testimonial(db, item_id: int) -> Testimonial:
|
||||
item = await db.get(Testimonial, item_id)
|
||||
if not item:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "Testimonial not found")
|
||||
return item
|
||||
|
||||
|
||||
@router.delete(
|
||||
"/admin/testimonials/{item_id}", status_code=status.HTTP_204_NO_CONTENT, tags=["Admin: testimonials"]
|
||||
)
|
||||
async def delete_testimonial(item_id: int, _: AnyAdmin, db: DbSession):
|
||||
item = await _get_testimonial(db, item_id)
|
||||
files = image_files(item)
|
||||
await db.delete(item)
|
||||
await db.commit()
|
||||
delete_media_files(*files)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/admin/testimonials/{item_id}/image",
|
||||
response_model=TestimonialAdmin,
|
||||
tags=["Admin: testimonials"],
|
||||
summary="Upload/replace the video still or customer photo (auto-watermarked)",
|
||||
)
|
||||
async def upload_testimonial_image(
|
||||
item_id: int, _: AnyAdmin, db: DbSession, file: Annotated[UploadFile, File()]
|
||||
):
|
||||
item = await _get_testimonial(db, item_id)
|
||||
await replace_image(db, item, file)
|
||||
return TestimonialAdmin.build(item)
|
||||
|
||||
|
||||
@router.delete(
|
||||
"/admin/testimonials/{item_id}/image", response_model=TestimonialAdmin, tags=["Admin: testimonials"]
|
||||
)
|
||||
async def delete_testimonial_image(item_id: int, _: AnyAdmin, db: DbSession):
|
||||
item = await _get_testimonial(db, item_id)
|
||||
await remove_image(db, item)
|
||||
return TestimonialAdmin.build(item)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ contact messages
|
||||
|
||||
|
||||
@router.post(
|
||||
"/contact",
|
||||
response_model=MessageResponse,
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
dependencies=[Depends(contact_limiter)],
|
||||
tags=["Contact"],
|
||||
summary="Submit the public contact form",
|
||||
)
|
||||
async def create_contact(body: ContactCreate, db: DbSession):
|
||||
if not body.website: # honeypot empty -> real submission
|
||||
db.add(ContactMessage(**body.model_dump(exclude={"website"})))
|
||||
await db.commit()
|
||||
return MessageResponse(message="Thank you for reaching out. We'll get back to you soon.")
|
||||
|
||||
|
||||
@router.get("/admin/contact-messages", response_model=Page[ContactOut], tags=["Admin: contact messages"])
|
||||
async def admin_list_contacts(
|
||||
_: AnyAdmin,
|
||||
db: DbSession,
|
||||
is_read: bool | None = None,
|
||||
page: Annotated[int, Query(ge=1)] = 1,
|
||||
page_size: Annotated[int, Query(ge=1, le=100)] = 20,
|
||||
):
|
||||
stmt = select(ContactMessage).order_by(ContactMessage.created_at.desc(), ContactMessage.id.desc())
|
||||
if is_read is not None:
|
||||
stmt = stmt.where(ContactMessage.is_read.is_(is_read))
|
||||
rows, total = await paginate(db, stmt, page, page_size)
|
||||
return Page(items=rows, total=total, page=page, page_size=page_size)
|
||||
|
||||
|
||||
@router.patch(
|
||||
"/admin/contact-messages/{item_id}", response_model=ContactOut, tags=["Admin: contact messages"]
|
||||
)
|
||||
async def admin_update_contact(item_id: int, body: ContactUpdate, _: AnyAdmin, db: DbSession):
|
||||
item = await db.get(ContactMessage, item_id)
|
||||
if not item:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "Message not found")
|
||||
item.is_read = body.is_read
|
||||
await db.commit()
|
||||
await db.refresh(item)
|
||||
return item
|
||||
|
||||
|
||||
@router.delete(
|
||||
"/admin/contact-messages/{item_id}",
|
||||
status_code=status.HTTP_204_NO_CONTENT,
|
||||
tags=["Admin: contact messages"],
|
||||
)
|
||||
async def admin_delete_contact(item_id: int, _: ManagerAdmin, db: DbSession):
|
||||
item = await db.get(ContactMessage, item_id)
|
||||
if not item:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "Message not found")
|
||||
await db.delete(item)
|
||||
await db.commit()
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ site content
|
||||
|
||||
|
||||
@router.get("/content", response_model=dict[str, dict[str, Any]], tags=["Site content"])
|
||||
async def get_all_content(db: DbSession):
|
||||
"""All editable content blocks as {key: value}."""
|
||||
return {row.key: row.value for row in await db.scalars(select(SiteContent))}
|
||||
|
||||
|
||||
@router.get("/content/{key}", response_model=SiteContentOut, tags=["Site content"])
|
||||
async def get_content(key: ContentKey, db: DbSession):
|
||||
row = await db.get(SiteContent, key)
|
||||
if not row:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "Content block not found")
|
||||
return row
|
||||
|
||||
|
||||
@router.put("/admin/content/{key}", response_model=SiteContentOut, tags=["Admin: site content"])
|
||||
async def upsert_content(key: ContentKey, body: SiteContentUpsert, admin: AnyAdmin, db: DbSession):
|
||||
row = await db.get(SiteContent, key)
|
||||
if row:
|
||||
row.value = body.value
|
||||
row.updated_by_id = admin.id
|
||||
else:
|
||||
row = SiteContent(key=key, value=body.value, updated_by_id=admin.id)
|
||||
db.add(row)
|
||||
await db.commit()
|
||||
await db.refresh(row)
|
||||
return row
|
||||
|
||||
|
||||
@router.delete(
|
||||
"/admin/content/{key}", status_code=status.HTTP_204_NO_CONTENT, tags=["Admin: site content"]
|
||||
)
|
||||
async def delete_content(key: ContentKey, _: ManagerAdmin, db: DbSession):
|
||||
row = await db.get(SiteContent, key)
|
||||
if not row:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "Content block not found")
|
||||
await db.delete(row)
|
||||
await db.commit()
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ dashboard
|
||||
|
||||
|
||||
@router.get("/admin/dashboard/stats", response_model=DashboardStats, tags=["Admin: dashboard"])
|
||||
async def dashboard_stats(_: AnyAdmin, db: DbSession):
|
||||
by_status = dict(
|
||||
(await db.execute(select(Enquiry.status, func.count()).group_by(Enquiry.status))).all()
|
||||
)
|
||||
since = datetime.now(UTC) - timedelta(days=30)
|
||||
project_counts = (
|
||||
await db.execute(
|
||||
select(
|
||||
func.count(),
|
||||
func.count().filter(Project.status == ProjectStatus.COMPLETED),
|
||||
func.count().filter(Project.is_published.is_(True)),
|
||||
)
|
||||
)
|
||||
).one()
|
||||
recent = await db.scalars(select(Enquiry).order_by(Enquiry.created_at.desc(), Enquiry.id.desc()).limit(5))
|
||||
return DashboardStats(
|
||||
total_enquiries=sum(by_status.values()),
|
||||
new_enquiries=by_status.get(EnquiryStatus.NEW, 0),
|
||||
contacted=by_status.get(EnquiryStatus.CONTACTED, 0),
|
||||
site_visits_scheduled=by_status.get(EnquiryStatus.SITE_VISIT_SCHEDULED, 0),
|
||||
quotations_sent=by_status.get(EnquiryStatus.QUOTATION_SENT, 0),
|
||||
converted=by_status.get(EnquiryStatus.CONVERTED, 0),
|
||||
rejected=by_status.get(EnquiryStatus.REJECTED, 0),
|
||||
enquiries_last_30_days=await db.scalar(
|
||||
select(func.count()).select_from(Enquiry).where(Enquiry.created_at >= since)
|
||||
)
|
||||
or 0,
|
||||
total_projects=project_counts[0],
|
||||
completed_projects=project_counts[1],
|
||||
published_projects=project_counts[2],
|
||||
published_services=await db.scalar(
|
||||
select(func.count()).select_from(Service).where(Service.is_published.is_(True))
|
||||
)
|
||||
or 0,
|
||||
unread_contact_messages=await db.scalar(
|
||||
select(func.count()).select_from(ContactMessage).where(ContactMessage.is_read.is_(False))
|
||||
)
|
||||
or 0,
|
||||
recent_enquiries=[EnquiryListItem.model_validate(e) for e in recent],
|
||||
)
|
||||
@@ -0,0 +1,297 @@
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, File, HTTPException, Query, UploadFile, status
|
||||
from fastapi.concurrency import run_in_threadpool
|
||||
from fastapi.responses import FileResponse
|
||||
from sqlalchemy import func, or_, select, update
|
||||
|
||||
from app.core.config import settings
|
||||
from app.core.deps import AnyAdmin, DbSession
|
||||
from app.models import Project, ProjectCategory, ProjectImage, ProjectStatus
|
||||
from app.schemas.common import Page
|
||||
from app.schemas.project import (
|
||||
ProjectAdmin,
|
||||
ProjectCreate,
|
||||
ProjectImageAdmin,
|
||||
ProjectImageUpdate,
|
||||
ProjectPublicDetail,
|
||||
ProjectPublicSummary,
|
||||
ProjectUpdate,
|
||||
UploadResult,
|
||||
)
|
||||
from app.services.image_processing import (
|
||||
ImageValidationError,
|
||||
StoredImage,
|
||||
WatermarkUnavailableError,
|
||||
delete_media_files,
|
||||
load_logo,
|
||||
process_image,
|
||||
read_upload,
|
||||
resolve_media_path,
|
||||
)
|
||||
from app.utils.helpers import escape_like, paginate, unique_slug
|
||||
|
||||
public_router = APIRouter(prefix="/projects", tags=["Projects"])
|
||||
admin_router = APIRouter(prefix="/admin/projects", tags=["Admin: projects"])
|
||||
images_router = APIRouter(prefix="/admin/project-images", tags=["Admin: project images"])
|
||||
|
||||
|
||||
async def _load_project(db, project_id: int) -> Project:
|
||||
project = await db.scalar(
|
||||
select(Project).where(Project.id == project_id).execution_options(populate_existing=True)
|
||||
)
|
||||
if not project:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "Project not found")
|
||||
return project
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ public
|
||||
|
||||
|
||||
@public_router.get("", response_model=Page[ProjectPublicSummary], summary="Published projects")
|
||||
async def list_published_projects(
|
||||
db: DbSession,
|
||||
category: ProjectCategory | None = None,
|
||||
project_status: Annotated[ProjectStatus | None, Query(alias="status")] = None,
|
||||
page: Annotated[int, Query(ge=1)] = 1,
|
||||
page_size: Annotated[int, Query(ge=1, le=100)] = 12,
|
||||
):
|
||||
stmt = (
|
||||
select(Project)
|
||||
.where(Project.is_published.is_(True))
|
||||
.order_by(Project.installation_date.desc().nulls_last(), Project.id.desc())
|
||||
)
|
||||
if category:
|
||||
stmt = stmt.where(Project.category == category)
|
||||
if project_status:
|
||||
stmt = stmt.where(Project.status == project_status)
|
||||
rows, total = await paginate(db, stmt, page, page_size)
|
||||
return Page(items=[ProjectPublicSummary.build(p) for p in rows], total=total, page=page, page_size=page_size)
|
||||
|
||||
|
||||
@public_router.get("/{id_or_slug}", response_model=ProjectPublicDetail, summary="Project by id or slug")
|
||||
async def get_published_project(id_or_slug: str, db: DbSession):
|
||||
cond = Project.id == int(id_or_slug) if id_or_slug.isdigit() else Project.slug == id_or_slug
|
||||
project = await db.scalar(select(Project).where(cond, Project.is_published.is_(True)))
|
||||
if not project:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "Project not found")
|
||||
return ProjectPublicDetail.build(project)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ admin CRUD
|
||||
|
||||
|
||||
@admin_router.get("", response_model=Page[ProjectAdmin])
|
||||
async def admin_list_projects(
|
||||
_: AnyAdmin,
|
||||
db: DbSession,
|
||||
search: Annotated[str | None, Query(max_length=100)] = None,
|
||||
category: ProjectCategory | None = None,
|
||||
project_status: Annotated[ProjectStatus | None, Query(alias="status")] = None,
|
||||
is_published: bool | None = None,
|
||||
page: Annotated[int, Query(ge=1)] = 1,
|
||||
page_size: Annotated[int, Query(ge=1, le=100)] = 20,
|
||||
):
|
||||
stmt = select(Project).order_by(Project.created_at.desc(), Project.id.desc())
|
||||
if search and (term := search.strip()):
|
||||
like = f"%{escape_like(term)}%"
|
||||
stmt = stmt.where(or_(Project.title.ilike(like), Project.location.ilike(like)))
|
||||
if category:
|
||||
stmt = stmt.where(Project.category == category)
|
||||
if project_status:
|
||||
stmt = stmt.where(Project.status == project_status)
|
||||
if is_published is not None:
|
||||
stmt = stmt.where(Project.is_published.is_(is_published))
|
||||
rows, total = await paginate(db, stmt, page, page_size)
|
||||
return Page(items=[ProjectAdmin.build(p) for p in rows], total=total, page=page, page_size=page_size)
|
||||
|
||||
|
||||
@admin_router.get("/{project_id}", response_model=ProjectAdmin)
|
||||
async def admin_get_project(project_id: int, _: AnyAdmin, db: DbSession):
|
||||
return ProjectAdmin.build(await _load_project(db, project_id))
|
||||
|
||||
|
||||
@admin_router.post("", response_model=ProjectAdmin, status_code=status.HTTP_201_CREATED)
|
||||
async def create_project(body: ProjectCreate, _: AnyAdmin, db: DbSession):
|
||||
data = body.model_dump()
|
||||
data["slug"] = await unique_slug(db, Project, data["slug"] or data["title"])
|
||||
project = Project(**data)
|
||||
db.add(project)
|
||||
await db.commit()
|
||||
return ProjectAdmin.build(await _load_project(db, project.id))
|
||||
|
||||
|
||||
@admin_router.put("/{project_id}", response_model=ProjectAdmin)
|
||||
async def update_project(project_id: int, body: ProjectUpdate, _: AnyAdmin, db: DbSession):
|
||||
project = await _load_project(db, project_id)
|
||||
data = body.model_dump(exclude_unset=True)
|
||||
for required in ("title", "category", "status", "is_published"):
|
||||
if required in data and data[required] is None:
|
||||
raise HTTPException(status.HTTP_422_UNPROCESSABLE_CONTENT, f"'{required}' cannot be null")
|
||||
if data.get("slug"):
|
||||
data["slug"] = await unique_slug(db, Project, data["slug"], exclude_id=project.id)
|
||||
else:
|
||||
data.pop("slug", None)
|
||||
for key, value in data.items():
|
||||
setattr(project, key, value)
|
||||
await db.commit()
|
||||
return ProjectAdmin.build(await _load_project(db, project_id))
|
||||
|
||||
|
||||
@admin_router.delete("/{project_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
async def delete_project(project_id: int, _: AnyAdmin, db: DbSession):
|
||||
project = await _load_project(db, project_id)
|
||||
files = [p for img in project.images for p in (img.original_path, img.watermarked_path, img.thumbnail_path)]
|
||||
await db.delete(project)
|
||||
await db.commit()
|
||||
delete_media_files(*files) # only after the DB change succeeded
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ images
|
||||
|
||||
|
||||
@admin_router.post(
|
||||
"/{project_id}/images",
|
||||
response_model=UploadResult,
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
summary="Upload one or more photos (auto-watermarked)",
|
||||
description=(
|
||||
"Accepts JPG/JPEG/PNG/WEBP. Each file is validated, the original is stored privately, "
|
||||
"a copy with the Saura Shakti logo watermark (bottom-right) is generated, plus a WEBP thumbnail. "
|
||||
"If any file is invalid the whole batch is rejected and nothing is saved."
|
||||
),
|
||||
)
|
||||
async def upload_project_images(
|
||||
project_id: int,
|
||||
_: AnyAdmin,
|
||||
db: DbSession,
|
||||
files: Annotated[list[UploadFile], File(description="Image files (field name: files)")],
|
||||
):
|
||||
project = await _load_project(db, project_id)
|
||||
if not files:
|
||||
raise HTTPException(status.HTTP_400_BAD_REQUEST, "No files uploaded")
|
||||
if len(files) > settings.MAX_FILES_PER_UPLOAD:
|
||||
raise HTTPException(
|
||||
status.HTTP_400_BAD_REQUEST, f"Upload at most {settings.MAX_FILES_PER_UPLOAD} files at a time"
|
||||
)
|
||||
try:
|
||||
load_logo()
|
||||
except WatermarkUnavailableError as exc:
|
||||
raise HTTPException(status.HTTP_503_SERVICE_UNAVAILABLE, str(exc)) from None
|
||||
|
||||
# 1. validate every file before touching disk
|
||||
validated, errors, worst = [], [], status.HTTP_400_BAD_REQUEST
|
||||
for f in files:
|
||||
try:
|
||||
validated.append(await read_upload(f))
|
||||
except ImageValidationError as exc:
|
||||
errors.append(exc.message)
|
||||
worst = exc.status_code
|
||||
if errors:
|
||||
raise HTTPException(worst if len(errors) == 1 else status.HTTP_400_BAD_REQUEST, {"errors": errors})
|
||||
|
||||
# 2. process (watermark + thumbnail) off the event loop
|
||||
stored: list[StoredImage] = []
|
||||
try:
|
||||
for v in validated:
|
||||
stored.append(await run_in_threadpool(process_image, v))
|
||||
|
||||
next_order = (
|
||||
await db.scalar(
|
||||
select(func.coalesce(func.max(ProjectImage.sort_order), -1)).where(
|
||||
ProjectImage.project_id == project.id
|
||||
)
|
||||
)
|
||||
) + 1
|
||||
has_featured = any(img.is_featured for img in project.images)
|
||||
new_rows = []
|
||||
for i, (v, s) in enumerate(zip(validated, stored, strict=True)):
|
||||
row = ProjectImage(
|
||||
project_id=project.id,
|
||||
original_filename=v.original_filename,
|
||||
original_path=s.original_path,
|
||||
watermarked_path=s.watermarked_path,
|
||||
thumbnail_path=s.thumbnail_path,
|
||||
mime_type=s.mime_type,
|
||||
file_size=s.file_size,
|
||||
width=s.width,
|
||||
height=s.height,
|
||||
sort_order=next_order + i,
|
||||
is_featured=not has_featured and i == 0,
|
||||
)
|
||||
db.add(row)
|
||||
new_rows.append(row)
|
||||
await db.commit()
|
||||
except Exception:
|
||||
await db.rollback()
|
||||
delete_media_files(*[p for s in stored for p in (s.original_path, s.watermarked_path, s.thumbnail_path)])
|
||||
raise
|
||||
|
||||
project = await _load_project(db, project_id)
|
||||
ids = {r.id for r in new_rows}
|
||||
return UploadResult(
|
||||
uploaded=[ProjectImageAdmin.build(img) for img in project.images if img.id in ids],
|
||||
project=ProjectAdmin.build(project),
|
||||
)
|
||||
|
||||
|
||||
async def _get_image(db, image_id: int) -> ProjectImage:
|
||||
image = await db.get(ProjectImage, image_id)
|
||||
if not image:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "Image not found")
|
||||
return image
|
||||
|
||||
|
||||
@images_router.patch("/{image_id}", response_model=ProjectAdmin, summary="Edit caption/order or set as featured")
|
||||
async def update_project_image(image_id: int, body: ProjectImageUpdate, _: AnyAdmin, db: DbSession):
|
||||
image = await _get_image(db, image_id)
|
||||
data = body.model_dump(exclude_unset=True)
|
||||
if data.get("is_featured") is True:
|
||||
await db.execute(
|
||||
update(ProjectImage)
|
||||
.where(ProjectImage.project_id == image.project_id, ProjectImage.id != image.id)
|
||||
.values(is_featured=False)
|
||||
)
|
||||
await db.flush()
|
||||
for key, value in data.items():
|
||||
if value is None and key in ("sort_order", "is_featured"):
|
||||
continue
|
||||
setattr(image, key, value)
|
||||
await db.commit()
|
||||
return ProjectAdmin.build(await _load_project(db, image.project_id))
|
||||
|
||||
|
||||
@images_router.delete("/{image_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
async def delete_project_image(image_id: int, _: AnyAdmin, db: DbSession):
|
||||
image = await _get_image(db, image_id)
|
||||
project_id, was_featured = image.project_id, image.is_featured
|
||||
files = (image.original_path, image.watermarked_path, image.thumbnail_path)
|
||||
await db.delete(image)
|
||||
await db.flush()
|
||||
if was_featured: # promote the next image so the project keeps a cover photo
|
||||
next_img = await db.scalar(
|
||||
select(ProjectImage)
|
||||
.where(ProjectImage.project_id == project_id)
|
||||
.order_by(ProjectImage.sort_order, ProjectImage.id)
|
||||
.limit(1)
|
||||
)
|
||||
if next_img:
|
||||
next_img.is_featured = True
|
||||
await db.commit()
|
||||
delete_media_files(*files)
|
||||
|
||||
|
||||
@images_router.get(
|
||||
"/{image_id}/original",
|
||||
response_class=FileResponse,
|
||||
summary="Download the un-watermarked original (admin only)",
|
||||
)
|
||||
async def download_original(image_id: int, _: AnyAdmin, db: DbSession):
|
||||
image = await _get_image(db, image_id)
|
||||
try:
|
||||
path = resolve_media_path(image.original_path)
|
||||
except ValueError:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "File not found") from None
|
||||
if not path.is_file():
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "File not found")
|
||||
return FileResponse(path, media_type=image.mime_type, filename=image.original_filename)
|
||||
@@ -0,0 +1,188 @@
|
||||
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()
|
||||
@@ -0,0 +1,114 @@
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, File, HTTPException, Query, UploadFile, status
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.core.deps import AnyAdmin, DbSession
|
||||
from app.models import Service
|
||||
from app.schemas.content import ServiceAdmin, ServiceCreate, ServicePublic, ServiceUpdate
|
||||
from app.routes.single_image import image_files, remove_image, replace_image
|
||||
from app.services.image_processing import delete_media_files
|
||||
from app.utils.helpers import unique_slug
|
||||
|
||||
public_router = APIRouter(prefix="/services", tags=["Services"])
|
||||
admin_router = APIRouter(prefix="/admin/services", tags=["Admin: services"])
|
||||
|
||||
_ORDER = (Service.sort_order, Service.id)
|
||||
|
||||
|
||||
async def _get(db, service_id: int) -> Service:
|
||||
service = await db.get(Service, service_id)
|
||||
if not service:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "Service not found")
|
||||
return service
|
||||
|
||||
|
||||
@public_router.get("", response_model=list[ServicePublic], summary="Published services")
|
||||
async def list_services(db: DbSession):
|
||||
rows = await db.scalars(select(Service).where(Service.is_published.is_(True)).order_by(*_ORDER))
|
||||
return [ServicePublic.build(s) for s in rows]
|
||||
|
||||
|
||||
@public_router.get("/{id_or_slug}", response_model=ServicePublic)
|
||||
async def get_service(id_or_slug: str, db: DbSession):
|
||||
cond = Service.id == int(id_or_slug) if id_or_slug.isdigit() else Service.slug == id_or_slug
|
||||
service = await db.scalar(select(Service).where(cond, Service.is_published.is_(True)))
|
||||
if not service:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "Service not found")
|
||||
return ServicePublic.build(service)
|
||||
|
||||
|
||||
@admin_router.get("", response_model=list[ServiceAdmin])
|
||||
async def admin_list_services(
|
||||
_: AnyAdmin, db: DbSession, is_published: Annotated[bool | None, Query()] = None
|
||||
):
|
||||
stmt = select(Service).order_by(*_ORDER)
|
||||
if is_published is not None:
|
||||
stmt = stmt.where(Service.is_published.is_(is_published))
|
||||
return [ServiceAdmin.build(s) for s in await db.scalars(stmt)]
|
||||
|
||||
|
||||
@admin_router.get("/{service_id}", response_model=ServiceAdmin)
|
||||
async def admin_get_service(service_id: int, _: AnyAdmin, db: DbSession):
|
||||
return ServiceAdmin.build(await _get(db, service_id))
|
||||
|
||||
|
||||
@admin_router.post("", response_model=ServiceAdmin, status_code=status.HTTP_201_CREATED)
|
||||
async def create_service(body: ServiceCreate, _: AnyAdmin, db: DbSession):
|
||||
data = body.model_dump()
|
||||
data["slug"] = await unique_slug(db, Service, data["slug"] or data["title"])
|
||||
service = Service(**data)
|
||||
db.add(service)
|
||||
await db.commit()
|
||||
await db.refresh(service)
|
||||
return ServiceAdmin.build(service)
|
||||
|
||||
|
||||
@admin_router.put("/{service_id}", response_model=ServiceAdmin)
|
||||
async def update_service(service_id: int, body: ServiceUpdate, _: AnyAdmin, db: DbSession):
|
||||
service = await _get(db, service_id)
|
||||
data = body.model_dump(exclude_unset=True)
|
||||
for required in ("title", "sort_order", "is_published"):
|
||||
if required in data and data[required] is None:
|
||||
raise HTTPException(status.HTTP_422_UNPROCESSABLE_CONTENT, f"'{required}' cannot be null")
|
||||
if data.get("slug"):
|
||||
data["slug"] = await unique_slug(db, Service, data["slug"], exclude_id=service.id)
|
||||
else:
|
||||
data.pop("slug", None)
|
||||
for key, value in data.items():
|
||||
setattr(service, key, value)
|
||||
await db.commit()
|
||||
await db.refresh(service)
|
||||
return ServiceAdmin.build(service)
|
||||
|
||||
|
||||
@admin_router.delete("/{service_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
async def delete_service(service_id: int, _: AnyAdmin, db: DbSession):
|
||||
service = await _get(db, service_id)
|
||||
files = image_files(service)
|
||||
await db.delete(service)
|
||||
await db.commit()
|
||||
delete_media_files(*files)
|
||||
|
||||
|
||||
@admin_router.post(
|
||||
"/{service_id}/image",
|
||||
response_model=ServiceAdmin,
|
||||
summary="Upload/replace the service image (auto-watermarked)",
|
||||
)
|
||||
async def upload_service_image(
|
||||
service_id: int,
|
||||
_: AnyAdmin,
|
||||
db: DbSession,
|
||||
file: Annotated[UploadFile, File(description="JPG/JPEG/PNG/WEBP image")],
|
||||
):
|
||||
service = await _get(db, service_id)
|
||||
await replace_image(db, service, file)
|
||||
return ServiceAdmin.build(service)
|
||||
|
||||
|
||||
@admin_router.delete("/{service_id}/image", response_model=ServiceAdmin)
|
||||
async def delete_service_image(service_id: int, _: AnyAdmin, db: DbSession):
|
||||
service = await _get(db, service_id)
|
||||
await remove_image(db, service)
|
||||
return ServiceAdmin.build(service)
|
||||
@@ -0,0 +1,54 @@
|
||||
"""Shared upload/remove logic for models holding one watermarked image
|
||||
(columns image_original_path / image_watermarked_path / image_thumbnail_path)."""
|
||||
|
||||
from fastapi import HTTPException, UploadFile, status
|
||||
from fastapi.concurrency import run_in_threadpool
|
||||
|
||||
from app.services.image_processing import (
|
||||
ImageValidationError,
|
||||
WatermarkUnavailableError,
|
||||
delete_media_files,
|
||||
load_logo,
|
||||
process_image,
|
||||
read_upload,
|
||||
)
|
||||
|
||||
_COLS = ("image_original_path", "image_watermarked_path", "image_thumbnail_path")
|
||||
|
||||
|
||||
async def replace_image(db, obj, file: UploadFile) -> None:
|
||||
try:
|
||||
load_logo()
|
||||
except WatermarkUnavailableError as exc:
|
||||
raise HTTPException(status.HTTP_503_SERVICE_UNAVAILABLE, str(exc)) from None
|
||||
try:
|
||||
validated = await read_upload(file)
|
||||
except ImageValidationError as exc:
|
||||
raise HTTPException(exc.status_code, {"errors": [exc.message]}) from None
|
||||
|
||||
stored = await run_in_threadpool(process_image, validated)
|
||||
old = tuple(getattr(obj, c) for c in _COLS)
|
||||
obj.image_original_path = stored.original_path
|
||||
obj.image_watermarked_path = stored.watermarked_path
|
||||
obj.image_thumbnail_path = stored.thumbnail_path
|
||||
try:
|
||||
await db.commit()
|
||||
except Exception:
|
||||
await db.rollback()
|
||||
delete_media_files(stored.original_path, stored.watermarked_path, stored.thumbnail_path)
|
||||
raise
|
||||
delete_media_files(*old)
|
||||
await db.refresh(obj)
|
||||
|
||||
|
||||
async def remove_image(db, obj) -> None:
|
||||
old = tuple(getattr(obj, c) for c in _COLS)
|
||||
for c in _COLS:
|
||||
setattr(obj, c, None)
|
||||
await db.commit()
|
||||
delete_media_files(*old)
|
||||
await db.refresh(obj)
|
||||
|
||||
|
||||
def image_files(obj) -> tuple:
|
||||
return tuple(getattr(obj, c) for c in _COLS)
|
||||
@@ -0,0 +1,70 @@
|
||||
from datetime import datetime
|
||||
|
||||
from pydantic import BaseModel, EmailStr, Field, field_validator
|
||||
|
||||
from app.models.enums import AdminRole
|
||||
from app.schemas.common import InputModel, OrmModel
|
||||
|
||||
|
||||
def _password_strength(value: str) -> str:
|
||||
if len(value) < 10:
|
||||
raise ValueError("Password must be at least 10 characters")
|
||||
if not any(c.isalpha() for c in value) or not any(c.isdigit() for c in value):
|
||||
raise ValueError("Password must contain letters and numbers")
|
||||
return value
|
||||
|
||||
|
||||
class LoginRequest(InputModel):
|
||||
email: EmailStr
|
||||
password: str = Field(min_length=1, max_length=256)
|
||||
|
||||
|
||||
class AdminOut(OrmModel):
|
||||
id: int
|
||||
email: EmailStr
|
||||
full_name: str
|
||||
role: AdminRole
|
||||
is_active: bool
|
||||
last_login_at: datetime | None
|
||||
created_at: datetime
|
||||
|
||||
|
||||
class TokenResponse(BaseModel):
|
||||
access_token: str
|
||||
token_type: str = "bearer"
|
||||
expires_in: int
|
||||
admin: AdminOut
|
||||
|
||||
|
||||
class ChangePasswordRequest(InputModel):
|
||||
current_password: str = Field(min_length=1, max_length=256)
|
||||
new_password: str = Field(max_length=256)
|
||||
|
||||
@field_validator("new_password")
|
||||
@classmethod
|
||||
def _pw(cls, v: str) -> str:
|
||||
return _password_strength(v)
|
||||
|
||||
|
||||
class AdminCreate(InputModel):
|
||||
email: EmailStr
|
||||
full_name: str = Field(min_length=2, max_length=150)
|
||||
password: str = Field(max_length=256)
|
||||
role: AdminRole = AdminRole.ADMIN
|
||||
|
||||
@field_validator("password")
|
||||
@classmethod
|
||||
def _pw(cls, v: str) -> str:
|
||||
return _password_strength(v)
|
||||
|
||||
|
||||
class AdminUpdate(InputModel):
|
||||
full_name: str | None = Field(default=None, min_length=2, max_length=150)
|
||||
role: AdminRole | None = None
|
||||
is_active: bool | None = None
|
||||
password: str | None = Field(default=None, max_length=256)
|
||||
|
||||
@field_validator("password")
|
||||
@classmethod
|
||||
def _pw(cls, v: str | None) -> str | None:
|
||||
return None if v is None else _password_strength(v)
|
||||
@@ -0,0 +1,41 @@
|
||||
import re
|
||||
from typing import Annotated, Generic, TypeVar
|
||||
|
||||
from pydantic import AfterValidator, BaseModel, ConfigDict
|
||||
|
||||
T = TypeVar("T")
|
||||
|
||||
_PHONE_ALLOWED = re.compile(r"^\+?[0-9\s\-()]{7,20}$")
|
||||
|
||||
|
||||
def _validate_phone(value: str) -> str:
|
||||
value = value.strip()
|
||||
if not _PHONE_ALLOWED.match(value):
|
||||
raise ValueError("Enter a valid phone number")
|
||||
digits = re.sub(r"\D", "", value)
|
||||
if not 7 <= len(digits) <= 15:
|
||||
raise ValueError("Phone number must have 7 to 15 digits")
|
||||
return ("+" if value.startswith("+") else "") + digits
|
||||
|
||||
|
||||
Phone = Annotated[str, AfterValidator(_validate_phone)]
|
||||
|
||||
|
||||
class InputModel(BaseModel):
|
||||
model_config = ConfigDict(str_strip_whitespace=True, extra="forbid")
|
||||
|
||||
|
||||
class OrmModel(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
|
||||
class Page(BaseModel, Generic[T]):
|
||||
items: list[T]
|
||||
total: int
|
||||
page: int
|
||||
page_size: int
|
||||
|
||||
|
||||
class MessageResponse(BaseModel):
|
||||
success: bool = True
|
||||
message: str
|
||||
@@ -0,0 +1,230 @@
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from pydantic import BaseModel, EmailStr, Field, field_validator
|
||||
|
||||
from app.schemas.common import InputModel, OrmModel, Phone
|
||||
from app.schemas.enquiry import EnquiryListItem
|
||||
from app.services.image_processing import media_url
|
||||
|
||||
# ----------------------------------------------------------------- services
|
||||
|
||||
|
||||
class ServicePublic(BaseModel):
|
||||
id: int
|
||||
title: str
|
||||
slug: str
|
||||
short_description: str | None
|
||||
description: str | None
|
||||
icon: str | None
|
||||
sort_order: int
|
||||
image_url: str | None
|
||||
thumbnail_url: str | None
|
||||
|
||||
@staticmethod
|
||||
def _fields(s) -> dict:
|
||||
return {
|
||||
"id": s.id,
|
||||
"title": s.title,
|
||||
"slug": s.slug,
|
||||
"short_description": s.short_description,
|
||||
"description": s.description,
|
||||
"icon": s.icon,
|
||||
"sort_order": s.sort_order,
|
||||
"image_url": media_url(s.image_watermarked_path),
|
||||
"thumbnail_url": media_url(s.image_thumbnail_path),
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def build(cls, s) -> "ServicePublic":
|
||||
return cls(**cls._fields(s))
|
||||
|
||||
|
||||
class ServiceAdmin(ServicePublic):
|
||||
is_published: bool
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
@classmethod
|
||||
def build(cls, s) -> "ServiceAdmin":
|
||||
return cls(
|
||||
**cls._fields(s),
|
||||
is_published=s.is_published,
|
||||
created_at=s.created_at,
|
||||
updated_at=s.updated_at,
|
||||
)
|
||||
|
||||
|
||||
class ServiceCreate(InputModel):
|
||||
title: str = Field(min_length=2, max_length=150)
|
||||
slug: str | None = Field(default=None, max_length=150, pattern=r"^[a-z0-9]+(?:-[a-z0-9]+)*$")
|
||||
short_description: str | None = Field(default=None, max_length=300)
|
||||
description: str | None = Field(default=None, max_length=10_000)
|
||||
icon: str | None = Field(default=None, max_length=60)
|
||||
sort_order: int = Field(default=0, ge=0, le=100_000)
|
||||
is_published: bool = False
|
||||
|
||||
|
||||
class ServiceUpdate(InputModel):
|
||||
title: str | None = Field(default=None, min_length=2, max_length=150)
|
||||
slug: str | None = Field(default=None, max_length=150, pattern=r"^[a-z0-9]+(?:-[a-z0-9]+)*$")
|
||||
short_description: str | None = Field(default=None, max_length=300)
|
||||
description: str | None = Field(default=None, max_length=10_000)
|
||||
icon: str | None = Field(default=None, max_length=60)
|
||||
sort_order: int | None = Field(default=None, ge=0, le=100_000)
|
||||
is_published: bool | None = None
|
||||
|
||||
|
||||
# ----------------------------------------------------------------- testimonials
|
||||
|
||||
|
||||
def _check_video_url(v: str | None) -> str | None:
|
||||
if v is None or not v.strip():
|
||||
return None
|
||||
v = v.strip()
|
||||
if not v.lower().startswith(("https://", "http://")):
|
||||
raise ValueError("Video link must start with https://")
|
||||
return v
|
||||
|
||||
|
||||
class TestimonialPublic(BaseModel):
|
||||
id: int
|
||||
customer_name: str
|
||||
designation: str | None
|
||||
location: str | None
|
||||
content: str | None
|
||||
video_url: str | None
|
||||
rating: int
|
||||
project_id: int | None
|
||||
sort_order: int
|
||||
image_url: str | None
|
||||
thumbnail_url: str | None
|
||||
|
||||
@staticmethod
|
||||
def _fields(t) -> dict:
|
||||
return {
|
||||
"id": t.id,
|
||||
"customer_name": t.customer_name,
|
||||
"designation": t.designation,
|
||||
"location": t.location,
|
||||
"content": t.content,
|
||||
"video_url": t.video_url,
|
||||
"rating": t.rating,
|
||||
"project_id": t.project_id,
|
||||
"sort_order": t.sort_order,
|
||||
"image_url": media_url(t.image_watermarked_path),
|
||||
"thumbnail_url": media_url(t.image_thumbnail_path),
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def build(cls, t) -> "TestimonialPublic":
|
||||
return cls(**cls._fields(t))
|
||||
|
||||
|
||||
class TestimonialAdmin(TestimonialPublic):
|
||||
is_published: bool
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
@classmethod
|
||||
def build(cls, t) -> "TestimonialAdmin":
|
||||
return cls(**cls._fields(t), is_published=t.is_published, created_at=t.created_at, updated_at=t.updated_at)
|
||||
|
||||
|
||||
class TestimonialCreate(InputModel):
|
||||
customer_name: str = Field(min_length=2, max_length=150)
|
||||
designation: str | None = Field(default=None, max_length=150)
|
||||
location: str | None = Field(default=None, max_length=150)
|
||||
content: str | None = Field(default=None, max_length=3000)
|
||||
video_url: str | None = Field(default=None, max_length=500)
|
||||
rating: int = Field(default=5, ge=1, le=5)
|
||||
project_id: int | None = None
|
||||
sort_order: int = Field(default=0, ge=0, le=100_000)
|
||||
is_published: bool = True
|
||||
|
||||
@field_validator("video_url")
|
||||
@classmethod
|
||||
def _video(cls, v: str | None) -> str | None:
|
||||
return _check_video_url(v)
|
||||
|
||||
|
||||
class TestimonialUpdate(InputModel):
|
||||
customer_name: str | None = Field(default=None, min_length=2, max_length=150)
|
||||
designation: str | None = Field(default=None, max_length=150)
|
||||
location: str | None = Field(default=None, max_length=150)
|
||||
content: str | None = Field(default=None, max_length=3000)
|
||||
video_url: str | None = Field(default=None, max_length=500)
|
||||
rating: int | None = Field(default=None, ge=1, le=5)
|
||||
project_id: int | None = None
|
||||
sort_order: int | None = Field(default=None, ge=0, le=100_000)
|
||||
is_published: bool | None = None
|
||||
|
||||
@field_validator("video_url")
|
||||
@classmethod
|
||||
def _video(cls, v: str | None) -> str | None:
|
||||
return _check_video_url(v)
|
||||
|
||||
|
||||
# ----------------------------------------------------------------- contact messages
|
||||
|
||||
|
||||
class ContactCreate(InputModel):
|
||||
name: str = Field(min_length=2, max_length=150)
|
||||
email: EmailStr
|
||||
phone: Phone | None = None
|
||||
subject: str | None = Field(default=None, max_length=200)
|
||||
message: str = Field(min_length=5, max_length=5000)
|
||||
website: str | None = Field(default=None, max_length=200) # honeypot
|
||||
|
||||
@field_validator("phone", "subject", "website", mode="before")
|
||||
@classmethod
|
||||
def _blank_to_none(cls, v):
|
||||
return None if isinstance(v, str) and not v.strip() else v
|
||||
|
||||
|
||||
class ContactOut(OrmModel):
|
||||
id: int
|
||||
name: str
|
||||
email: str
|
||||
phone: str | None
|
||||
subject: str | None
|
||||
message: str
|
||||
is_read: bool
|
||||
created_at: datetime
|
||||
|
||||
|
||||
class ContactUpdate(InputModel):
|
||||
is_read: bool
|
||||
|
||||
|
||||
# ----------------------------------------------------------------- site content
|
||||
|
||||
|
||||
class SiteContentOut(OrmModel):
|
||||
key: str
|
||||
value: dict[str, Any]
|
||||
updated_at: datetime
|
||||
|
||||
|
||||
class SiteContentUpsert(InputModel):
|
||||
value: dict[str, Any] = Field(description="Arbitrary JSON object for this content block")
|
||||
|
||||
|
||||
# ----------------------------------------------------------------- dashboard
|
||||
|
||||
|
||||
class DashboardStats(BaseModel):
|
||||
total_enquiries: int
|
||||
new_enquiries: int
|
||||
contacted: int
|
||||
site_visits_scheduled: int
|
||||
quotations_sent: int
|
||||
converted: int
|
||||
rejected: int
|
||||
enquiries_last_30_days: int
|
||||
completed_projects: int
|
||||
published_projects: int
|
||||
total_projects: int
|
||||
published_services: int
|
||||
unread_contact_messages: int
|
||||
recent_enquiries: list[EnquiryListItem]
|
||||
@@ -0,0 +1,67 @@
|
||||
from datetime import datetime
|
||||
|
||||
from pydantic import EmailStr, Field, field_validator
|
||||
|
||||
from app.models.enums import EnquiryStatus, PropertyType
|
||||
from app.schemas.common import InputModel, OrmModel, Phone
|
||||
|
||||
|
||||
class EnquiryCreate(InputModel):
|
||||
name: str = Field(min_length=2, max_length=150)
|
||||
phone: Phone
|
||||
email: EmailStr | None = None
|
||||
city: str | None = Field(default=None, max_length=120)
|
||||
address: str | None = Field(default=None, max_length=500)
|
||||
property_type: PropertyType | None = None
|
||||
monthly_bill: float | None = Field(default=None, ge=0, le=100_000_000)
|
||||
required_capacity_kw: float | None = Field(default=None, gt=0, le=100_000)
|
||||
message: str | None = Field(default=None, max_length=2000)
|
||||
# Honeypot: real users never see/fill this field; bots often do.
|
||||
website: str | None = Field(default=None, max_length=200)
|
||||
|
||||
@field_validator("email", "city", "address", "message", "website", mode="before")
|
||||
@classmethod
|
||||
def _blank_to_none(cls, v):
|
||||
return None if isinstance(v, str) and not v.strip() else v
|
||||
|
||||
|
||||
class EnquiryNoteOut(OrmModel):
|
||||
id: int
|
||||
content: str
|
||||
author_name: str | None = None
|
||||
created_at: datetime
|
||||
|
||||
@classmethod
|
||||
def from_note(cls, note) -> "EnquiryNoteOut":
|
||||
return cls(
|
||||
id=note.id,
|
||||
content=note.content,
|
||||
author_name=note.author.full_name if note.author else None,
|
||||
created_at=note.created_at,
|
||||
)
|
||||
|
||||
|
||||
class EnquiryListItem(OrmModel):
|
||||
id: int
|
||||
name: str
|
||||
phone: str | None
|
||||
email: str | None
|
||||
city: str | None
|
||||
property_type: PropertyType | None
|
||||
required_capacity_kw: float | None
|
||||
status: EnquiryStatus
|
||||
source: str
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
|
||||
class EnquiryDetail(EnquiryListItem):
|
||||
address: str | None
|
||||
monthly_bill: float | None
|
||||
message: str | None
|
||||
notes: list[EnquiryNoteOut] = []
|
||||
|
||||
|
||||
class EnquiryUpdate(InputModel):
|
||||
status: EnquiryStatus | None = None
|
||||
note: str | None = Field(default=None, min_length=1, max_length=5000, description="Appends an internal note")
|
||||
@@ -0,0 +1,161 @@
|
||||
from datetime import date, datetime
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.models.enums import ProjectCategory, ProjectStatus
|
||||
from app.schemas.common import InputModel
|
||||
from app.services.image_processing import media_url
|
||||
|
||||
|
||||
class ProjectImagePublic(BaseModel):
|
||||
id: int
|
||||
url: str
|
||||
thumbnail_url: str
|
||||
width: int
|
||||
height: int
|
||||
caption: str | None
|
||||
is_featured: bool
|
||||
sort_order: int
|
||||
|
||||
@classmethod
|
||||
def build(cls, img) -> "ProjectImagePublic":
|
||||
return cls(
|
||||
id=img.id,
|
||||
url=media_url(img.watermarked_path),
|
||||
thumbnail_url=media_url(img.thumbnail_path),
|
||||
width=img.width,
|
||||
height=img.height,
|
||||
caption=img.caption,
|
||||
is_featured=img.is_featured,
|
||||
sort_order=img.sort_order,
|
||||
)
|
||||
|
||||
|
||||
class ProjectImageAdmin(ProjectImagePublic):
|
||||
project_id: int
|
||||
original_filename: str
|
||||
mime_type: str
|
||||
file_size: int
|
||||
original_download_path: str
|
||||
created_at: datetime
|
||||
|
||||
@classmethod
|
||||
def build(cls, img) -> "ProjectImageAdmin":
|
||||
base = ProjectImagePublic.build(img).model_dump()
|
||||
return cls(
|
||||
**base,
|
||||
project_id=img.project_id,
|
||||
original_filename=img.original_filename,
|
||||
mime_type=img.mime_type,
|
||||
file_size=img.file_size,
|
||||
original_download_path=f"/api/admin/project-images/{img.id}/original",
|
||||
created_at=img.created_at,
|
||||
)
|
||||
|
||||
|
||||
class _ProjectBase(BaseModel):
|
||||
id: int
|
||||
title: str
|
||||
slug: str
|
||||
category: ProjectCategory
|
||||
location: str | None
|
||||
capacity_kw: float | None
|
||||
installation_date: date | None
|
||||
description: str | None
|
||||
status: ProjectStatus
|
||||
|
||||
@staticmethod
|
||||
def _fields(p) -> dict:
|
||||
return {
|
||||
"id": p.id,
|
||||
"title": p.title,
|
||||
"slug": p.slug,
|
||||
"category": p.category,
|
||||
"location": p.location,
|
||||
"capacity_kw": float(p.capacity_kw) if p.capacity_kw is not None else None,
|
||||
"installation_date": p.installation_date,
|
||||
"description": p.description,
|
||||
"status": p.status,
|
||||
}
|
||||
|
||||
|
||||
class ProjectPublicSummary(_ProjectBase):
|
||||
featured_image: ProjectImagePublic | None
|
||||
image_count: int
|
||||
|
||||
@classmethod
|
||||
def build(cls, p) -> "ProjectPublicSummary":
|
||||
fi = p.featured_image
|
||||
return cls(
|
||||
**cls._fields(p),
|
||||
featured_image=ProjectImagePublic.build(fi) if fi else None,
|
||||
image_count=len(p.images),
|
||||
)
|
||||
|
||||
|
||||
class ProjectPublicDetail(ProjectPublicSummary):
|
||||
images: list[ProjectImagePublic]
|
||||
|
||||
@classmethod
|
||||
def build(cls, p) -> "ProjectPublicDetail":
|
||||
return cls(
|
||||
**ProjectPublicSummary.build(p).model_dump(),
|
||||
images=[ProjectImagePublic.build(i) for i in p.images],
|
||||
)
|
||||
|
||||
|
||||
class ProjectAdmin(_ProjectBase):
|
||||
is_published: bool
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
featured_image: ProjectImageAdmin | None
|
||||
images: list[ProjectImageAdmin]
|
||||
|
||||
@classmethod
|
||||
def build(cls, p) -> "ProjectAdmin":
|
||||
fi = p.featured_image
|
||||
return cls(
|
||||
**cls._fields(p),
|
||||
is_published=p.is_published,
|
||||
created_at=p.created_at,
|
||||
updated_at=p.updated_at,
|
||||
featured_image=ProjectImageAdmin.build(fi) if fi else None,
|
||||
images=[ProjectImageAdmin.build(i) for i in p.images],
|
||||
)
|
||||
|
||||
|
||||
class ProjectCreate(InputModel):
|
||||
title: str = Field(min_length=2, max_length=200)
|
||||
slug: str | None = Field(default=None, max_length=200, pattern=r"^[a-z0-9]+(?:-[a-z0-9]+)*$")
|
||||
category: ProjectCategory
|
||||
location: str | None = Field(default=None, max_length=200)
|
||||
capacity_kw: float | None = Field(default=None, gt=0, le=100_000)
|
||||
installation_date: date | None = None
|
||||
description: str | None = Field(default=None, max_length=10_000)
|
||||
status: ProjectStatus = ProjectStatus.COMPLETED
|
||||
is_published: bool = False
|
||||
|
||||
|
||||
class ProjectUpdate(InputModel):
|
||||
"""PUT body. Only fields that are sent are changed."""
|
||||
|
||||
title: str | None = Field(default=None, min_length=2, max_length=200)
|
||||
slug: str | None = Field(default=None, max_length=200, pattern=r"^[a-z0-9]+(?:-[a-z0-9]+)*$")
|
||||
category: ProjectCategory | None = None
|
||||
location: str | None = Field(default=None, max_length=200)
|
||||
capacity_kw: float | None = Field(default=None, gt=0, le=100_000)
|
||||
installation_date: date | None = None
|
||||
description: str | None = Field(default=None, max_length=10_000)
|
||||
status: ProjectStatus | None = None
|
||||
is_published: bool | None = None
|
||||
|
||||
|
||||
class ProjectImageUpdate(InputModel):
|
||||
caption: str | None = Field(default=None, max_length=300)
|
||||
sort_order: int | None = Field(default=None, ge=0, le=100_000)
|
||||
is_featured: bool | None = Field(default=None, description="true makes this the project's featured image")
|
||||
|
||||
|
||||
class UploadResult(BaseModel):
|
||||
uploaded: list[ProjectImageAdmin]
|
||||
project: ProjectAdmin
|
||||
@@ -0,0 +1,47 @@
|
||||
"""Outgoing email. Uses SMTP when configured; otherwise writes .eml files to OUTBOX_DIR
|
||||
so the full flow can be tested locally without sending real mail."""
|
||||
|
||||
import logging
|
||||
import smtplib
|
||||
import ssl
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from email.message import EmailMessage
|
||||
from pathlib import Path
|
||||
|
||||
from app.core.config import settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def send_email(
|
||||
to: str,
|
||||
subject: str,
|
||||
text: str,
|
||||
attachments: list[tuple[str, bytes, str]] | None = None,
|
||||
) -> str:
|
||||
"""Returns "smtp" or "outbox:<path>". Raises on SMTP failure."""
|
||||
msg = EmailMessage()
|
||||
msg["From"] = settings.MAIL_FROM
|
||||
msg["To"] = to
|
||||
msg["Subject"] = subject
|
||||
msg.set_content(text)
|
||||
for filename, data, mime in attachments or []:
|
||||
maintype, subtype = mime.split("/", 1)
|
||||
msg.add_attachment(data, maintype=maintype, subtype=subtype, filename=filename)
|
||||
|
||||
if settings.SMTP_HOST:
|
||||
with smtplib.SMTP(settings.SMTP_HOST, settings.SMTP_PORT, timeout=20) as smtp:
|
||||
if settings.SMTP_STARTTLS:
|
||||
smtp.starttls(context=ssl.create_default_context())
|
||||
if settings.SMTP_USER:
|
||||
smtp.login(settings.SMTP_USER, settings.SMTP_PASSWORD)
|
||||
smtp.send_message(msg)
|
||||
return "smtp"
|
||||
|
||||
outbox = Path(settings.OUTBOX_DIR)
|
||||
outbox.mkdir(parents=True, exist_ok=True)
|
||||
path = outbox / f"{datetime.now():%Y%m%d-%H%M%S}-{uuid.uuid4().hex[:8]}.eml"
|
||||
path.write_bytes(bytes(msg))
|
||||
logger.info("SMTP not configured; email to %s saved to %s", to, path)
|
||||
return f"outbox:{path}"
|
||||
@@ -0,0 +1,333 @@
|
||||
"""Image validation, watermarking and thumbnail generation (Pillow).
|
||||
|
||||
Pipeline for every admin upload:
|
||||
read_upload() -> size limit, extension allow-list, real content sniffing, pixel limit
|
||||
process_image() -> save untouched original, save watermarked copy, save WEBP thumbnail
|
||||
All files get server-generated UUID names; client filenames are only stored as metadata.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import logging
|
||||
import os
|
||||
import uuid
|
||||
import warnings
|
||||
from dataclasses import dataclass
|
||||
from functools import lru_cache
|
||||
from pathlib import Path, PurePosixPath
|
||||
|
||||
from fastapi import UploadFile, status
|
||||
from PIL import Image, ImageFilter, ImageOps, ImageStat, UnidentifiedImageError
|
||||
|
||||
from app.core.config import settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
ORIGINALS = "originals"
|
||||
WATERMARKED = "watermarked"
|
||||
THUMBNAILS = "thumbnails"
|
||||
|
||||
# Pillow format -> (allowed extensions, canonical extension, mime type)
|
||||
SUPPORTED_FORMATS: dict[str, tuple[set[str], str, str]] = {
|
||||
"JPEG": ({".jpg", ".jpeg"}, ".jpg", "image/jpeg"),
|
||||
"PNG": ({".png"}, ".png", "image/png"),
|
||||
"WEBP": ({".webp"}, ".webp", "image/webp"),
|
||||
}
|
||||
ALLOWED_EXTENSIONS = set().union(*(exts for exts, _, _ in SUPPORTED_FORMATS.values()))
|
||||
|
||||
Image.MAX_IMAGE_PIXELS = settings.MAX_IMAGE_PIXELS
|
||||
|
||||
|
||||
class ImageValidationError(Exception):
|
||||
def __init__(self, message: str, status_code: int = status.HTTP_400_BAD_REQUEST):
|
||||
super().__init__(message)
|
||||
self.message = message
|
||||
self.status_code = status_code
|
||||
|
||||
|
||||
class WatermarkUnavailableError(Exception):
|
||||
"""Raised when the official logo file is missing or unreadable."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ValidatedUpload:
|
||||
data: bytes
|
||||
original_filename: str
|
||||
pil_format: str # JPEG | PNG | WEBP
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class StoredImage:
|
||||
original_path: str
|
||||
watermarked_path: str
|
||||
thumbnail_path: str
|
||||
mime_type: str
|
||||
file_size: int
|
||||
width: int
|
||||
height: int
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- validation
|
||||
|
||||
|
||||
def _sanitise_display_name(name: str | None) -> str:
|
||||
"""Keep only a safe basename for display; never used to build a path."""
|
||||
base = PurePosixPath((name or "").replace("\\", "/")).name
|
||||
base = "".join(ch for ch in base if ch.isprintable()).strip()
|
||||
return base[:255] or "upload"
|
||||
|
||||
|
||||
async def read_upload(upload: UploadFile) -> ValidatedUpload:
|
||||
display_name = _sanitise_display_name(upload.filename)
|
||||
ext = os.path.splitext(display_name)[1].lower()
|
||||
if ext not in ALLOWED_EXTENSIONS:
|
||||
raise ImageValidationError(
|
||||
f"'{display_name}': unsupported file type. Allowed: JPG, JPEG, PNG, WEBP.",
|
||||
status.HTTP_415_UNSUPPORTED_MEDIA_TYPE,
|
||||
)
|
||||
|
||||
limit = settings.max_upload_bytes
|
||||
chunks: list[bytes] = []
|
||||
total = 0
|
||||
while chunk := await upload.read(1024 * 1024):
|
||||
total += len(chunk)
|
||||
if total > limit:
|
||||
raise ImageValidationError(
|
||||
f"'{display_name}': file is larger than {settings.MAX_UPLOAD_SIZE_MB} MB.",
|
||||
status.HTTP_413_CONTENT_TOO_LARGE,
|
||||
)
|
||||
chunks.append(chunk)
|
||||
data = b"".join(chunks)
|
||||
if not data:
|
||||
raise ImageValidationError(f"'{display_name}': file is empty.")
|
||||
|
||||
pil_format = _sniff_image(data, display_name)
|
||||
allowed_exts = SUPPORTED_FORMATS[pil_format][0]
|
||||
if ext not in allowed_exts:
|
||||
raise ImageValidationError(
|
||||
f"'{display_name}': file extension does not match its content ({pil_format}).",
|
||||
status.HTTP_415_UNSUPPORTED_MEDIA_TYPE,
|
||||
)
|
||||
return ValidatedUpload(data=data, original_filename=display_name, pil_format=pil_format)
|
||||
|
||||
|
||||
def _sniff_image(data: bytes, display_name: str) -> str:
|
||||
"""Identify the real format from file content and fully decode it once."""
|
||||
try:
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("error", Image.DecompressionBombWarning)
|
||||
with Image.open(io.BytesIO(data)) as img:
|
||||
fmt = img.format
|
||||
if fmt not in SUPPORTED_FORMATS:
|
||||
raise ImageValidationError(
|
||||
f"'{display_name}': unsupported image format.",
|
||||
status.HTTP_415_UNSUPPORTED_MEDIA_TYPE,
|
||||
)
|
||||
if getattr(img, "n_frames", 1) > 1:
|
||||
raise ImageValidationError(f"'{display_name}': animated images are not supported.")
|
||||
img.verify() # structural check
|
||||
with Image.open(io.BytesIO(data)) as img:
|
||||
img.load() # full decode catches truncated / corrupt pixel data
|
||||
except ImageValidationError:
|
||||
raise
|
||||
except (Image.DecompressionBombError, Image.DecompressionBombWarning):
|
||||
raise ImageValidationError(
|
||||
f"'{display_name}': image dimensions are too large.",
|
||||
status.HTTP_413_CONTENT_TOO_LARGE,
|
||||
) from None
|
||||
except (UnidentifiedImageError, OSError, SyntaxError, ValueError):
|
||||
raise ImageValidationError(f"'{display_name}': file is not a valid image.") from None
|
||||
return fmt
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- watermark
|
||||
|
||||
|
||||
@lru_cache(maxsize=4)
|
||||
def _load_logo_cached(path: str, mtime: float) -> Image.Image:
|
||||
with Image.open(path) as logo:
|
||||
logo.load()
|
||||
return logo.convert("RGBA")
|
||||
|
||||
|
||||
def load_logo() -> Image.Image:
|
||||
path = Path(settings.WATERMARK_LOGO_PATH)
|
||||
try:
|
||||
return _load_logo_cached(str(path), path.stat().st_mtime)
|
||||
except FileNotFoundError:
|
||||
raise WatermarkUnavailableError(
|
||||
f"Watermark logo not found at {path}. Add the official Saura Shakti logo (transparent PNG)."
|
||||
) from None
|
||||
except (UnidentifiedImageError, OSError) as exc:
|
||||
raise WatermarkUnavailableError(f"Watermark logo at {path} is not a readable image: {exc}") from None
|
||||
|
||||
|
||||
def _luminance(img: Image.Image, mask: Image.Image | None = None) -> float:
|
||||
"""Mean perceived brightness 0..255 (optionally weighted by a mask)."""
|
||||
stat = ImageStat.Stat(img.convert("L"), mask)
|
||||
return stat.mean[0] if stat.count[0] else 127.0
|
||||
|
||||
|
||||
def apply_watermark(image: Image.Image, logo: Image.Image) -> Image.Image:
|
||||
"""Composite the logo bottom-right. Returns a new RGBA image of identical size."""
|
||||
base = image.convert("RGBA")
|
||||
W, H = base.size
|
||||
short_side = min(W, H)
|
||||
|
||||
# --- proportional sizing (aspect ratio always preserved) ---
|
||||
target_w = W * settings.WATERMARK_WIDTH_RATIO
|
||||
target_w = max(settings.WATERMARK_MIN_WIDTH, min(settings.WATERMARK_MAX_WIDTH, target_w))
|
||||
target_w = min(target_w, W * 0.5) # never dominate small images
|
||||
target_w = min(target_w, logo.width) # never upscale the logo (keeps it crisp)
|
||||
scale = target_w / logo.width
|
||||
if logo.height * scale > H * 0.3: # very tall logos: limit by height instead
|
||||
scale = (H * 0.3) / logo.height
|
||||
lw, lh = max(1, round(logo.width * scale)), max(1, round(logo.height * scale))
|
||||
mark = logo.resize((lw, lh), Image.Resampling.LANCZOS)
|
||||
|
||||
margin = max(8, round(short_side * settings.WATERMARK_MARGIN_RATIO))
|
||||
x, y = W - margin - lw, H - margin - lh
|
||||
x, y = max(0, x), max(0, y)
|
||||
|
||||
# --- adaptive contrast halo: visible on both bright and dark photos ---
|
||||
logo_alpha = mark.getchannel("A")
|
||||
region = base.crop((x, y, x + lw, y + lh))
|
||||
region_lum = _luminance(region)
|
||||
logo_lum = _luminance(mark, logo_alpha)
|
||||
halo_rgb = (0, 0, 0) if logo_lum >= 128 else (255, 255, 255)
|
||||
contrast = abs(region_lum - logo_lum) / 255.0
|
||||
halo_opacity = min(0.7, settings.WATERMARK_SHADOW_OPACITY + (1 - contrast) * 0.3)
|
||||
|
||||
pad = max(2, round(lw * 0.04))
|
||||
blur = max(1.5, lw * 0.02)
|
||||
halo_mask = Image.new("L", (lw + 2 * pad, lh + 2 * pad), 0)
|
||||
halo_mask.paste(logo_alpha, (pad, pad))
|
||||
halo_mask = halo_mask.filter(ImageFilter.MaxFilter(3)).filter(ImageFilter.GaussianBlur(blur))
|
||||
halo_mask = halo_mask.point(lambda a: round(a * halo_opacity))
|
||||
halo = Image.new("RGBA", halo_mask.size, (*halo_rgb, 0))
|
||||
halo.putalpha(halo_mask)
|
||||
|
||||
# --- apply logo transparency ---
|
||||
mark.putalpha(logo_alpha.point(lambda a: round(a * settings.WATERMARK_OPACITY)))
|
||||
|
||||
overlay = Image.new("RGBA", base.size, (0, 0, 0, 0))
|
||||
overlay.alpha_composite(halo, (max(0, x - pad), max(0, y - pad)), (max(0, pad - x), max(0, pad - y)))
|
||||
overlay.alpha_composite(mark, (x, y))
|
||||
return Image.alpha_composite(base, overlay)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- storage
|
||||
|
||||
|
||||
def _upload_root() -> Path:
|
||||
return Path(settings.UPLOAD_DIR).resolve()
|
||||
|
||||
|
||||
def ensure_upload_dirs() -> None:
|
||||
for sub in (ORIGINALS, WATERMARKED, THUMBNAILS):
|
||||
(_upload_root() / sub).mkdir(parents=True, exist_ok=True)
|
||||
|
||||
|
||||
def _write_atomic(rel_path: str, writer) -> None:
|
||||
dest = _upload_root() / rel_path
|
||||
tmp = dest.with_name(f".{dest.name}.tmp")
|
||||
try:
|
||||
with open(tmp, "wb") as fh:
|
||||
writer(fh)
|
||||
os.replace(tmp, dest)
|
||||
finally:
|
||||
tmp.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def resolve_media_path(rel_path: str) -> Path:
|
||||
"""Resolve a stored relative path, refusing anything outside UPLOAD_DIR."""
|
||||
root = _upload_root()
|
||||
full = (root / rel_path).resolve()
|
||||
if not full.is_relative_to(root) or full == root:
|
||||
raise ValueError(f"Refusing path outside upload dir: {rel_path!r}")
|
||||
return full
|
||||
|
||||
|
||||
def delete_media_files(*rel_paths: str | None) -> None:
|
||||
for rel in rel_paths:
|
||||
if not rel:
|
||||
continue
|
||||
try:
|
||||
resolve_media_path(rel).unlink(missing_ok=True)
|
||||
except (ValueError, OSError) as exc: # log, never fail the request on cleanup
|
||||
logger.warning("Could not delete media file %s: %s", rel, exc)
|
||||
|
||||
|
||||
def media_url(rel_path: str | None) -> str | None:
|
||||
if not rel_path:
|
||||
return None
|
||||
return f"{settings.MEDIA_BASE_URL.rstrip('/')}/{rel_path}"
|
||||
|
||||
|
||||
def _encode(img: Image.Image, pil_format: str, has_alpha: bool, icc: bytes | None, fh) -> None:
|
||||
extra = {"icc_profile": icc} if icc else {}
|
||||
if pil_format == "JPEG":
|
||||
img.convert("RGB").save(fh, "JPEG", quality=92, optimize=True, progressive=True, **extra)
|
||||
elif pil_format == "PNG":
|
||||
(img if has_alpha else img.convert("RGB")).save(fh, "PNG", compress_level=6, **extra)
|
||||
else: # WEBP
|
||||
(img if has_alpha else img.convert("RGB")).save(fh, "WEBP", quality=92, method=4, **extra)
|
||||
|
||||
|
||||
def process_image(upload: ValidatedUpload) -> StoredImage:
|
||||
"""CPU-bound: call via run_in_threadpool. Cleans up its own files on failure."""
|
||||
logo = load_logo() # fail fast before writing anything
|
||||
ensure_upload_dirs()
|
||||
|
||||
_, ext, mime = SUPPORTED_FORMATS[upload.pil_format]
|
||||
stem = uuid.uuid4().hex
|
||||
original_rel = f"{ORIGINALS}/{stem}{ext}"
|
||||
watermarked_rel = f"{WATERMARKED}/{stem}{ext}"
|
||||
thumbnail_rel = f"{THUMBNAILS}/{stem}.webp"
|
||||
|
||||
written: list[str] = []
|
||||
try:
|
||||
# 1. untouched original (private, never served publicly)
|
||||
_write_atomic(original_rel, lambda fh: fh.write(upload.data))
|
||||
written.append(original_rel)
|
||||
|
||||
with Image.open(io.BytesIO(upload.data)) as src:
|
||||
icc = src.info.get("icc_profile")
|
||||
img = ImageOps.exif_transpose(src) # honour camera orientation
|
||||
has_alpha = img.mode in ("RGBA", "LA", "PA") or (
|
||||
img.mode == "P" and "transparency" in img.info
|
||||
)
|
||||
if img.mode not in ("RGB", "RGBA"):
|
||||
img = img.convert("RGBA" if has_alpha else "RGB")
|
||||
|
||||
# 2. watermarked full-size copy (EXIF dropped: avoids leaking GPS data)
|
||||
marked = apply_watermark(img, logo)
|
||||
width, height = marked.size
|
||||
_write_atomic(
|
||||
watermarked_rel, lambda fh: _encode(marked, upload.pil_format, has_alpha, icc, fh)
|
||||
)
|
||||
written.append(watermarked_rel)
|
||||
|
||||
# 3. thumbnail derived from the watermarked image
|
||||
thumb = marked.copy()
|
||||
thumb.thumbnail(
|
||||
(settings.THUMBNAIL_MAX_SIZE, settings.THUMBNAIL_MAX_SIZE), Image.Resampling.LANCZOS
|
||||
)
|
||||
if not has_alpha:
|
||||
thumb = thumb.convert("RGB")
|
||||
_write_atomic(thumbnail_rel, lambda fh: thumb.save(fh, "WEBP", quality=82, method=4))
|
||||
written.append(thumbnail_rel)
|
||||
except Exception:
|
||||
delete_media_files(*written)
|
||||
raise
|
||||
|
||||
return StoredImage(
|
||||
original_path=original_rel,
|
||||
watermarked_path=watermarked_rel,
|
||||
thumbnail_path=thumbnail_rel,
|
||||
mime_type=mime,
|
||||
file_size=len(upload.data),
|
||||
width=width,
|
||||
height=height,
|
||||
)
|
||||
@@ -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
|
||||
@@ -0,0 +1,36 @@
|
||||
import re
|
||||
import unicodedata
|
||||
|
||||
from sqlalchemy import Select, func, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
|
||||
def slugify(value: str, max_length: int = 150) -> str:
|
||||
value = unicodedata.normalize("NFKD", value).encode("ascii", "ignore").decode()
|
||||
value = re.sub(r"[^a-zA-Z0-9]+", "-", value).strip("-").lower()
|
||||
return value[:max_length].strip("-") or "item"
|
||||
|
||||
|
||||
async def unique_slug(db: AsyncSession, model, base: str, exclude_id: int | None = None) -> str:
|
||||
"""Return `base`, or `base-2`, `base-3`... whichever is free for model.slug."""
|
||||
base = slugify(base)
|
||||
stmt = select(model.slug).where(model.slug.op("~")(f"^{re.escape(base)}(-[0-9]+)?$"))
|
||||
if exclude_id is not None:
|
||||
stmt = stmt.where(model.id != exclude_id)
|
||||
taken = set((await db.scalars(stmt)).all())
|
||||
if base not in taken:
|
||||
return base
|
||||
n = 2
|
||||
while f"{base}-{n}" in taken:
|
||||
n += 1
|
||||
return f"{base}-{n}"
|
||||
|
||||
|
||||
async def paginate(db: AsyncSession, stmt: Select, page: int, page_size: int):
|
||||
total = await db.scalar(select(func.count()).select_from(stmt.order_by(None).subquery()))
|
||||
rows = (await db.scalars(stmt.limit(page_size).offset((page - 1) * page_size))).unique().all()
|
||||
return rows, total or 0
|
||||
|
||||
|
||||
def escape_like(term: str) -> str:
|
||||
return term.replace("\\", "\\\\").replace("%", r"\%").replace("_", r"\_")
|
||||
Reference in New Issue
Block a user