feat: complete CMS as fully autonomous self-contained module
Transform CMS from a thin wrapper into a fully self-contained module with all code living within app/modules/cms/: Module Structure: - models/: ContentPage model (canonical location with dynamic discovery) - schemas/: Pydantic schemas for API validation - services/: ContentPageService business logic - exceptions/: Module-specific exceptions - routes/api/: REST API endpoints (admin, vendor, shop) - routes/pages/: HTML page routes (admin, vendor) - templates/cms/: Jinja2 templates (namespaced) - static/: JavaScript files (admin/vendor) - locales/: i18n translations (en, fr, de, lb) Key Changes: - Move ContentPage model to module with dynamic model discovery - Create Pydantic schemas package for request/response validation - Extract API routes from app/api/v1/*/ to module - Extract page routes from admin_pages.py/vendor_pages.py to module - Move static JS files to module with dedicated mount point - Update templates to use cms_static for module assets - Add module static file mounting in main.py - Delete old scattered files (no shims - hard errors on old imports) This establishes the pattern for migrating other modules to be fully autonomous and independently deployable. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,5 +1,27 @@
|
||||
# models/database/__init__.py
|
||||
"""Database models package."""
|
||||
"""
|
||||
Database models package.
|
||||
|
||||
This package imports all SQLAlchemy models to ensure they are registered
|
||||
with Base.metadata. This includes:
|
||||
1. Core models (defined in this directory)
|
||||
2. Module models (discovered from app/modules/<module>/models/)
|
||||
|
||||
Module Model Discovery:
|
||||
- Modules can define their own models in app/modules/<module>/models/
|
||||
- These are automatically imported when this package loads
|
||||
- Module models must use `from app.core.database import Base`
|
||||
"""
|
||||
|
||||
import importlib
|
||||
import logging
|
||||
from pathlib import Path
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# ============================================================================
|
||||
# CORE MODELS (always loaded)
|
||||
# ============================================================================
|
||||
|
||||
from .admin import (
|
||||
AdminAuditLog,
|
||||
@@ -18,7 +40,6 @@ from .architecture_scan import (
|
||||
)
|
||||
from .base import Base
|
||||
from .company import Company
|
||||
from .content_page import ContentPage
|
||||
from .platform import Platform
|
||||
from .platform_module import PlatformModule
|
||||
from .vendor_platform import VendorPlatform
|
||||
@@ -82,6 +103,49 @@ from .vendor import Role, Vendor, VendorUser
|
||||
from .vendor_domain import VendorDomain
|
||||
from .vendor_theme import VendorTheme
|
||||
|
||||
# ============================================================================
|
||||
# MODULE MODELS (dynamically discovered)
|
||||
# ============================================================================
|
||||
|
||||
|
||||
def _discover_module_models():
|
||||
"""
|
||||
Discover and import models from app/modules/<module>/models/ directories.
|
||||
|
||||
This ensures module models are registered with Base.metadata for:
|
||||
1. Alembic migrations
|
||||
2. SQLAlchemy queries
|
||||
|
||||
Module models must:
|
||||
- Be in app/modules/<module>/models/__init__.py or individual files
|
||||
- Import Base from app.core.database
|
||||
"""
|
||||
modules_dir = Path(__file__).parent.parent.parent / "app" / "modules"
|
||||
|
||||
if not modules_dir.exists():
|
||||
return
|
||||
|
||||
for module_dir in sorted(modules_dir.iterdir()):
|
||||
if not module_dir.is_dir():
|
||||
continue
|
||||
|
||||
models_init = module_dir / "models" / "__init__.py"
|
||||
if models_init.exists():
|
||||
module_name = f"app.modules.{module_dir.name}.models"
|
||||
try:
|
||||
importlib.import_module(module_name)
|
||||
logger.debug(f"[Models] Loaded module models: {module_name}")
|
||||
except ImportError as e:
|
||||
logger.warning(f"[Models] Failed to import {module_name}: {e}")
|
||||
|
||||
|
||||
# Run discovery at import time
|
||||
_discover_module_models()
|
||||
|
||||
# ============================================================================
|
||||
# EXPORTS
|
||||
# ============================================================================
|
||||
|
||||
__all__ = [
|
||||
# Admin-specific models
|
||||
"AdminAuditLog",
|
||||
@@ -113,8 +177,6 @@ __all__ = [
|
||||
"Role",
|
||||
"VendorDomain",
|
||||
"VendorTheme",
|
||||
# Content
|
||||
"ContentPage",
|
||||
# Platform
|
||||
"Platform",
|
||||
"PlatformModule",
|
||||
|
||||
@@ -1,235 +0,0 @@
|
||||
# models/database/content_page.py
|
||||
"""
|
||||
Content Page Model
|
||||
|
||||
Manages static content pages (About, FAQ, Contact, Shipping, Returns, etc.)
|
||||
with a three-tier hierarchy:
|
||||
|
||||
1. Platform Marketing Pages (is_platform_page=True, vendor_id=NULL)
|
||||
- Homepage, pricing, platform about, contact
|
||||
- Describes the platform/business offering itself
|
||||
|
||||
2. Vendor Default Pages (is_platform_page=False, vendor_id=NULL)
|
||||
- Generic storefront pages that all vendors inherit
|
||||
- About Us, Shipping Policy, Return Policy, etc.
|
||||
|
||||
3. Vendor Override/Custom Pages (is_platform_page=False, vendor_id=set)
|
||||
- Vendor-specific customizations
|
||||
- Either overrides a default or is a completely custom page
|
||||
|
||||
Features:
|
||||
- Multi-platform support (each platform has its own pages)
|
||||
- Three-tier content resolution
|
||||
- Rich text content (HTML/Markdown)
|
||||
- SEO metadata
|
||||
- Published/Draft status
|
||||
- Navigation placement (header, footer, legal)
|
||||
|
||||
NOTE: This is the canonical location for the ContentPage model.
|
||||
The CMS module (app.modules.cms) re-exports this model.
|
||||
"""
|
||||
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from sqlalchemy import (
|
||||
JSON,
|
||||
Boolean,
|
||||
Column,
|
||||
DateTime,
|
||||
ForeignKey,
|
||||
Index,
|
||||
Integer,
|
||||
String,
|
||||
Text,
|
||||
UniqueConstraint,
|
||||
)
|
||||
from sqlalchemy.orm import relationship
|
||||
|
||||
from app.core.database import Base
|
||||
|
||||
|
||||
class ContentPage(Base):
|
||||
"""
|
||||
Content pages with three-tier hierarchy.
|
||||
|
||||
Page Types:
|
||||
1. Platform Marketing Page: platform_id=X, vendor_id=NULL, is_platform_page=True
|
||||
- Platform's own pages (homepage, pricing, about)
|
||||
2. Vendor Default Page: platform_id=X, vendor_id=NULL, is_platform_page=False
|
||||
- Fallback pages for vendors who haven't customized
|
||||
3. Vendor Override/Custom: platform_id=X, vendor_id=Y, is_platform_page=False
|
||||
- Vendor-specific content
|
||||
|
||||
Resolution Logic:
|
||||
1. Check for vendor override (platform_id + vendor_id + slug)
|
||||
2. Fall back to vendor default (platform_id + vendor_id=NULL + is_platform_page=False)
|
||||
3. If neither exists, return 404
|
||||
"""
|
||||
|
||||
__tablename__ = "content_pages"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
|
||||
# Platform association (REQUIRED - determines which platform this page belongs to)
|
||||
platform_id = Column(
|
||||
Integer,
|
||||
ForeignKey("platforms.id", ondelete="CASCADE"),
|
||||
nullable=False,
|
||||
index=True,
|
||||
comment="Platform this page belongs to",
|
||||
)
|
||||
|
||||
# Vendor association (NULL = platform page or vendor default)
|
||||
vendor_id = Column(
|
||||
Integer,
|
||||
ForeignKey("vendors.id", ondelete="CASCADE"),
|
||||
nullable=True,
|
||||
index=True,
|
||||
comment="Vendor this page belongs to (NULL for platform/default pages)",
|
||||
)
|
||||
|
||||
# Distinguish platform marketing pages from vendor defaults
|
||||
is_platform_page = Column(
|
||||
Boolean,
|
||||
default=False,
|
||||
nullable=False,
|
||||
comment="True = platform marketing page (homepage, pricing); False = vendor default or override",
|
||||
)
|
||||
|
||||
# Page identification
|
||||
slug = Column(
|
||||
String(100), nullable=False, index=True
|
||||
) # about, faq, contact, shipping, returns, etc.
|
||||
title = Column(String(200), nullable=False)
|
||||
|
||||
# Content
|
||||
content = Column(Text, nullable=False) # HTML or Markdown
|
||||
content_format = Column(String(20), default="html") # html, markdown
|
||||
|
||||
# Template selection (for landing pages)
|
||||
# Options: 'default', 'minimal', 'modern', 'full'
|
||||
# Only used for landing pages (slug='landing' or 'home')
|
||||
template = Column(String(50), default="default", nullable=False)
|
||||
|
||||
# Homepage sections (structured JSON for section-based editing)
|
||||
# Only used for homepage (slug='home'). Contains hero, features, pricing, cta sections
|
||||
# with multi-language support via TranslatableText pattern
|
||||
sections = Column(
|
||||
JSON,
|
||||
nullable=True,
|
||||
default=None,
|
||||
comment="Structured homepage sections (hero, features, pricing, cta) with i18n",
|
||||
)
|
||||
|
||||
# SEO
|
||||
meta_description = Column(String(300), nullable=True)
|
||||
meta_keywords = Column(String(300), nullable=True)
|
||||
|
||||
# Publishing
|
||||
is_published = Column(Boolean, default=False, nullable=False)
|
||||
published_at = Column(DateTime(timezone=True), nullable=True)
|
||||
|
||||
# Ordering (for menus, footers)
|
||||
display_order = Column(Integer, default=0, nullable=False)
|
||||
show_in_footer = Column(Boolean, default=True, nullable=False)
|
||||
show_in_header = Column(Boolean, default=False, nullable=False)
|
||||
show_in_legal = Column(Boolean, default=False, nullable=False) # Bottom bar with copyright
|
||||
|
||||
# Timestamps
|
||||
created_at = Column(
|
||||
DateTime(timezone=True),
|
||||
default=lambda: datetime.now(UTC),
|
||||
nullable=False,
|
||||
)
|
||||
updated_at = Column(
|
||||
DateTime(timezone=True),
|
||||
default=lambda: datetime.now(UTC),
|
||||
onupdate=lambda: datetime.now(UTC),
|
||||
nullable=False,
|
||||
)
|
||||
|
||||
# Author tracking (admin or vendor user who created/updated)
|
||||
created_by = Column(
|
||||
Integer, ForeignKey("users.id", ondelete="SET NULL"), nullable=True
|
||||
)
|
||||
updated_by = Column(
|
||||
Integer, ForeignKey("users.id", ondelete="SET NULL"), nullable=True
|
||||
)
|
||||
|
||||
# Relationships
|
||||
platform = relationship("Platform", back_populates="content_pages")
|
||||
vendor = relationship("Vendor", back_populates="content_pages")
|
||||
creator = relationship("User", foreign_keys=[created_by])
|
||||
updater = relationship("User", foreign_keys=[updated_by])
|
||||
|
||||
# Constraints
|
||||
__table_args__ = (
|
||||
# Unique combination: platform + vendor + slug
|
||||
# Platform pages: platform_id + vendor_id=NULL + is_platform_page=True
|
||||
# Vendor defaults: platform_id + vendor_id=NULL + is_platform_page=False
|
||||
# Vendor overrides: platform_id + vendor_id + slug
|
||||
UniqueConstraint("platform_id", "vendor_id", "slug", name="uq_platform_vendor_slug"),
|
||||
# Indexes for performance
|
||||
Index("idx_platform_vendor_published", "platform_id", "vendor_id", "is_published"),
|
||||
Index("idx_platform_slug_published", "platform_id", "slug", "is_published"),
|
||||
Index("idx_platform_page_type", "platform_id", "is_platform_page"),
|
||||
)
|
||||
|
||||
def __repr__(self):
|
||||
vendor_name = self.vendor.name if self.vendor else "PLATFORM"
|
||||
return f"<ContentPage(id={self.id}, vendor={vendor_name}, slug={self.slug}, title={self.title})>"
|
||||
|
||||
@property
|
||||
def is_vendor_default(self):
|
||||
"""Check if this is a vendor default page (fallback for all vendors)."""
|
||||
return self.vendor_id is None and not self.is_platform_page
|
||||
|
||||
@property
|
||||
def is_vendor_override(self):
|
||||
"""Check if this is a vendor-specific override or custom page."""
|
||||
return self.vendor_id is not None
|
||||
|
||||
@property
|
||||
def page_tier(self) -> str:
|
||||
"""Get the tier level of this page for display purposes."""
|
||||
if self.is_platform_page:
|
||||
return "platform"
|
||||
elif self.vendor_id is None:
|
||||
return "vendor_default"
|
||||
else:
|
||||
return "vendor_override"
|
||||
|
||||
def to_dict(self):
|
||||
"""Convert to dictionary for API responses."""
|
||||
return {
|
||||
"id": self.id,
|
||||
"platform_id": self.platform_id,
|
||||
"platform_code": self.platform.code if self.platform else None,
|
||||
"platform_name": self.platform.name if self.platform else None,
|
||||
"vendor_id": self.vendor_id,
|
||||
"vendor_name": self.vendor.name if self.vendor else None,
|
||||
"slug": self.slug,
|
||||
"title": self.title,
|
||||
"content": self.content,
|
||||
"content_format": self.content_format,
|
||||
"template": self.template,
|
||||
"sections": self.sections,
|
||||
"meta_description": self.meta_description,
|
||||
"meta_keywords": self.meta_keywords,
|
||||
"is_published": self.is_published,
|
||||
"published_at": (
|
||||
self.published_at.isoformat() if self.published_at else None
|
||||
),
|
||||
"display_order": self.display_order,
|
||||
"show_in_footer": self.show_in_footer or False,
|
||||
"show_in_header": self.show_in_header or False,
|
||||
"show_in_legal": self.show_in_legal or False,
|
||||
"is_platform_page": self.is_platform_page,
|
||||
"is_vendor_default": self.is_vendor_default,
|
||||
"is_vendor_override": self.is_vendor_override,
|
||||
"page_tier": self.page_tier,
|
||||
"created_at": self.created_at.isoformat() if self.created_at else None,
|
||||
"updated_at": self.updated_at.isoformat() if self.updated_at else None,
|
||||
"created_by": self.created_by,
|
||||
"updated_by": self.updated_by,
|
||||
}
|
||||
Reference in New Issue
Block a user