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