-
@@ -0,0 +1,5 @@
|
||||
# Copy to .env — used by docker-compose for the development PostgreSQL container.
|
||||
POSTGRES_USER=saurashakti
|
||||
POSTGRES_PASSWORD=change-me
|
||||
POSTGRES_DB=saurashakti
|
||||
POSTGRES_PORT=5440
|
||||
@@ -0,0 +1,44 @@
|
||||
# Secrets / local config
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
*.pem
|
||||
|
||||
# Python
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
.venv/
|
||||
venv/
|
||||
.pytest_cache/
|
||||
.coverage
|
||||
htmlcov/
|
||||
|
||||
# Uploaded media (keep folder structure only)
|
||||
backend/uploads/**/*
|
||||
!backend/uploads/**/
|
||||
!backend/uploads/**/.gitkeep
|
||||
|
||||
# Node / frontend
|
||||
node_modules/
|
||||
dist/
|
||||
.vite/
|
||||
|
||||
# Editors / OS
|
||||
.vscode/
|
||||
.idea/
|
||||
.DS_Store
|
||||
*.log
|
||||
|
||||
# Dev server
|
||||
backend/.uvicorn.pid
|
||||
backend/outbox/
|
||||
|
||||
# Frontend dev server
|
||||
frontend/.vite.pid
|
||||
|
||||
# Raw Figma exports (large, re-downloadable with the Figma token)
|
||||
design/raw/
|
||||
design/assets/
|
||||
design/renders/
|
||||
design/slices/
|
||||
.playwright-cli/
|
||||
@@ -0,0 +1,124 @@
|
||||
# Saura Shakti — Solar Company Website
|
||||
|
||||
Development project (not deployed). React + Vite + Tailwind frontend, FastAPI + PostgreSQL backend,
|
||||
admin dashboard, and automatic logo watermarking of uploaded photos.
|
||||
|
||||
| Part | Status |
|
||||
|---|---|
|
||||
| Public website (from Figma) | ✅ All 8 Figma sections, responsive; plus projects gallery, legal pages |
|
||||
| Admin dashboard | ✅ Login, dashboard, enquiries, projects + photos, services, testimonials, messages, subscribers, website text, admin users |
|
||||
| Photo upload + watermark | ✅ Official logo from Figma, applied automatically |
|
||||
| Backend API + database | ✅ 34 automated tests passing |
|
||||
|
||||
## Start / stop (everything)
|
||||
|
||||
```bash
|
||||
scripts/dev.sh start # PostgreSQL (Docker) + API + website
|
||||
scripts/dev.sh stop # stop all (database data is kept)
|
||||
scripts/dev.sh status
|
||||
scripts/dev.sh logs # follow API + website logs
|
||||
scripts/dev.sh test # backend test suite (separate saurashakti_test database)
|
||||
scripts/dev.sh migrate # apply database migrations
|
||||
```
|
||||
|
||||
| What | URL |
|
||||
|---|---|
|
||||
| Website | http://localhost:5173 |
|
||||
| Admin dashboard | http://localhost:5173/admin |
|
||||
| API docs (Swagger) | http://localhost:8020/docs |
|
||||
| PostgreSQL | 127.0.0.1:5440 (container `saurashakti-website-dev-db`) |
|
||||
|
||||
Ports 8000/5432 were already used by other applications on this server, so 8020/5440 are used.
|
||||
The website dev server proxies `/api` and `/media` to the API, so the browser only talks to port 5173.
|
||||
|
||||
## First-time setup
|
||||
|
||||
```bash
|
||||
cp .env.example .env # DB credentials for docker-compose
|
||||
cp backend/.env.example backend/.env # same DB password + a random JWT secret
|
||||
cd backend && python3 -m venv .venv && .venv/bin/pip install -r requirements.txt && cd ..
|
||||
cd frontend && npm install && cd ..
|
||||
scripts/dev.sh start
|
||||
|
||||
# create your admin account (password is prompted, never typed on the command line)
|
||||
cd backend && .venv/bin/python -m app.cli create-admin --email you@example.com --name "Your Name"
|
||||
# roles: super_admin (default) | admin | editor --update resets an existing account
|
||||
```
|
||||
|
||||
To run Python commands yourself, use the project environment: `source backend/.venv/bin/activate`
|
||||
(or call `backend/.venv/bin/python`), not the conda base Python.
|
||||
|
||||
## Design (Figma)
|
||||
|
||||
The design was read via the Figma API: `design/DESIGN_ANALYSIS.md` lists sections, colours, fonts and the
|
||||
decisions taken where the design had gaps. Original exports are in `design/` (renders, full-size images,
|
||||
icons). The site uses web-optimised WebP versions (`frontend/src/assets`).
|
||||
|
||||
All copy on the page is admin-editable (**Website content**). Empty fields fall back to the Figma text, and the
|
||||
layout never changes. Until real services/testimonials are added, the sections show the design content.
|
||||
|
||||
## Watermark
|
||||
|
||||
The official logo (exported from Figma, transparent PNG, trimmed) is at `backend/assets/watermark/logo.png`.
|
||||
Every admin image upload (projects, services, testimonials) is processed:
|
||||
|
||||
- Original saved untouched in `uploads/originals/` (**not public**; admins can download it).
|
||||
- Watermarked copy in `uploads/watermarked/`: logo bottom-right, 18% of image width (never upscaled beyond
|
||||
the logo's own resolution), 75% opacity, plus an automatic soft halo so it reads on bright and dark photos.
|
||||
- WEBP thumbnail ≤640px in `uploads/thumbnails/`.
|
||||
- Validation: JPG/JPEG/PNG/WEBP only, real content check, extension must match content, ≤10 MB,
|
||||
no animated/oversized images, random UUID filenames, multi-file uploads are all-or-nothing.
|
||||
|
||||
A larger logo file (e.g. 1500px wide or SVG) would give a sharper watermark on very large photos.
|
||||
|
||||
## Quote calculator
|
||||
|
||||
Rates match the per-kW figures in the Figma design (₹37,000/kW equipment, ₹9,000/kW installation,
|
||||
100 sq ft per kW). Subsidy follows PM Surya Ghar rules for residential (₹30k/kW up to 2 kW, ₹18k for the
|
||||
3rd kW, max ₹78k), none for commercial. All rates are editable in **Website content → Quote calculator rates**.
|
||||
|
||||
- **Download Quotation** → PDF generated by the backend.
|
||||
- **Email Quotation** → saves a lead in Enquiries (source "Quote calculator") and emails the PDF.
|
||||
Without SMTP settings, emails are saved as `.eml` files in `backend/outbox/` (open them with any mail app).
|
||||
To send real email, set `SMTP_HOST`, `SMTP_PORT`, `SMTP_USER`, `SMTP_PASSWORD`, `MAIL_FROM` in `backend/.env`.
|
||||
|
||||
## API overview
|
||||
|
||||
Full docs at http://localhost:8020/docs.
|
||||
|
||||
**Public:** `GET /api/health` · `POST /api/enquiries` · `POST /api/contact` · `POST /api/subscribe` ·
|
||||
`GET /api/projects`, `/api/projects/{id|slug}` · `GET /api/services`, `/api/services/{id|slug}` ·
|
||||
`GET /api/testimonials` · `GET /api/content`, `/api/content/{key}` ·
|
||||
`GET /api/quotations/settings` · `POST /api/quotations/calculate | pdf | email`
|
||||
|
||||
**Auth:** `POST /api/auth/login` · `GET /api/auth/me` · `POST /api/auth/change-password`
|
||||
|
||||
**Admin (Bearer token):** dashboard stats · enquiries (list/search/filter/detail/status/notes/delete) ·
|
||||
projects CRUD · project images (multi-upload, caption, featured, delete, original download) ·
|
||||
services CRUD + image · testimonials CRUD + image + video link · contact messages · subscribers ·
|
||||
site content blocks · admin users (super admin only).
|
||||
|
||||
### Roles
|
||||
|
||||
| | super_admin | admin | editor |
|
||||
|---|---|---|---|
|
||||
| Projects, photos, services, testimonials, website text | ✅ | ✅ | ✅ |
|
||||
| View/update enquiries & messages | ✅ | ✅ | ✅ |
|
||||
| Delete enquiries, messages, subscribers; reset text | ✅ | ✅ | ❌ |
|
||||
| Manage admin accounts | ✅ | ❌ | ❌ |
|
||||
|
||||
## Security notes
|
||||
|
||||
Argon2id password hashing · JWT with expiry (expired sessions return to login) · per-request account checks ·
|
||||
rate limits on login and public forms · honeypot spam field · strict upload validation · originals never public ·
|
||||
secrets only in git-ignored `.env` files · dev servers bind to 127.0.0.1.
|
||||
|
||||
## Project structure
|
||||
|
||||
```
|
||||
backend/ FastAPI app (app/core, models, schemas, routes, services, middleware, utils), alembic/, tests/, uploads/
|
||||
frontend/ React app: src/sections (Figma sections), pages, components, admin/ (dashboard), services/api.js
|
||||
design/ Figma analysis, renders, original images, icons
|
||||
docker-compose.yml development PostgreSQL only
|
||||
scripts/dev.sh start/stop helper
|
||||
```
|
||||
@@ -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"}
|
||||
@@ -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"\_")
|
||||
|
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]
|
||||
@@ -0,0 +1,85 @@
|
||||
# Saura Shakti — Design Analysis (from Figma)
|
||||
|
||||
Source: Figma file `hod3VwudD5fCjR6z0TYOES` ("Saura Shaki Landing Page"), read via API on 2026-11-13.
|
||||
Raw data, renders, original images and icons are in `design/` (`raw/`, `renders/`, `assets/`, `icons/`).
|
||||
|
||||
## Pages / frames
|
||||
|
||||
- **Design page** → one desktop frame, 1440 × 6832: the landing page.
|
||||
- **Components page** → interactive variants used by the landing page (slider pages, accordion states,
|
||||
process steps, quotation states, button hover/success states).
|
||||
It also holds 5 grey wireframe sections (meet experts, services, results, testimonials, mission)
|
||||
with `$` prices. They are **not** part of the landing page and are not implemented.
|
||||
|
||||
There is **no** mobile/tablet frame, so the responsive layouts are derived from the desktop design.
|
||||
|
||||
## Section order (desktop, y-offset)
|
||||
|
||||
| # | Section | y | Height | Background |
|
||||
|---|---|---|---|---|
|
||||
| 1 | Hero + navbar + features bar | 0 | 785 | photo + gradient `#0E5177/32% → #082D42/60% → #00070B`, 80% |
|
||||
| 2 | Use case slider "Powering Homes, Businesses & Beyond" (3 pages) | 785 | 618 | `#FFFFFF` |
|
||||
| 3 | Solar awareness "Know Your Solar" + 4 glass cards | 1403 | 777 | photo + `#0B1528` 65% |
|
||||
| 4 | Myths accordion (5 items, image changes per item) | 2180 | 863 | `#FFFFFF` |
|
||||
| 5 | Custom quote calculator | 3043 | 770 | `#F4F6F8` |
|
||||
| 6 | Installation process, 4 steps (active card expands) | 3813 | 927 | `#034C75` |
|
||||
| 7 | Testimonials: featured video + carousel + pager | 4740 | 1330 | `#F7F7F7` |
|
||||
| 8 | Footer with giant "SAURA SHAKTI" watermark text | 6070 | 778 | `#010F1C` (approx.) |
|
||||
|
||||
Content width 1280 (80px side padding); section vertical padding 80 (process: 96).
|
||||
|
||||
## Colour palette
|
||||
|
||||
| Token | Hex | Used for |
|
||||
|---|---|---|
|
||||
| navy | `#0F172A` | headings, body text |
|
||||
| brand-blue | `#034C75` | process bg, accordion active, metric numbers, nav CTA |
|
||||
| green | `#66BB22` | tag dots, slider track; `#1FAD20` highlighted words; `#4ADE80` awareness dot |
|
||||
| lime | `#ACD860` | selected property-type pill, button hover fill |
|
||||
| pale-lime | `#D2E59E` | hero feature icons |
|
||||
| yellow | `#F2BD1F` / `#EDBD20` / `#F0BC25` | primary CTA, step badge, quote icons, subscribe |
|
||||
| slate | `#4D5660` | arrow buttons, numbers, labels |
|
||||
| muted | `#7A8F9F` | "Let's Clear It Up." line, location icon |
|
||||
| forest | `#224233` | quote buttons and inputs (stroke and text), slider handle |
|
||||
| ink | `#1C2421` | accordion answer, row values |
|
||||
| grey bg | `#F4F6F8`, `#F7F7F7` | quote / testimonials section |
|
||||
| footer | `#010F1C`, social `#16171D` | footer |
|
||||
|
||||
## Typography
|
||||
|
||||
- **Manrope** (primary): H2 800 48/56 −1.5; hero H1 800 48/64 −1.5; card titles 600 24/32;
|
||||
lead 400/500 20/32; body 400 16/24; nav 600 16/22; tag 800 14/19 +1 uppercase.
|
||||
- **Inter**: accordion numbers 700 16; metrics 900 40/48; pills 400 14; buttons 500 16; Learn More 600 18.
|
||||
- **Poppins** 900 270px, 7% opacity: footer watermark word.
|
||||
|
||||
## Radii and effects
|
||||
|
||||
Pills 100; cards 12 / 24 / 32 / 34; hero navbar 94; images 12–24.
|
||||
Glass cards: `rgba(255,255,255,.07)`, 1.4px border at 60% white, backdrop blur 22.
|
||||
Thumbnail play button: shadow `0 4 12 rgba(0,0,0,.1)`.
|
||||
|
||||
## Interactions (from component variants)
|
||||
|
||||
- Use case: 3 pages (Home / Business / Agriculture) with arrows; thumbnails on the left; hover turns the arrow lime.
|
||||
- Myths: single-open accordion; the active item gets a grey bg, blue text and a minus icon; the right image changes per item.
|
||||
- Quote: Residential/Commercial toggle; roof-area slider (250/500/750/1000/2000 sq ft at 20/40/60/80/100%);
|
||||
location input; Download → "Quotation downloaded successfully." banner; Email → inline email input, then
|
||||
"Your quotation has also been sent to your email." banner. Buttons fill lime on hover.
|
||||
- Process: the active card shows a yellow badge, a lighter overlay and a description; the others are dimmed.
|
||||
- Testimonials: featured video card with progress bar and time; thumbnail carousel; "3 Of 12" pager.
|
||||
|
||||
## Assets
|
||||
|
||||
All original images exported at full resolution (hero, awareness bg, 3 use-case photos, 5 myth photos,
|
||||
4 step photos, 5 testimonial stills, footer panel, logo). The icons are custom vectors, exported as SVG.
|
||||
|
||||
## Gaps in the design → decisions taken
|
||||
|
||||
| Gap | Decision |
|
||||
|---|---|
|
||||
| No enquiry/contact form | "Get a consultation" / "Support" open a modal form in the same visual style → `POST /api/enquiries` / `/api/contact` |
|
||||
| No project gallery | `/projects` and `/projects/:slug` pages in the same design language; the use-case images link there |
|
||||
| Quote figures in variants are inconsistent (cost after subsidy ≠ equipment + install − subsidy) | Calculated properly: ₹37,000/kW equipment, ₹9,000/kW installation (both match the design), subsidy per PM Surya Ghar rules; all rates are editable by admins |
|
||||
| Footer copy is template text ("Evora…", "Engineered for the void") | Replaced with Saura Shakti wording; editable in admin |
|
||||
| Process section tag says "CLARIFYING SOLAR MYTHS" (copied from the myths section) | Kept as designed and editable in admin; flagged for confirmation |
|
||||
| No mobile design | Responsive layouts derived from desktop: stacked columns, hamburger menu, horizontal scroll for carousels |
|
||||
@@ -0,0 +1,10 @@
|
||||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<g clip-path="url(#clip0_0_71)">
|
||||
<path d="M5.54998 14.0125L-0.150024 8.31255L1.27498 6.88755L5.54998 11.1625L14.725 1.98755L16.15 3.41255L5.54998 14.0125Z" fill="black"/>
|
||||
</g>
|
||||
<defs>
|
||||
<clipPath id="clip0_0_71">
|
||||
<rect width="16" height="16" fill="white"/>
|
||||
</clipPath>
|
||||
</defs>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 377 B |
@@ -0,0 +1,10 @@
|
||||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<g clip-path="url(#clip0_0_52)">
|
||||
<path d="M5.54998 14.0008L-0.150024 8.30083L1.27498 6.87583L5.54998 11.1508L14.725 1.97583L16.15 3.40083L5.54998 14.0008Z" fill="black"/>
|
||||
</g>
|
||||
<defs>
|
||||
<clipPath id="clip0_0_52">
|
||||
<rect width="16" height="16" fill="white"/>
|
||||
</clipPath>
|
||||
</defs>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 377 B |
@@ -0,0 +1,10 @@
|
||||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<g clip-path="url(#clip0_0_62)">
|
||||
<path d="M5.5501 14.0133L-0.149902 8.31328L1.2751 6.88828L5.5501 11.1633L14.7251 1.98828L16.1501 3.41328L5.5501 14.0133Z" fill="black"/>
|
||||
</g>
|
||||
<defs>
|
||||
<clipPath id="clip0_0_62">
|
||||
<rect width="16" height="16" fill="white"/>
|
||||
</clipPath>
|
||||
</defs>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 376 B |
@@ -0,0 +1,10 @@
|
||||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<g clip-path="url(#clip0_0_80)">
|
||||
<path d="M5.54998 14.0125L-0.150024 8.31255L1.27498 6.88755L5.54998 11.1625L14.725 1.98755L16.15 3.41255L5.54998 14.0125Z" fill="black"/>
|
||||
</g>
|
||||
<defs>
|
||||
<clipPath id="clip0_0_80">
|
||||
<rect width="16" height="16" fill="white"/>
|
||||
</clipPath>
|
||||
</defs>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 377 B |
@@ -0,0 +1,3 @@
|
||||
<svg width="31" height="31" viewBox="0 0 31 31" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M28.4176 18.0831V12.9165M5.16579 7.74982H20.667C22.0939 7.74982 23.2506 8.90641 23.2506 10.3331V20.6665C23.2506 22.0932 22.0939 23.2498 20.667 23.2498H5.16579C3.73894 23.2498 2.58225 22.0932 2.58225 20.6665V10.3331C2.58225 8.90641 3.73894 7.74982 5.16579 7.74982Z" stroke-width="2.81818" stroke-linecap="round" stroke="white"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 440 B |
@@ -0,0 +1,3 @@
|
||||
<svg width="31" height="31" viewBox="0 0 31 31" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M15.4997 25.834V28.4175M15.4997 25.834H21.9585M15.4997 25.834H9.04085M15.4997 2.58213V5.16566M15.4997 5.16566H9.04085M15.4997 5.16566H21.9585M21.9585 25.834V28.4175M21.9585 25.834H23.2503C24.6772 25.834 25.8339 24.6773 25.8339 23.2504V21.9587M21.9585 2.58213V5.16566M21.9585 5.16566H23.2503C24.6772 5.16566 25.8339 6.32235 25.8339 7.7492V9.04097M2.582 15.4998H5.16554M5.16554 15.4998V21.9587M5.16554 15.4998V9.04097M2.582 21.9587H5.16554M5.16554 21.9587V23.2504C5.16554 24.6773 6.32223 25.834 7.74908 25.834H9.04085M2.582 9.04097H5.16554M5.16554 9.04097V7.7492C5.16554 6.32235 6.32223 5.16566 7.74908 5.16566H9.04085M25.8339 15.4998H28.4174M25.8339 15.4998V9.04097M25.8339 15.4998V21.9587M25.8339 21.9587H28.4174M25.8339 9.04097H28.4174M9.04085 25.834V28.4175M9.04085 2.58213V5.16566M11.6244 10.3327H19.375C20.0884 10.3327 20.6668 10.9111 20.6668 11.6245V19.3751C20.6668 20.0886 20.0884 20.6669 19.375 20.6669H11.6244C10.911 20.6669 10.3326 20.0886 10.3326 19.3751V11.6245C10.3326 10.9111 10.911 10.3327 11.6244 10.3327Z" stroke-width="2.81818" stroke-linecap="round" stroke="white"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.2 KiB |
@@ -0,0 +1,10 @@
|
||||
<svg width="31" height="31" viewBox="0 0 31 31" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<g clip-path="url(#clip0_5_41)">
|
||||
<path d="M2.58225 27.1248C2.58225 24.3703 3.78969 22.0334 5.98653 20.6153M5.98653 20.6153C6.88026 20.0384 7.93773 19.6136 9.14428 19.3745C12.2703 18.7545 15.4996 16.791 16.7914 15.4993M5.98653 20.6153C6.48525 21.6838 7.19243 22.6537 8.07763 23.4633C9.75138 24.9941 11.9393 25.84 14.2076 25.8331C20.9504 25.8331 27.1249 20.0203 27.1249 12.9159C27.1249 7.98152 25.8332 5.16557 24.5415 2.58213C21.958 5.78559 20.0204 6.45729 12.6575 7.87818C10.4216 8.26014 8.41102 9.46844 7.02439 11.2634C5.63776 13.0584 4.97641 15.309 5.1715 17.5688C5.26341 18.6335 5.54226 19.6635 5.98653 20.6153Z" stroke-width="2.81818" stroke-linecap="round" stroke="white"/>
|
||||
</g>
|
||||
<defs>
|
||||
<clipPath id="clip0_5_41">
|
||||
<rect width="30.8171" height="30.8171" fill="white" transform="scale(1.00593)"/>
|
||||
</clipPath>
|
||||
</defs>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 921 B |
@@ -0,0 +1,3 @@
|
||||
<svg width="31" height="31" viewBox="0 0 31 31" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M14.209 2.58213H16.7924M18.4455 18.0834L15.5004 23.2504M18.4455 18.0834H10.3343C9.87069 18.0833 9.41555 18.2079 9.01668 18.4443C8.6178 18.6807 8.28989 19.02 8.06733 19.4268L5.88845 23.2504M18.4455 18.0834H25.8352C26.0627 18.0832 26.2862 18.143 26.4831 18.2569C26.68 18.3708 26.8434 18.5347 26.9566 18.732C27.0699 18.9293 27.129 19.153 27.1281 19.3804C27.1272 19.6079 27.0662 19.8311 26.9513 20.0275L25.1138 23.2517M15.5004 23.2504L12.5552 28.4175M15.5004 23.2504H25.1133L25.1138 23.2517M15.5004 23.2504H5.88845M12.5552 28.4175H20.6683C21.1314 28.4176 21.5861 28.2932 21.9847 28.0574C22.3833 27.8215 22.7112 27.4827 22.934 27.0767L25.1138 23.2517M12.5552 28.4175H5.16737C4.93982 28.4176 4.71627 28.3576 4.51935 28.2436C4.32244 28.1295 4.15915 27.9654 4.04601 27.768C3.93286 27.5706 3.87389 27.3467 3.87505 27.1192C3.87621 26.8916 3.93746 26.6684 4.0526 26.4721L5.88845 23.2504M27.1259 28.4175L25.1138 23.2517M5.88845 23.2504H5.88707M3.87503 12.9163V15.4998M9.042 2.58213C9.042 3.95252 8.49762 5.26679 7.52863 6.2358C6.55963 7.20482 5.2454 7.7492 3.87503 7.7492M11.1865 9.89374L13.0078 11.7151" stroke-width="2.81818" stroke-linecap="round" stroke="white"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.2 KiB |
@@ -0,0 +1,3 @@
|
||||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M3.33282 3.33364C3.33276 3.09905 3.3946 2.8686 3.5121 2.66554C3.62961 2.46249 3.79862 2.29404 4.00207 2.17718C4.20553 2.06033 4.43622 1.99921 4.67085 2.00001C4.90548 2.0008 5.13575 2.06348 5.3384 2.18172L13.3374 6.84674C13.5393 6.96385 13.7068 7.13189 13.8234 7.33405C13.94 7.53621 14.0014 7.76541 14.0016 7.99876C14.0018 8.2321 13.9408 8.46142 13.8246 8.66378C13.7083 8.86614 13.541 9.03446 13.3394 9.15192L5.3384 13.8183C5.13575 13.9365 4.90548 13.9992 4.67085 14C4.43622 14.0008 4.20553 13.9397 4.00207 13.8228C3.79862 13.706 3.62961 13.5375 3.5121 13.3345C3.3946 13.1314 3.33276 12.9009 3.33282 12.6664V3.33364Z" stroke-width="2" stroke-linecap="round" stroke="#111111"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 788 B |
@@ -0,0 +1,10 @@
|
||||
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<g clip-path="url(#clip0_9_228)">
|
||||
<path d="M1.66602 17.5C1.66602 15.7229 2.44501 14.2152 3.86233 13.3003M3.86233 13.3003C4.43893 12.9281 5.12117 12.654 5.89959 12.4998C7.91637 12.0998 9.99982 10.8331 10.8332 9.9997M3.86233 13.3003C4.18408 13.9897 4.64033 14.6154 5.21142 15.1378C6.29127 16.1254 7.70285 16.6711 9.16621 16.6666C13.5165 16.6666 17.5 12.9165 17.5 8.33296C17.5 5.1495 16.6666 3.33275 15.8333 1.66602C14.1665 3.73277 12.9164 4.16612 8.16616 5.08283C6.72369 5.32925 5.42651 6.10881 4.53191 7.26687C3.63731 8.42493 3.21064 9.87692 3.3365 11.3348C3.3958 12.0217 3.5757 12.6863 3.86233 13.3003Z" stroke-width="2" stroke-linecap="round" stroke="#D2E59E"/>
|
||||
</g>
|
||||
<defs>
|
||||
<clipPath id="clip0_9_228">
|
||||
<rect width="20" height="20" fill="white"/>
|
||||
</clipPath>
|
||||
</defs>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 870 B |
@@ -0,0 +1,10 @@
|
||||
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<g clip-path="url(#clip0_9_221)">
|
||||
<path d="M-1 18V8L6 3L13 8L12.2875 8.7125L11.575 9.425L6 5.45L1 9V16H3V11H9V18H7V13H5V18H-1ZM21 0V10.125C20.7167 9.825 20.4083 9.55417 20.075 9.3125C19.7417 9.07083 19.3833 8.85833 19 8.675V2H10V3.4L8 1.95V0H21ZM15 6H17V4H15V6ZM16 20C14.6167 20 13.4375 19.5125 12.4625 18.5375C11.4875 17.5625 11 16.3833 11 15C11 13.6167 11.4875 12.4375 12.4625 11.4625C13.4375 10.4875 14.6167 10 16 10C17.3833 10 18.5625 10.4875 19.5375 11.4625C20.5125 12.4375 21 13.6167 21 15C21 16.3833 20.5125 17.5625 19.5375 18.5375C18.5625 19.5125 17.3833 20 16 20ZM15.5 18H16.5V15.5H19V14.5H16.5V12H15.5V14.5H13V15.5H15.5V18Z" fill="#D2E59E"/>
|
||||
</g>
|
||||
<defs>
|
||||
<clipPath id="clip0_9_221">
|
||||
<rect width="20" height="20" fill="white"/>
|
||||
</clipPath>
|
||||
</defs>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 859 B |
@@ -0,0 +1,10 @@
|
||||
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<g clip-path="url(#clip0_9_214)">
|
||||
<path d="M1.98617 17.4995V8.12451L0.18617 9.49951L-0.988831 7.92451L9.98617 -0.500488L20.9862 7.89951L19.7862 9.49951L9.98617 1.99951L3.98617 6.59951V15.4995H7.98617V17.4995H1.98617ZM15.4862 19.8745C14.7862 20.3578 14.0153 20.562 13.1737 20.487C12.332 20.412 11.6112 20.0745 11.0112 19.4745C10.4112 18.8745 10.0737 18.1537 9.99867 17.312C9.92367 16.4703 10.1278 15.6995 10.6112 14.9995C10.1278 14.2995 9.92367 13.5287 9.99867 12.687C10.0737 11.8453 10.4112 11.1245 11.0112 10.5245C11.6112 9.92451 12.332 9.58701 13.1737 9.51201C14.0153 9.43701 14.7862 9.64118 15.4862 10.1245C16.1862 9.64118 16.957 9.43701 17.7987 9.51201C18.6403 9.58701 19.3612 9.92451 19.9612 10.5245C20.5612 11.1245 20.8987 11.8453 20.9737 12.687C21.0487 13.5287 20.8445 14.2995 20.3612 14.9995C20.8445 15.6995 21.0487 16.4703 20.9737 17.312C20.8987 18.1537 20.5612 18.8745 19.9612 19.4745C19.3612 20.0745 18.6403 20.412 17.7987 20.487C16.957 20.562 16.1862 20.3578 15.4862 19.8745ZM15.4862 17.4245L16.6362 18.2245C16.9362 18.4412 17.2612 18.5328 17.6112 18.4995C17.9612 18.4662 18.2695 18.3162 18.5362 18.0495C18.8028 17.7828 18.9528 17.4745 18.9862 17.1245C19.0195 16.7745 18.9278 16.4495 18.7112 16.1495L17.9112 14.9995L18.7112 13.8495C18.9278 13.5495 19.0195 13.2245 18.9862 12.8745C18.9528 12.5245 18.8028 12.2162 18.5362 11.9495C18.2695 11.6828 17.9612 11.5328 17.6112 11.4995C17.2612 11.4662 16.9362 11.5578 16.6362 11.7745L15.4862 12.5745L14.3362 11.7745C14.0362 11.5578 13.7112 11.4662 13.3612 11.4995C13.0112 11.5328 12.7028 11.6828 12.4362 11.9495C12.1695 12.2162 12.0195 12.5245 11.9862 12.8745C11.9528 13.2245 12.0445 13.5495 12.2612 13.8495L13.0612 14.9995L12.2612 16.1495C12.0445 16.4495 11.9528 16.7745 11.9862 17.1245C12.0195 17.4745 12.1695 17.7828 12.4362 18.0495C12.7028 18.3162 13.0112 18.4662 13.3612 18.4995C13.7112 18.5328 14.0362 18.4412 14.3362 18.2245L15.4862 17.4245ZM16.3737 15.887C16.6153 15.6453 16.7362 15.3495 16.7362 14.9995C16.7362 14.6495 16.6153 14.3537 16.3737 14.112C16.132 13.8703 15.8362 13.7495 15.4862 13.7495C15.1362 13.7495 14.8403 13.8703 14.5987 14.112C14.357 14.3537 14.2362 14.6495 14.2362 14.9995C14.2362 15.3495 14.357 15.6453 14.5987 15.887C14.8403 16.1287 15.1362 16.2495 15.4862 16.2495C15.8362 16.2495 16.132 16.1287 16.3737 15.887Z" fill="#D2E59E"/>
|
||||
</g>
|
||||
<defs>
|
||||
<clipPath id="clip0_9_214">
|
||||
<rect width="20" height="20" fill="white"/>
|
||||
</clipPath>
|
||||
</defs>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 2.5 KiB |
@@ -0,0 +1,10 @@
|
||||
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<g clip-path="url(#clip0_9_235)">
|
||||
<path d="M7.25007 20L6.85007 16.8C6.63341 16.7167 6.42924 16.6167 6.23757 16.5C6.04591 16.3833 5.85841 16.2583 5.67507 16.125L2.70007 17.375L-0.0499268 12.625L2.52507 10.675C2.50841 10.5583 2.50007 10.4458 2.50007 10.3375V9.6625C2.50007 9.55417 2.50841 9.44167 2.52507 9.325L-0.0499268 7.375L2.70007 2.625L5.67507 3.875C5.85841 3.74167 6.05007 3.61667 6.25007 3.5C6.45007 3.38333 6.65007 3.28333 6.85007 3.2L7.25007 0H12.7501L13.1501 3.2C13.3667 3.28333 13.5709 3.38333 13.7626 3.5C13.9542 3.61667 14.1417 3.74167 14.3251 3.875L17.3001 2.625L20.0501 7.375L17.4751 9.325C17.4917 9.44167 17.5001 9.55417 17.5001 9.6625V10.3375C17.5001 10.4458 17.4834 10.5583 17.4501 10.675L20.0251 12.625L17.2751 17.375L14.3251 16.125C14.1417 16.2583 13.9501 16.3833 13.7501 16.5C13.5501 16.6167 13.3501 16.7167 13.1501 16.8L12.7501 20H7.25007ZM9.00007 18H10.9751L11.3251 15.35C11.8417 15.2167 12.3209 15.0208 12.7626 14.7625C13.2042 14.5042 13.6084 14.1917 13.9751 13.825L16.4501 14.85L17.4251 13.15L15.2751 11.525C15.3584 11.2917 15.4167 11.0458 15.4501 10.7875C15.4834 10.5292 15.5001 10.2667 15.5001 10C15.5001 9.73333 15.4834 9.47083 15.4501 9.2125C15.4167 8.95417 15.3584 8.70833 15.2751 8.475L17.4251 6.85L16.4501 5.15L13.9751 6.2C13.6084 5.81667 13.2042 5.49583 12.7626 5.2375C12.3209 4.97917 11.8417 4.78333 11.3251 4.65L11.0001 2H9.02507L8.67507 4.65C8.15841 4.78333 7.67924 4.97917 7.23757 5.2375C6.79591 5.49583 6.39174 5.80833 6.02507 6.175L3.55007 5.15L2.57507 6.85L4.72507 8.45C4.64174 8.7 4.58341 8.95 4.55007 9.2C4.51674 9.45 4.50007 9.71667 4.50007 10C4.50007 10.2667 4.51674 10.525 4.55007 10.775C4.58341 11.025 4.64174 11.275 4.72507 11.525L2.57507 13.15L3.55007 14.85L6.02507 13.8C6.39174 14.1833 6.79591 14.5042 7.23757 14.7625C7.67924 15.0208 8.15841 15.2167 8.67507 15.35L9.00007 18ZM10.0501 13.5C11.0167 13.5 11.8417 13.1583 12.5251 12.475C13.2084 11.7917 13.5501 10.9667 13.5501 10C13.5501 9.03333 13.2084 8.20833 12.5251 7.525C11.8417 6.84167 11.0167 6.5 10.0501 6.5C9.06674 6.5 8.23757 6.84167 7.56257 7.525C6.88757 8.20833 6.55007 9.03333 6.55007 10C6.55007 10.9667 6.88757 11.7917 7.56257 12.475C8.23757 13.1583 9.06674 13.5 10.0501 13.5Z" fill="#D2E59E"/>
|
||||
</g>
|
||||
<defs>
|
||||
<clipPath id="clip0_9_235">
|
||||
<rect width="20" height="20" fill="white"/>
|
||||
</clipPath>
|
||||
</defs>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 2.4 KiB |
@@ -0,0 +1,3 @@
|
||||
<svg width="15" height="15" viewBox="0 0 15 15" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M9.375 11.25L5.625 7.5L9.375 3.75" stroke-width="2.5" stroke-linecap="square" stroke="#666666"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 209 B |
@@ -0,0 +1,3 @@
|
||||
<svg width="15" height="15" viewBox="0 0 15 15" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M5.625 11.25L9.375 7.5L5.625 3.75" stroke-width="2.5" stroke-linecap="square" stroke="#666666"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 209 B |
@@ -0,0 +1,3 @@
|
||||
<svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M8.7502 1.75H10.5004C10.8226 1.75 11.0838 2.01117 11.0838 2.33333V11.6667C11.0838 11.9888 10.8226 12.25 10.5004 12.25H8.7502C8.428 12.25 8.1668 11.9888 8.1668 11.6667V2.33333C8.1668 2.01117 8.428 1.75 8.7502 1.75ZM3.4996 1.75H5.2498C5.572 1.75 5.8332 2.01117 5.8332 2.33333V11.6667C5.8332 11.9888 5.572 12.25 5.2498 12.25H3.4996C3.1774 12.25 2.9162 11.9888 2.9162 11.6667V2.33333C2.9162 2.01117 3.1774 1.75 3.4996 1.75Z" stroke-width="2" stroke-linecap="round" stroke="white"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 590 B |
@@ -0,0 +1,3 @@
|
||||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M8 10V2M11.3333 6.66667L8 10L4.66667 6.66667M14 10V12.6667C14 13.0203 13.8595 13.3594 13.6095 13.6095C13.3594 13.8595 13.0203 14 12.6667 14H3.33333C2.97971 14 2.64057 13.8595 2.39052 13.6095C2.14048 13.3594 2 13.0203 2 12.6667V10" stroke-width="2" stroke-linecap="round" stroke="#224233"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 402 B |
@@ -0,0 +1,10 @@
|
||||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<g clip-path="url(#clip0_0_107)">
|
||||
<path d="M14.6672 4.66704L8.67268 8.48465C8.46926 8.60278 8.23821 8.66501 8.00296 8.66501C7.76772 8.66501 7.53666 8.60278 7.33324 8.48465L1.33276 4.66704M14.6672 4.66704V4.00044C14.6672 3.26413 14.0702 2.66724 13.3337 2.66724H2.6662C1.92977 2.66724 1.33276 3.26413 1.33276 4.00044V4.66704M14.6672 4.66704V11.9996C14.6672 12.7359 14.0702 13.3328 13.3337 13.3328H2.6662C1.92977 13.3328 1.33276 12.7359 1.33276 11.9996V4.66704" stroke-width="2" stroke-linecap="round" stroke="#224233"/>
|
||||
</g>
|
||||
<defs>
|
||||
<clipPath id="clip0_0_107">
|
||||
<rect width="16" height="16" fill="white"/>
|
||||
</clipPath>
|
||||
</defs>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 725 B |
@@ -0,0 +1,3 @@
|
||||
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M13.4125 11.4125C13.8042 11.0208 14 10.55 14 10C14 9.45 13.8042 8.97917 13.4125 8.5875C13.0208 8.19583 12.55 8 12 8C11.45 8 10.9792 8.19583 10.5875 8.5875C10.1958 8.97917 10 9.45 10 10C10 10.55 10.1958 11.0208 10.5875 11.4125C10.9792 11.8042 11.45 12 12 12C12.55 12 13.0208 11.8042 13.4125 11.4125ZM12 22C9.31667 19.7167 7.3125 17.5958 5.9875 15.6375C4.6625 13.6792 4 11.8667 4 10.2C4 7.7 4.80417 5.70833 6.4125 4.225C8.02083 2.74167 9.88333 2 12 2C14.1167 2 15.9792 2.74167 17.5875 4.225C19.1958 5.70833 20 7.7 20 10.2C20 11.8667 19.3375 13.6792 18.0125 15.6375C16.6875 17.5958 14.6833 19.7167 12 22Z" fill="#7A8F9F"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 732 B |
@@ -0,0 +1,3 @@
|
||||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M10.0002 1.33282H12V3.9997H10.0002C9.82338 3.9997 9.65383 4.06995 9.52881 4.19498C9.4038 4.32002 9.33356 4.4896 9.33356 4.66642V6.66658H12L11.3334 9.33347H9.33356V14.6672H6.66709V9.33347H4.66724V6.66658H6.66709V4.66642C6.66709 3.7823 7.01825 2.93438 7.64333 2.30921C8.26841 1.68404 9.11619 1.33282 10.0002 1.33282Z" fill="#F2BD1F" stroke-linecap="round" stroke="#F2BD1F"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 485 B |
@@ -0,0 +1,11 @@
|
||||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<g clip-path="url(#clip0_43_288)">
|
||||
<path d="M11.3336 1.33282H4.66636C2.82527 1.33282 1.33276 2.82533 1.33276 4.66642V11.3336C1.33276 13.1747 2.82527 14.6672 4.66636 14.6672H11.3336C13.1747 14.6672 14.6672 13.1747 14.6672 11.3336V4.66642C14.6672 2.82533 13.1747 1.33282 11.3336 1.33282Z" fill="#F2BD1F"/>
|
||||
<path d="M11.6669 4.33306H11.6736M4.66636 1.33282H11.3336C13.1747 1.33282 14.6672 2.82533 14.6672 4.66642V11.3336C14.6672 13.1747 13.1747 14.6672 11.3336 14.6672H4.66636C2.82527 14.6672 1.33276 13.1747 1.33276 11.3336V4.66642C1.33276 2.82533 2.82527 1.33282 4.66636 1.33282ZM10.6666 7.58019C10.7489 8.13507 10.6542 8.70176 10.3958 9.19967C10.1374 9.69757 9.72867 10.1013 9.22762 10.3535C8.72656 10.6057 8.15875 10.6935 7.60493 10.6044C7.05111 10.5153 6.53949 10.2538 6.14285 9.85715C5.7462 9.4605 5.48472 8.94888 5.39561 8.39507C5.30649 7.84125 5.39427 7.27343 5.64646 6.77238C5.89866 6.27132 6.30242 5.86255 6.80033 5.6042C7.29823 5.34584 7.86493 5.25106 8.4198 5.33335C8.9858 5.41728 9.50979 5.68102 9.91438 6.08561C10.319 6.4902 10.5827 7.0142 10.6666 7.58019Z" stroke-width="1.2" stroke-linecap="round" stroke="#16171D"/>
|
||||
</g>
|
||||
<defs>
|
||||
<clipPath id="clip0_43_288">
|
||||
<rect width="16" height="16" fill="white"/>
|
||||
</clipPath>
|
||||
</defs>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.3 KiB |
@@ -0,0 +1,6 @@
|
||||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M13.4955 6.50462C12.7453 5.75444 11.7278 5.33299 10.6668 5.33299C9.60589 5.33299 8.5884 5.75444 7.83819 6.50462C7.08799 7.25479 6.66652 8.27225 6.66652 9.33316V14H9.3334V9.33316C9.3334 8.97952 9.47389 8.64037 9.72396 8.39031C9.97403 8.14025 10.3132 7.99977 10.6668 7.99977C11.0205 7.99977 11.3597 8.14025 11.6097 8.39031C11.8598 8.64037 12.0003 8.97952 12.0003 9.33316V14H14.6672V9.33316C14.6672 8.27225 14.2457 7.25479 13.4955 6.50462Z" fill="#F2BD1F"/>
|
||||
<path d="M3.99964 5.99969H1.33276V14H3.99964V5.99969Z" fill="#F2BD1F"/>
|
||||
<path d="M2.6662 3.9996C3.40264 3.9996 3.99964 3.40262 3.99964 2.66621C3.99964 1.9298 3.40264 1.33282 2.6662 1.33282C1.92977 1.33282 1.33276 1.9298 1.33276 2.66621C1.33276 3.40262 1.92977 3.9996 2.6662 3.9996Z" fill="#F2BD1F"/>
|
||||
<path d="M10.6668 5.33299C11.7278 5.33299 12.7453 5.75444 13.4955 6.50462C14.2457 7.25479 14.6672 8.27225 14.6672 9.33316V14H12.0003V9.33316C12.0003 8.97952 11.8598 8.64037 11.6097 8.39031C11.3597 8.14025 11.0205 7.99977 10.6668 7.99977C10.3132 7.99977 9.97403 8.14025 9.72396 8.39031C9.47389 8.64037 9.3334 8.97952 9.3334 9.33316V14H6.66652V9.33316C6.66652 8.27225 7.08799 7.25479 7.83819 6.50462C8.5884 5.75444 9.60589 5.33299 10.6668 5.33299ZM1.33276 5.99969H3.99964V14H1.33276V5.99969ZM3.99964 2.66621C3.99964 3.40262 3.40264 3.9996 2.6662 3.9996C1.92977 3.9996 1.33276 3.40262 1.33276 2.66621C1.33276 1.9298 1.92977 1.33282 2.6662 1.33282C3.40264 1.33282 3.99964 1.9298 3.99964 2.66621Z" stroke-linecap="round" stroke="#F2BD1F"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.6 KiB |
@@ -0,0 +1,3 @@
|
||||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M12 4L8 8M8 8L4 12M8 8L4 4M8 8L12 12" stroke-width="3" stroke-linecap="square" stroke="#F2BD1F"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 210 B |
@@ -0,0 +1,3 @@
|
||||
<svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M12.7494 12.7493V5.25052H5.25059M12.7494 5.25052L5.25059 12.7493" stroke-width="2.57143" stroke-linecap="square" stroke="#0D0E12"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 244 B |
@@ -0,0 +1,25 @@
|
||||
# Development-only services. Not a production configuration.
|
||||
name: saurashakti-website-dev
|
||||
|
||||
services:
|
||||
db:
|
||||
image: postgres:16-alpine
|
||||
container_name: saurashakti-website-dev-db
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
POSTGRES_USER: ${POSTGRES_USER}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
|
||||
POSTGRES_DB: ${POSTGRES_DB}
|
||||
ports:
|
||||
- "127.0.0.1:${POSTGRES_PORT:-5440}:5432"
|
||||
volumes:
|
||||
- pgdata:/var/lib/postgresql/data
|
||||
- ./docker/postgres/init:/docker-entrypoint-initdb.d:ro
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 10
|
||||
|
||||
volumes:
|
||||
pgdata:
|
||||
@@ -0,0 +1,5 @@
|
||||
#!/bin/sh
|
||||
# Runs once on first container start: creates the database used by the automated tests.
|
||||
set -e
|
||||
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" \
|
||||
-c "CREATE DATABASE \"${POSTGRES_DB}_test\" OWNER \"$POSTGRES_USER\";"
|
||||
@@ -0,0 +1,4 @@
|
||||
# Backend that the Vite dev server proxies /api and /media to
|
||||
VITE_BACKEND_URL=http://127.0.0.1:8020
|
||||
# API base path used by the browser (leave as /api when using the dev proxy)
|
||||
VITE_API_BASE_URL=/api
|
||||
@@ -0,0 +1,24 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"$schema": "./node_modules/oxlint/configuration_schema.json",
|
||||
"plugins": ["react", "oxc"],
|
||||
"rules": {
|
||||
"react/rules-of-hooks": "error",
|
||||
"react/only-export-components": ["warn", { "allowConstantExport": true }]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
# React + Vite
|
||||
|
||||
This template provides a minimal setup to get React working in Vite with HMR and some Oxlint rules.
|
||||
|
||||
Currently, two official plugins are available:
|
||||
|
||||
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs)
|
||||
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
|
||||
|
||||
## React Compiler
|
||||
|
||||
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
|
||||
|
||||
## Expanding the Oxlint configuration
|
||||
|
||||
If you are developing a production application, we recommend using TypeScript with type-aware lint rules enabled. Check out the [TS template](https://github.com/vitejs/vite/tree/main/packages/create-vite/template-react-ts) for information on how to integrate TypeScript and Oxlint's TypeScript related rules in your project.
|
||||
@@ -0,0 +1,15 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/png" href="/favicon.png" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta name="description" content="Saura Shakti — rooftop and on-grid solar for homes, businesses and farms, supported by the PM Surya Ghar subsidy." />
|
||||
<meta name="theme-color" content="#010F1C" />
|
||||
<title>Saura Shakti — Rooftop Solar</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.jsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"name": "frontend",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"lint": "oxlint",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fontsource/inter": "^5.3.0",
|
||||
"@fontsource/manrope": "^5.3.0",
|
||||
"@fontsource/poppins": "^5.3.0",
|
||||
"axios": "^1.21.1",
|
||||
"framer-motion": "^14.13.0",
|
||||
"lucide-react": "^1.72.0",
|
||||
"react": "^19.3.1",
|
||||
"react-dom": "^19.3.1",
|
||||
"react-router-dom": "^7.18.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/vite": "^4.3.5",
|
||||
"@types/react": "^19.3.0",
|
||||
"@types/react-dom": "^19.3.0",
|
||||
"@vitejs/plugin-react": "^6.1.2",
|
||||
"oxlint": "^1.90.0",
|
||||
"tailwindcss": "^4.3.5",
|
||||
"vite": "^8.3.6"
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 8.5 KiB |
|
After Width: | Height: | Size: 9.3 KiB |
@@ -0,0 +1,24 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg">
|
||||
<symbol id="bluesky-icon" viewBox="0 0 16 17">
|
||||
<g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
|
||||
<defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
|
||||
</symbol>
|
||||
<symbol id="discord-icon" viewBox="0 0 20 19">
|
||||
<path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
|
||||
</symbol>
|
||||
<symbol id="documentation-icon" viewBox="0 0 21 20">
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
|
||||
</symbol>
|
||||
<symbol id="github-icon" viewBox="0 0 19 19">
|
||||
<path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
|
||||
</symbol>
|
||||
<symbol id="social-icon" viewBox="0 0 20 20">
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
|
||||
</symbol>
|
||||
<symbol id="x-icon" viewBox="0 0 19 19">
|
||||
<path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
|
||||
</symbol>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 4.9 KiB |
@@ -0,0 +1,57 @@
|
||||
import { lazy, Suspense } from 'react'
|
||||
import { Route, Routes } from 'react-router-dom'
|
||||
import { ContentProvider } from './context/ContentContext'
|
||||
import { LeadModalProvider } from './context/LeadModalContext'
|
||||
import { Spinner } from './components/ui'
|
||||
import HomePage from './pages/HomePage'
|
||||
import PublicLayout from './layouts/PublicLayout'
|
||||
import ProjectsPage from './pages/ProjectsPage'
|
||||
import ProjectDetailPage from './pages/ProjectDetailPage'
|
||||
import LegalPage, { NotFoundPage } from './pages/LegalPage'
|
||||
|
||||
// Admin dashboard is code-split so public visitors never download it.
|
||||
const AdminApp = lazy(() => import('./admin/AdminApp'))
|
||||
|
||||
function PublicSite({ children }) {
|
||||
return (
|
||||
<ContentProvider>
|
||||
<LeadModalProvider>{children}</LeadModalProvider>
|
||||
</ContentProvider>
|
||||
)
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<Routes>
|
||||
<Route
|
||||
path="/admin/*"
|
||||
element={
|
||||
<Suspense fallback={<div className="grid min-h-dvh place-items-center text-brand"><Spinner className="size-8" /></div>}>
|
||||
<AdminApp />
|
||||
</Suspense>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/"
|
||||
element={
|
||||
<PublicSite>
|
||||
<HomePage />
|
||||
</PublicSite>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
element={
|
||||
<PublicSite>
|
||||
<PublicLayout />
|
||||
</PublicSite>
|
||||
}
|
||||
>
|
||||
<Route path="/projects" element={<ProjectsPage />} />
|
||||
<Route path="/projects/:slug" element={<ProjectDetailPage />} />
|
||||
<Route path="/terms" element={<LegalPage kind="terms" />} />
|
||||
<Route path="/privacy" element={<LegalPage kind="privacy" />} />
|
||||
<Route path="*" element={<NotFoundPage />} />
|
||||
</Route>
|
||||
</Routes>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { Navigate, Route, Routes, useLocation } from 'react-router-dom'
|
||||
import { AuthProvider, useAuth } from '../context/AuthContext'
|
||||
import { FeedbackProvider, LoadingBlock } from './components/feedback'
|
||||
import AdminLayout from './layouts/AdminLayout'
|
||||
import LoginPage from './pages/LoginPage'
|
||||
import DashboardPage from './pages/DashboardPage'
|
||||
import EnquiriesPage from './pages/EnquiriesPage'
|
||||
import EnquiryDetailPage from './pages/EnquiryDetailPage'
|
||||
import ProjectsPage from './pages/ProjectsPage'
|
||||
import ProjectEditorPage from './pages/ProjectEditorPage'
|
||||
import ServicesPage from './pages/ServicesPage'
|
||||
import TestimonialsPage from './pages/TestimonialsPage'
|
||||
import MessagesPage from './pages/MessagesPage'
|
||||
import SubscribersPage from './pages/SubscribersPage'
|
||||
import ContentPage from './pages/ContentPage'
|
||||
import UsersPage from './pages/UsersPage'
|
||||
|
||||
function RequireAuth({ children }) {
|
||||
const { admin, loading } = useAuth()
|
||||
const location = useLocation()
|
||||
if (loading) return <div className="grid min-h-dvh place-items-center bg-surface"><LoadingBlock /></div>
|
||||
if (!admin) return <Navigate to="/admin/login" replace state={{ from: location.pathname }} />
|
||||
return children
|
||||
}
|
||||
|
||||
export default function AdminApp() {
|
||||
return (
|
||||
<AuthProvider>
|
||||
<FeedbackProvider>
|
||||
<Routes>
|
||||
<Route path="login" element={<LoginPage />} />
|
||||
<Route
|
||||
element={
|
||||
<RequireAuth>
|
||||
<AdminLayout />
|
||||
</RequireAuth>
|
||||
}
|
||||
>
|
||||
<Route index element={<DashboardPage />} />
|
||||
<Route path="enquiries" element={<EnquiriesPage />} />
|
||||
<Route path="enquiries/:id" element={<EnquiryDetailPage />} />
|
||||
<Route path="projects" element={<ProjectsPage />} />
|
||||
<Route path="projects/new" element={<ProjectEditorPage />} />
|
||||
<Route path="projects/:id" element={<ProjectEditorPage />} />
|
||||
<Route path="services" element={<ServicesPage />} />
|
||||
<Route path="testimonials" element={<TestimonialsPage />} />
|
||||
<Route path="messages" element={<MessagesPage />} />
|
||||
<Route path="subscribers" element={<SubscribersPage />} />
|
||||
<Route path="content" element={<ContentPage />} />
|
||||
<Route path="users" element={<UsersPage />} />
|
||||
<Route path="*" element={<Navigate to="/admin" replace />} />
|
||||
</Route>
|
||||
</Routes>
|
||||
</FeedbackProvider>
|
||||
</AuthProvider>
|
||||
)
|
||||
}
|
||||