commit 53dbfa976b838ccaf1fd2868a143199be3f3c97f Author: Shubhankar45 Date: Fri Nov 13 12:14:55 2026 +0000 - diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..2b3e952 --- /dev/null +++ b/.env.example @@ -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 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..23d8d1a --- /dev/null +++ b/.gitignore @@ -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/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..ed201b4 --- /dev/null +++ b/README.md @@ -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 +``` diff --git a/backend/.env.example b/backend/.env.example new file mode 100644 index 0000000..945dca4 --- /dev/null +++ b/backend/.env.example @@ -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 diff --git a/backend/alembic.ini b/backend/alembic.ini new file mode 100644 index 0000000..8f7b64c --- /dev/null +++ b/backend/alembic.ini @@ -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 diff --git a/backend/alembic/env.py b/backend/alembic/env.py new file mode 100644 index 0000000..69a60b5 --- /dev/null +++ b/backend/alembic/env.py @@ -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()) diff --git a/backend/alembic/script.py.mako b/backend/alembic/script.py.mako new file mode 100644 index 0000000..3b77323 --- /dev/null +++ b/backend/alembic/script.py.mako @@ -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"} diff --git a/backend/alembic/versions/20261113_be067e89c214_testimonial_media_subscribers_nullable_.py b/backend/alembic/versions/20261113_be067e89c214_testimonial_media_subscribers_nullable_.py new file mode 100644 index 0000000..1a8a02e --- /dev/null +++ b/backend/alembic/versions/20261113_be067e89c214_testimonial_media_subscribers_nullable_.py @@ -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 ### diff --git a/backend/alembic/versions/20261113_d572dd3db977_initial_schema.py b/backend/alembic/versions/20261113_d572dd3db977_initial_schema.py new file mode 100644 index 0000000..9cf85ce --- /dev/null +++ b/backend/alembic/versions/20261113_d572dd3db977_initial_schema.py @@ -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 ### diff --git a/backend/app/__init__.py b/backend/app/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/app/cli.py b/backend/app/cli.py new file mode 100644 index 0000000..25a22ce --- /dev/null +++ b/backend/app/cli.py @@ -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() diff --git a/backend/app/core/__init__.py b/backend/app/core/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/app/core/config.py b/backend/app/core/config.py new file mode 100644 index 0000000..a721d55 --- /dev/null +++ b/backend/app/core/config.py @@ -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 " + 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() diff --git a/backend/app/core/database.py b/backend/app/core/database.py new file mode 100644 index 0000000..4c4d035 --- /dev/null +++ b/backend/app/core/database.py @@ -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 diff --git a/backend/app/core/deps.py b/backend/app/core/deps.py new file mode 100644 index 0000000..87f7207 --- /dev/null +++ b/backend/app/core/deps.py @@ -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))] diff --git a/backend/app/core/security.py b/backend/app/core/security.py new file mode 100644 index 0000000..e5ee9c9 --- /dev/null +++ b/backend/app/core/security.py @@ -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 diff --git a/backend/app/main.py b/backend/app/main.py new file mode 100644 index 0000000..3d49312 --- /dev/null +++ b/backend/app/main.py @@ -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 ` 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"} diff --git a/backend/app/middleware/__init__.py b/backend/app/middleware/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/app/middleware/rate_limit.py b/backend/app/middleware/rate_limit.py new file mode 100644 index 0000000..babe9ba --- /dev/null +++ b/backend/app/middleware/rate_limit.py @@ -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() diff --git a/backend/app/middleware/security_headers.py b/backend/app/middleware/security_headers.py new file mode 100644 index 0000000..aed8de1 --- /dev/null +++ b/backend/app/middleware/security_headers.py @@ -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 diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py new file mode 100644 index 0000000..11b85e3 --- /dev/null +++ b/backend/app/models/__init__.py @@ -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", +] diff --git a/backend/app/models/admin.py b/backend/app/models/admin.py new file mode 100644 index 0000000..b958530 --- /dev/null +++ b/backend/app/models/admin.py @@ -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)) diff --git a/backend/app/models/base.py b/backend/app/models/base.py new file mode 100644 index 0000000..069148b --- /dev/null +++ b/backend/app/models/base.py @@ -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 + ) diff --git a/backend/app/models/content.py b/backend/app/models/content.py new file mode 100644 index 0000000..6ebaac8 --- /dev/null +++ b/backend/app/models/content.py @@ -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")) diff --git a/backend/app/models/enquiry.py b/backend/app/models/enquiry.py new file mode 100644 index 0000000..bc43d24 --- /dev/null +++ b/backend/app/models/enquiry.py @@ -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") + diff --git a/backend/app/models/enums.py b/backend/app/models/enums.py new file mode 100644 index 0000000..fabe470 --- /dev/null +++ b/backend/app/models/enums.py @@ -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, + ) diff --git a/backend/app/models/project.py b/backend/app/models/project.py new file mode 100644 index 0000000..3a5fc73 --- /dev/null +++ b/backend/app/models/project.py @@ -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") diff --git a/backend/app/routes/__init__.py b/backend/app/routes/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/app/routes/auth.py b/backend/app/routes/auth.py new file mode 100644 index 0000000..a065589 --- /dev/null +++ b/backend/app/routes/auth.py @@ -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 diff --git a/backend/app/routes/enquiries.py b/backend/app/routes/enquiries.py new file mode 100644 index 0000000..150e3e8 --- /dev/null +++ b/backend/app/routes/enquiries.py @@ -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() diff --git a/backend/app/routes/misc.py b/backend/app/routes/misc.py new file mode 100644 index 0000000..b403918 --- /dev/null +++ b/backend/app/routes/misc.py @@ -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], + ) diff --git a/backend/app/routes/projects.py b/backend/app/routes/projects.py new file mode 100644 index 0000000..368d422 --- /dev/null +++ b/backend/app/routes/projects.py @@ -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) diff --git a/backend/app/routes/quotations.py b/backend/app/routes/quotations.py new file mode 100644 index 0000000..e89b5a7 --- /dev/null +++ b/backend/app/routes/quotations.py @@ -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() diff --git a/backend/app/routes/services.py b/backend/app/routes/services.py new file mode 100644 index 0000000..14e0039 --- /dev/null +++ b/backend/app/routes/services.py @@ -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) diff --git a/backend/app/routes/single_image.py b/backend/app/routes/single_image.py new file mode 100644 index 0000000..779aa01 --- /dev/null +++ b/backend/app/routes/single_image.py @@ -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) diff --git a/backend/app/schemas/__init__.py b/backend/app/schemas/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/app/schemas/auth.py b/backend/app/schemas/auth.py new file mode 100644 index 0000000..015f79f --- /dev/null +++ b/backend/app/schemas/auth.py @@ -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) diff --git a/backend/app/schemas/common.py b/backend/app/schemas/common.py new file mode 100644 index 0000000..7255ff0 --- /dev/null +++ b/backend/app/schemas/common.py @@ -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 diff --git a/backend/app/schemas/content.py b/backend/app/schemas/content.py new file mode 100644 index 0000000..f18851f --- /dev/null +++ b/backend/app/schemas/content.py @@ -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] diff --git a/backend/app/schemas/enquiry.py b/backend/app/schemas/enquiry.py new file mode 100644 index 0000000..1331d2c --- /dev/null +++ b/backend/app/schemas/enquiry.py @@ -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") diff --git a/backend/app/schemas/project.py b/backend/app/schemas/project.py new file mode 100644 index 0000000..d9ef8a1 --- /dev/null +++ b/backend/app/schemas/project.py @@ -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 diff --git a/backend/app/services/__init__.py b/backend/app/services/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/app/services/email.py b/backend/app/services/email.py new file mode 100644 index 0000000..8d682b4 --- /dev/null +++ b/backend/app/services/email.py @@ -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:". 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}" diff --git a/backend/app/services/image_processing.py b/backend/app/services/image_processing.py new file mode 100644 index 0000000..b4703eb --- /dev/null +++ b/backend/app/services/image_processing.py @@ -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, + ) diff --git a/backend/app/services/quotation.py b/backend/app/services/quotation.py new file mode 100644 index 0000000..787d4dd --- /dev/null +++ b/backend/app/services/quotation.py @@ -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 diff --git a/backend/app/utils/__init__.py b/backend/app/utils/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/app/utils/helpers.py b/backend/app/utils/helpers.py new file mode 100644 index 0000000..e91981a --- /dev/null +++ b/backend/app/utils/helpers.py @@ -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"\_") diff --git a/backend/assets/watermark/.gitkeep b/backend/assets/watermark/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/backend/assets/watermark/logo.png b/backend/assets/watermark/logo.png new file mode 100644 index 0000000..2ed5bad Binary files /dev/null and b/backend/assets/watermark/logo.png differ diff --git a/backend/pytest.ini b/backend/pytest.ini new file mode 100644 index 0000000..8a47bbc --- /dev/null +++ b/backend/pytest.ini @@ -0,0 +1,6 @@ +[pytest] +testpaths = tests +asyncio_mode = auto +asyncio_default_fixture_loop_scope = function +filterwarnings = + ignore::DeprecationWarning:passlib.* diff --git a/backend/requirements.txt b/backend/requirements.txt new file mode 100644 index 0000000..cc7d8b2 --- /dev/null +++ b/backend/requirements.txt @@ -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 diff --git a/backend/tests/__init__.py b/backend/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py new file mode 100644 index 0000000..57aa511 --- /dev/null +++ b/backend/tests/conftest.py @@ -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() diff --git a/backend/tests/test_auth.py b/backend/tests/test_auth.py new file mode 100644 index 0000000..254060b --- /dev/null +++ b/backend/tests/test_auth.py @@ -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 diff --git a/backend/tests/test_enquiries_content.py b/backend/tests/test_enquiries_content.py new file mode 100644 index 0000000..6f8fe51 --- /dev/null +++ b/backend/tests/test_enquiries_content.py @@ -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 diff --git a/backend/tests/test_projects_images.py b/backend/tests/test_projects_images.py new file mode 100644 index 0000000..80cd560 --- /dev/null +++ b/backend/tests/test_projects_images.py @@ -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 diff --git a/backend/tests/test_quotations.py b/backend/tests/test_quotations.py new file mode 100644 index 0000000..3b7cc2a --- /dev/null +++ b/backend/tests/test_quotations.py @@ -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("*")) == [] diff --git a/backend/tests/test_watermark_unit.py b/backend/tests/test_watermark_unit.py new file mode 100644 index 0000000..9536a3c --- /dev/null +++ b/backend/tests/test_watermark_unit.py @@ -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] diff --git a/backend/uploads/originals/.gitkeep b/backend/uploads/originals/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/backend/uploads/thumbnails/.gitkeep b/backend/uploads/thumbnails/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/backend/uploads/watermarked/.gitkeep b/backend/uploads/watermarked/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/design/DESIGN_ANALYSIS.md b/design/DESIGN_ANALYSIS.md new file mode 100644 index 0000000..5ecfa28 --- /dev/null +++ b/design/DESIGN_ANALYSIS.md @@ -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 | diff --git a/design/icons/breakdown-list__credit-card.svg b/design/icons/breakdown-list__credit-card.svg new file mode 100644 index 0000000..5825e8d --- /dev/null +++ b/design/icons/breakdown-list__credit-card.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/design/icons/breakdown-list__shield-check.svg b/design/icons/breakdown-list__shield-check.svg new file mode 100644 index 0000000..d162567 --- /dev/null +++ b/design/icons/breakdown-list__shield-check.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/design/icons/breakdown-list__sparkles.svg b/design/icons/breakdown-list__sparkles.svg new file mode 100644 index 0000000..2a5d62c --- /dev/null +++ b/design/icons/breakdown-list__sparkles.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/design/icons/breakdown-list__trending-up.svg b/design/icons/breakdown-list__trending-up.svg new file mode 100644 index 0000000..a017233 --- /dev/null +++ b/design/icons/breakdown-list__trending-up.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/design/icons/cards-container__battery.svg b/design/icons/cards-container__battery.svg new file mode 100644 index 0000000..7f999e8 --- /dev/null +++ b/design/icons/cards-container__battery.svg @@ -0,0 +1,3 @@ + + + diff --git a/design/icons/cards-container__cpu.svg b/design/icons/cards-container__cpu.svg new file mode 100644 index 0000000..e2228b4 --- /dev/null +++ b/design/icons/cards-container__cpu.svg @@ -0,0 +1,3 @@ + + + diff --git a/design/icons/cards-container__leaf.svg b/design/icons/cards-container__leaf.svg new file mode 100644 index 0000000..f2c5518 --- /dev/null +++ b/design/icons/cards-container__leaf.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/design/icons/cards-container__solar-panel.svg b/design/icons/cards-container__solar-panel.svg new file mode 100644 index 0000000..ccdbca9 --- /dev/null +++ b/design/icons/cards-container__solar-panel.svg @@ -0,0 +1,3 @@ + + + diff --git a/design/icons/carousel-grid__play.svg b/design/icons/carousel-grid__play.svg new file mode 100644 index 0000000..77e1598 --- /dev/null +++ b/design/icons/carousel-grid__play.svg @@ -0,0 +1,3 @@ + + + diff --git a/design/icons/features-bar__leaf.svg b/design/icons/features-bar__leaf.svg new file mode 100644 index 0000000..c67cb6f --- /dev/null +++ b/design/icons/features-bar__leaf.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/design/icons/features-bar__lock.svg b/design/icons/features-bar__lock.svg new file mode 100644 index 0000000..3363fb9 --- /dev/null +++ b/design/icons/features-bar__lock.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/design/icons/features-bar__shield-check.svg b/design/icons/features-bar__shield-check.svg new file mode 100644 index 0000000..3d89f1d --- /dev/null +++ b/design/icons/features-bar__shield-check.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/design/icons/features-bar__sun.svg b/design/icons/features-bar__sun.svg new file mode 100644 index 0000000..ff7de57 --- /dev/null +++ b/design/icons/features-bar__sun.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/design/icons/pagination-container__chevron-left.svg b/design/icons/pagination-container__chevron-left.svg new file mode 100644 index 0000000..1420939 --- /dev/null +++ b/design/icons/pagination-container__chevron-left.svg @@ -0,0 +1,3 @@ + + + diff --git a/design/icons/pagination-container__chevron-right.svg b/design/icons/pagination-container__chevron-right.svg new file mode 100644 index 0000000..673158a --- /dev/null +++ b/design/icons/pagination-container__chevron-right.svg @@ -0,0 +1,3 @@ + + + diff --git a/design/icons/player-controls__pause.svg b/design/icons/player-controls__pause.svg new file mode 100644 index 0000000..1c6f860 --- /dev/null +++ b/design/icons/player-controls__pause.svg @@ -0,0 +1,3 @@ + + + diff --git a/design/icons/secondary-actions-row__download.svg b/design/icons/secondary-actions-row__download.svg new file mode 100644 index 0000000..7c2600f --- /dev/null +++ b/design/icons/secondary-actions-row__download.svg @@ -0,0 +1,3 @@ + + + diff --git a/design/icons/secondary-actions-row__mail.svg b/design/icons/secondary-actions-row__mail.svg new file mode 100644 index 0000000..c53984e --- /dev/null +++ b/design/icons/secondary-actions-row__mail.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/design/icons/slider-feed-in-tariff__location_on.svg b/design/icons/slider-feed-in-tariff__location_on.svg new file mode 100644 index 0000000..e2621b8 --- /dev/null +++ b/design/icons/slider-feed-in-tariff__location_on.svg @@ -0,0 +1,3 @@ + + + diff --git a/design/icons/social-icons__facebook.svg b/design/icons/social-icons__facebook.svg new file mode 100644 index 0000000..cf0132a --- /dev/null +++ b/design/icons/social-icons__facebook.svg @@ -0,0 +1,3 @@ + + + diff --git a/design/icons/social-icons__instagram.svg b/design/icons/social-icons__instagram.svg new file mode 100644 index 0000000..11a414a --- /dev/null +++ b/design/icons/social-icons__instagram.svg @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/design/icons/social-icons__linkedin.svg b/design/icons/social-icons__linkedin.svg new file mode 100644 index 0000000..08b2b54 --- /dev/null +++ b/design/icons/social-icons__linkedin.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/design/icons/social-icons__x.svg b/design/icons/social-icons__x.svg new file mode 100644 index 0000000..3025366 --- /dev/null +++ b/design/icons/social-icons__x.svg @@ -0,0 +1,3 @@ + + + diff --git a/design/icons/subscription-row__arrow-up-right.svg b/design/icons/subscription-row__arrow-up-right.svg new file mode 100644 index 0000000..20062b9 --- /dev/null +++ b/design/icons/subscription-row__arrow-up-right.svg @@ -0,0 +1,3 @@ + + + diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..02413da --- /dev/null +++ b/docker-compose.yml @@ -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: diff --git a/docker/postgres/init/01-create-test-db.sh b/docker/postgres/init/01-create-test-db.sh new file mode 100755 index 0000000..e98da7a --- /dev/null +++ b/docker/postgres/init/01-create-test-db.sh @@ -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\";" diff --git a/frontend/.env.example b/frontend/.env.example new file mode 100644 index 0000000..0da304b --- /dev/null +++ b/frontend/.env.example @@ -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 diff --git a/frontend/.gitignore b/frontend/.gitignore new file mode 100644 index 0000000..a547bf3 --- /dev/null +++ b/frontend/.gitignore @@ -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? diff --git a/frontend/.oxlintrc.json b/frontend/.oxlintrc.json new file mode 100644 index 0000000..1255078 --- /dev/null +++ b/frontend/.oxlintrc.json @@ -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 }] + } +} diff --git a/frontend/README.md b/frontend/README.md new file mode 100644 index 0000000..d937833 --- /dev/null +++ b/frontend/README.md @@ -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. diff --git a/frontend/index.html b/frontend/index.html new file mode 100644 index 0000000..f84ce2f --- /dev/null +++ b/frontend/index.html @@ -0,0 +1,15 @@ + + + + + + + + + Saura Shakti — Rooftop Solar + + +
+ + + diff --git a/frontend/package-lock.json b/frontend/package-lock.json new file mode 100644 index 0000000..c76f6b4 --- /dev/null +++ b/frontend/package-lock.json @@ -0,0 +1,2286 @@ +{ + "name": "frontend", + "version": "0.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "frontend", + "version": "0.0.0", + "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" + } + }, + "node_modules/@emnapi/core": { + "version": "2.0.0-beta.2", + "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-2.0.0-beta.2.tgz", + "integrity": "sha512-MzCVoWtcg4Pm2B3je5mMvYMvj3MmBKw+fU7vbsJc9/iT8ip6/eYIHo/Dsm/mr+wsHB6SEyJDuxB09Yy6r/8+4A==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/wasi-threads": "2.2.0", + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/runtime": { + "version": "2.0.0-beta.2", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-2.0.0-beta.2.tgz", + "integrity": "sha512-JcrSPzPvZuNZvJqPTF9Fw25LbOJ8avzFVlaf2grmH4Cku0oGP47tRgqPZadcfj3YoZMHkFVnCYFbQM8I+i5QEw==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/wasi-threads": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-2.2.0.tgz", + "integrity": "sha512-JP7OYH38Q7+pyTAe14raZHLQIK7BDKbdwji+Xi3pcd/6QkJYQH3SX4wu6EplGrGJWRepoNzedfm0G3B9Z4e9Rw==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@fontsource/inter": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/@fontsource/inter/-/inter-5.3.0.tgz", + "integrity": "sha512-RofMylZmjlJEfELXeNHFWBRcSs75rGU/6bV2S2jfnvv/3rPXPGe0LgUJTklcHZ9lM4OZmAVFhcJPnACfb91A3g==", + "license": "OFL-1.1", + "funding": { + "url": "https://github.com/sponsors/ayuhito" + } + }, + "node_modules/@fontsource/manrope": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/@fontsource/manrope/-/manrope-5.3.0.tgz", + "integrity": "sha512-obJ1Dv3+uCA6HlHgW8u4BGYxJR9In2HW7gjJhlflEvkrj1X1iSEwu0fToL+JYGC/FEKFfIz1sBuPduvcL2gIAA==", + "license": "OFL-1.1", + "funding": { + "url": "https://github.com/sponsors/ayuhito" + } + }, + "node_modules/@fontsource/poppins": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/@fontsource/poppins/-/poppins-5.3.0.tgz", + "integrity": "sha512-cms1nM7U6SN8epIV1WMVOV8VsA645aSm3wHfzIQnkk188U341ThbJGSl2Sv54V29gnDbT2arMPfLzvVIIVCceQ==", + "license": "OFL-1.1", + "funding": { + "url": "https://github.com/sponsors/ayuhito" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.3.tgz", + "integrity": "sha512-lhTtjtoEArWBjismtfS761S9Hlyn+nIZqOZVYoZ1Xn82PMNMVnk+jj/NhC4fAXGTs7ydONcJiR5vyQBTMDu27g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@napi-rs/wasm-runtime": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.6.tgz", + "integrity": "sha512-mRyDmEw9/fCDXCGfL1sbgIw/GUK0PVxRW4YwgPN61F3LQ+fSyoBFarJVzgGyhF6kRzEQZ0FejDqm4WLXSeqQmw==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@tybys/wasm-util": "^0.10.3" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + }, + "peerDependencies": { + "@emnapi/core": "^1.7.1 || 2.0.0-beta.2", + "@emnapi/runtime": "^1.7.1 || 2.0.0-beta.2" + } + }, + "node_modules/@oxc-project/types": { + "version": "0.156.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.156.0.tgz", + "integrity": "sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/oxc-project" + } + }, + "node_modules/@oxlint/binding-android-arm-eabi": { + "version": "1.93.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-android-arm-eabi/-/binding-android-arm-eabi-1.93.0.tgz", + "integrity": "sha512-KKw70pbD5Pvq3G2lJ+WQ71XPMjCmg37rkSe2+mDqCRP3PoTSdDMuEi4UOnE8JBtyNM7bek61EC2s0Jt7S7u+Sg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-android-arm64": { + "version": "1.93.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-android-arm64/-/binding-android-arm64-1.93.0.tgz", + "integrity": "sha512-fvr1fTUZGelwRxKDt64pf28aL1WaWgviwz3X+E/FcRYvrlEahH0NECRz/c1SY+K+KWmZk5uAf6h1kQnyBkp/2A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-darwin-arm64": { + "version": "1.93.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-darwin-arm64/-/binding-darwin-arm64-1.93.0.tgz", + "integrity": "sha512-VdvSN9JRf4Es6ZzoAdvEeh8tgKdw8L4H82WmA8MMPVfPdZGCwE/nI27Z1HrRHYQhPxOh4kmnxQEioSUFrOvDaw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-darwin-x64": { + "version": "1.93.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-darwin-x64/-/binding-darwin-x64-1.93.0.tgz", + "integrity": "sha512-QR1V890Ml0YGRG0F/iV0K9igG+pOhe+VWd+aZnxY849rRHZf3F2gEoQks5+GVHf105X9Mh/6HdShTP5juekG2g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-freebsd-x64": { + "version": "1.93.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-freebsd-x64/-/binding-freebsd-x64-1.93.0.tgz", + "integrity": "sha512-jDfIbi30zZaKi+rTvig3sge+Xhi8pFFSgHxb0jzovc4qh8ETm/irKV9c7N/JsuwnYc5sbvf4IC8w1vQQ0IL+BA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-arm-gnueabihf": { + "version": "1.93.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.93.0.tgz", + "integrity": "sha512-qtxZ714ND/koFgVH00QgxlzZiIbRPmguaPhnHRU5DFFtrtEdOrSnZD4U/H2AzXrXkZ59eQbMBnJwbum5XohrIQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-arm-musleabihf": { + "version": "1.93.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-1.93.0.tgz", + "integrity": "sha512-5pJ9NjMvH7WMUqXB6bTTOSemBm39w2cod27Hu3+Yom/GhbTeNXlYcpDx1o4CgBP6fhp0YHG66TNdVaUm6sHjsA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-arm64-gnu": { + "version": "1.93.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.93.0.tgz", + "integrity": "sha512-pRf+7jtbt2fHE23SX7qBxRgnBZicUgsoCK1PVIjnOk+t3a6UBkpt/GrKI99WlxsKUxftz/5nv/kfKvScmYywkw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-arm64-musl": { + "version": "1.93.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.93.0.tgz", + "integrity": "sha512-zM8Fd/K8sqGvsBcJBZ3oVZ3ctGWbszA08IaGt5gFFF5RcunppAI/ZnAXbouABvnWeJ//S44KKlfPZnDDbeiphg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-ppc64-gnu": { + "version": "1.93.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.93.0.tgz", + "integrity": "sha512-7qKCnvhZKDXJG2pdbLazd2hw4FxjJHbZOFrrbzyy5PdHfPLH9vnNUa1le01A8uItZuYKPBPncH+HCoEiFT4SgA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-riscv64-gnu": { + "version": "1.93.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-1.93.0.tgz", + "integrity": "sha512-2pgulxC6G8V5wE750NJE/fRkf9aO6i6yoj10wyaR2EdiNtan4OemsOtsQ0ZTXGdY8Q3IoTmlND3GYvjJsvikYg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-riscv64-musl": { + "version": "1.93.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-1.93.0.tgz", + "integrity": "sha512-yWsn6Gg2PnGG5jlyDz5+pHGiMTMiy4adaa4WRMzDgzB8efaShk1JMmTHIBSVLQMh0tYXRs4CN5uJCO79r4Mi4g==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-s390x-gnu": { + "version": "1.93.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.93.0.tgz", + "integrity": "sha512-WCn5plwp/ezS2RDPQKp0/EXEVRr9/dDexUdRKmsMFqzNM5xBSZ1wbsi3PuMk1VfkMRnI5BuazCsziCWMXRDOlw==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-x64-gnu": { + "version": "1.93.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.93.0.tgz", + "integrity": "sha512-F2CGjb9LAkzH+IYTZSzd1klQ1vk5z6Utjax64WeLByCkYXbVDbsun+Oy2hLfW2MDSKCvW+jwy/9ld0EPgdeu+A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-x64-musl": { + "version": "1.93.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-x64-musl/-/binding-linux-x64-musl-1.93.0.tgz", + "integrity": "sha512-plf5DE2objcG8Tf7mXRuRa8tT8rzDkpjqXQtKoGsKHWkpgsialbON1+cCtoSEUTVbQUjXvuAm8vV9+3rR0yCBw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-openharmony-arm64": { + "version": "1.93.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-openharmony-arm64/-/binding-openharmony-arm64-1.93.0.tgz", + "integrity": "sha512-Kp2yJrKvoTe9FfKdO/xwLNUbs2bYTMKx0+aoQD1s0h/Tx0kSgtHSdGmrk8tTKdluosjFbo88qYRIaNIX43AfFw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-win32-arm64-msvc": { + "version": "1.93.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.93.0.tgz", + "integrity": "sha512-vigjcHCFsR6KjnWTEVfaCxcMYapEuaK9FZa1MpewwQ1S+Xud3v0okfkj1RySsD6RF1NRHIjSlQSalTnKIaj3nA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-win32-ia32-msvc": { + "version": "1.93.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-1.93.0.tgz", + "integrity": "sha512-0Ot3BEe/AAr2/uQhe55r8CmPlperYk2mQmxdutOru7oU0kir6IiEVHb1TG3GORRlfra97lPHVDLhgmihiKzLrg==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-win32-x64-msvc": { + "version": "1.93.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.93.0.tgz", + "integrity": "sha512-ZzzIIVs/Qkm8trUWYKF0OYub5ALlv50/3gsEZbKAvWgz+yNJX6uRmQ8ySPXU2Q0/Y9m4JCOjhpmC8XUYbPHX5Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-android-arm-eabi": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.19.tgz", + "integrity": "sha512-e+Ebe0WT+9tbXmNKPIiC8YrWAHYwug3m6i4p3rZGGulfZri1jtI4HslT+OZnFf/OIHowWF71DTlHwXBP2SiA7A==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-android-arm64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.19.tgz", + "integrity": "sha512-hOombrTJ+szt2ciEzS7oCA78lMPBgF5UMQWCJIyNfnrI7GLl8HYoFqCnpL2gcPOaXMqryGCU5ExdQKyDDcC+yA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-arm64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.19.tgz", + "integrity": "sha512-XoMA2pwCKGTQzUjPgtRwkedH4WmXhdIPKT6l6oOxd1PUbNodGI6DcBekgN7EC//+x3pfBYX/qL1gNmZAqivw5g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-x64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.19.tgz", + "integrity": "sha512-zo8EsSSwMZCY/e+fRnGaX02YGgvJD0yvhNi/9hpGPA2MJ9ZF8dPCw75UGfpI6OpQ/myR/dIYmogRvqiZD0TrXg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-freebsd-x64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.19.tgz", + "integrity": "sha512-O8ISAOfI1nj7AuBPd30FSF47z7f7lzlk5poQVGgiikvQuGEBFYvW8ki+UEnT+YJPnNGjQzn304klt4O9FUE7mA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm-gnueabihf": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.19.tgz", + "integrity": "sha512-/lYCba5NO0yq4S0jGMH8QTBtkvQxoXjoQWzF5BcWp9MjB9jxVRD1GQDNofkVjcOj30DWyhLIN/4Oe60JKzaONw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-gnu": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.19.tgz", + "integrity": "sha512-pm/apFMBnSbFb3O6nG5pHO1iqHhZrjGDFEjSm+ot9J17XXPvH9L90y5h+jgfHCE+Qdlsvy8qKEcU4VKxgjD+vA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-musl": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.19.tgz", + "integrity": "sha512-K1SmQp3FFichn8oqrNIwvFoZ5wcvjC7goBzpaMNvLf9FZc+QB/QvLmnpJZgAAGHiD980tP8FZZnXk2K94rvlxg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-ppc64-gnu": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.19.tgz", + "integrity": "sha512-I0xwD57jP/3A7+5UPZin2w8Y7XHEmEM5zqpYZOcQ45MlNW6tUJUziymV3yRr7rL4vwyfEcRsRksC4a7Kc08p5Q==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-s390x-gnu": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.19.tgz", + "integrity": "sha512-BrtEHT24SNXj9HiXqy+s/kXiSiQGt6EKCPUlRirAoIioVxKGnbXBUEkbZASAei7iZJB0/Ynm+0JP00Ipx7AnSw==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-gnu": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.19.tgz", + "integrity": "sha512-rm75/9DkHKeU2WnA8w4X94WGYgLlDCFCfkQC+4bguVJmC/jvDRv2B+2wLOYhyE0fVuv7//Ckk39OoOufyCu76Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-musl": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.19.tgz", + "integrity": "sha512-irh/4+iYFM4GAzpluDErgjz89bj6NDtqqMAG/6O1LG38Ed3NpyebzCpcVNkFW8uhy+/3/BocUvnXDR33CXWe9A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-openharmony-arm64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.19.tgz", + "integrity": "sha512-+KWTWNoPt+CfSq94CiceWu3yPE+QzkaG+phPyz9G60tmZLwfQkcA4AeksafzvJAw4pvg1mcd5a1TkUqVv0s4JA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-wasm32-wasi": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.2.19.tgz", + "integrity": "sha512-7EH+skOsl5qpWnK0vzamgJFhOv1cwxQpsxm8tI883K9fur5c27p8q87fzEO6BbBPabA2/+s/zR63/pLc137iOg==", + "cpu": [ + "wasm32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/core": "2.0.0-beta.2", + "@emnapi/runtime": "2.0.0-beta.2", + "@napi-rs/wasm-runtime": "1.2.6" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + } + }, + "node_modules/@rolldown/binding-win32-arm64-msvc": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.19.tgz", + "integrity": "sha512-3Q1Yg1Q7tEvBWoZf5rFvG/GKZQPgwfru+p4wBajDfJFBs0SHCpL++dfTjW9gyAKd1T7ZpIYvdaUax7Pa/IhFVQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-x64-msvc": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.19.tgz", + "integrity": "sha512-y/sqRRc6d7hECzOFc5n3LSeqctmIp9mMjY1Kq4s14uLPd/LZ4z7i1zrW6fMtp2mPeuQIC4e6ULMcwQzMomqQag==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.1.1.tgz", + "integrity": "sha512-glFIJDvLNDtJhT9qrMFWLPbvS+skxgt4L0K8Ei2YtnhPysAJnsI7nyxSJxKj4ADeKX0OLjC4ntRkwpLOoS3rwA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@tailwindcss/node": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/node/-/node-4.3.5.tgz", + "integrity": "sha512-yT53FzV4ke0cr/BguDxhWMpm5MJu1O2muzk+tKw6lKHjODAsYArBbWwFbJiaksfzFv1tpkO9QHGzmfs1hJT66g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/remapping": "^2.3.5", + "enhanced-resolve": "^5.24.5", + "jiti": "^2.7.0", + "lightningcss": "1.33.0", + "magic-string": "^1.1.0", + "source-map-js": "^1.2.1", + "tailwindcss": "4.3.5" + } + }, + "node_modules/@tailwindcss/oxide": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide/-/oxide-4.3.5.tgz", + "integrity": "sha512-PynqGLZsZvwM9tqD/CUxkOIfyd6K5elZ2MooauzJryP/UqXYgi3yYbtt3N0Xe+MHV/eFKPFQCEfIKAqlAS1CBg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 20" + }, + "optionalDependencies": { + "@tailwindcss/oxide-android-arm64": "4.3.5", + "@tailwindcss/oxide-darwin-arm64": "4.3.5", + "@tailwindcss/oxide-darwin-x64": "4.3.5", + "@tailwindcss/oxide-freebsd-x64": "4.3.5", + "@tailwindcss/oxide-linux-arm-gnueabihf": "4.3.5", + "@tailwindcss/oxide-linux-arm64-gnu": "4.3.5", + "@tailwindcss/oxide-linux-arm64-musl": "4.3.5", + "@tailwindcss/oxide-linux-x64-gnu": "4.3.5", + "@tailwindcss/oxide-linux-x64-musl": "4.3.5", + "@tailwindcss/oxide-wasm32-wasi": "4.3.5", + "@tailwindcss/oxide-win32-arm64-msvc": "4.3.5", + "@tailwindcss/oxide-win32-x64-msvc": "4.3.5" + } + }, + "node_modules/@tailwindcss/oxide-android-arm64": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-android-arm64/-/oxide-android-arm64-4.3.5.tgz", + "integrity": "sha512-Se0z5xMqcSQanJD1IYmO0cGpK3iv0fp3ZsIT7xRJZ1Da5PghvNoc46zz4jIQn+aan3dV9T8AermFNN9QPmsh0Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-darwin-arm64": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-arm64/-/oxide-darwin-arm64-4.3.5.tgz", + "integrity": "sha512-UPrgTDuUbvmqGMZuCnmI3FKee/tYKzKdp00/kuB4oSGB213VYg8QTdF7lVhnPoBXq/mIfJ+ILoBFqNOboWcMwQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-darwin-x64": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-x64/-/oxide-darwin-x64-4.3.5.tgz", + "integrity": "sha512-E+p7HEtjI0b8D7kbbWxH067cGui6d4c79COGko9fAPVE3rwc1E7ld2HFCbaG86AOGWS5VKQYqZOaf38ya4uxTQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-freebsd-x64": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-freebsd-x64/-/oxide-freebsd-x64-4.3.5.tgz", + "integrity": "sha512-yWEWcWyAG7rWOcTpJTjdhQ3pcaFY2h+0bqTRfgU3G2fz87ZU3AKdvdZKhslD+kyHnjBUWKvNdRYwIYC5dI1tIg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-arm-gnueabihf": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm-gnueabihf/-/oxide-linux-arm-gnueabihf-4.3.5.tgz", + "integrity": "sha512-WmeVjtJhZlr+smpqcdR2kQkkn6arHIJnUIBxTO2EJcTLGY1ecVXNo2hbSn8xc0IH2aEtys936iMWKGyj0GaKnA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-arm64-gnu": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-gnu/-/oxide-linux-arm64-gnu-4.3.5.tgz", + "integrity": "sha512-DTCSyucc6ShMp1QMqV5R94Z7xlgNgUzkGmFF1rL5HH2Qjy4eSmEqy+YLGkqqYvWa4sILtgrBt1JjRKbneQtiFQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-arm64-musl": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-musl/-/oxide-linux-arm64-musl-4.3.5.tgz", + "integrity": "sha512-H9lsvO4x9E4nE4Hi8h7NHHw0O/kcVSu+iOyFHNGdYzazGgDjFHZbE6S3hQ8kMcbNXSBlMdNi67LV5EVqtpaJtw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-x64-gnu": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-gnu/-/oxide-linux-x64-gnu-4.3.5.tgz", + "integrity": "sha512-4uxQvtBvPuIdl13WfUBj9xMZHH14PtHZ8OZdtLmdyDtG66sCa1t599NZT+jagkUzRtWhuul1qRZQ1nAJscXN5g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-x64-musl": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-musl/-/oxide-linux-x64-musl-4.3.5.tgz", + "integrity": "sha512-0JQAzs7jwbA7O6+z/adU+Jk3AXwsu3npAhtr5escXS7TqEqWcaDV7qHuI+0Vy/KQRuVGnLQREcSJWYauyV3oqg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-wasm32-wasi/-/oxide-wasm32-wasi-4.3.5.tgz", + "integrity": "sha512-OJhFmlEfdzMr+avACdi40RPtnkW0B6hXyxL/8r+tnEHBWZji36CYRjEXrrvgBmaYsD3oEOBqwYFRKsYvzFe7Bw==", + "bundleDependencies": [ + "@napi-rs/wasm-runtime", + "@emnapi/core", + "@emnapi/runtime", + "@tybys/wasm-util", + "@emnapi/wasi-threads", + "tslib" + ], + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/core": "^1.11.3", + "@emnapi/runtime": "^1.11.3", + "@emnapi/wasi-threads": "^1.2.3", + "@napi-rs/wasm-runtime": "^1.2.2", + "@tybys/wasm-util": "^0.10.3", + "tslib": "^2.8.1" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core": { + "version": "1.11.3", + "dev": true, + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/wasi-threads": "1.2.3", + "tslib": "^2.4.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime": { + "version": "1.11.3", + "dev": true, + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads": { + "version": "1.2.3", + "dev": true, + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@napi-rs/wasm-runtime": { + "version": "1.2.2", + "dev": true, + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@tybys/wasm-util": "^0.10.3" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + }, + "peerDependencies": { + "@emnapi/core": "^1.7.1 || ^2.0.0-alpha.3", + "@emnapi/runtime": "^1.7.1 || ^2.0.0-alpha.3" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util": { + "version": "0.10.3", + "dev": true, + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib": { + "version": "2.8.1", + "dev": true, + "inBundle": true, + "license": "0BSD", + "optional": true + }, + "node_modules/@tailwindcss/oxide-win32-arm64-msvc": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-arm64-msvc/-/oxide-win32-arm64-msvc-4.3.5.tgz", + "integrity": "sha512-9o8jgthi+QE5eandnboiJT64VQfnIArfZzSTdgbhEK5aafdiu2jTW9Honi/mwYHxBZuH1vAC57IFyrh+0iK5Gg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-win32-x64-msvc": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-x64-msvc/-/oxide-win32-x64-msvc-4.3.5.tgz", + "integrity": "sha512-XiKFfIy1RWe7qK4WqByxNW7Oz1/nkOy8o/BWhHminyV1PmpUd8Eedj5v2A8h2kpqeVlz6xRnwk9Fr/ZXNLcZfg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/vite": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/vite/-/vite-4.3.5.tgz", + "integrity": "sha512-BCNiY0a1ZjdOHVqw7kyb7U72BwfMF3dfUuN+tQsLWky/J5JOI/r7abibglXfygrZhVO/3u3V+E25kkKTeMkXaQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@tailwindcss/node": "4.3.5", + "@tailwindcss/oxide": "4.3.5", + "tailwindcss": "4.3.5" + }, + "peerDependencies": { + "vite": "^5.2.0 || ^6 || ^7 || ^8" + } + }, + "node_modules/@tybys/wasm-util": { + "version": "0.10.4", + "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.4.tgz", + "integrity": "sha512-W3c4gRigFS0T/Ma4qIYF3GDAc5AQdHb1yL5znJT1Zv1YaD9Kitx656wBjvr19qbiosmZT8lWDM5BEMynUqX65A==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@types/react": { + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz", + "integrity": "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==", + "dev": true, + "license": "MIT", + "dependencies": { + "csstype": "^3.2.2" + } + }, + "node_modules/@types/react-dom": { + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.3.0.tgz", + "integrity": "sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@types/react": "^19.3.0" + } + }, + "node_modules/@vitejs/plugin-react": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-6.3.0.tgz", + "integrity": "sha512-H9E955aVvD2F4zNHCw4eIZbIfF6xKldlh7MNu+hSU7xwQzh65lI/N+CJWqmfhi0PEjDXIt/H7T7J/4wU63KJiw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@rolldown/pluginutils": "^1.0.1" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "peerDependencies": { + "@rolldown/plugin-babel": "^0.1.7 || ^0.2.0 || ^0.3.0", + "babel-plugin-react-compiler": "^1.0.0", + "oxc-transform-react": ">=0.152.0 <0.157.0", + "vite": "^8.0.0" + }, + "peerDependenciesMeta": { + "@rolldown/plugin-babel": { + "optional": true + }, + "babel-plugin-react-compiler": { + "optional": true + }, + "oxc-transform-react": { + "optional": true + } + } + }, + "node_modules/agent-base": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", + "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", + "license": "MIT", + "dependencies": { + "debug": "4" + }, + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", + "license": "MIT" + }, + "node_modules/axios": { + "version": "1.21.1", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.21.1.tgz", + "integrity": "sha512-6eI5Q/Y4u/Um9dDlsRoq5pY2rxnUTv+L4PpLitnbk/i4jb3MxLZ5CsN5Ih3IysbeRYK4pR+P7qfMsOQl9fwwFQ==", + "license": "MIT", + "dependencies": { + "follow-redirects": "^1.16.2", + "form-data": "^4.0.6", + "https-proxy-agent": "^5.0.1", + "proxy-from-env": "^2.1.0" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "license": "MIT", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/cookie": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz", + "integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/csstype": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", + "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "license": "MIT", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/enhanced-resolve": { + "version": "5.27.0", + "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.27.0.tgz", + "integrity": "sha512-Do6BB2xzlcc/odFg+XEYyneAx4T/WfywO71yw9ePS2tVfRsf7JVR4mUeELadIeHzixkzbG5DpluiEFPi2WGfYQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.4", + "tapable": "^2.3.3" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-set-tostringtag": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", + "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/follow-redirects": { + "version": "1.16.3", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.3.tgz", + "integrity": "sha512-toOSoqN6d51Wjf1aOFJYcoVv1aND9rj/CwjLU0Vz40oDuSpWDayCeKe4JpL5NL0WdFvoOOCI3BRo69HahjbR1A==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "license": "MIT", + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, + "node_modules/form-data": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz", + "integrity": "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==", + "license": "MIT", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "es-set-tostringtag": "^2.1.0", + "hasown": "^2.0.4", + "mime-types": "^2.1.35" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/framer-motion": { + "version": "14.13.0", + "resolved": "https://registry.npmjs.org/framer-motion/-/framer-motion-14.13.0.tgz", + "integrity": "sha512-62FgGVeqEI3pgI5jG/d6yagg/hX9z7Vw3ytE0gGAsDXWBBruUCr74b5LQJXMSF1E62Zp7HKO88nDu/hhUdRSCQ==", + "license": "MIT", + "dependencies": { + "motion-dom": "14.13.0", + "motion-utils": "14.7.0", + "tslib": "^2.4.0" + }, + "peerDependencies": { + "react": "^18.0.0 || ^19.0.0", + "react-dom": "^18.0.0 || ^19.0.0", + "remix": "^3.1.0" + }, + "peerDependenciesMeta": { + "react": { + "optional": true + }, + "react-dom": { + "optional": true + }, + "remix": { + "optional": true + } + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.12", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.12.tgz", + "integrity": "sha512-iuyGF2E4oafQfPsRrG2wtY2ILupMhvtdrhzrxB+0VcjsPpSPttpfYdjnGFGsTi5MaJFjI1jOKHPQ6UTbTj9TAw==", + "dev": true, + "license": "BlueOak-1.0.0" + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "license": "MIT", + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/https-proxy-agent": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", + "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", + "license": "MIT", + "dependencies": { + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/jiti": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.7.0.tgz", + "integrity": "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==", + "dev": true, + "license": "MIT", + "bin": { + "jiti": "lib/jiti-cli.mjs" + } + }, + "node_modules/lightningcss": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", + "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", + "dev": true, + "license": "MPL-2.0", + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.33.0", + "lightningcss-darwin-arm64": "1.33.0", + "lightningcss-darwin-x64": "1.33.0", + "lightningcss-freebsd-x64": "1.33.0", + "lightningcss-linux-arm-gnueabihf": "1.33.0", + "lightningcss-linux-arm64-gnu": "1.33.0", + "lightningcss-linux-arm64-musl": "1.33.0", + "lightningcss-linux-x64-gnu": "1.33.0", + "lightningcss-linux-x64-musl": "1.33.0", + "lightningcss-win32-arm64-msvc": "1.33.0", + "lightningcss-win32-x64-msvc": "1.33.0" + } + }, + "node_modules/lightningcss-android-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz", + "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz", + "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz", + "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-freebsd-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz", + "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz", + "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz", + "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz", + "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz", + "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz", + "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz", + "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz", + "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lucide-react": { + "version": "1.72.0", + "resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-1.72.0.tgz", + "integrity": "sha512-fbF5i1GU8GODETa3Q7rXqrJrcx3iPYrQtxthom103zGx+Z0BGwKYAW9s+9435ohYJ7hQm0av0PoZcqI1CRwNrg==", + "license": "ISC", + "peerDependencies": { + "@types/react": "*", + "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/magic-string": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.5.tgz", + "integrity": "sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.6.0" + } + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/motion-dom": { + "version": "14.13.0", + "resolved": "https://registry.npmjs.org/motion-dom/-/motion-dom-14.13.0.tgz", + "integrity": "sha512-nWrB6Psw7mFTBNL9r5hw9nm/a5+21WZ1LymOml/V2b43LdiIDO1oi+oBMSR3bcyuzEQKJoaa+t5qnsCWYhcNvA==", + "license": "MIT", + "dependencies": { + "motion-utils": "14.7.0" + } + }, + "node_modules/motion-utils": { + "version": "14.7.0", + "resolved": "https://registry.npmjs.org/motion-utils/-/motion-utils-14.7.0.tgz", + "integrity": "sha512-woO0/Nb7ys75f94fjvQi/6leiHGvZUYkeHUPEZ3vxsV+9OpEVhkxp01x8MlRwX0zt31EqgXsKDAoBoJLC148Tw==", + "license": "MIT" + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/oxlint": { + "version": "1.93.0", + "resolved": "https://registry.npmjs.org/oxlint/-/oxlint-1.93.0.tgz", + "integrity": "sha512-19JMsQFX+YvEbcUTFQxjTwhvs0Ibg0D6CFneSLgpwnACWcY/6LjhpGpkPodh0T5aIT1pjMTLlYaeBFzaVgugTA==", + "dev": true, + "license": "MIT", + "bin": { + "oxlint": "bin/oxlint" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/sponsors/oxc-project" + }, + "optionalDependencies": { + "@oxlint/binding-android-arm-eabi": "1.93.0", + "@oxlint/binding-android-arm64": "1.93.0", + "@oxlint/binding-darwin-arm64": "1.93.0", + "@oxlint/binding-darwin-x64": "1.93.0", + "@oxlint/binding-freebsd-x64": "1.93.0", + "@oxlint/binding-linux-arm-gnueabihf": "1.93.0", + "@oxlint/binding-linux-arm-musleabihf": "1.93.0", + "@oxlint/binding-linux-arm64-gnu": "1.93.0", + "@oxlint/binding-linux-arm64-musl": "1.93.0", + "@oxlint/binding-linux-ppc64-gnu": "1.93.0", + "@oxlint/binding-linux-riscv64-gnu": "1.93.0", + "@oxlint/binding-linux-riscv64-musl": "1.93.0", + "@oxlint/binding-linux-s390x-gnu": "1.93.0", + "@oxlint/binding-linux-x64-gnu": "1.93.0", + "@oxlint/binding-linux-x64-musl": "1.93.0", + "@oxlint/binding-openharmony-arm64": "1.93.0", + "@oxlint/binding-win32-arm64-msvc": "1.93.0", + "@oxlint/binding-win32-ia32-msvc": "1.93.0", + "@oxlint/binding-win32-x64-msvc": "1.93.0" + }, + "peerDependencies": { + "oxlint-tsgolint": ">=7.0.2005", + "vite-plus": "*" + }, + "peerDependenciesMeta": { + "oxlint-tsgolint": { + "optional": true + }, + "vite-plus": { + "optional": true + } + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.32", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.32.tgz", + "integrity": "sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.20", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/proxy-from-env": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-2.1.0.tgz", + "integrity": "sha512-cJ+oHTW1VAEa8cJslgmUZrc+sjRKgAKl3Zyse6+PV38hZe/V6Z14TbCuXcan9F9ghlz4QrFr2c92TNF82UkYHA==", + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/react": { + "version": "19.3.1", + "resolved": "https://registry.npmjs.org/react/-/react-19.3.1.tgz", + "integrity": "sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-dom": { + "version": "19.3.1", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.3.1.tgz", + "integrity": "sha512-Y0bARz53lhEC1NMCASs0/j+faB/zqt3R8hpvg1e8+61ZVJ4UL0UdC4cBbXfZMcIuhrfgeILTLe+ZeBCavQPtKQ==", + "license": "MIT", + "dependencies": { + "scheduler": "^0.28.0" + }, + "peerDependencies": { + "react": "^19.3.1" + } + }, + "node_modules/react-router": { + "version": "7.18.5", + "resolved": "https://registry.npmjs.org/react-router/-/react-router-7.18.5.tgz", + "integrity": "sha512-dTgvcXDOrLPrlLHrcZAqWveiK1hMSqN+rGAJzegP8HtmNkfRxOoshGWBNX3ZJ0cZjOHkRdlUJtaIhZMLLyGyPw==", + "license": "MIT", + "dependencies": { + "cookie": "^1.0.1", + "set-cookie-parser": "^2.6.0" + }, + "engines": { + "node": ">=20.0.0" + }, + "peerDependencies": { + "react": ">=18", + "react-dom": ">=18" + }, + "peerDependenciesMeta": { + "react-dom": { + "optional": true + } + } + }, + "node_modules/react-router-dom": { + "version": "7.18.5", + "resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-7.18.5.tgz", + "integrity": "sha512-9HcfDMU6JJ/fp6gJZYGwNE6RknVGS4kBjH1HkNw959mCJi70TVwdipQWv2FEol9uGpi+SZTFtVpJPtEQfayeOw==", + "license": "MIT", + "dependencies": { + "react-router": "7.18.5" + }, + "engines": { + "node": ">=20.0.0" + }, + "peerDependencies": { + "react": ">=18", + "react-dom": ">=18" + } + }, + "node_modules/rolldown": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.19.tgz", + "integrity": "sha512-QIiV1J9d0pzN4jeeTH4sjPy0AZ6cAy2cG0ExeoE1+U8Rvj+hR3gYkokx0YbeUNGlZqiQJJ2utcETe0oKXwzsuA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@oxc-project/types": "=0.156.0", + "@rolldown/pluginutils": "^1.0.0" + }, + "bin": { + "rolldown": "bin/cli.mjs" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "optionalDependencies": { + "@rolldown/binding-android-arm-eabi": "1.2.19", + "@rolldown/binding-android-arm64": "1.2.19", + "@rolldown/binding-darwin-arm64": "1.2.19", + "@rolldown/binding-darwin-x64": "1.2.19", + "@rolldown/binding-freebsd-x64": "1.2.19", + "@rolldown/binding-linux-arm-gnueabihf": "1.2.19", + "@rolldown/binding-linux-arm64-gnu": "1.2.19", + "@rolldown/binding-linux-arm64-musl": "1.2.19", + "@rolldown/binding-linux-ppc64-gnu": "1.2.19", + "@rolldown/binding-linux-s390x-gnu": "1.2.19", + "@rolldown/binding-linux-x64-gnu": "1.2.19", + "@rolldown/binding-linux-x64-musl": "1.2.19", + "@rolldown/binding-openharmony-arm64": "1.2.19", + "@rolldown/binding-wasm32-wasi": "1.2.19", + "@rolldown/binding-win32-arm64-msvc": "1.2.19", + "@rolldown/binding-win32-x64-msvc": "1.2.19" + } + }, + "node_modules/scheduler": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.28.0.tgz", + "integrity": "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==", + "license": "MIT" + }, + "node_modules/set-cookie-parser": { + "version": "2.7.3", + "resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.7.3.tgz", + "integrity": "sha512-irZHtTqurLna57KQG/s+fzOwv/J6XSH4cs8M/vsrY3uCaQ3S6+QJguAH0WdN47SXlk82voMZ4naWMQf8fdEoIg==", + "license": "MIT" + }, + "node_modules/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/tailwindcss": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.3.5.tgz", + "integrity": "sha512-FcQk9BuffmEHJP2G0XmB2SplU1aLTI7j07Kunk+U74Ny+XiWOtzXz9aujFZ/avntw1e2cOv/3PkgzflQ7gX2vQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/tapable": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/tapable/-/tapable-2.3.3.tgz", + "integrity": "sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tslib": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz", + "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==", + "license": "0BSD" + }, + "node_modules/vite": { + "version": "8.3.8", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.8.tgz", + "integrity": "sha512-LzOn3h9rG/0vhLdXrV4yJ4QFA9eEoqCl+Yx+kGJd7aB9w6nfNgVHKSYwLPZUHrz4ZGa+t+kXjV9itvcHDLQouA==", + "dev": true, + "license": "MIT", + "dependencies": { + "lightningcss": "^1.33.0", + "picomatch": "^4.0.7", + "postcss": "^8.5.32", + "rolldown": "~1.2.18", + "tinyglobby": "^0.2.17" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "@vitejs/devtools": "^0.7.1 || ^0.8.0", + "esbuild": "^0.27.0 || ^0.28.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "@vitejs/devtools": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + } + } +} diff --git a/frontend/package.json b/frontend/package.json new file mode 100644 index 0000000..dfec035 --- /dev/null +++ b/frontend/package.json @@ -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" + } +} diff --git a/frontend/public/favicon.png b/frontend/public/favicon.png new file mode 100644 index 0000000..42d684b Binary files /dev/null and b/frontend/public/favicon.png differ diff --git a/frontend/public/favicon.svg b/frontend/public/favicon.svg new file mode 100644 index 0000000..6893eb1 --- /dev/null +++ b/frontend/public/favicon.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/frontend/public/icons.svg b/frontend/public/icons.svg new file mode 100644 index 0000000..e952219 --- /dev/null +++ b/frontend/public/icons.svg @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx new file mode 100644 index 0000000..09c82e9 --- /dev/null +++ b/frontend/src/App.jsx @@ -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 ( + + {children} + + ) +} + +export default function App() { + return ( + + }> + + + } + /> + + + + } + /> + + + + } + > + } /> + } /> + } /> + } /> + } /> + + + ) +} diff --git a/frontend/src/admin/AdminApp.jsx b/frontend/src/admin/AdminApp.jsx new file mode 100644 index 0000000..703c49e --- /dev/null +++ b/frontend/src/admin/AdminApp.jsx @@ -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
+ if (!admin) return + return children +} + +export default function AdminApp() { + return ( + + + + } /> + + + + } + > + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + + + + + ) +} diff --git a/frontend/src/admin/components/ImageUploader.jsx b/frontend/src/admin/components/ImageUploader.jsx new file mode 100644 index 0000000..e847e57 --- /dev/null +++ b/frontend/src/admin/components/ImageUploader.jsx @@ -0,0 +1,100 @@ +import { useRef, useState } from 'react' +import { ImagePlus, Stamp } from 'lucide-react' +import api, { errorMessage } from '../../services/api' + +const ACCEPT = ['image/jpeg', 'image/png', 'image/webp'] +const EXT = /\.(jpe?g|png|webp)$/i +const MAX_MB = 10 + +/** + * Drag & drop / click uploader. Validates type and size client-side (the server + * re-validates everything), shows upload progress, and reports the response. + */ +export default function ImageUploader({ url, field = 'files', multiple = true, onUploaded, onError, compact = false }) { + const inputRef = useRef(null) + const [drag, setDrag] = useState(false) + const [progress, setProgress] = useState(null) + const [problems, setProblems] = useState([]) + + const upload = async (fileList) => { + const files = Array.from(fileList || []) + if (!files.length) return + const bad = [] + const good = files.filter((f) => { + if (!ACCEPT.includes(f.type) && !EXT.test(f.name)) return bad.push(`${f.name}: only JPG, PNG or WEBP`) && false + if (f.size > MAX_MB * 1024 * 1024) return bad.push(`${f.name}: larger than ${MAX_MB} MB`) && false + return true + }) + setProblems(bad) + if (!good.length) return + const form = new FormData() + ;(multiple ? good : good.slice(0, 1)).forEach((f) => form.append(field, f)) + setProgress(0) + try { + const res = await api.post(url, form, { + onUploadProgress: (e) => e.total && setProgress(Math.round((e.loaded / e.total) * 100)), + timeout: 180000, + }) + onUploaded?.(res.data) + } catch (e) { + const msg = errorMessage(e, 'Upload failed.') + setProblems((p) => [...p, msg]) + onError?.(msg) + } finally { + setProgress(null) + if (inputRef.current) inputRef.current.value = '' + } + } + + const busy = progress !== null + return ( +
+
!busy && inputRef.current?.click()} + onKeyDown={(e) => (e.key === 'Enter' || e.key === ' ') && !busy && inputRef.current?.click()} + onDragOver={(e) => { + e.preventDefault() + setDrag(true) + }} + onDragLeave={() => setDrag(false)} + onDrop={(e) => { + e.preventDefault() + setDrag(false) + if (!busy) upload(e.dataTransfer.files) + }} + className={`flex cursor-pointer flex-col items-center justify-center rounded-2xl border-2 border-dashed text-center transition ${compact ? 'px-4 py-6' : 'px-6 py-10'} ${ + drag ? 'border-brand bg-brand/5' : 'border-[#D0D5DD] bg-surface hover:border-brand/60' + } ${busy ? 'cursor-wait' : ''}`} + aria-label="Upload images" + > + + {busy ? ( +
+

{progress < 100 ? `Uploading… ${progress}%` : 'Adding watermark & thumbnails…'}

+
+
+
+
+ ) : ( + <> +

+ {multiple ? 'Drop photos here or click to choose' : 'Drop a photo here or click to choose'} +

+

JPG, PNG or WEBP · up to {MAX_MB} MB{multiple ? ' each · up to 20 at once' : ''}

+

+ Saura Shakti watermark is added automatically +

+ + )} + upload(e.target.files)} /> +
+ {problems.length > 0 && ( +
    + {problems.map((p) =>
  • {p}
  • )} +
+ )} +
+ ) +} diff --git a/frontend/src/admin/components/feedback.jsx b/frontend/src/admin/components/feedback.jsx new file mode 100644 index 0000000..f1ce426 --- /dev/null +++ b/frontend/src/admin/components/feedback.jsx @@ -0,0 +1,111 @@ +import { createContext, useCallback, useContext, useMemo, useRef, useState } from 'react' +import { AnimatePresence, motion } from 'framer-motion' +import { AlertTriangle, CheckCircle2, X, XCircle } from 'lucide-react' +import Modal from '../../components/Modal' +import { Spinner } from '../../components/ui' + +const FeedbackContext = createContext(null) + +export function FeedbackProvider({ children }) { + const [toasts, setToasts] = useState([]) + const [confirmState, setConfirmState] = useState(null) + const idRef = useRef(0) + + const toast = useCallback((message, type = 'success') => { + const id = ++idRef.current + setToasts((t) => [...t, { id, message, type }]) + setTimeout(() => setToasts((t) => t.filter((x) => x.id !== id)), type === 'error' ? 6000 : 3500) + }, []) + + /** confirm({title, message, confirmLabel, danger}) → Promise */ + const confirm = useCallback( + (opts) => new Promise((resolve) => setConfirmState({ ...opts, resolve })), + [], + ) + + const value = useMemo(() => ({ toast, confirm }), [toast, confirm]) + const closeConfirm = (result) => { + confirmState?.resolve(result) + setConfirmState(null) + } + + return ( + + {children} +
+ + {toasts.map((t) => ( + + {t.type === 'error' ? : } + {t.message} + + + ))} + +
+ closeConfirm(false)} title={confirmState?.title || 'Are you sure?'} width="max-w-[440px]"> +
+ {confirmState?.danger && } +

{confirmState?.message}

+
+
+ + +
+
+
+ ) +} + +// eslint-disable-next-line react-refresh/only-export-components +export const useFeedback = () => useContext(FeedbackContext) + +export function LoadingBlock({ label = 'Loading…' }) { + return ( +
+ {label} +
+ ) +} + +export function ErrorBlock({ message, onRetry }) { + return ( +
+

{message}

+ {onRetry && ( + + )} +
+ ) +} + +export function EmptyBlock({ title, text, action }) { + return ( +
+

{title}

+ {text &&

{text}

} + {action &&
{action}
} +
+ ) +} diff --git a/frontend/src/admin/components/kit.jsx b/frontend/src/admin/components/kit.jsx new file mode 100644 index 0000000..3335d47 --- /dev/null +++ b/frontend/src/admin/components/kit.jsx @@ -0,0 +1,114 @@ +import { ChevronLeft, ChevronRight } from 'lucide-react' +import { Spinner } from '../../components/ui' + +export const STATUS = { + new: { label: 'New', cls: 'bg-[#EFF8FF] text-[#175CD3] ring-[#B2DDFF]' }, + contacted: { label: 'Contacted', cls: 'bg-[#F4F3FF] text-[#5925DC] ring-[#D9D6FE]' }, + site_visit_scheduled: { label: 'Site Visit Scheduled', cls: 'bg-[#FFFAEB] text-[#B54708] ring-[#FEDF89]' }, + quotation_sent: { label: 'Quotation Sent', cls: 'bg-[#F0F9FF] text-[#026AA2] ring-[#B9E6FE]' }, + converted: { label: 'Converted', cls: 'bg-[#ECFDF3] text-[#067647] ring-[#ABEFC6]' }, + rejected: { label: 'Rejected', cls: 'bg-[#F2F4F7] text-[#475467] ring-[#D0D5DD]' }, +} + +export function StatusBadge({ status }) { + const s = STATUS[status] || { label: status, cls: 'bg-surface text-slate ring-line' } + return {s.label} +} + +export function Pill({ on, children }) { + return ( + + {children} + + ) +} + +export function PageHeader({ title, subtitle, actions }) { + return ( +
+
+

{title}

+ {subtitle &&

{subtitle}

} +
+ {actions &&
{actions}
} +
+ ) +} + +export function Btn({ variant = 'primary', busy, children, className = '', as: Comp = 'button', disabled, ...props }) { + const v = { + primary: 'bg-brand text-white hover:bg-[#023a5a]', + accent: 'bg-yellow-cta text-black hover:brightness-105', + ghost: 'bg-white text-navy ring-1 ring-line hover:bg-surface', + danger: 'bg-white text-[#B42318] ring-1 ring-[#FECDCA] hover:bg-[#FEF3F2]', + }[variant] + const buttonProps = Comp === 'button' ? { type: 'button', disabled: busy || disabled } : {} + return ( + + {busy && } + {children} + + ) +} + +export function Card({ children, className = '' }) { + return
{children}
+} + +export const aInput = + 'w-full rounded-xl border border-[#D0D5DD] bg-white px-3.5 py-2.5 text-[14px] text-navy outline-none transition placeholder:text-[#98A2B3] focus:border-brand focus:ring-4 focus:ring-brand/10 disabled:bg-surface aria-[invalid=true]:border-[#F04438]' + +export function AField({ label, error, hint, children, className = '' }) { + return ( + + ) +} + +export function Toggle({ checked, onChange, label }) { + return ( + + ) +} + +export function Pagination({ page, pageSize, total, onPage }) { + const pages = Math.max(1, Math.ceil(total / pageSize)) + if (total <= pageSize) return null + return ( +
+ + {(page - 1) * pageSize + 1}–{Math.min(page * pageSize, total)} of {total} + +
+ + +
+
+ ) +} + +export const fmtDate = (d) => + d ? new Date(d).toLocaleString('en-IN', { day: '2-digit', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit' }) : '—' +export const fmtDay = (d) => (d ? new Date(d).toLocaleDateString('en-IN', { day: '2-digit', month: 'short', year: 'numeric' }) : '—') diff --git a/frontend/src/admin/layouts/AdminLayout.jsx b/frontend/src/admin/layouts/AdminLayout.jsx new file mode 100644 index 0000000..2cc14e3 --- /dev/null +++ b/frontend/src/admin/layouts/AdminLayout.jsx @@ -0,0 +1,111 @@ +import { useEffect, useState } from 'react' +import { NavLink, Outlet, useLocation } from 'react-router-dom' +import { + ExternalLink, + FileText, + FolderKanban, + Inbox, + LayoutDashboard, + LogOut, + Mail, + Menu, + MessageSquareQuote, + Newspaper, + Shield, + Sun, + X, +} from 'lucide-react' +import logo from '../../assets/images/logo.webp' +import { can, useAuth } from '../../context/AuthContext' + +const NAV = [ + { to: '/admin', label: 'Dashboard', icon: LayoutDashboard, end: true }, + { to: '/admin/enquiries', label: 'Enquiries', icon: Inbox }, + { to: '/admin/projects', label: 'Projects', icon: FolderKanban }, + { to: '/admin/services', label: 'Services', icon: Sun }, + { to: '/admin/testimonials', label: 'Testimonials', icon: MessageSquareQuote }, + { to: '/admin/messages', label: 'Contact messages', icon: Mail }, + { to: '/admin/subscribers', label: 'Subscribers', icon: Newspaper }, + { to: '/admin/content', label: 'Website content', icon: FileText }, + { to: '/admin/users', label: 'Admin users', icon: Shield, perm: 'users' }, +] + +const ROLE_LABEL = { super_admin: 'Super admin', admin: 'Admin', editor: 'Editor' } + +export default function AdminLayout() { + const { admin, logout } = useAuth() + const [open, setOpen] = useState(false) + const { pathname } = useLocation() + useEffect(() => setOpen(false), [pathname]) + useEffect(() => { + document.title = 'Admin — Saura Shakti' + }, []) + + const sidebar = ( +
+
+ Saura Shakti + +
+ + +
+ ) + + return ( +
+ + {open && ( +
+
setOpen(false)} aria-hidden /> + +
+ )} + +
+ +
+
+
+

{admin?.full_name}

+

{ROLE_LABEL[admin?.role] || admin?.role}

+
+ +
+
+ +
+ +
+
+ ) +} diff --git a/frontend/src/admin/pages/ContentPage.jsx b/frontend/src/admin/pages/ContentPage.jsx new file mode 100644 index 0000000..574e8ba --- /dev/null +++ b/frontend/src/admin/pages/ContentPage.jsx @@ -0,0 +1,167 @@ +import { useEffect, useMemo, useState } from 'react' +import { RotateCcw } from 'lucide-react' +import { CONTENT_DEFAULTS } from '../../content/defaults' +import { can, useAuth } from '../../context/AuthContext' +import { useApi } from '../../hooks/useApi' +import api, { errorMessage } from '../../services/api' +import { DEFAULT_QUOTE_SETTINGS } from '../../utils/quote' +import { ErrorBlock, LoadingBlock, useFeedback } from '../components/feedback' +import { aInput, AField, Btn, Card, PageHeader } from '../components/kit' + +// Section blocks the admin can edit. Lists keep the design's item count so the layout never breaks. +const BLOCKS = [ + { key: 'hero', label: 'Hero (top of page)' }, + { key: 'solutions', label: 'Solutions slider (used when no services are published)' }, + { key: 'awareness', label: 'Solar awareness' }, + { key: 'myths', label: 'Solar myths (FAQ)' }, + { key: 'quotation', label: 'Quote calculator text' }, + { key: 'quote_settings', label: 'Quote calculator rates', defaults: DEFAULT_QUOTE_SETTINGS }, + { key: 'process', label: 'Installation process' }, + { key: 'testimonials', label: 'Testimonials heading' }, + { key: 'footer', label: 'Footer' }, + { key: 'contact', label: 'Contact details & social links' }, + { key: 'legal', label: 'Terms & privacy pages' }, +] + +const LABELS = { + sqft_per_kw: 'Roof area needed per kW (sq ft)', + panel_cost_per_kw: 'Panel & equipment cost per kW (₹)', + installation_cost_per_kw: 'Installation cost per kW (₹)', + min_area_sqft: 'Minimum roof area (sq ft)', + max_area_sqft: 'Maximum roof area (sq ft)', + subsidy_first_2kw_per_kw: 'Subsidy per kW for first 2 kW (₹)', + subsidy_third_kw: 'Subsidy for 3rd kW (₹)', + subsidy_cap: 'Maximum subsidy (₹)', + commercial_subsidy: 'Commercial subsidy (₹)', +} +const human = (k) => LABELS[k] || k.replace(/_/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase()) +const isLong = (k, v) => ['terms', 'privacy'].includes(k) || (typeof v === 'string' && v.length > 70) + +function FieldFor({ name, value, def, onChange }) { + if (Array.isArray(def)) { + return ( +
+ {human(name)} + {def.map((itemDef, i) => ( +
+

#{i + 1}

+
+ {Object.keys(itemDef).map((k) => ( + { + const next = def.map((d, j) => ({ ...d, ...(value?.[j] || {}) })) + next[i] = { ...next[i], [k]: v } + onChange(next) + }} + /> + ))} +
+
+ ))} +
+ ) + } + const numeric = typeof def === 'number' + const props = { + className: `${aInput} ${isLong(name, def) ? 'min-h-24' : ''}`, + value: value ?? '', + placeholder: typeof def === 'string' ? def : String(def ?? ''), + onChange: (e) => onChange(numeric ? (e.target.value === '' ? '' : Number(e.target.value)) : e.target.value), + } + return ( + + {isLong(name, def) ?