-
This commit is contained in:
@@ -0,0 +1,25 @@
|
||||
# Copy to backend/.env and fill in. Never commit the real file.
|
||||
ENVIRONMENT=development
|
||||
|
||||
# Must match the credentials in the root .env (docker-compose PostgreSQL on port 5440)
|
||||
DATABASE_URL=postgresql+asyncpg://saurashakti:change-me@localhost:5440/saurashakti
|
||||
# Used only by the test suite; database name must end in _test
|
||||
TEST_DATABASE_URL=postgresql+asyncpg://saurashakti:change-me@localhost:5440/saurashakti_test
|
||||
|
||||
# Generate with: python -c "import secrets; print(secrets.token_urlsafe(48))"
|
||||
JWT_SECRET_KEY=replace-with-a-long-random-string-at-least-32-chars
|
||||
JWT_EXPIRE_MINUTES=120
|
||||
|
||||
# Frontend dev server origin(s), comma separated
|
||||
CORS_ORIGINS=http://localhost:5173,http://127.0.0.1:5173
|
||||
|
||||
# Public URL prefix for watermarked images / thumbnails (relative: served via the Vite proxy in dev)
|
||||
MEDIA_BASE_URL=/media
|
||||
|
||||
# Optional overrides (defaults shown)
|
||||
# MAX_UPLOAD_SIZE_MB=10
|
||||
# MAX_FILES_PER_UPLOAD=20
|
||||
# WATERMARK_LOGO_PATH=assets/watermark/logo.png
|
||||
# WATERMARK_WIDTH_RATIO=0.18
|
||||
# WATERMARK_OPACITY=0.75
|
||||
# THUMBNAIL_MAX_SIZE=640
|
||||
@@ -0,0 +1,39 @@
|
||||
[alembic]
|
||||
script_location = %(here)s/alembic
|
||||
prepend_sys_path = .
|
||||
file_template = %%(year)d%%(month).2d%%(day).2d_%%(rev)s_%%(slug)s
|
||||
# sqlalchemy.url is taken from DATABASE_URL in backend/.env (see alembic/env.py)
|
||||
|
||||
[loggers]
|
||||
keys = root,sqlalchemy,alembic
|
||||
|
||||
[handlers]
|
||||
keys = console
|
||||
|
||||
[formatters]
|
||||
keys = generic
|
||||
|
||||
[logger_root]
|
||||
level = WARNING
|
||||
handlers = console
|
||||
qualname =
|
||||
|
||||
[logger_sqlalchemy]
|
||||
level = WARNING
|
||||
handlers =
|
||||
qualname = sqlalchemy.engine
|
||||
|
||||
[logger_alembic]
|
||||
level = INFO
|
||||
handlers =
|
||||
qualname = alembic
|
||||
|
||||
[handler_console]
|
||||
class = StreamHandler
|
||||
args = (sys.stderr,)
|
||||
level = NOTSET
|
||||
formatter = generic
|
||||
|
||||
[formatter_generic]
|
||||
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||
datefmt = %H:%M:%S
|
||||
@@ -0,0 +1,44 @@
|
||||
import asyncio
|
||||
from logging.config import fileConfig
|
||||
|
||||
from sqlalchemy.ext.asyncio import create_async_engine
|
||||
|
||||
from alembic import context
|
||||
from app.core.config import settings
|
||||
from app.models import Base
|
||||
|
||||
config = context.config
|
||||
if config.config_file_name is not None:
|
||||
fileConfig(config.config_file_name)
|
||||
|
||||
target_metadata = Base.metadata
|
||||
|
||||
|
||||
def run_migrations_offline() -> None:
|
||||
context.configure(
|
||||
url=settings.DATABASE_URL,
|
||||
target_metadata=target_metadata,
|
||||
literal_binds=True,
|
||||
compare_type=True,
|
||||
)
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
def _do_run(connection) -> None:
|
||||
context.configure(connection=connection, target_metadata=target_metadata, compare_type=True)
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
async def run_migrations_online() -> None:
|
||||
engine = create_async_engine(settings.DATABASE_URL)
|
||||
async with engine.connect() as connection:
|
||||
await connection.run_sync(_do_run)
|
||||
await engine.dispose()
|
||||
|
||||
|
||||
if context.is_offline_mode():
|
||||
run_migrations_offline()
|
||||
else:
|
||||
asyncio.run(run_migrations_online())
|
||||
@@ -0,0 +1,24 @@
|
||||
"""${message}
|
||||
|
||||
Revision ID: ${up_revision}
|
||||
Revises: ${down_revision | comma,n}
|
||||
Create Date: ${create_date}
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
${imports if imports else ""}
|
||||
|
||||
revision: str = ${repr(up_revision)}
|
||||
down_revision: Union[str, None] = ${repr(down_revision)}
|
||||
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
|
||||
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
${upgrades if upgrades else "pass"}
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
${downgrades if downgrades else "pass"}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
"""testimonial media, subscribers, nullable enquiry phone
|
||||
|
||||
Revision ID: be067e89c214
|
||||
Revises: d572dd3db977
|
||||
Create Date: 2026-11-13 09:54:54.154603
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
|
||||
revision: str = 'be067e89c214'
|
||||
down_revision: Union[str, None] = 'd572dd3db977'
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.create_table('subscribers',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('email', sa.String(length=255), nullable=False),
|
||||
sa.Column('is_active', sa.Boolean(), server_default=sa.text('true'), nullable=False),
|
||||
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||
sa.PrimaryKeyConstraint('id', name=op.f('pk_subscribers'))
|
||||
)
|
||||
op.create_index(op.f('ix_subscribers_email'), 'subscribers', ['email'], unique=True)
|
||||
op.alter_column('enquiries', 'phone',
|
||||
existing_type=sa.VARCHAR(length=20),
|
||||
nullable=True)
|
||||
op.add_column('testimonials', sa.Column('video_url', sa.String(length=500), nullable=True))
|
||||
op.add_column('testimonials', sa.Column('image_original_path', sa.String(length=300), nullable=True))
|
||||
op.add_column('testimonials', sa.Column('image_watermarked_path', sa.String(length=300), nullable=True))
|
||||
op.add_column('testimonials', sa.Column('image_thumbnail_path', sa.String(length=300), nullable=True))
|
||||
op.alter_column('testimonials', 'content',
|
||||
existing_type=sa.TEXT(),
|
||||
nullable=True)
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.alter_column('testimonials', 'content',
|
||||
existing_type=sa.TEXT(),
|
||||
nullable=False)
|
||||
op.drop_column('testimonials', 'image_thumbnail_path')
|
||||
op.drop_column('testimonials', 'image_watermarked_path')
|
||||
op.drop_column('testimonials', 'image_original_path')
|
||||
op.drop_column('testimonials', 'video_url')
|
||||
op.alter_column('enquiries', 'phone',
|
||||
existing_type=sa.VARCHAR(length=20),
|
||||
nullable=False)
|
||||
op.drop_index(op.f('ix_subscribers_email'), table_name='subscribers')
|
||||
op.drop_table('subscribers')
|
||||
# ### end Alembic commands ###
|
||||
@@ -0,0 +1,192 @@
|
||||
"""initial schema
|
||||
|
||||
Revision ID: d572dd3db977
|
||||
Revises:
|
||||
Create Date: 2026-11-13 06:46:38.545847
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
from sqlalchemy.dialects import postgresql
|
||||
|
||||
revision: str = 'd572dd3db977'
|
||||
down_revision: Union[str, None] = None
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.create_table('admins',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('email', sa.String(length=255), nullable=False),
|
||||
sa.Column('full_name', sa.String(length=150), nullable=False),
|
||||
sa.Column('hashed_password', sa.String(length=255), nullable=False),
|
||||
sa.Column('role', sa.Enum('super_admin', 'admin', 'editor', name='admin_role', native_enum=False, create_constraint=True, length=32), server_default='admin', nullable=False),
|
||||
sa.Column('is_active', sa.Boolean(), server_default=sa.text('true'), nullable=False),
|
||||
sa.Column('last_login_at', sa.DateTime(timezone=True), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||
sa.PrimaryKeyConstraint('id', name=op.f('pk_admins'))
|
||||
)
|
||||
op.create_index(op.f('ix_admins_email'), 'admins', ['email'], unique=True)
|
||||
op.create_table('contact_messages',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('name', sa.String(length=150), nullable=False),
|
||||
sa.Column('email', sa.String(length=255), nullable=False),
|
||||
sa.Column('phone', sa.String(length=20), nullable=True),
|
||||
sa.Column('subject', sa.String(length=200), nullable=True),
|
||||
sa.Column('message', sa.Text(), nullable=False),
|
||||
sa.Column('is_read', sa.Boolean(), server_default=sa.text('false'), nullable=False),
|
||||
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||
sa.PrimaryKeyConstraint('id', name=op.f('pk_contact_messages'))
|
||||
)
|
||||
op.create_index(op.f('ix_contact_messages_email'), 'contact_messages', ['email'], unique=False)
|
||||
op.create_index(op.f('ix_contact_messages_is_read'), 'contact_messages', ['is_read'], unique=False)
|
||||
op.create_table('enquiries',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('name', sa.String(length=150), nullable=False),
|
||||
sa.Column('phone', sa.String(length=20), nullable=False),
|
||||
sa.Column('email', sa.String(length=255), nullable=True),
|
||||
sa.Column('city', sa.String(length=120), nullable=True),
|
||||
sa.Column('address', sa.String(length=500), nullable=True),
|
||||
sa.Column('property_type', sa.Enum('residential', 'commercial', 'industrial', 'other', name='property_type', native_enum=False, create_constraint=True, length=32), nullable=True),
|
||||
sa.Column('monthly_bill', sa.Numeric(precision=12, scale=2), nullable=True),
|
||||
sa.Column('required_capacity_kw', sa.Numeric(precision=10, scale=2), nullable=True),
|
||||
sa.Column('message', sa.Text(), nullable=True),
|
||||
sa.Column('source', sa.String(length=50), server_default='website', nullable=False),
|
||||
sa.Column('status', sa.Enum('new', 'contacted', 'site_visit_scheduled', 'quotation_sent', 'converted', 'rejected', name='enquiry_status', native_enum=False, create_constraint=True, length=32), server_default='new', nullable=False),
|
||||
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||
sa.CheckConstraint('monthly_bill IS NULL OR monthly_bill >= 0', name=op.f('ck_enquiries_monthly_bill_non_negative')),
|
||||
sa.CheckConstraint('required_capacity_kw IS NULL OR required_capacity_kw > 0', name=op.f('ck_enquiries_capacity_positive')),
|
||||
sa.PrimaryKeyConstraint('id', name=op.f('pk_enquiries'))
|
||||
)
|
||||
op.create_index(op.f('ix_enquiries_email'), 'enquiries', ['email'], unique=False)
|
||||
op.create_index(op.f('ix_enquiries_phone'), 'enquiries', ['phone'], unique=False)
|
||||
op.create_index('ix_enquiries_status_created_at', 'enquiries', ['status', 'created_at'], unique=False)
|
||||
op.create_table('projects',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('title', sa.String(length=200), nullable=False),
|
||||
sa.Column('slug', sa.String(length=220), nullable=False),
|
||||
sa.Column('category', sa.Enum('residential', 'commercial', name='project_category', native_enum=False, create_constraint=True, length=32), nullable=False),
|
||||
sa.Column('location', sa.String(length=200), nullable=True),
|
||||
sa.Column('capacity_kw', sa.Numeric(precision=10, scale=2), nullable=True),
|
||||
sa.Column('installation_date', sa.Date(), nullable=True),
|
||||
sa.Column('description', sa.Text(), nullable=True),
|
||||
sa.Column('status', sa.Enum('ongoing', 'completed', name='project_status', native_enum=False, create_constraint=True, length=32), server_default='completed', nullable=False),
|
||||
sa.Column('is_published', sa.Boolean(), server_default=sa.text('false'), nullable=False),
|
||||
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||
sa.CheckConstraint('capacity_kw IS NULL OR capacity_kw > 0', name=op.f('ck_projects_capacity_positive')),
|
||||
sa.PrimaryKeyConstraint('id', name=op.f('pk_projects'))
|
||||
)
|
||||
op.create_index('ix_projects_published_category', 'projects', ['is_published', 'category'], unique=False)
|
||||
op.create_index(op.f('ix_projects_slug'), 'projects', ['slug'], unique=True)
|
||||
op.create_table('services',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('title', sa.String(length=150), nullable=False),
|
||||
sa.Column('slug', sa.String(length=170), nullable=False),
|
||||
sa.Column('short_description', sa.String(length=300), nullable=True),
|
||||
sa.Column('description', sa.Text(), nullable=True),
|
||||
sa.Column('icon', sa.String(length=60), nullable=True),
|
||||
sa.Column('sort_order', sa.Integer(), server_default='0', nullable=False),
|
||||
sa.Column('is_published', sa.Boolean(), server_default=sa.text('false'), nullable=False),
|
||||
sa.Column('image_original_path', sa.String(length=300), nullable=True),
|
||||
sa.Column('image_watermarked_path', sa.String(length=300), nullable=True),
|
||||
sa.Column('image_thumbnail_path', sa.String(length=300), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||
sa.PrimaryKeyConstraint('id', name=op.f('pk_services'))
|
||||
)
|
||||
op.create_index(op.f('ix_services_slug'), 'services', ['slug'], unique=True)
|
||||
op.create_table('enquiry_notes',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('enquiry_id', sa.Integer(), nullable=False),
|
||||
sa.Column('author_id', sa.Integer(), nullable=True),
|
||||
sa.Column('content', sa.Text(), nullable=False),
|
||||
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||
sa.ForeignKeyConstraint(['author_id'], ['admins.id'], name=op.f('fk_enquiry_notes_author_id_admins'), ondelete='SET NULL'),
|
||||
sa.ForeignKeyConstraint(['enquiry_id'], ['enquiries.id'], name=op.f('fk_enquiry_notes_enquiry_id_enquiries'), ondelete='CASCADE'),
|
||||
sa.PrimaryKeyConstraint('id', name=op.f('pk_enquiry_notes'))
|
||||
)
|
||||
op.create_index(op.f('ix_enquiry_notes_enquiry_id'), 'enquiry_notes', ['enquiry_id'], unique=False)
|
||||
op.create_table('project_images',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('project_id', sa.Integer(), nullable=False),
|
||||
sa.Column('original_filename', sa.String(length=255), nullable=False),
|
||||
sa.Column('original_path', sa.String(length=300), nullable=False),
|
||||
sa.Column('watermarked_path', sa.String(length=300), nullable=False),
|
||||
sa.Column('thumbnail_path', sa.String(length=300), nullable=False),
|
||||
sa.Column('mime_type', sa.String(length=50), nullable=False),
|
||||
sa.Column('file_size', sa.Integer(), nullable=False),
|
||||
sa.Column('width', sa.Integer(), nullable=False),
|
||||
sa.Column('height', sa.Integer(), nullable=False),
|
||||
sa.Column('caption', sa.String(length=300), nullable=True),
|
||||
sa.Column('sort_order', sa.Integer(), server_default='0', nullable=False),
|
||||
sa.Column('is_featured', sa.Boolean(), server_default=sa.text('false'), nullable=False),
|
||||
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||
sa.CheckConstraint('file_size > 0', name=op.f('ck_project_images_file_size_positive')),
|
||||
sa.ForeignKeyConstraint(['project_id'], ['projects.id'], name=op.f('fk_project_images_project_id_projects'), ondelete='CASCADE'),
|
||||
sa.PrimaryKeyConstraint('id', name=op.f('pk_project_images'))
|
||||
)
|
||||
op.create_index(op.f('ix_project_images_project_id'), 'project_images', ['project_id'], unique=False)
|
||||
op.create_index('uq_project_images_one_featured', 'project_images', ['project_id'], unique=True, postgresql_where=sa.text('is_featured'))
|
||||
op.create_table('site_content',
|
||||
sa.Column('key', sa.String(length=80), nullable=False),
|
||||
sa.Column('value', postgresql.JSONB(astext_type=sa.Text()), nullable=False),
|
||||
sa.Column('updated_by_id', sa.Integer(), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||
sa.ForeignKeyConstraint(['updated_by_id'], ['admins.id'], name=op.f('fk_site_content_updated_by_id_admins'), ondelete='SET NULL'),
|
||||
sa.PrimaryKeyConstraint('key', name=op.f('pk_site_content'))
|
||||
)
|
||||
op.create_table('testimonials',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('customer_name', sa.String(length=150), nullable=False),
|
||||
sa.Column('designation', sa.String(length=150), nullable=True),
|
||||
sa.Column('location', sa.String(length=150), nullable=True),
|
||||
sa.Column('content', sa.Text(), nullable=False),
|
||||
sa.Column('rating', sa.SmallInteger(), server_default='5', nullable=False),
|
||||
sa.Column('project_id', sa.Integer(), nullable=True),
|
||||
sa.Column('sort_order', sa.Integer(), server_default='0', nullable=False),
|
||||
sa.Column('is_published', sa.Boolean(), server_default=sa.text('true'), nullable=False),
|
||||
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||
sa.CheckConstraint('rating BETWEEN 1 AND 5', name=op.f('ck_testimonials_rating_range')),
|
||||
sa.ForeignKeyConstraint(['project_id'], ['projects.id'], name=op.f('fk_testimonials_project_id_projects'), ondelete='SET NULL'),
|
||||
sa.PrimaryKeyConstraint('id', name=op.f('pk_testimonials'))
|
||||
)
|
||||
op.create_index(op.f('ix_testimonials_project_id'), 'testimonials', ['project_id'], unique=False)
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_index(op.f('ix_testimonials_project_id'), table_name='testimonials')
|
||||
op.drop_table('testimonials')
|
||||
op.drop_table('site_content')
|
||||
op.drop_index('uq_project_images_one_featured', table_name='project_images', postgresql_where=sa.text('is_featured'))
|
||||
op.drop_index(op.f('ix_project_images_project_id'), table_name='project_images')
|
||||
op.drop_table('project_images')
|
||||
op.drop_index(op.f('ix_enquiry_notes_enquiry_id'), table_name='enquiry_notes')
|
||||
op.drop_table('enquiry_notes')
|
||||
op.drop_index(op.f('ix_services_slug'), table_name='services')
|
||||
op.drop_table('services')
|
||||
op.drop_index(op.f('ix_projects_slug'), table_name='projects')
|
||||
op.drop_index('ix_projects_published_category', table_name='projects')
|
||||
op.drop_table('projects')
|
||||
op.drop_index('ix_enquiries_status_created_at', table_name='enquiries')
|
||||
op.drop_index(op.f('ix_enquiries_phone'), table_name='enquiries')
|
||||
op.drop_index(op.f('ix_enquiries_email'), table_name='enquiries')
|
||||
op.drop_table('enquiries')
|
||||
op.drop_index(op.f('ix_contact_messages_is_read'), table_name='contact_messages')
|
||||
op.drop_index(op.f('ix_contact_messages_email'), table_name='contact_messages')
|
||||
op.drop_table('contact_messages')
|
||||
op.drop_index(op.f('ix_admins_email'), table_name='admins')
|
||||
op.drop_table('admins')
|
||||
# ### end Alembic commands ###
|
||||
@@ -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"\_")
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 124 KiB |
@@ -0,0 +1,6 @@
|
||||
[pytest]
|
||||
testpaths = tests
|
||||
asyncio_mode = auto
|
||||
asyncio_default_fixture_loop_scope = function
|
||||
filterwarnings =
|
||||
ignore::DeprecationWarning:passlib.*
|
||||
@@ -0,0 +1,29 @@
|
||||
# Web framework
|
||||
fastapi==0.162.5
|
||||
uvicorn[standard]==0.54.0
|
||||
python-multipart==0.0.33
|
||||
|
||||
# Database
|
||||
SQLAlchemy[asyncio]==2.1.8
|
||||
asyncpg==0.32.0
|
||||
alembic==1.20.1
|
||||
|
||||
# Validation / config
|
||||
pydantic==2.14.3
|
||||
pydantic-settings==2.16.2
|
||||
email-validator==2.3.0
|
||||
python-dotenv==1.2.4
|
||||
|
||||
# Auth
|
||||
PyJWT==2.15.1
|
||||
pwdlib[argon2]==0.3.1
|
||||
argon2-cffi==25.1.0
|
||||
|
||||
# Images
|
||||
pillow==13.0.0
|
||||
reportlab==5.1.0
|
||||
|
||||
# Testing
|
||||
pytest==9.2.0
|
||||
pytest-asyncio==1.5.0
|
||||
httpx==0.28.1
|
||||
@@ -0,0 +1,161 @@
|
||||
"""Test setup: separate PostgreSQL database + temporary upload dir.
|
||||
|
||||
The watermark logo used here is a generated TEST FIXTURE only (a plain shape),
|
||||
written to a temp dir. It is never used by the running application.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import io
|
||||
import os
|
||||
import shutil
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
from dotenv import dotenv_values
|
||||
from PIL import Image, ImageDraw
|
||||
|
||||
BACKEND_DIR = Path(__file__).resolve().parents[1]
|
||||
_env = dotenv_values(BACKEND_DIR / ".env")
|
||||
TEST_DB_URL = os.environ.get("TEST_DATABASE_URL") or _env.get("TEST_DATABASE_URL")
|
||||
if not TEST_DB_URL:
|
||||
raise RuntimeError("Set TEST_DATABASE_URL (see backend/.env.example)")
|
||||
if not TEST_DB_URL.rsplit("/", 1)[-1].endswith("_test"):
|
||||
raise RuntimeError("Refusing to run tests against a database whose name does not end in _test")
|
||||
|
||||
TMP_ROOT = Path(tempfile.mkdtemp(prefix="saurashakti-tests-"))
|
||||
LOGO_PATH = TMP_ROOT / "fixture-logo.png"
|
||||
|
||||
os.environ.update(
|
||||
{
|
||||
"ENVIRONMENT": "test",
|
||||
"DATABASE_URL": TEST_DB_URL,
|
||||
"UPLOAD_DIR": str(TMP_ROOT / "uploads"),
|
||||
"WATERMARK_LOGO_PATH": str(LOGO_PATH),
|
||||
"MEDIA_BASE_URL": "http://testserver/media",
|
||||
"LOGIN_RATE_LIMIT_PER_MINUTE": "5",
|
||||
"PUBLIC_FORM_RATE_LIMIT_PER_MINUTE": "50",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def _make_fixture_logo() -> None:
|
||||
# 400x120 transparent PNG: white rounded bar with orange dot (wide aspect, like a wordmark)
|
||||
logo = Image.new("RGBA", (400, 120), (0, 0, 0, 0))
|
||||
d = ImageDraw.Draw(logo)
|
||||
d.rounded_rectangle((0, 20, 400, 100), radius=30, fill=(255, 255, 255, 255))
|
||||
d.ellipse((20, 30, 80, 90), fill=(245, 130, 32, 255))
|
||||
logo.save(LOGO_PATH)
|
||||
|
||||
|
||||
_make_fixture_logo()
|
||||
|
||||
import pytest # noqa: E402
|
||||
from httpx import ASGITransport, AsyncClient # noqa: E402
|
||||
from sqlalchemy import text # noqa: E402
|
||||
|
||||
from app.core.database import SessionLocal, engine # noqa: E402
|
||||
from app.core.security import hash_password # noqa: E402
|
||||
from app.main import app # noqa: E402
|
||||
from app.middleware.rate_limit import reset_all_limiters # noqa: E402
|
||||
from app.models import Admin, AdminRole, Base # noqa: E402
|
||||
|
||||
PASSWORD = "TestPassw0rd!"
|
||||
|
||||
|
||||
@pytest.fixture(scope="session", autouse=True)
|
||||
def _schema():
|
||||
async def create():
|
||||
async with engine.begin() as conn:
|
||||
await conn.run_sync(Base.metadata.drop_all)
|
||||
await conn.run_sync(Base.metadata.create_all)
|
||||
|
||||
async def drop():
|
||||
async with engine.begin() as conn:
|
||||
await conn.run_sync(Base.metadata.drop_all)
|
||||
|
||||
asyncio.run(create())
|
||||
yield
|
||||
asyncio.run(drop())
|
||||
shutil.rmtree(TMP_ROOT, ignore_errors=True)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
async def _clean_state():
|
||||
reset_all_limiters()
|
||||
yield
|
||||
tables = ", ".join(t.name for t in Base.metadata.sorted_tables)
|
||||
async with engine.begin() as conn:
|
||||
await conn.execute(text(f"TRUNCATE {tables} RESTART IDENTITY CASCADE"))
|
||||
uploads = TMP_ROOT / "uploads"
|
||||
for sub in ("originals", "watermarked", "thumbnails"):
|
||||
for f in (uploads / sub).glob("*"):
|
||||
f.unlink()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def client():
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://testserver") as c:
|
||||
yield c
|
||||
|
||||
|
||||
async def _create_admin(email: str, role: AdminRole, active: bool = True) -> Admin:
|
||||
async with SessionLocal() as db:
|
||||
admin = Admin(
|
||||
email=email,
|
||||
full_name=email.split("@")[0].title(),
|
||||
hashed_password=hash_password(PASSWORD),
|
||||
role=role,
|
||||
is_active=active,
|
||||
)
|
||||
db.add(admin)
|
||||
await db.commit()
|
||||
await db.refresh(admin)
|
||||
return admin
|
||||
|
||||
|
||||
async def _token(client, email: str) -> dict[str, str]:
|
||||
r = await client.post("/api/auth/login", json={"email": email, "password": PASSWORD})
|
||||
assert r.status_code == 200, r.text
|
||||
return {"Authorization": f"Bearer {r.json()['access_token']}"}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def super_headers(client):
|
||||
await _create_admin("owner@example.com", AdminRole.SUPER_ADMIN)
|
||||
return await _token(client, "owner@example.com")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def admin_headers(client):
|
||||
await _create_admin("admin@example.com", AdminRole.ADMIN)
|
||||
return await _token(client, "admin@example.com")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def editor_headers(client):
|
||||
await _create_admin("editor@example.com", AdminRole.EDITOR)
|
||||
return await _token(client, "editor@example.com")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def create_admin():
|
||||
return _create_admin
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def upload_dir() -> Path:
|
||||
return TMP_ROOT / "uploads"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def logo_path() -> Path:
|
||||
return LOGO_PATH
|
||||
|
||||
|
||||
def make_image(fmt: str, size=(1600, 1000), color=(30, 90, 160), mode="RGB", **save_kw) -> bytes:
|
||||
img = Image.new(mode, size, color if mode == "RGB" else (*color, 255))
|
||||
# some structure so it isn't a flat colour
|
||||
ImageDraw.Draw(img).rectangle((0, 0, size[0] // 2, size[1] // 2), fill=(200, 200, 40))
|
||||
buf = io.BytesIO()
|
||||
img.save(buf, fmt, **save_kw)
|
||||
return buf.getvalue()
|
||||
@@ -0,0 +1,142 @@
|
||||
from datetime import UTC, datetime, timedelta
|
||||
|
||||
import jwt
|
||||
|
||||
from app.core.config import settings
|
||||
from app.models import AdminRole
|
||||
from tests.conftest import PASSWORD
|
||||
|
||||
|
||||
async def test_health(client):
|
||||
r = await client.get("/api/health")
|
||||
assert r.status_code == 200
|
||||
body = r.json()
|
||||
assert body["status"] == "ok" and body["database"] == "ok"
|
||||
assert body["watermark_logo_present"] is True
|
||||
|
||||
|
||||
async def test_login_success_and_me(client, create_admin):
|
||||
await create_admin("Owner@Example.com".lower(), AdminRole.SUPER_ADMIN)
|
||||
r = await client.post("/api/auth/login", json={"email": "OWNER@example.com", "password": PASSWORD})
|
||||
assert r.status_code == 200
|
||||
data = r.json()
|
||||
assert data["token_type"] == "bearer" and data["expires_in"] > 0
|
||||
assert "hashed_password" not in data["admin"]
|
||||
|
||||
me = await client.get("/api/auth/me", headers={"Authorization": f"Bearer {data['access_token']}"})
|
||||
assert me.status_code == 200
|
||||
assert me.json()["email"] == "owner@example.com"
|
||||
assert me.json()["last_login_at"] is not None
|
||||
|
||||
|
||||
async def test_login_wrong_password_and_unknown_email(client, create_admin):
|
||||
await create_admin("a@example.com", AdminRole.ADMIN)
|
||||
r1 = await client.post("/api/auth/login", json={"email": "a@example.com", "password": "nope"})
|
||||
r2 = await client.post("/api/auth/login", json={"email": "ghost@example.com", "password": "nope"})
|
||||
assert r1.status_code == r2.status_code == 401
|
||||
assert r1.json()["detail"] == r2.json()["detail"] # no user enumeration
|
||||
|
||||
|
||||
async def test_disabled_account_cannot_login(client, create_admin):
|
||||
await create_admin("off@example.com", AdminRole.ADMIN, active=False)
|
||||
r = await client.post("/api/auth/login", json={"email": "off@example.com", "password": PASSWORD})
|
||||
assert r.status_code == 403
|
||||
|
||||
|
||||
async def test_admin_routes_require_token(client):
|
||||
for method, url in [
|
||||
("get", "/api/auth/me"),
|
||||
("get", "/api/admin/enquiries"),
|
||||
("get", "/api/admin/dashboard/stats"),
|
||||
("post", "/api/admin/projects"),
|
||||
("post", "/api/admin/projects/1/images"),
|
||||
("delete", "/api/admin/project-images/1"),
|
||||
("post", "/api/admin/services"),
|
||||
("put", "/api/admin/content/hero"),
|
||||
]:
|
||||
r = await getattr(client, method)(url)
|
||||
assert r.status_code == 401, (method, url, r.status_code)
|
||||
|
||||
|
||||
async def test_invalid_and_expired_tokens(client, create_admin):
|
||||
admin = await create_admin("t@example.com", AdminRole.ADMIN)
|
||||
r = await client.get("/api/auth/me", headers={"Authorization": "Bearer not-a-jwt"})
|
||||
assert r.status_code == 401
|
||||
|
||||
forged = jwt.encode({"sub": str(admin.id), "type": "access", "iat": datetime.now(UTC),
|
||||
"exp": datetime.now(UTC) + timedelta(hours=1)}, "x" * 40, algorithm="HS256")
|
||||
r = await client.get("/api/auth/me", headers={"Authorization": f"Bearer {forged}"})
|
||||
assert r.status_code == 401
|
||||
|
||||
past = datetime.now(UTC) - timedelta(hours=2)
|
||||
expired = jwt.encode({"sub": str(admin.id), "type": "access", "iat": past,
|
||||
"exp": past + timedelta(minutes=1)}, settings.JWT_SECRET_KEY, algorithm="HS256")
|
||||
r = await client.get("/api/auth/me", headers={"Authorization": f"Bearer {expired}"})
|
||||
assert r.status_code == 401
|
||||
assert "expired" in r.json()["detail"].lower()
|
||||
|
||||
|
||||
async def test_login_rate_limited(client):
|
||||
codes = [
|
||||
(await client.post("/api/auth/login", json={"email": "x@example.com", "password": "bad"})).status_code
|
||||
for _ in range(6)
|
||||
]
|
||||
assert codes[:5] == [401] * 5
|
||||
assert codes[5] == 429
|
||||
|
||||
|
||||
async def test_role_based_access(client, editor_headers, admin_headers):
|
||||
# create an enquiry publicly
|
||||
await client.post("/api/enquiries", json={"name": "Ravi", "phone": "9876543210"})
|
||||
# editor can read but not delete enquiries
|
||||
assert (await client.get("/api/admin/enquiries", headers=editor_headers)).status_code == 200
|
||||
assert (await client.delete("/api/admin/enquiries/1", headers=editor_headers)).status_code == 403
|
||||
assert (await client.delete("/api/admin/enquiries/1", headers=admin_headers)).status_code == 204
|
||||
# only super admins manage admin accounts
|
||||
assert (await client.get("/api/admin/users", headers=admin_headers)).status_code == 403
|
||||
|
||||
|
||||
async def test_super_admin_manages_users(client, super_headers):
|
||||
r = await client.post(
|
||||
"/api/admin/users",
|
||||
headers=super_headers,
|
||||
json={"email": "New@Example.com", "full_name": "New Person", "password": "weak", "role": "editor"},
|
||||
)
|
||||
assert r.status_code == 422
|
||||
r = await client.post(
|
||||
"/api/admin/users",
|
||||
headers=super_headers,
|
||||
json={"email": "New@Example.com", "full_name": "New Person", "password": "Str0ngEnough", "role": "editor"},
|
||||
)
|
||||
assert r.status_code == 201
|
||||
assert r.json()["email"] == "new@example.com"
|
||||
dup = await client.post(
|
||||
"/api/admin/users",
|
||||
headers=super_headers,
|
||||
json={"email": "new@example.com", "full_name": "Dup", "password": "Str0ngEnough"},
|
||||
)
|
||||
assert dup.status_code == 409
|
||||
|
||||
uid = r.json()["id"]
|
||||
r = await client.patch(f"/api/admin/users/{uid}", headers=super_headers, json={"is_active": False})
|
||||
assert r.status_code == 200 and r.json()["is_active"] is False
|
||||
me = (await client.get("/api/auth/me", headers=super_headers)).json()
|
||||
r = await client.patch(f"/api/admin/users/{me['id']}", headers=super_headers, json={"is_active": False})
|
||||
assert r.status_code == 400 # cannot lock yourself out
|
||||
|
||||
|
||||
async def test_change_password(client, admin_headers):
|
||||
r = await client.post(
|
||||
"/api/auth/change-password",
|
||||
headers=admin_headers,
|
||||
json={"current_password": "wrong", "new_password": "An0therPassword"},
|
||||
)
|
||||
assert r.status_code == 400
|
||||
r = await client.post(
|
||||
"/api/auth/change-password",
|
||||
headers=admin_headers,
|
||||
json={"current_password": PASSWORD, "new_password": "An0therPassword"},
|
||||
)
|
||||
assert r.status_code == 200
|
||||
r = await client.post("/api/auth/login", json={"email": "admin@example.com", "password": "An0therPassword"})
|
||||
assert r.status_code == 200
|
||||
@@ -0,0 +1,143 @@
|
||||
VALID = {
|
||||
"name": "Priya Sharma",
|
||||
"phone": "+91 98765-43210",
|
||||
"email": "priya@example.com",
|
||||
"city": "Bhubaneswar",
|
||||
"property_type": "residential",
|
||||
"monthly_bill": 3500,
|
||||
"required_capacity_kw": 5,
|
||||
"message": "Need rooftop solar for my house.",
|
||||
}
|
||||
|
||||
|
||||
async def test_enquiry_submit_and_validation(client, admin_headers):
|
||||
r = await client.post("/api/enquiries", json=VALID)
|
||||
assert r.status_code == 201
|
||||
assert r.json()["success"] is True
|
||||
assert "id" not in r.json() # public response doesn't leak ids
|
||||
|
||||
bad = await client.post("/api/enquiries", json={"name": "A", "phone": "abc", "email": "nope"})
|
||||
assert bad.status_code == 422
|
||||
fields = {e["field"] for e in bad.json()["errors"]}
|
||||
assert {"name", "phone", "email"} <= fields
|
||||
|
||||
extra = await client.post("/api/enquiries", json={**VALID, "status": "converted"})
|
||||
assert extra.status_code == 422 # clients cannot set status
|
||||
|
||||
lst = (await client.get("/api/admin/enquiries", headers=admin_headers)).json()
|
||||
assert lst["total"] == 1
|
||||
item = lst["items"][0]
|
||||
assert item["phone"] == "+919876543210" # normalised
|
||||
assert item["status"] == "new"
|
||||
|
||||
|
||||
async def test_enquiry_honeypot_not_saved(client, admin_headers):
|
||||
r = await client.post("/api/enquiries", json={**VALID, "website": "http://spam.example"})
|
||||
assert r.status_code == 201
|
||||
assert (await client.get("/api/admin/enquiries", headers=admin_headers)).json()["total"] == 0
|
||||
|
||||
|
||||
async def test_enquiry_admin_workflow(client, admin_headers):
|
||||
for i, city in enumerate(["Cuttack", "Puri", "Cuttack"]):
|
||||
await client.post("/api/enquiries", json={**VALID, "name": f"Customer {i}", "city": city})
|
||||
|
||||
r = await client.get("/api/admin/enquiries", params={"search": "cuttack"}, headers=admin_headers)
|
||||
assert r.json()["total"] == 2
|
||||
r = await client.get("/api/admin/enquiries", params={"search": "100%_"}, headers=admin_headers)
|
||||
assert r.json()["total"] == 0 # LIKE wildcards are escaped
|
||||
|
||||
r = await client.patch(
|
||||
"/api/admin/enquiries/1",
|
||||
headers=admin_headers,
|
||||
json={"status": "site_visit_scheduled", "note": "Visit booked for Monday 11am"},
|
||||
)
|
||||
assert r.status_code == 200
|
||||
body = r.json()
|
||||
assert body["status"] == "site_visit_scheduled"
|
||||
assert body["notes"][0]["content"] == "Visit booked for Monday 11am"
|
||||
assert body["notes"][0]["author_name"] == "Admin"
|
||||
|
||||
r = await client.patch("/api/admin/enquiries/1", headers=admin_headers, json={"status": "bogus"})
|
||||
assert r.status_code == 422
|
||||
r = await client.patch("/api/admin/enquiries/1", headers=admin_headers, json={})
|
||||
assert r.status_code == 422
|
||||
|
||||
r = await client.get("/api/admin/enquiries", params={"status": "site_visit_scheduled"}, headers=admin_headers)
|
||||
assert r.json()["total"] == 1
|
||||
|
||||
detail = (await client.get("/api/admin/enquiries/1", headers=admin_headers)).json()
|
||||
assert detail["monthly_bill"] == 3500 and detail["message"]
|
||||
|
||||
stats = (await client.get("/api/admin/dashboard/stats", headers=admin_headers)).json()
|
||||
assert stats["total_enquiries"] == 3
|
||||
assert stats["new_enquiries"] == 2
|
||||
assert stats["site_visits_scheduled"] == 1
|
||||
assert len(stats["recent_enquiries"]) == 3
|
||||
|
||||
assert (await client.delete("/api/admin/enquiries/1", headers=admin_headers)).status_code == 204
|
||||
assert (await client.get("/api/admin/enquiries/1", headers=admin_headers)).status_code == 404
|
||||
assert (await client.delete("/api/admin/enquiries/999", headers=admin_headers)).status_code == 404
|
||||
|
||||
|
||||
async def test_contact_messages(client, admin_headers):
|
||||
r = await client.post("/api/contact", json={"name": "Asha", "email": "asha@example.com", "message": "Hello there"})
|
||||
assert r.status_code == 201
|
||||
bad = await client.post("/api/contact", json={"name": "Asha", "email": "bad", "message": "hi"})
|
||||
assert bad.status_code == 422
|
||||
lst = (await client.get("/api/admin/contact-messages", headers=admin_headers)).json()
|
||||
assert lst["total"] == 1 and lst["items"][0]["is_read"] is False
|
||||
r = await client.patch("/api/admin/contact-messages/1", headers=admin_headers, json={"is_read": True})
|
||||
assert r.json()["is_read"] is True
|
||||
stats = (await client.get("/api/admin/dashboard/stats", headers=admin_headers)).json()
|
||||
assert stats["unread_contact_messages"] == 0
|
||||
assert (await client.delete("/api/admin/contact-messages/1", headers=admin_headers)).status_code == 204
|
||||
|
||||
|
||||
async def test_testimonials(client, editor_headers):
|
||||
r = await client.post(
|
||||
"/api/admin/testimonials",
|
||||
headers=editor_headers,
|
||||
json={"customer_name": "Mr. Das", "content": "Excellent installation!", "rating": 5},
|
||||
)
|
||||
assert r.status_code == 201
|
||||
hidden = await client.post(
|
||||
"/api/admin/testimonials",
|
||||
headers=editor_headers,
|
||||
json={"customer_name": "Draft", "content": "Not yet public", "is_published": False},
|
||||
)
|
||||
assert hidden.status_code == 201
|
||||
bad = await client.post(
|
||||
"/api/admin/testimonials", headers=editor_headers, json={"customer_name": "X Y", "content": "Bad rating", "rating": 9}
|
||||
)
|
||||
assert bad.status_code == 422
|
||||
missing_project = await client.post(
|
||||
"/api/admin/testimonials", headers=editor_headers,
|
||||
json={"customer_name": "X Y", "content": "Linked", "project_id": 999},
|
||||
)
|
||||
assert missing_project.status_code == 422
|
||||
|
||||
public = (await client.get("/api/testimonials")).json()
|
||||
assert [t["customer_name"] for t in public] == ["Mr. Das"]
|
||||
assert "is_published" not in public[0]
|
||||
|
||||
r = await client.put("/api/admin/testimonials/2", headers=editor_headers, json={"is_published": True})
|
||||
assert r.status_code == 200
|
||||
assert len((await client.get("/api/testimonials")).json()) == 2
|
||||
assert (await client.delete("/api/admin/testimonials/2", headers=editor_headers)).status_code == 204
|
||||
|
||||
|
||||
async def test_site_content(client, editor_headers, admin_headers):
|
||||
r = await client.put(
|
||||
"/api/admin/content/hero",
|
||||
headers=editor_headers,
|
||||
json={"value": {"title": "Power your home with the sun", "cta": "Get a free quote"}},
|
||||
)
|
||||
assert r.status_code == 200
|
||||
assert (await client.get("/api/content/hero")).json()["value"]["cta"] == "Get a free quote"
|
||||
assert (await client.get("/api/content")).json() == {
|
||||
"hero": {"title": "Power your home with the sun", "cta": "Get a free quote"}
|
||||
}
|
||||
assert (await client.put("/api/admin/content/Bad Key!", headers=editor_headers, json={"value": {}})).status_code == 422
|
||||
assert (await client.get("/api/content/missing")).status_code == 404
|
||||
assert (await client.delete("/api/admin/content/hero", headers=editor_headers)).status_code == 403
|
||||
assert (await client.delete("/api/admin/content/hero", headers=admin_headers)).status_code == 204
|
||||
@@ -0,0 +1,268 @@
|
||||
import io
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from app.core.config import settings
|
||||
from tests.conftest import make_image
|
||||
|
||||
PROJECT = {
|
||||
"title": "5 kW Rooftop – Patia",
|
||||
"category": "residential",
|
||||
"location": "Patia, Bhubaneswar",
|
||||
"capacity_kw": 5,
|
||||
"installation_date": "2026-03-15",
|
||||
"description": "On-grid rooftop system.",
|
||||
}
|
||||
|
||||
|
||||
async def _project(client, headers, **overrides) -> dict:
|
||||
r = await client.post("/api/admin/projects", headers=headers, json={**PROJECT, **overrides})
|
||||
assert r.status_code == 201, r.text
|
||||
return r.json()
|
||||
|
||||
|
||||
def _files(*items):
|
||||
return [("files", (name, data, mime)) for name, data, mime in items]
|
||||
|
||||
|
||||
async def test_project_crud_and_publishing(client, editor_headers):
|
||||
p = await _project(client, editor_headers)
|
||||
assert p["slug"] == "5-kw-rooftop-patia"
|
||||
assert p["is_published"] is False
|
||||
p2 = await _project(client, editor_headers)
|
||||
assert p2["slug"] == "5-kw-rooftop-patia-2"
|
||||
|
||||
bad = await client.post("/api/admin/projects", headers=editor_headers, json={**PROJECT, "capacity_kw": -1, "category": "space"})
|
||||
assert bad.status_code == 422
|
||||
|
||||
# unpublished projects are hidden from the public site
|
||||
assert (await client.get("/api/projects")).json()["total"] == 0
|
||||
assert (await client.get(f"/api/projects/{p['id']}")).status_code == 404
|
||||
|
||||
r = await client.put(f"/api/admin/projects/{p['id']}", headers=editor_headers, json={"is_published": True, "capacity_kw": 6.5})
|
||||
assert r.status_code == 200 and r.json()["capacity_kw"] == 6.5
|
||||
assert (await client.put(f"/api/admin/projects/{p['id']}", headers=editor_headers, json={"title": None})).status_code == 422
|
||||
|
||||
public = (await client.get("/api/projects")).json()
|
||||
assert public["total"] == 1
|
||||
assert "is_published" not in public["items"][0]
|
||||
assert (await client.get(f"/api/projects/{p['slug']}")).status_code == 200
|
||||
assert (await client.get("/api/projects", params={"category": "commercial"})).json()["total"] == 0
|
||||
|
||||
lst = (await client.get("/api/admin/projects", params={"search": "patia"}, headers=editor_headers)).json()
|
||||
assert lst["total"] == 2
|
||||
|
||||
assert (await client.delete(f"/api/admin/projects/{p2['id']}", headers=editor_headers)).status_code == 204
|
||||
assert (await client.get(f"/api/admin/projects/{p2['id']}", headers=editor_headers)).status_code == 404
|
||||
|
||||
|
||||
async def test_upload_jpeg_png_webp_with_watermark_and_thumbnails(client, editor_headers, upload_dir):
|
||||
p = await _project(client, editor_headers, is_published=True)
|
||||
jpeg = make_image("JPEG", (2400, 1600), quality=95)
|
||||
png = make_image("PNG", (1200, 900), mode="RGBA")
|
||||
webp = make_image("WEBP", (800, 1200), quality=90)
|
||||
|
||||
r = await client.post(
|
||||
f"/api/admin/projects/{p['id']}/images",
|
||||
headers=editor_headers,
|
||||
files=_files(("roof.jpg", jpeg, "image/jpeg"), ("site.PNG", png, "image/png"), ("panel.webp", webp, "image/webp")),
|
||||
)
|
||||
assert r.status_code == 201, r.text
|
||||
body = r.json()
|
||||
uploaded = body["uploaded"]
|
||||
assert [u["mime_type"] for u in uploaded] == ["image/jpeg", "image/png", "image/webp"]
|
||||
assert [u["is_featured"] for u in uploaded] == [True, False, False]
|
||||
assert body["project"]["featured_image"]["id"] == uploaded[0]["id"]
|
||||
|
||||
for u, (w, h), src in zip(uploaded, [(2400, 1600), (1200, 900), (800, 1200)], [jpeg, png, webp], strict=True):
|
||||
assert (u["width"], u["height"]) == (w, h) # aspect ratio + size preserved
|
||||
assert u["file_size"] == len(src)
|
||||
name = u["url"].rsplit("/", 1)[-1]
|
||||
assert len(name.split(".")[0]) == 32 # server-generated uuid name
|
||||
|
||||
orig_path = next((upload_dir / "originals").glob(name.split(".")[0] + ".*"))
|
||||
assert orig_path.read_bytes() == src # original kept byte-for-byte
|
||||
|
||||
marked = Image.open(upload_dir / "watermarked" / name)
|
||||
original = Image.open(io.BytesIO(src)).convert("RGB")
|
||||
marked_rgb = marked.convert("RGB")
|
||||
assert marked.size == original.size
|
||||
# watermark: clearly visible change confined to the bottom-right corner
|
||||
from PIL import ImageChops
|
||||
|
||||
changed = ImageChops.difference(original, marked_rgb).convert("L").point(lambda v: 255 if v > 30 else 0)
|
||||
x0, y0, x1, y1 = changed.getbbox()
|
||||
assert x0 > w / 2 and y0 > h / 2, "watermark not in bottom-right"
|
||||
assert _region_diff(original, marked_rgb, (x0, y0, x1, y1)) > 25, "watermark too faint"
|
||||
diff_tl = _region_diff(original, marked_rgb, (0, 0, int(w * 0.5), int(h * 0.5)))
|
||||
assert diff_tl < 3, f"photo altered outside watermark ({diff_tl})"
|
||||
|
||||
thumb = Image.open(upload_dir / "thumbnails" / u["thumbnail_url"].rsplit("/", 1)[-1])
|
||||
assert thumb.format == "WEBP"
|
||||
assert max(thumb.size) == settings.THUMBNAIL_MAX_SIZE
|
||||
|
||||
# public gallery returns watermarked URLs, which are actually served
|
||||
detail = (await client.get(f"/api/projects/{p['slug']}")).json()
|
||||
assert len(detail["images"]) == 3
|
||||
assert "original_filename" not in detail["images"][0]
|
||||
path = detail["images"][0]["url"].replace("http://testserver", "")
|
||||
served = await client.get(path)
|
||||
assert served.status_code == 200 and served.headers["content-type"] == "image/jpeg"
|
||||
|
||||
# originals are never publicly reachable
|
||||
orig_name = next((upload_dir / "originals").glob("*")).name
|
||||
assert (await client.get(f"/media/originals/{orig_name}")).status_code == 404
|
||||
# ...but admins can download them
|
||||
dl = await client.get(uploaded[0]["original_download_path"], headers=editor_headers)
|
||||
assert dl.status_code == 200 and dl.content == jpeg
|
||||
assert (await client.get(uploaded[0]["original_download_path"])).status_code == 401
|
||||
|
||||
|
||||
def _region_diff(a: Image.Image, b: Image.Image, box) -> float:
|
||||
from PIL import ImageChops, ImageStat
|
||||
|
||||
return max(ImageStat.Stat(ImageChops.difference(a.crop(box), b.crop(box))).mean)
|
||||
|
||||
|
||||
async def test_invalid_uploads_rejected(client, editor_headers, upload_dir, monkeypatch):
|
||||
p = await _project(client, editor_headers)
|
||||
url = f"/api/admin/projects/{p['id']}/images"
|
||||
|
||||
cases = [
|
||||
(("notes.txt", b"hello", "text/plain"), 415),
|
||||
(("fake.jpg", b"this is not an image at all", "image/jpeg"), 400),
|
||||
(("evil.gif", make_image("GIF"), "image/gif"), 415),
|
||||
(("mismatch.jpg", make_image("PNG"), "image/jpeg"), 415), # content PNG, name .jpg
|
||||
(("empty.png", b"", "image/png"), 400),
|
||||
(("truncated.jpg", make_image("JPEG")[:2000], "image/jpeg"), 400),
|
||||
]
|
||||
for file, code in cases:
|
||||
r = await client.post(url, headers=editor_headers, files=_files(file))
|
||||
assert r.status_code == code, (file[0], r.status_code, r.text)
|
||||
assert r.json()["detail"]["errors"]
|
||||
|
||||
# one bad file in a batch -> whole batch rejected, nothing written
|
||||
r = await client.post(
|
||||
url,
|
||||
headers=editor_headers,
|
||||
files=_files(("ok.jpg", make_image("JPEG"), "image/jpeg"), ("bad.jpg", b"junk", "image/jpeg")),
|
||||
)
|
||||
assert r.status_code == 400
|
||||
assert not any(list((upload_dir / d).glob("*")) for d in ("originals", "watermarked", "thumbnails"))
|
||||
|
||||
# size limit
|
||||
monkeypatch.setattr(settings, "MAX_UPLOAD_SIZE_MB", 1)
|
||||
big = make_image("PNG", (3000, 3000), mode="RGB", compress_level=0)
|
||||
assert len(big) > 1024 * 1024
|
||||
r = await client.post(url, headers=editor_headers, files=_files(("big.png", big, "image/png")))
|
||||
assert r.status_code == 413
|
||||
|
||||
# no files at all
|
||||
r = await client.post(url, headers=editor_headers)
|
||||
assert r.status_code == 422
|
||||
|
||||
# unknown project
|
||||
r = await client.post("/api/admin/projects/999/images", headers=editor_headers,
|
||||
files=_files(("ok.jpg", make_image("JPEG"), "image/jpeg")))
|
||||
assert r.status_code == 404
|
||||
|
||||
|
||||
async def test_path_traversal_filename_is_neutralised(client, editor_headers, upload_dir):
|
||||
p = await _project(client, editor_headers)
|
||||
r = await client.post(
|
||||
f"/api/admin/projects/{p['id']}/images",
|
||||
headers=editor_headers,
|
||||
files=_files(("../../../etc/evil.jpg", make_image("JPEG"), "image/jpeg")),
|
||||
)
|
||||
assert r.status_code == 201
|
||||
img = r.json()["uploaded"][0]
|
||||
assert img["original_filename"] == "evil.jpg"
|
||||
assert ".." not in img["url"]
|
||||
assert len(list((upload_dir / "originals").glob("*"))) == 1
|
||||
|
||||
|
||||
async def test_featured_image_and_deletion(client, editor_headers, upload_dir):
|
||||
p = await _project(client, editor_headers)
|
||||
r = await client.post(
|
||||
f"/api/admin/projects/{p['id']}/images",
|
||||
headers=editor_headers,
|
||||
files=_files(*[(f"p{i}.jpg", make_image("JPEG"), "image/jpeg") for i in range(3)]),
|
||||
)
|
||||
ids = [u["id"] for u in r.json()["uploaded"]]
|
||||
|
||||
r = await client.patch(f"/api/admin/project-images/{ids[2]}", headers=editor_headers,
|
||||
json={"is_featured": True, "caption": "Completed array"})
|
||||
assert r.status_code == 200
|
||||
featured = [i for i in r.json()["images"] if i["is_featured"]]
|
||||
assert [f["id"] for f in featured] == [ids[2]]
|
||||
assert r.json()["featured_image"]["caption"] == "Completed array"
|
||||
|
||||
# second upload batch keeps existing featured image and appends sort order
|
||||
r = await client.post(f"/api/admin/projects/{p['id']}/images", headers=editor_headers,
|
||||
files=_files(("more.webp", make_image("WEBP"), "image/webp")))
|
||||
assert r.json()["uploaded"][0]["is_featured"] is False
|
||||
assert r.json()["uploaded"][0]["sort_order"] == 3
|
||||
|
||||
# deleting the featured image removes its files and promotes another image
|
||||
assert len(list((upload_dir / "watermarked").glob("*"))) == 4
|
||||
assert (await client.delete(f"/api/admin/project-images/{ids[2]}", headers=editor_headers)).status_code == 204
|
||||
for d in ("originals", "watermarked", "thumbnails"):
|
||||
assert len(list((upload_dir / d).glob("*"))) == 3
|
||||
proj = (await client.get(f"/api/admin/projects/{p['id']}", headers=editor_headers)).json()
|
||||
assert proj["featured_image"]["id"] == ids[0]
|
||||
assert sum(i["is_featured"] for i in proj["images"]) == 1
|
||||
assert (await client.delete(f"/api/admin/project-images/{ids[2]}", headers=editor_headers)).status_code == 404
|
||||
|
||||
# deleting the project removes all of its files
|
||||
assert (await client.delete(f"/api/admin/projects/{p['id']}", headers=editor_headers)).status_code == 204
|
||||
for d in ("originals", "watermarked", "thumbnails"):
|
||||
assert list((upload_dir / d).glob("*")) == []
|
||||
|
||||
|
||||
async def test_upload_fails_cleanly_without_logo(client, editor_headers, monkeypatch, tmp_path, upload_dir):
|
||||
p = await _project(client, editor_headers)
|
||||
monkeypatch.setattr(settings, "WATERMARK_LOGO_PATH", tmp_path / "missing.png")
|
||||
r = await client.post(f"/api/admin/projects/{p['id']}/images", headers=editor_headers,
|
||||
files=_files(("a.jpg", make_image("JPEG"), "image/jpeg")))
|
||||
assert r.status_code == 503
|
||||
assert "logo" in r.json()["detail"].lower()
|
||||
assert list((upload_dir / "originals").glob("*")) == []
|
||||
|
||||
|
||||
async def test_services_with_watermarked_image(client, editor_headers, upload_dir):
|
||||
r = await client.post("/api/admin/services", headers=editor_headers,
|
||||
json={"title": "Rooftop Solar", "short_description": "Homes", "sort_order": 1})
|
||||
assert r.status_code == 201
|
||||
sid = r.json()["id"]
|
||||
assert r.json()["slug"] == "rooftop-solar"
|
||||
assert (await client.get("/api/services")).json() == []
|
||||
|
||||
r = await client.put(f"/api/admin/services/{sid}", headers=editor_headers,
|
||||
json={"is_published": True, "description": "Full description"})
|
||||
assert r.status_code == 200
|
||||
|
||||
r = await client.post(f"/api/admin/services/{sid}/image", headers=editor_headers,
|
||||
files={"file": ("svc.png", make_image("PNG"), "image/png")})
|
||||
assert r.status_code == 200, r.text
|
||||
first_url = r.json()["image_url"]
|
||||
assert first_url and r.json()["thumbnail_url"]
|
||||
|
||||
# replacing deletes the old files
|
||||
r = await client.post(f"/api/admin/services/{sid}/image", headers=editor_headers,
|
||||
files={"file": ("svc2.jpg", make_image("JPEG"), "image/jpeg")})
|
||||
assert r.json()["image_url"] != first_url
|
||||
assert len(list((upload_dir / "watermarked").glob("*"))) == 1
|
||||
|
||||
bad = await client.post(f"/api/admin/services/{sid}/image", headers=editor_headers,
|
||||
files={"file": ("x.jpg", b"nope", "image/jpeg")})
|
||||
assert bad.status_code == 400
|
||||
|
||||
public = (await client.get("/api/services")).json()
|
||||
assert len(public) == 1 and "is_published" not in public[0]
|
||||
assert (await client.get("/api/services/rooftop-solar")).status_code == 200
|
||||
|
||||
r = await client.delete(f"/api/admin/services/{sid}/image", headers=editor_headers)
|
||||
assert r.json()["image_url"] is None
|
||||
assert list((upload_dir / "watermarked").glob("*")) == []
|
||||
assert (await client.delete(f"/api/admin/services/{sid}", headers=editor_headers)).status_code == 204
|
||||
assert (await client.get("/api/services/rooftop-solar")).status_code == 404
|
||||
@@ -0,0 +1,107 @@
|
||||
from email import message_from_bytes
|
||||
|
||||
from app.core.config import settings
|
||||
from app.services.quotation import DEFAULT_QUOTE_SETTINGS, calculate_quote, format_inr
|
||||
from tests.conftest import make_image
|
||||
|
||||
|
||||
def test_format_inr_indian_grouping():
|
||||
assert format_inr(59500) == "₹59,500"
|
||||
assert format_inr(197000) == "₹1,97,000"
|
||||
assert format_inr(8420000) == "₹84,20,000"
|
||||
assert format_inr(999) == "₹999"
|
||||
|
||||
|
||||
def test_quote_matches_design_rates_and_subsidy_rules():
|
||||
cfg = dict(DEFAULT_QUOTE_SETTINGS)
|
||||
q = calculate_quote(cfg, "residential", 250, "Bhubaneswar, India")
|
||||
assert q.capacity_kw == 2.5
|
||||
assert q.panel_cost == 92_500 and q.installation_cost == 22_500 # as in Figma
|
||||
assert q.subsidy == 69_000 # 2 kW x 30,000 + 0.5 kW x 18,000
|
||||
assert q.total_after_subsidy == 92_500 + 22_500 - 69_000
|
||||
|
||||
big = calculate_quote(cfg, "residential", 2000, "")
|
||||
assert big.capacity_kw == 20 and big.subsidy == 78_000 # capped
|
||||
assert big.panel_cost == 740_000 and big.installation_cost == 180_000 # as in Figma
|
||||
|
||||
com = calculate_quote(cfg, "commercial", 500, "")
|
||||
assert com.subsidy == 0 and com.total_after_subsidy == 230_000
|
||||
|
||||
clamped = calculate_quote(cfg, "residential", 999_999, "")
|
||||
assert clamped.roof_area_sqft == cfg["max_area_sqft"]
|
||||
|
||||
|
||||
async def test_quote_endpoints_and_admin_overrides(client, admin_headers):
|
||||
r = await client.post("/api/quotations/calculate", json={"property_type": "residential", "roof_area_sqft": 500})
|
||||
assert r.status_code == 200 and r.json()["capacity_kw"] == 5
|
||||
|
||||
await client.put("/api/admin/content/quote_settings", headers=admin_headers,
|
||||
json={"value": {"panel_cost_per_kw": 40000, "sqft_per_kw": "abc"}})
|
||||
s = (await client.get("/api/quotations/settings")).json()
|
||||
assert s["panel_cost_per_kw"] == 40000 and s["sqft_per_kw"] == 100 # invalid value ignored
|
||||
r = await client.post("/api/quotations/calculate", json={"roof_area_sqft": 500})
|
||||
assert r.json()["panel_cost"] == 200_000
|
||||
|
||||
bad = await client.post("/api/quotations/calculate", json={"property_type": "villa", "roof_area_sqft": 0})
|
||||
assert bad.status_code == 422
|
||||
|
||||
|
||||
async def test_quote_pdf(client):
|
||||
r = await client.post("/api/quotations/pdf", json={"property_type": "commercial", "roof_area_sqft": 750, "location": "Cuttack"})
|
||||
assert r.status_code == 200
|
||||
assert r.headers["content-type"] == "application/pdf"
|
||||
assert r.content.startswith(b"%PDF")
|
||||
|
||||
|
||||
async def test_email_quote_saves_lead_and_writes_outbox(client, admin_headers, tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(settings, "OUTBOX_DIR", tmp_path)
|
||||
r = await client.post("/api/quotations/email",
|
||||
json={"roof_area_sqft": 750, "location": "Puri", "email": "lead@example.com"})
|
||||
assert r.status_code == 200
|
||||
assert "sent to your email" in r.json()["message"]
|
||||
|
||||
files = list(tmp_path.glob("*.eml"))
|
||||
assert len(files) == 1
|
||||
msg = message_from_bytes(files[0].read_bytes())
|
||||
assert msg["To"] == "lead@example.com"
|
||||
assert any(p.get_filename() == "saura-shakti-quotation.pdf" for p in msg.walk())
|
||||
|
||||
enquiries = (await client.get("/api/admin/enquiries", headers=admin_headers)).json()
|
||||
assert enquiries["total"] == 1
|
||||
lead = enquiries["items"][0]
|
||||
assert lead["source"] == "quote_calculator" and lead["phone"] is None
|
||||
assert lead["required_capacity_kw"] == 7.5
|
||||
|
||||
# honeypot: nothing saved or sent
|
||||
await client.post("/api/quotations/email", json={"roof_area_sqft": 750, "email": "bot@example.com", "website": "x"})
|
||||
assert len(list(tmp_path.glob("*.eml"))) == 1
|
||||
bad = await client.post("/api/quotations/email", json={"roof_area_sqft": 750, "email": "nope"})
|
||||
assert bad.status_code == 422
|
||||
|
||||
|
||||
async def test_newsletter(client, admin_headers, editor_headers):
|
||||
assert (await client.post("/api/subscribe", json={"email": "Fan@Example.com"})).status_code == 201
|
||||
assert (await client.post("/api/subscribe", json={"email": "fan@example.com"})).status_code == 201 # idempotent
|
||||
assert (await client.post("/api/subscribe", json={"email": "bad"})).status_code == 422
|
||||
lst = (await client.get("/api/admin/subscribers", headers=editor_headers)).json()
|
||||
assert lst["total"] == 1 and lst["items"][0]["email"] == "fan@example.com"
|
||||
assert (await client.delete("/api/admin/subscribers/1", headers=editor_headers)).status_code == 403
|
||||
assert (await client.delete("/api/admin/subscribers/1", headers=admin_headers)).status_code == 204
|
||||
|
||||
|
||||
async def test_testimonial_video_and_image(client, editor_headers, upload_dir):
|
||||
bad = await client.post("/api/admin/testimonials", headers=editor_headers,
|
||||
json={"customer_name": "Rajesh Kumar", "video_url": "javascript:alert(1)"})
|
||||
assert bad.status_code == 422
|
||||
r = await client.post("/api/admin/testimonials", headers=editor_headers,
|
||||
json={"customer_name": "Rajesh Kumar", "designation": "Homeowner",
|
||||
"video_url": "https://www.youtube.com/watch?v=abc123"})
|
||||
assert r.status_code == 201 and r.json()["content"] is None
|
||||
tid = r.json()["id"]
|
||||
r = await client.post(f"/api/admin/testimonials/{tid}/image", headers=editor_headers,
|
||||
files={"file": ("still.jpg", make_image("JPEG"), "image/jpeg")})
|
||||
assert r.status_code == 200 and r.json()["thumbnail_url"]
|
||||
pub = (await client.get("/api/testimonials")).json()[0]
|
||||
assert pub["video_url"].startswith("https://") and pub["image_url"]
|
||||
assert (await client.delete(f"/api/admin/testimonials/{tid}", headers=editor_headers)).status_code == 204
|
||||
assert list((upload_dir / "watermarked").glob("*")) == []
|
||||
@@ -0,0 +1,62 @@
|
||||
"""Unit tests for the watermark algorithm itself (no HTTP / DB)."""
|
||||
|
||||
from PIL import Image, ImageChops, ImageStat
|
||||
|
||||
from app.core.config import settings
|
||||
from app.services.image_processing import apply_watermark
|
||||
|
||||
|
||||
def _logo(path) -> Image.Image:
|
||||
return Image.open(path).convert("RGBA")
|
||||
|
||||
|
||||
def _bbox_of_change(a: Image.Image, b: Image.Image):
|
||||
return ImageChops.difference(a.convert("RGB"), b.convert("RGB")).getbbox()
|
||||
|
||||
|
||||
def test_watermark_bottom_right_and_proportional(logo_path):
|
||||
logo = _logo(logo_path)
|
||||
for size in [(4000, 3000), (1200, 800), (800, 1200), (300, 200)]:
|
||||
img = Image.new("RGB", size, (90, 120, 150))
|
||||
out = apply_watermark(img, logo)
|
||||
assert out.size == size
|
||||
x0, y0, x1, y1 = _bbox_of_change(img, out)
|
||||
W, H = size
|
||||
assert x0 > W / 2 and y0 > H / 2, "watermark must sit in the bottom-right quadrant"
|
||||
margin = max(8, round(min(W, H) * settings.WATERMARK_MARGIN_RATIO))
|
||||
assert W - x1 <= margin + 2 and H - y1 <= margin + 2 # consistent margins (halo may bleed slightly)
|
||||
# scales with image size, capped at 50% width for small images
|
||||
assert (x1 - x0) <= W * 0.5 + 10
|
||||
|
||||
|
||||
def test_logo_aspect_ratio_never_distorted(logo_path):
|
||||
logo = _logo(logo_path)
|
||||
img = Image.new("RGB", (2000, 2000), (0, 0, 0))
|
||||
out = apply_watermark(img, logo)
|
||||
# Find the solid logo area: pixels clearly brighter than the halo
|
||||
diff = ImageChops.difference(img, out.convert("RGB")).convert("L").point(lambda v: 255 if v > 100 else 0)
|
||||
x0, y0, x1, y1 = diff.getbbox()
|
||||
w, h = x1 - x0, y1 - y0
|
||||
# fixture content is 400x80 inside a 400x120 canvas -> ratio 5.0
|
||||
assert abs((w / h) - 5.0) < 0.25
|
||||
|
||||
|
||||
def test_visible_on_bright_and_dark_photos(logo_path):
|
||||
logo = _logo(logo_path) # white logo -> hardest case is a white photo
|
||||
for colour in [(255, 255, 255), (0, 0, 0), (128, 128, 128)]:
|
||||
img = Image.new("RGB", (1600, 1000), colour)
|
||||
out = apply_watermark(img, logo).convert("RGB")
|
||||
box = _bbox_of_change(img, out)
|
||||
region_diff = ImageStat.Stat(ImageChops.difference(img.crop(box), out.crop(box))).mean
|
||||
assert max(region_diff) > 20, f"watermark not visible on {colour}"
|
||||
|
||||
|
||||
def test_transparency_keeps_photo_visible(logo_path):
|
||||
logo = _logo(logo_path)
|
||||
img = Image.new("RGB", (1600, 1000), (20, 140, 60))
|
||||
out = apply_watermark(img, logo).convert("RGB")
|
||||
x0, y0, x1, y1 = _bbox_of_change(img, out)
|
||||
centre = out.getpixel(((x0 + x1) // 2, (y0 + y1) // 2))
|
||||
# with partial opacity the green photo still shows through the white logo
|
||||
assert centre != (255, 255, 255)
|
||||
assert centre[1] > centre[0]
|
||||
Reference in New Issue
Block a user