Commit Graph

489 Commits

Author SHA1 Message Date
915734e9b4 docs: add seed scripts audit and Makefile refactoring documentation
- Create comprehensive seed scripts audit document
  - Inventory of all seed/create scripts
  - Analysis of current vs intended workflow
  - Identification of duplicates and orphaned scripts
  - Refactoring recommendations

- Create Makefile refactoring completion document
  - Summary of architecture decisions
  - Before/after comparison
  - Updated workflows for production and development
  - Script classification (production, demo, utility, test)
  - New developer onboarding workflow
  - Production deployment workflow

Documentation provides clear guidance on:
- Which scripts to run in production vs development
- How init-prod differs from seed-demo
- When to use utility commands
- Proper setup workflow for new developers
2025-12-01 21:50:45 +01:00
c9c280a8c7 refactor: update seed script and Makefile for company architecture
Seed Script Updates:
- Add create_demo_companies() function to seed 3 demo companies with owners
- Update create_demo_vendors() to link vendors to companies (not create owners)
- Fix VendorTheme to use JSON colors format (not individual columns)
- Fix VendorDomain to use 'domain' field (not 'domain_name')
- Update seed summary to show company information
- Update credentials output to show company owners instead of vendor owners

Makefile Refactoring:
- Separate production initialization from demo data seeding
- Update init-prod to run 4 steps:
  1. Create admin user + alerts (init_production.py)
  2. Initialize log settings (init_log_settings.py)
  3. Create CMS defaults (create_default_content_pages.py)
  4. Create platform pages (create_platform_pages.py)
- Update db-setup workflow: migrate-up + init-prod + seed-demo
- Update db-reset workflow: migrate-down + migrate-up + init-prod + seed-demo-reset
- Add utility commands: create-cms-defaults, create-platform-pages, init-logging
- Enhance help documentation with clear production vs demo distinction

Architecture:
- init-prod: Production-safe platform initialization (run in prod + dev)
- seed-demo: Demo data only (NEVER run in production)
- Clear separation of concerns for production deployment
2025-12-01 21:50:36 +01:00
801510ecc6 feat: add complete company management UI
- Create companies list page with stats (total, verified, active, vendor count)
- Add company creation form with owner account generation
- Implement companies.js with full CRUD operations (list, create, edit, delete)
- Add Companies menu item to admin sidebar (desktop + mobile)
- Create company admin page routes (/admin/companies, /admin/companies/create)
- Register companies API router in admin __init__.py

Features:
- List all companies with pagination
- Create company with automatic owner user creation
- Display temporary password for new owner accounts
- Edit company information
- Delete company (only if no vendors)
- Toggle active/verified status
- Show vendor count per company

UI Components:
- Stats cards (total companies, verified, active, total vendors)
- Company table with status badges
- Create form with validation
- Success/error messaging
- Responsive design with dark mode support
2025-12-01 21:50:20 +01:00
4ca738dc7f feat: implement company-based ownership architecture
- Add database migration to make vendor.owner_user_id nullable
- Update Vendor model to support company-based ownership (DEPRECATED vendor.owner_user_id)
- Implement company_service with singleton pattern (consistent with vendor_service)
- Create Company model with proper relationships to vendors and users
- Add company exception classes for proper error handling
- Refactor companies API to use singleton service pattern

Architecture Change:
- OLD: Each vendor has its own owner (vendor.owner_user_id)
- NEW: Vendors belong to a company, company has one owner (company.owner_user_id)
- This allows one company owner to manage multiple vendor brands

Technical Details:
- Company service uses singleton pattern (not factory)
- Company service accepts db: Session as parameter (follows SVC-003)
- Uses AuthManager for password hashing (consistent with admin_service)
- Added _generate_temp_password() helper method
2025-12-01 21:50:09 +01:00
281181d7ea fix: add missing code quality violation detail template
Problem:
- Accessing /admin/code-quality/violations/{id} returned 500 error
- TemplateNotFound: 'admin/code-quality-violation-detail.html'
- Route existed but template file was missing

Solution:
Created complete violation detail template with:

Features:
- Displays violation details (severity, status, rule, file, line)
- Shows code context and suggestions
- Status management (open, assigned, resolved, ignored)
- Assignment to users
- Comment system for collaboration
- Alpine.js component for API integration
- Loading and error states
- Proper dark mode support

Template Structure:
- Extends admin/base.html
- Uses codeQualityViolationDetail(violationId) Alpine component
- Loads violation data via API on init
- Interactive status updates and comments
- Breadcrumb navigation back to violations list

API Endpoints Used:
- GET /api/v1/admin/code-quality/violations/{id}
- PATCH /api/v1/admin/code-quality/violations/{id}/status
- PATCH /api/v1/admin/code-quality/violations/{id}/assign
- POST /api/v1/admin/code-quality/violations/{id}/comments

Now violation detail page loads successfully.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-28 20:19:17 +01:00
c7c2c83007 fix: add missing last_scan field in code quality dashboard empty state
Problem:
- GET /api/v1/admin/code-quality/stats returned 500 error
- Pydantic validation error: "last_scan Field required"
- When no scan data exists, service returned dict without last_scan field
- DashboardStatsResponse model required last_scan field

Solution:
1. Added last_scan: None to empty state return dictionary
2. Made last_scan field explicitly optional with default value (= None)
3. Ensures field is always present in response

Changes:
- app/services/code_quality_service.py: Added "last_scan": None
- app/api/v1/admin/code_quality.py: Changed to last_scan: str | None = None

This fixes the 500 error when accessing /admin/code-quality page
with no architecture scan data in the database.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-28 20:15:07 +01:00
b8a46e1746 fix: protect critical re-export imports from linter removal
Problem:
- Ruff removed 'from app.core.database import Base' from models/database/base.py
- Import appeared "unused" (F401) but was actually a critical re-export
- Caused ImportError: cannot import name 'Base' at runtime
- Re-export pattern: import in one file to export from package

Solution:
1. Added F401 ignore for models/database/base.py in pyproject.toml
2. Created scripts/verify_critical_imports.py verification script
3. Integrated verification into make check and CI pipeline
4. Updated documentation with explanation

New Verification Script:
- Checks all critical re-export imports exist
- Detects import variations (parentheses, 'as' clauses)
- Handles SQLAlchemy declarative_base alternatives
- Runs as part of make check automatically

Protected Files:
- models/database/base.py - Re-exports Base for all models
- models/__init__.py - Exports Base for Alembic
- models/database/__init__.py - Exports Base from package
- All __init__.py files (already protected)

Makefile Changes:
- make verify-imports - Run import verification
- make check - Now includes verify-imports
- make ci - Includes verify-imports in pipeline

Documentation Updated:
- Code quality guide explains re-export protection
- Pre-commit workflow includes verification
- Examples of why re-exports matter

This prevents future issues where linters remove seemingly
"unused" imports that are actually critical for application structure.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-28 20:10:22 +01:00
4279c458c4 docs: add comprehensive architecture rules reference documentation
Created detailed documentation for all 51 architectural rules:

New Documentation:
- docs/development/architecture-rules.md (comprehensive reference)
- Added to mkdocs.yml navigation

Documentation Includes:
- Overview and usage instructions
- Severity level explanations
- All 51 rules organized by category:
  * Backend Rules (API, Service, Model, Exception)
  * Frontend Rules (JavaScript, Templates, Styling)
  * Naming Convention Rules
  * Security & Multi-Tenancy Rules
  * Code Quality Rules
  * Middleware Rules

For Each Rule:
- Rule ID and name
- Severity level
- Detailed description
- Good and bad code examples
- Anti-patterns detected
- File patterns affected

Additional Sections:
- Quick reference tables
- Pre-commit checklist
- Common violations and fixes
- Ignored patterns explanation
- Summary statistics (51 rules, 35 errors, 16 warnings)

This documentation complements:
- .architecture-rules.yaml (rule definitions)
- scripts/validate_architecture.py (enforcement)
- Code Quality guide
- Contributing guide

Documentation builds successfully with mkdocs.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-28 20:03:45 +01:00
63ad3f2441 feat: comprehensive architecture rules v2.0 with all enforcement patterns
Massively expanded architecture rules based on documentation analysis:

New Rule Categories Added:
- Naming Convention Rules (NAM-001 to NAM-005)
- JavaScript Rules (JS-001 to JS-007)
- Template Rules (TPL-001 to TPL-007)
- Styling Rules (CSS-001 to CSS-004)
- Middleware Rules (MDW-001 to MDW-002)
- Multi-Tenancy Rules (MT-001 to MT-002)
- Auth Rules (AUTH-001 to AUTH-003)
- Code Quality Rules (QUAL-001 to QUAL-003)

Enhanced Existing Rules:
- API rules now include multi-tenant scoping (API-005)
- Service rules include vendor scoping check (SVC-005)
- Model rules include from_attributes check (MDL-003)
- Exception rules include logging guidance (EXC-003)

Total Rules: 50+ comprehensive architectural patterns
- Backend: 20 rules
- Frontend JS: 7 rules
- Frontend Templates: 7 rules
- Frontend Styling: 4 rules
- Naming: 5 rules
- Quality: 3 rules
- Security: 5 rules

All rules documented with:
- File patterns
- Severity levels
- Good/bad examples
- Enforcement mechanisms

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-28 19:58:38 +01:00
1a5782f6c8 fix: correct malformed JS-001 validation logic
Fixed broken conditional logic in JavaScript validation that was causing
false positives on every single line of JS files.

Problem:
- Malformed ternary expression with 'if' inside condition
- 'else True' caused every line WITHOUT 'window.apiClient' to trigger
- Result: 3,144 violations (mostly false positives)

Solution:
- Simplified conditional to check if 'window.apiClient' exists first
- Then check if it's not in a comment
- Clearer, more maintainable logic

Results:
- Before: 3,144 total violations (3,000+ false JS-001 violations)
- After: 184 total violations (all legitimate)
- JS-001 violations: 0 (correct - no actual window.apiClient usage)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-28 19:50:46 +01:00
c0794295e2 fix: exclude venv and .venv from architecture validation
- Update .architecture-rules.yaml to ignore venv/.venv directories
- Improve _should_ignore_file() method to handle venv path exclusions
- Add explicit checks for .venv/ and venv/ in file paths

This prevents the architecture validator from scanning thousands of
files in virtual environment directories, reducing validation time
from scanning all dependency files to just project files.

Before: Scanned venv files (thousands of violations in dependencies)
After: Only scans project files (123 files checked)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-28 19:47:57 +01:00
cde4e8eefc docs: add comprehensive code quality and contributing documentation
- Add detailed Code Quality guide covering Ruff, mypy, and pytest
- Add Contributing Guide with workflow, standards, and best practices
- Update mkdocs.yml navigation to include new documentation
- Successfully build documentation without errors

New Documentation:
- docs/development/code-quality.md - Complete guide to code quality tools
- docs/development/contributing.md - Contributing guidelines and workflow
- Added Code Quality Dashboard implementation to navigation

Documentation includes:
- Ruff usage and configuration
- mypy type checking
- pytest testing guidelines
- Makefile command reference
- Pre-commit workflow
- IDE integration instructions
- Migration guide from old tools
- Best practices and common issues

Documentation builds cleanly with mkdocs build.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-28 19:43:08 +01:00
238c1ec9b8 refactor: modernize code quality tooling with Ruff
- Replace black, isort, and flake8 with Ruff (all-in-one linter and formatter)
- Add comprehensive pyproject.toml configuration
- Simplify Makefile code quality targets
- Configure exclusions for venv/.venv in pyproject.toml
- Auto-fix 1,359 linting issues across codebase

Benefits:
- Much faster builds (Ruff is written in Rust)
- Single tool replaces multiple tools
- More comprehensive rule set (UP, B, C4, SIM, PIE, RET, Q)
- All configuration centralized in pyproject.toml
- Better import sorting and formatting consistency

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-28 19:37:38 +01:00
21c13ca39b style: apply black and isort formatting across entire codebase
- Standardize quote style (single to double quotes)
- Reorder and group imports alphabetically
- Fix line breaks and indentation for consistency
- Apply PEP 8 formatting standards

Also updated Makefile to exclude both venv and .venv from code quality checks.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-28 19:30:17 +01:00
13f0094743 fix: resolve JavaScript errors in code quality dashboard
Fix multiple JavaScript errors on code quality dashboard pages:

Issues Fixed:
1. ReferenceError: getAccessToken is not defined
   - Changed to use apiClient.get() and apiClient.post() from api-client.js
   - Properly uses existing authentication infrastructure

2. ReferenceError: dark/isSideMenuOpen/currentPage is not defined
   - Extended base data() function using spread operator
   - Inherits all base Alpine.js state from init-alpine.js

3. RegExp validation error
   - Not directly addressed but likely resolved by proper Alpine initialization

Changes:
- static/admin/js/code-quality-dashboard.js:
  * Spread ...data() to inherit base Alpine.js state
  * Set currentPage: 'code-quality' for navigation highlighting
  * Use apiClient.get('/admin/code-quality/stats') for API calls
  * Use apiClient.post('/admin/code-quality/scan') for scan triggers
  * Simplified error handling with apiClient error messages

- static/admin/js/code-quality-violations.js:
  * Spread ...data() to inherit base Alpine.js state
  * Set currentPage: 'code-quality' for navigation highlighting
  * Use apiClient.get('/admin/code-quality/violations', params) for API calls
  * Simplified query parameter building using object instead of URLSearchParams

Testing:
- Dashboard should now load without JavaScript errors
- API calls should work with proper authentication
- Dark mode toggle and sidebar menu should function correctly
- Navigation highlighting should work properly

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-28 10:31:23 +01:00
9db0da25ec feat: implement code quality dashboard with architecture violation tracking
Implement comprehensive code quality dashboard (Phase 2-4) to track and manage
architecture violations found by the validation script.

Backend Implementation:
- Add JSON output support to validate_architecture.py script
- Create CodeQualityService with scan management, violation tracking, and statistics
- Implement REST API endpoints for code quality management:
  * POST /admin/code-quality/scan - trigger new architecture scan
  * GET /admin/code-quality/scans - list scan history
  * GET /admin/code-quality/violations - list violations with filtering/pagination
  * GET /admin/code-quality/violations/{id} - get violation details
  * POST /admin/code-quality/violations/{id}/assign - assign to developer
  * POST /admin/code-quality/violations/{id}/resolve - mark as resolved
  * POST /admin/code-quality/violations/{id}/ignore - mark as ignored
  * POST /admin/code-quality/violations/{id}/comments - add comments
  * GET /admin/code-quality/stats - dashboard statistics
- Fix architecture_scan model imports to use app.core.database

Frontend Implementation:
- Create code quality dashboard page (code-quality-dashboard.html)
  * Summary cards for total violations, errors, warnings, health score
  * Status breakdown (open, assigned, resolved, ignored)
  * Trend visualization for last 7 scans
  * Top violating files list
  * Violations by rule and module
  * Quick action links
- Create violations list page (code-quality-violations.html)
  * Filterable table by severity, status, rule ID, file path
  * Pagination support
  * Violation detail view links
- Add Alpine.js components (code-quality-dashboard.js, code-quality-violations.js)
  * Dashboard state management and scan triggering
  * Violations list with filtering and pagination
  * API integration with authentication
- Add "Code Quality" navigation link in admin sidebar (Developer Tools section)

Routes:
- GET /admin/code-quality - dashboard page
- GET /admin/code-quality/violations - violations list
- GET /admin/code-quality/violations/{id} - violation details

Features:
- Real-time scan execution from UI
- Technical debt score calculation (0-100 scale)
- Violation workflow: open → assigned → resolved/ignored
- Trend tracking across multiple scans
- File and module-level insights
- Assignment system with priorities and due dates
- Collaborative comments on violations

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-28 09:40:14 +01:00
74bf2367f8 docs: add comprehensive implementation plan for code quality dashboard
Created detailed implementation guide for remaining phases (2-4):

Phase 2 - Service Layer:
- CodeQualityService class specification
- Scan management methods
- Violation CRUD operations
- Statistics and metrics calculation
- Integration with validator script

Phase 3 - API Endpoints:
- REST API specification for code quality
- Pydantic request/response models
- Endpoint documentation (/admin/code-quality/*)

Phase 4 - Frontend:
- Dashboard layout and components
- Alpine.js component structure
- Violations table with filtering
- Charts and visualizations
- Navigation integration

Implementation Details:
- Database schema documentation
- JSON output format for validator
- Testing checklist
- Priority order for next session
- Time estimates (3-4 hours)

Additional Features:
- Background job support considerations
- Email notifications
- GitHub/GitLab PR integration
- Historical trend analysis

This document serves as a complete blueprint for completing
the code quality dashboard in the next development session.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-28 09:26:20 +01:00
a44f776206 feat: add database foundation for code quality dashboard (Phase 1/4)
Implemented database models and migration for tracking architecture violations
in the admin dashboard. This is the foundation for the code quality UI.

Database Models Added (app/models/architecture_scan.py):
- ArchitectureScan: Tracks validator runs with statistics
- ArchitectureViolation: Individual violations with status tracking
- ArchitectureRule: Rule configuration with enable/disable support
- ViolationAssignment: Assign violations to developers
- ViolationComment: Collaboration on violations

Schema Features:
- Full violation history tracking
- Status workflow (open → assigned → resolved/ignored/technical_debt)
- Assignment and due date tracking
- Comments for collaboration
- Rule management (enable/disable, severity override)
- Scan statistics (errors, warnings, duration)

Migration:
- Created 5 tables with proper indexes and foreign keys
- SQLite-compatible datetime defaults
- Supports relationships between scans, violations, users

Next Steps (Remaining Phases):
- Phase 2: Service layer (code_quality_service.py)
- Phase 3: API endpoints (/admin/code-quality/*)
- Phase 4: Frontend dashboard and UI

Benefits:
- Track technical debt over time
- Assign violations to developers
- Prioritize fixes by severity
- Measure code quality improvements
- Collaborative violation resolution

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-28 09:24:49 +01:00
3c7af0ccdf refactor: standardize markdown file naming to kebab-case convention
Renamed all documentation files to follow kebab-case naming standard:
- UPPERCASE files → lowercase (e.g., RBAC.md → rbac.md)
- snake_case files → kebab-case (e.g., icons_guide.md → icons-guide.md)
- SCREAMING_SNAKE_CASE → kebab-case (e.g., DATABASE_SETUP_GUIDE.md → database-setup-guide.md)

Files renamed (15 total):
API Documentation:
  - api/RBAC.md → api/rbac.md

Architecture:
  - architecture/API_CONSOLIDATION_PROPOSAL.md → api-consolidation-proposal.md
  - architecture/API_MIGRATION_STATUS.md → api-migration-status.md

Development:
  - development/AUTH_DEPENDENCIES_GUIDE.md → auth-dependencies-guide.md
  - development/CUSTOMER_AUTHENTICATION_IMPLEMENTATION.md → customer-authentication-implementation.md
  - development/CUSTOMER_AUTH_SUMMARY.md → customer-auth-summary.md
  - development/icons_guide.md → icons-guide.md

Database Seeder:
  - database-seeder/DATABASE_INIT_GUIDE.md → database-init-guide.md
  - database-seeder/DATABASE_QUICK_REFERENCE_GUIDE.md → database-quick-reference-guide.md
  - database-seeder/DATABASE_SEEDER_DOCUMENTATION.md → database-seeder-documentation.md
  - database-seeder/MAKEFILE_DATABASE_SEEDER.md → makefile-database-seeder.md

Error Rendering:
  - error-rendering/ERROR_RENDERING_DEVELOPER_DOCUMENTATION.md → error-rendering-developer-documentation.md
  - error-rendering/HTML_ERROR_RENDERING_FLOW_DIAGRAM.md → html-error-rendering-flow-diagram.md

Getting Started:
  - getting-started/DATABASE_QUICK_REFERENCE.md → database-quick-reference.md
  - getting-started/DATABASE_SETUP_GUIDE.md → database-setup-guide.md

Updates:
- Updated all references in mkdocs.yml
- Updated all cross-references in markdown files
- Verified mkdocs builds without warnings or errors

Standard: Use kebab-case (lowercase-with-hyphens) for all markdown files

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-28 07:58:33 +01:00
1e720ae0e5 feat: add architecture validation system with comprehensive pattern enforcement
Implemented automated architecture validation to enforce design decisions:

Architecture Validation System:
- Created .architecture-rules.yaml with comprehensive rule definitions
- Implemented validate_architecture.py script with AST-based validation
- Added pre-commit hook configuration for automatic validation
- Comprehensive documentation in docs/architecture/architecture-patterns.md

Key Design Rules Enforced:
- API-001 to API-004: API endpoint patterns (Pydantic models, no business logic, exception handling, auth)
- SVC-001 to SVC-004: Service layer patterns (domain exceptions, db session params, no HTTP concerns)
- MDL-001 to MDL-002: Model separation (SQLAlchemy vs Pydantic)
- EXC-001 to EXC-002: Exception handling (custom exceptions, no bare except)
- JS-001 to JS-003: JavaScript patterns (apiClient, logger, Alpine components)
- TPL-001: Template patterns (extend base.html)

Features:
- Validates separation of concerns (routes vs services vs models)
- Enforces proper exception handling (domain exceptions in services, HTTP in routes)
- Checks database session patterns and Pydantic model usage
- JavaScript and template validation
- Detailed error reporting with suggestions
- Integration with pre-commit hooks and CI/CD

UI Fix:
- Fixed icon names in content-pages.html (pencil→edit, trash→delete)

Documentation:
- Added architecture patterns guide with examples
- Created scripts/README.md for validator usage
- Updated mkdocs.yml with architecture documentation
- Built and verified documentation successfully

Usage:
  python scripts/validate_architecture.py              # Validate all
  python scripts/validate_architecture.py --verbose    # With details
  python scripts/validate_architecture.py --errors-only # Errors only

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-28 07:44:51 +01:00
83a6831b2e feat: add platform homepage and content management system with improved UI
Implemented a comprehensive CMS for managing platform homepage and content pages:

- Platform homepage manager with template selection (default, minimal, modern)
- Content pages CRUD with platform defaults and vendor overrides
- Sidebar navigation for Content Management section
- Dedicated API endpoints for creating, updating, deleting pages
- Template support for customizable homepage layouts
- Header/footer navigation integration for content pages
- Comprehensive documentation for platform homepage setup
- Migration script for creating initial platform pages

UI improvements:
- Fixed action buttons styling in content pages table to match design system
- Added proper hover states, rounded corners, and better contrast
- Increased button size and padding for better usability

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-28 07:17:30 +01:00
9f8ad71d85 feat: add local Inter font fallback for offline support
Add self-hosted Inter font files to ensure application works offline
and reduce dependency on external CDN (Google Fonts).

Problem:
- Google Fonts (fonts.googleapis.com) fails when no internet connection
- Application shows NS_ERROR_UNKNOWN_HOST errors
- Font rendering falls back to system fonts, breaking design consistency

Solution:
- Download Inter font files (weights 400, 500, 600, 700, 800) from Google Fonts
- Host locally in static/shared/fonts/inter/
- Create inter.css with @font-face declarations
- Update all templates to load local fonts FIRST, then Google Fonts as fallback

Files Added:
- static/shared/fonts/inter.css (font-face declarations)
- static/shared/fonts/inter/inter-400.ttf (318KB - Regular)
- static/shared/fonts/inter/inter-500.ttf (318KB - Medium)
- static/shared/fonts/inter/inter-600.ttf (319KB - Semi-bold)
- static/shared/fonts/inter/inter-700.ttf (319KB - Bold)
- static/shared/fonts/inter/inter-800.ttf (320KB - Extra-bold)

Templates Updated (7 files):
- app/templates/admin/base.html
- app/templates/admin/login.html
- app/templates/vendor/base.html
- app/templates/vendor/login.html
- app/templates/shop/account/login.html
- app/templates/shop/account/register.html
- app/templates/shop/account/forgot-password.html

Font Loading Strategy:
1. Load local fonts first (always available, fast)
2. Load Google Fonts second (better quality when online)
3. Browser uses first available source

Example change:
  Before:
    <link href="https://fonts.googleapis.com/css2?family=Inter..." />

  After:
    <link href="/static/shared/fonts/inter.css" rel="stylesheet" />
    <link href="https://fonts.googleapis.com/css2?family=Inter..." />

Benefits:
-  Works offline without font loading errors
-  Faster initial load (local fonts, no DNS lookup)
-  Reduced external dependencies
-  Consistent typography even when CDN is down
-  Still uses Google Fonts when available (higher quality)
-  Total size: ~1.6MB (reasonable for 5 font weights)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-25 21:27:27 +01:00
05fa3647e5 fix: correct base_url calculation in error renderer for path-based routing
Fix error page links not respecting vendor context in path-based routing
by aligning with the pattern used throughout the codebase.

Problem:
- Error pages showed links like /shop/ instead of /vendors/wizamart/shop/
- error_renderer.py was checking request.state.access_method (never set)
- This meant access_method was always None, so base_url defaulted to "/"
- Links ignored vendor context and broke multi-access routing

Root Cause:
- Inconsistent pattern: error_renderer.py used wrong attribute
- Rest of codebase (6 locations) correctly uses vendor_context.get('detection_method')
- No code ever sets request.state.access_method anywhere

Solution:
- Change from: access_method = getattr(request.state, "access_method", None)
- Change to: access_method = vendor_context.get('detection_method', 'unknown')
- Aligns with pattern used in:
  * app/exceptions/handler.py:384 (login redirect)
  * main.py:336 (root redirect)
  * app/routes/shop_pages.py:85, 391 (shop pages)
  * app/api/v1/shop/auth.py:159, 223 (auth endpoints)

Changes:
- Line 263-264: Get vendor_context first, then extract detection_method from it
- Line 266: Now correctly detects path-based access method
- base_url now properly set to /vendors/wizamart/ for path-based routing

Impact:
-  Path-based routing: /vendors/wizamart/shop123 → links to /vendors/wizamart/shop/
-  Direct shop access: /shop/test → links to /shop/ (unchanged)
-  No breaking changes (access_method was never used before)
-  Consistent with entire codebase pattern

Testing:
- curl http://localhost:8000/vendors/wizamart/shop123
  Before: href="/shop/" (wrong)
  After: href="/vendors/wizamart/shop/" (correct)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-25 21:22:28 +01:00
803776ee6e fix: correct navigation links in shop error pages for multi-access routing
Fix broken links in shop error pages that were not respecting the base_url
for multi-access routing (domain, subdomain, and path-based vendor access).

Problem:
- Links used `{{ base_url or '/' }}` pattern which incorrectly fell back to '/'
- This broke navigation when accessing via path-based routing (e.g., /vendor/vendor1/)
- Links like "Continue Shopping" and "View All Products" went to wrong URLs

Solution:
- Remove `or '/'` fallback since base_url is always provided by error_renderer.py
- Add proper path prefixes (shop/, shop/products, shop/account/login, etc.)
- Ensure all links use `{{ base_url }}shop/...` pattern

Files Updated (10 templates):
- base.html: Fixed default action buttons and contact links
- 404.html: Fixed "Continue Shopping" and "View All Products" links
- 401.html: Fixed login and register links to use shop/account/* paths
- 403.html: Fixed login and home links
- 400.html: Fixed home and contact links
- 422.html: Fixed home and contact links
- 429.html: Fixed home and contact links
- 500.html: Fixed home and contact links
- 502.html: Fixed home and contact links
- generic.html: Fixed home and contact links

Example fix:
  Before: href="{{ base_url or '/' }}shop/products"
  After:  href="{{ base_url }}shop/products"

  Result for path-based access (/vendor/vendor1/):
  Before: /shop/products (wrong - ignores vendor context)
  After:  /vendor/vendor1/shop/products (correct)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-25 21:14:50 +01:00
86d67b5cfb feat: add customer authentication pages and documentation
Add complete customer authentication UI with login, registration,
forgot password, and dashboard pages.

Templates Added:
- app/templates/shop/account/login.html
  - Two-column layout with vendor branding
  - Email/password login with validation
  - Password visibility toggle
  - "Remember me" functionality
  - Error/success alerts
  - Loading states with spinner
- app/templates/shop/account/register.html
  - Customer registration form
  - Client-side validation (password strength, email format)
  - Marketing consent checkbox
  - Confirm password matching
- app/templates/shop/account/forgot-password.html
  - Password reset request page
  - Email validation
  - Success confirmation
- app/templates/shop/account/dashboard.html
  - Customer account dashboard
  - Overview of orders, profile, addresses

Styles Added:
- static/shared/css/auth.css
  - Authentication page styling
  - Two-column layout system
  - Form components and validation states
  - Theme-aware with CSS variables
  - Dark mode support
  - Mobile responsive
- static/shared/css/base.css updates
  - Enhanced utility classes
  - Additional form styles
  - Improved button states

Documentation Added:
- docs/frontend/shop/authentication-pages.md
  - Comprehensive guide to auth page implementation
  - Component architecture
  - API integration patterns
  - Theme customization
- docs/development/CUSTOMER_AUTHENTICATION_IMPLEMENTATION.md
  - Implementation details and technical decisions
  - Security considerations
  - Testing procedures
- docs/development/CUSTOMER_AUTH_SUMMARY.md
  - Quick reference guide
  - Endpoints and flows
- Updated docs/frontend/shop/architecture.md
  - Added authentication section
  - Documented all auth pages
- Updated docs/frontend/shop/page-templates.md
  - Added auth template documentation
- Updated mkdocs.yml
  - Added new documentation pages to navigation

Features:
- Full theme integration with vendor branding
- Alpine.js reactive components
- Tailwind CSS utility-first styling
- Client and server-side validation
- JWT token management
- Multi-access routing support (domain/subdomain/path)
- Error handling with user-friendly messages
- Loading states and animations
- Mobile responsive design
- Dark mode support

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-25 21:09:27 +01:00
6735d99df2 feat: implement customer authentication with JWT tokens
Implement secure customer authentication system with dedicated JWT tokens,
separate from admin/vendor authentication.

Backend Changes:
- Add customer JWT token support in deps.py
  - New get_current_customer_from_cookie_or_header dependency
  - Validates customer-specific tokens with type checking
  - Returns Customer object instead of User for shop routes
- Extend AuthService with customer token support
  - Add verify_password() method
  - Add create_access_token_with_data() for custom token payloads
- Update CustomerService authentication
  - Generate customer-specific JWT tokens with type="customer"
  - Use vendor-scoped customer lookup
- Enhance exception handler
  - Sanitize validation errors to prevent password leaks in logs
  - Fix shop login redirect to support multi-access routing
- Improve vendor context detection from Referer header
  - Consistent "path" detection method for cookie path logic

Schema Changes:
- Rename UserLogin.username to email_or_username for flexibility
- Update field validators accordingly

API Changes:
- Update admin/vendor auth endpoints to use email_or_username
- Customer auth already uses email field correctly

Route Changes:
- Update shop account routes to use Customer dependency
- Add /account redirect (without trailing slash)
- Change parameter names from current_user to current_customer

Frontend Changes:
- Update login forms to use email_or_username in API calls
- Change button text from "Log in" to "Sign in" for consistency
- Improve loading spinner layout with flexbox

Security Improvements:
- Customer tokens scoped to vendor_id
- Token type validation prevents cross-context token usage
- Password inputs redacted from validation error logs

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-25 21:08:49 +01:00
1f2ccb4668 refactor: move fallback error templates to shared directory with improved naming
Reorganize error template structure to consolidate shared templates in a dedicated location.

Changes:
- Move templates/fallback/* to templates/shared/ with -fallback suffix
  - 404.html → 404-fallback.html
  - 500.html → 500-fallback.html
  - generic.html → generic-fallback.html
- Update error_renderer.py to use new template paths
  - Modified template selection logic in _find_template()
  - Updated documentation strings to reflect new paths
- Update error rendering documentation
  - HTML_ERROR_RENDERING_FLOW_DIAGRAM.md: Updated diagrams and examples
  - ERROR_RENDERING_DEVELOPER_DOCUMENTATION.md: Updated file structure and paths

Benefits:
- Clearer organization with all shared templates in shared/ directory
- Consistent naming convention (-fallback suffix) indicates purpose
- Aligns with existing cdn-fallback.html in same directory

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-25 21:06:16 +01:00
5fd68ce6bd fix: resolve cart functionality issues with product name and frontend integration
Fixed two critical issues preventing cart from working:

1. Product Name Attribute Error:
   - Product model doesn't have 'name' attribute directly
   - Product name comes from marketplace_product.title relationship
   - Updated all references in cart_service.py:
     * get_cart() - product display in cart
     * add_to_cart() - logging and exception messages
     * update_cart_item() - exception messages
   - Also updated image_url to use marketplace_product.image_link

2. Products Page Not Calling API:
   - products.html had stub addToCart() with TODO comment
   - Implemented actual API call:
     * POST to /api/v1/shop/cart/{sessionId}/items
     * Sends product_id and quantity
     * Updates cartCount on success
     * Shows error toast on failure
     * Proper error handling with try/catch

Testing Results:
- API endpoint now works correctly (tested with curl)
- Cart items are properly saved to database
- Product names display correctly from marketplace_product relationship
- Frontend can successfully add items to cart

Related Models:
- Product has relationship to MarketplaceProduct
- Product.marketplace_product.title contains the product name
- Product.marketplace_product.image_link contains the image URL

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-23 20:38:27 +01:00
e619776054 docs: update documentation for cart implementation
Updated API reference, error handling, and architecture docs to reflect
the new persistent cart system with database storage.

API Reference Updates (shop-api-reference.md):
- Updated last modified date to 2025-11-23
- Updated cart response schemas to match CartResponse/CartItemResponse models
- Added detailed schema tables for all cart endpoints
- Documented all cart exceptions with examples (CART_ITEM_NOT_FOUND, INSUFFICIENT_INVENTORY_FOR_CART, etc.)
- Added implementation notes about cart persistence and duplicate prevention
- Updated all endpoint documentation with proper request/response schemas
- Added CartOperationResponse and ClearCartResponse documentation

Error Handling Updates (error-handling.md):
- Added Shopping Cart Exceptions section with 6 cart-specific exceptions
- Added Product Exceptions section
- Added Inventory Exceptions section
- Updated error response format to show structured WizamartException format
- Added examples with error_code, message, status_code, and details fields
- Documented the difference between structured and generic error formats

Architecture Updates (overview.md):
- Added cart_items table to database schema diagram
- Documented session-based shopping cart in data model hierarchy

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-23 20:27:50 +01:00
756e12fe7b removing references to letzshop, replacing by wizamart 2025-11-23 20:19:00 +01:00
c100d839f1 feat: implement persistent cart with database storage and proper exception handling
Implemented a complete shopping cart system with database persistence,
replacing the previous stub implementation. The cart now properly stores
items across sessions and follows the project's architecture patterns.

Database Changes:
- Add cart_items table with vendor_id, session_id, product_id, quantity, price_at_add
- Create unique constraint to prevent duplicate items per session
- Add indexes for session lookups and old cart cleanup
- Run migration a2064e1dfcd4 to create cart_items table

New Models & Schemas:
- models/database/cart.py: CartItem SQLAlchemy model with relationships
- models/schema/cart.py: Pydantic schemas for requests/responses
  * AddToCartRequest, UpdateCartItemRequest
  * CartResponse, CartItemResponse, CartOperationResponse, ClearCartResponse

Exception Handling:
- app/exceptions/cart.py: Cart-specific exceptions following project patterns
  * CartItemNotFoundException - item not found in cart
  * InsufficientInventoryForCartException - not enough inventory for cart operation
  * InvalidCartQuantityException - invalid quantity validation
  * CartValidationException - general cart validation
  * EmptyCartException - operations on empty cart
  * ProductNotAvailableForCartException - product unavailable
- Updated app/exceptions/__init__.py to export cart exceptions

Service Layer:
- Implement cart_service.get_cart() - fetch cart from database with totals
- Implement cart_service.add_to_cart() - create or update cart items with inventory checks
- Implement cart_service.update_cart_item() - update quantity with validation
- Implement cart_service.remove_from_cart() - delete cart item
- Implement cart_service.clear_cart() - remove all items for session
- Replace generic exceptions with cart-specific ones
- Fix InsufficientInventoryException usage (was using wrong parameters)

API Layer:
- Update app/api/v1/shop/cart.py to use Pydantic schemas
- Add response_model declarations to all endpoints
- Add return type hints for type safety
- Convert service dict responses to Pydantic models

Features:
- Cart items persist in database across server restarts
- Inventory validation before adding/updating items
- Price captured at time of adding to cart
- Duplicate items update quantity instead of creating new entries
- Full CRUD operations with proper error handling
- Type-safe API with auto-generated OpenAPI documentation

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-23 20:17:16 +01:00
cf2aa2c5af fix: add new documentation pages to mkdocs navigation
Added three new documentation pages to mkdocs.yml navigation:

- Features → Vendor Landing Pages (features/vendor-landing-pages.md)
- Frontend Development → Shop Frontend → Navigation Flow (frontend/shop/navigation-flow.md)
- Troubleshooting → Shop Frontend (troubleshooting/shop-frontend.md)

This fixes the MkDocs build warnings about orphaned pages not in navigation.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-23 09:42:00 +01:00
71b0202876 docs: add comprehensive changelog for November 23, 2025 work
Detailed changelog documenting all work completed today:

- Landing page system implementation (4 templates)
- Shop template refactoring (product, cart pages)
- Cart functionality fixes (inventory, session management)
- Routing and navigation improvements
- Placeholder image system
- Documentation updates
- Scripts created (inventory, landing pages)

Includes:
- Feature descriptions
- Problem/solution pairs
- Code examples
- Files changed
- Testing verification
- Next steps

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-23 09:40:44 +01:00
f217defd60 docs: comprehensive updates for today's shop frontend improvements
Updated documentation to cover all work completed today:

## Database Setup (docs/getting-started/database-setup.md)
- Added data seeding section with all three scripts
- Documented inventory creation requirement
- Added complete setup workflow
- Included common issues and solutions
- Added database reset instructions

## New Troubleshooting Guide (docs/troubleshooting/shop-frontend.md)
Comprehensive troubleshooting for:

### Cart and Product Issues
- Products cannot be added to cart (inventory = 0)
- Cart is empty after adding products (session ID issue)
- Root causes and solutions with code examples

### Styling and Layout Issues
- Pages with no styling (not extending base template)
- Images not loading (placeholder SVG implementation)
- Detailed before/after examples

### Navigation and Routing Issues
- Product detail 404 (duplicate /shop prefix)
- Missing /shop/ in links
- Breadcrumb navigation patterns

### Landing Page Issues
- Vendor root 404 (no landing page)
- Breadcrumb home link configuration
- Auto-redirect behavior

### Alpine.js Issues
- Component data not available (parent init not called)
- Product ID undefined (window globals solution)
- Debugging tips and console commands

All issues encountered today are now documented with:
- Clear symptoms
- Root cause explanation
- How the system works
- Step-by-step solutions
- Code examples
- Verification steps

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-23 09:39:27 +01:00
3d585e563f feat: add script to create inventory entries for products
Created script to populate inventory table for products that have 0 inventory.

Issue:
- Products had 0 available_inventory because inventory table was empty
- available_inventory is calculated from inventory_entries relationship
- Empty inventory table = 0 inventory for all products
- Add to cart fails when inventory is 0

Solution:
- Create inventory entries for all products
- Each product gets 100 units in 'Main Warehouse'
- Script can be run multiple times (only creates missing entries)

Usage:
  python scripts/create_inventory.py

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-23 09:36:00 +01:00
b4e52f5a13 feat: add detailed logging to add to cart functionality for debugging
Added comprehensive console logging to track:
- Cart eligibility checks
- API request URL and payload
- Response status and data
- Error details

This will help identify why items aren't being added to cart.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-23 09:31:35 +01:00
4c69a94f14 fix: properly call parent init in cart and product components
Issue:
- sessionId was undefined when cart/product pages loaded
- Parent shopLayoutData init() was being overridden, not called
- Session ID setup in parent wasn't running

Solution:
- Store reference to baseData before spreading
- Explicitly call baseData.init() in child component init
- This ensures sessionId is initialized before cart/product logic runs
- Add session ID logging for debugging

Now the session ID is properly initialized and cart functionality works.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-23 09:28:15 +01:00
84c6c38a50 fix: add sessionId to shopLayoutData for cart functionality
Issue:
- Cart was empty after adding products
- Product and cart pages reference this.sessionId but it wasn't defined
- Session ID was being created separately in each page component

Solution:
- Add sessionId property to shopLayoutData base component
- Add getOrCreateSessionId() method to manage session across all pages
- Initialize sessionId in init() so it's available to all child components
- Session ID stored in localStorage as 'cart_session_id'

Now the cart session is shared across all shop pages and cart items
persist correctly.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-23 09:25:27 +01:00
651e58ac6d fix: refactor cart page to extend base template and fix styling
Issue:
- Cart page was standalone HTML without proper styling
- Referenced non-existent CSS files (/static/css/shared/base.css, /static/css/vendor/vendor.css)
- Missing header, footer, and navigation
- Not integrated with shop layout system

Changes:
- Extend shop/base.html for consistent styling and layout
- Remove hardcoded CSS references (now inherited from base)
- Add proper breadcrumbs with landing page navigation
- Integrate with shopLayoutData() for cart and toast functionality
- Use Tailwind classes consistent with other shop pages
- Add @error handler for broken product images
- Update all URLs to use {{ base_url }} for multi-tenant support
- Modernize layout with responsive grid system

The cart page now has proper styling, navigation, and integrates
seamlessly with the rest of the shop frontend.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-23 09:23:44 +01:00
8c9190b054 feat: add automatic fallback to placeholder for broken product images
Issue:
- Product images in database have fake URLs (wizamart.example.com) that don't exist
- Browser shows broken image icons instead of placeholder

Solution:
- Add @error handler to all product images to fallback to placeholder.svg
- When any image fails to load, automatically switch to placeholder
- Applies to: product detail page, products list, related products

Now all broken/invalid image URLs will automatically show the placeholder
instead of broken image icons.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-23 09:19:36 +01:00
6fa9ccb552 fix: use proper SVG placeholder image across all shop templates
Issues fixed:
- placeholder.jpg contained SVG content but browsers won't render SVG in .jpg files
- Multiple templates referenced wrong placeholder paths

Changes:
- Rename placeholder.jpg to placeholder.svg with proper SVG file
- Update product.html to use /static/shop/img/placeholder.svg
- Update products.html to use /static/shop/img/placeholder.svg
- Update cart.html to use /static/shop/img/placeholder.svg (was /static/images/)

All shop pages now correctly display placeholder images when products
have no image_link set.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-23 06:30:23 +01:00
e94b3f9dca fix: resolve product detail page data access and add placeholder image
Issues fixed:
- Product ID was undefined - Alpine.js couldn't access data-product-id from nested div
- Missing placeholder image caused 404 errors

Changes:
- Pass product_id and vendor.id through window globals instead of dataset
- Initialize productId and vendorId directly from window variables
- Add placeholder.jpg SVG for products without images
- Add debug logging to track initialization

The product detail page now correctly loads products and handles missing images.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-23 06:26:51 +01:00
1df4f12e92 fix: refactor product detail page to extend base template and use correct paths
Issues resolved:
- Product detail page was standalone HTML without proper styling
- Referenced non-existent CSS files (/static/css/shared/base.css, /static/css/vendor/vendor.css)
- Used wrong image path (/static/images/ instead of /static/shop/img/)
- Missing header, footer, and navigation
- Not integrated with shop layout system

Changes:
- Extend shop/base.html for consistent styling and layout
- Remove hardcoded CSS references (now inherited from base)
- Update image paths to /static/shop/img/placeholder.jpg
- Integrate with shopLayoutData() for cart and toast functionality
- Add proper breadcrumbs with landing page navigation
- Use Tailwind classes consistent with other shop pages
- Use theme CSS variables from base template

The product detail page now has proper styling, navigation, and
integrates seamlessly with the rest of the shop frontend.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-23 06:23:25 +01:00
b7bf505a61 feat: implement vendor landing pages with multi-template support and fix shop routing
Major improvements to shop URL routing and vendor landing page system:

## Landing Page System
- Add template field to ContentPage model for flexible landing page designs
- Create 4 landing page templates: default, minimal, modern, and full
- Implement smart root handler to serve landing pages or redirect to shop
- Add create_landing_page.py script for easy landing page management
- Support both domain/subdomain and path-based vendor access
- Add comprehensive landing page documentation

## Route Fixes
- Fix duplicate /shop prefix in shop_pages.py routes
- Correct product detail page routing (was /shop/shop/products/{id})
- Update all shop routes to work with router prefix mounting
- Remove unused public vendor endpoints (/api/v1/public/vendors)

## Template Link Corrections
- Fix all shop template links to include /shop/ prefix
- Update breadcrumb 'Home' links to point to vendor root (landing page)
- Update header navigation 'Home' link to point to vendor root
- Correct CMS page links in footer navigation
- Fix account, cart, and error page navigation links

## Navigation Architecture
- Establish two-tier navigation: landing page (/) and shop (/shop/)
- Document complete navigation flow and URL hierarchy
- Support for vendors with or without landing pages (auto-redirect fallback)
- Consistent breadcrumb and header navigation behavior

## Documentation
- Add vendor-landing-pages.md feature documentation
- Add navigation-flow.md with complete URL hierarchy
- Update shop architecture docs with error handling section
- Add orphaned docs to mkdocs.yml navigation
- Document multi-access routing patterns

## Database
- Migration f68d8da5315a: add template field to content_pages table
- Support template values: default, minimal, modern, full

This establishes a complete landing page system allowing vendors to have
custom marketing homepages separate from their e-commerce shop, with
flexible template options and proper navigation hierarchy.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-23 00:10:45 +01:00
d85a68f175 docs: add error handling and error pages section to shop architecture
Added comprehensive documentation for:
- Error page templates (10 templates)
- Error renderer base_url calculation
- Multi-access aware error links
- Template usage examples (bad vs good)
- How error pages work across domain/subdomain/path access

This documents the error page improvements made during shop API migration.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-22 23:09:08 +01:00
5a9f44f3d1 Complete shop API consolidation to /api/v1/shop/* with middleware-based vendor context
## API Migration (Complete)

### New Shop API Endpoints Created
- **Products API** (app/api/v1/shop/products.py)
  - GET /api/v1/shop/products - Product catalog with pagination/search/filters
  - GET /api/v1/shop/products/{id} - Product details

- **Cart API** (app/api/v1/shop/cart.py)
  - GET /api/v1/shop/cart/{session_id} - Get cart
  - POST /api/v1/shop/cart/{session_id}/items - Add to cart
  - PUT /api/v1/shop/cart/{session_id}/items/{product_id} - Update quantity
  - DELETE /api/v1/shop/cart/{session_id}/items/{product_id} - Remove item
  - DELETE /api/v1/shop/cart/{session_id} - Clear cart

- **Orders API** (app/api/v1/shop/orders.py)
  - POST /api/v1/shop/orders - Place order (authenticated)
  - GET /api/v1/shop/orders - Order history (authenticated)
  - GET /api/v1/shop/orders/{id} - Order details (authenticated)

- **Auth API** (app/api/v1/shop/auth.py)
  - POST /api/v1/shop/auth/register - Customer registration
  - POST /api/v1/shop/auth/login - Customer login (sets cookie at path=/shop)
  - POST /api/v1/shop/auth/logout - Customer logout
  - POST /api/v1/shop/auth/forgot-password - Password reset request
  - POST /api/v1/shop/auth/reset-password - Password reset

**Total: 18 new shop API endpoints**

### Middleware Enhancement
Updated VendorContextMiddleware (middleware/vendor_context.py):
- Added is_shop_api_request() to detect /api/v1/shop/* routes
- Added extract_vendor_from_referer() to extract vendor from Referer header
  - Supports path-based: /vendors/wizamart/shop/* → wizamart
  - Supports subdomain: wizamart.platform.com → wizamart
  - Supports custom domain: customshop.com → customshop.com
- Modified dispatch() to handle shop API specially (no longer skips)
- Vendor context now injected into request.state.vendor for shop API calls

### Frontend Migration (Complete)
Updated all shop templates to use new API endpoints:
- app/templates/shop/account/login.html - Updated login endpoint
- app/templates/shop/account/register.html - Updated register endpoint
- app/templates/shop/product.html - Updated 4 API calls (products, cart)
- app/templates/shop/cart.html - Updated 3 API calls (get, update, delete)
- app/templates/shop/products.html - Activated product loading from API

**Total: 9 API endpoint migrations across 5 templates**

### Old Endpoint Cleanup (Complete)
Removed deprecated /api/v1/public/vendors/* shop endpoints:
- Deleted app/api/v1/public/vendors/auth.py
- Deleted app/api/v1/public/vendors/products.py
- Deleted app/api/v1/public/vendors/cart.py
- Deleted app/api/v1/public/vendors/orders.py
- Deleted app/api/v1/public/vendors/payments.py (empty)
- Deleted app/api/v1/public/vendors/search.py (empty)
- Deleted app/api/v1/public/vendors/shop.py (empty)

Updated app/api/v1/public/__init__.py to only include vendor lookup endpoints:
- GET /api/v1/public/vendors/by-code/{code}
- GET /api/v1/public/vendors/by-subdomain/{subdomain}
- GET /api/v1/public/vendors/{id}/info

**Result: Only 3 truly public endpoints remain**

### Error Page Improvements
Updated all shop error templates to use base_url:
- app/templates/shop/errors/*.html (10 files)
- Updated error_renderer.py to calculate base_url from vendor context
- Links now work correctly for path-based, subdomain, and custom domain access

### CMS Route Handler
Added catch-all CMS route to app/routes/vendor_pages.py:
- Handles /{vendor_code}/{slug} for content pages
- Uses content_page_service for two-tier lookup (vendor override → platform default)

### Template Architecture Fix
Updated app/templates/shop/base.html:
- Changed x-data to use {% block alpine_data %} for component override
- Allows pages to specify custom Alpine.js components
- Enables page-specific state while extending shared shopLayoutData()

### Documentation (Complete)
Created comprehensive documentation:
- docs/api/shop-api-reference.md - Complete API reference with examples
- docs/architecture/API_CONSOLIDATION_PROPOSAL.md - Analysis of 3 options
- docs/architecture/API_MIGRATION_STATUS.md - Migration tracking (100% complete)
- Updated docs/api/index.md - Added Shop API section
- Updated docs/frontend/shop/architecture.md - New API structure and component pattern

## Benefits Achieved

### Cleaner URLs (~40% shorter)
Before: /api/v1/public/vendors/{vendor_id}/products
After:  /api/v1/shop/products

### Better Architecture
- Middleware-driven vendor context (no manual vendor_id passing)
- Proper separation of concerns (public vs shop vs vendor APIs)
- Consistent authentication pattern
- RESTful design

### Developer Experience
- No need to track vendor_id in frontend state
- Automatic vendor context from Referer header
- Simpler API calls
- Better documentation

## Testing
- Verified middleware extracts vendor from Referer correctly
- Tested all shop API endpoints with vendor context
- Confirmed products page loads and displays products
- Verified error pages show correct links
- No old API references remain in templates

Migration Status:  100% Complete (8/8 success criteria met)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-22 23:03:05 +01:00
0d7915c275 docs: update authentication dependency names across documentation
Updated all documentation to use correct authentication dependency names:
- HTML pages: get_current_admin_from_cookie_or_header, get_current_vendor_from_cookie_or_header, get_current_customer_from_cookie_or_header
- API endpoints: get_current_admin_api, get_current_vendor_api, get_current_customer_api

Changes:
- Updated authentication flow diagrams with correct dependency names for admin and vendor flows
- Added comprehensive customer/shop authentication flow documentation
- Updated cookie isolation architecture to show all three contexts (admin, vendor, shop)
- Expanded security boundary enforcement diagram to include shop routes
- Added customer cross-context prevention examples
- Updated all code examples in frontend and backend documentation
- Fixed import statements to use app.api.deps instead of app.core.auth

Files updated:
- docs/api/authentication-flow-diagrams.md (added customer flows)
- docs/frontend/admin/page-templates.md
- docs/frontend/admin/architecture.md
- docs/frontend/shared/ui-components.md
- docs/frontend/shared/sidebar.md
- docs/development/exception-handling.md
- docs/architecture/diagrams/vendor-domain-diagrams.md
- docs/backend/admin-integration-guide.md
- docs/backend/admin-feature-integration.md

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-22 18:21:23 +01:00
7a9c12dcdf docs: fix broken link in auth dependencies guide
Fix MkDocs build error by removing markdown link to source code file.
Change from [API Dependencies](../app/api/deps.py) to plain text
reference to avoid strict mode warning about non-documentation files.

Fixes: Doc file contains a link to 'app/api/deps.py' not in docs

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-22 16:07:24 +01:00
ac1017928c docs: add authentication dependencies guide
Add comprehensive guide explaining when to use each authentication
dependency:

- get_current_admin_from_cookie_or_header vs get_current_admin_api
- get_current_vendor_from_cookie_or_header vs get_current_vendor_api
- get_current_customer_from_cookie_or_header vs get_current_customer_api

Key distinctions:
- HTML pages (templates) → use _from_cookie_or_header (accepts cookies)
- API endpoints (JSON) → use _api (header-only, no cookies, CSRF-safe)
- Login pages → use _optional (returns None instead of exception)

Includes:
- Complete reference table
- When to use which dependency
- Migration guide from old names
- Code examples for each scenario
- Quick reference cheat sheet

This clarifies the naming change from get_current_admin_user to the
more specific variants and helps developers choose the right dependency.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-22 16:03:03 +01:00
c1ff0a00db fix: correct authentication dependency names in CMS API endpoints
Fix ImportError by using correct authentication dependency names:
- Use get_current_admin_api instead of get_current_admin_user
- Use get_current_vendor_api instead of get_current_vendor_user

These are the correct dependency names for API endpoints that require
Authorization header authentication (no cookie support).

Fixes: ImportError: cannot import name 'get_current_admin_user'

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-22 15:59:15 +01:00