-
This commit is contained in:
@@ -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)
|
||||
Reference in New Issue
Block a user