MkDocs documentation integration

This commit is contained in:
2025-09-19 21:23:19 +02:00
parent f042616fdd
commit d0924f90c4
8 changed files with 1183 additions and 24 deletions

View File

@@ -18,7 +18,8 @@ install-test:
install-dev:
pip install -r requirements.txt
pip install -r tests/requirements-test.txt
pip install black isort flake8 mypy flake8-docstrings
pip install -r requirements-dev.txt
pip install -r requirements-docs.txt
install-all: install install-test install-dev

164
docs/api/index.md Normal file
View File

@@ -0,0 +1,164 @@
# API Overview
The Letzshop Import API provides comprehensive endpoints for managing products, shops, users, and marketplace imports. This section provides high-level guidance and concepts for working with our API.
## Interactive Documentation
For hands-on API exploration and testing, use our interactive documentation:
!!! tip "Live API Documentation"
- **[Swagger UI](http://localhost:8000/docs)** - Interactive API testing interface
- **[ReDoc](http://localhost:8000/redoc)** - Clean, readable API reference
- **[OpenAPI Spec](http://localhost:8000/openapi.json)** - Machine-readable API specification
## API Structure
### Base URL
```
Production: https://api.letzshop.com/api/v1
Development: http://localhost:8000/api/v1
```
### API Versioning
All API endpoints are versioned using URL path versioning:
- Current version: `v1`
- All endpoints are prefixed with `/api/v1/`
## Endpoint Categories
### Authentication (`/auth/`)
- User registration and login
- Token refresh and validation
- Password reset workflows
### Admin (`/admin/`)
- User management (admin only)
- System statistics
- Configuration management
### Products (`/products/`)
- Product CRUD operations
- Product search and filtering
- Bulk operations
### Shops (`/shops/`)
- Shop management
- Shop-product associations
- Shop statistics
### Stock (`/stock/`)
- Inventory management
- Stock movements
- Stock reporting
### Marketplace (`/marketplace/`)
- Import job management
- CSV file processing
- Import status tracking
### Statistics (`/stats/`)
- System-wide statistics
- User activity metrics
- Import performance data
## Request/Response Format
### Content Type
All API endpoints use JSON for request and response bodies:
```
Content-Type: application/json
```
### Standard Response Format
```json
{
"data": {...}, // Main response data
"message": "Success", // Human-readable message
"status": 200 // HTTP status code
}
```
### Error Response Format
```json
{
"detail": "Error description",
"type": "validation_error",
"errors": [ // Field-specific errors (if applicable)
{
"field": "email",
"message": "Invalid email format"
}
]
}
```
## Common Patterns
### Pagination
Most list endpoints support pagination:
```bash
GET /api/v1/products?skip=0&limit=20
```
Response includes pagination metadata:
```json
{
"items": [...],
"total": 150,
"skip": 0,
"limit": 20,
"has_next": true
}
```
### Filtering and Searching
Many endpoints support filtering and search:
```bash
GET /api/v1/products?search=laptop&category=electronics&min_price=100
```
### Sorting
Use the `sort` parameter with field names:
```bash
GET /api/v1/products?sort=name&order=desc
```
## Status Codes
| Code | Meaning | Description |
|------|---------|-------------|
| 200 | OK | Request successful |
| 201 | Created | Resource created successfully |
| 204 | No Content | Request successful, no content returned |
| 400 | Bad Request | Invalid request data |
| 401 | Unauthorized | Authentication required |
| 403 | Forbidden | Insufficient permissions |
| 404 | Not Found | Resource not found |
| 422 | Unprocessable Entity | Validation error |
| 429 | Too Many Requests | Rate limit exceeded |
| 500 | Internal Server Error | Server error |
## Rate Limiting
API endpoints are rate limited to ensure fair usage:
- **Default limit**: 100 requests per minute per IP
- **Authenticated users**: 1000 requests per minute
- **Admin users**: 5000 requests per minute
Rate limit headers are included in responses:
```
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1640995200
```
## Next Steps
- **[Authentication Guide](authentication.md)** - Learn about API authentication
- **[Error Handling](error-handling.md)** - Understanding API errors
- **[Rate Limiting](rate-limiting.md)** - Rate limiting details
- **[Interactive Docs](http://localhost:8000/docs)** - Try the API live

View File

@@ -0,0 +1,242 @@
# Installation Guide
This guide will help you set up the Letzshop Import application for development or production use.
## Prerequisites
Before you begin, ensure you have the following installed:
- **Python 3.10 or higher**
- **PostgreSQL 12 or higher**
- **Git**
- **Docker** (optional, for containerized deployment)
## Development Setup
### 1. Clone the Repository
```bash
git clone https://github.com/yourusername/letzshop-import.git
cd letzshop-import
```
### 2. Create Virtual Environment
=== "Windows"
```bash
python -m venv venv
venv\Scripts\activate
```
=== "macOS/Linux"
```bash
python -m venv venv
source venv/bin/activate
```
### 3. Install Dependencies
```bash
# Install main application dependencies
pip install -r requirements.txt
# Install development dependencies
pip install -r requirements-dev.txt
# Install test dependencies
pip install -r tests/requirements-test.txt
# Install documentation dependencies (optional)
pip install -r requirements-docs.txt
```
### 4. Database Setup
#### Option A: Local PostgreSQL
1. **Create Database**:
```sql
CREATE DATABASE letzshop_import;
CREATE USER letzshop_user WITH PASSWORD 'your_password';
GRANT ALL PRIVILEGES ON DATABASE letzshop_import TO letzshop_user;
```
2. **Create Environment File**:
```bash
cp .env.example .env
```
3. **Configure `.env` file**:
```env
# Database
DATABASE_URL=postgresql://letzshop_user:your_password@localhost/letzshop_import
# Security
SECRET_KEY=your-super-secret-key-here
JWT_SECRET_KEY=your-jwt-secret-key-here
# Environment
ENVIRONMENT=development
DEBUG=True
```
#### Option B: Docker PostgreSQL
```bash
docker run --name letzshop-postgres \
-e POSTGRES_DB=letzshop_import \
-e POSTGRES_USER=letzshop_user \
-e POSTGRES_PASSWORD=your_password \
-p 5432:5432 \
-d postgres:15
```
### 5. Initialize Database
```bash
# Run database migrations
python -m alembic upgrade head
# Create initial admin user (optional)
python scripts/create_admin.py
```
### 6. Run the Application
```bash
# Start development server
uvicorn main:app --reload --host 0.0.0.0 --port 8000
```
The application will be available at:
- **API**: http://localhost:8000
- **Interactive API Docs**: http://localhost:8000/docs
- **Alternative API Docs**: http://localhost:8000/redoc
## Docker Setup
### Quick Start with Docker Compose
1. **Clone and navigate to project**:
```bash
git clone https://github.com/yourusername/letzshop-import.git
cd letzshop-import
```
2. **Start all services**:
```bash
docker-compose up -d
```
3. **Initialize database**:
```bash
docker-compose exec api python -m alembic upgrade head
```
### Manual Docker Setup
1. **Build the image**:
```bash
docker build -t letzshop-import .
```
2. **Run with environment variables**:
```bash
docker run -d \
--name letzshop-api \
-p 8000:8000 \
-e DATABASE_URL="postgresql://user:pass@host/db" \
-e SECRET_KEY="your-secret-key" \
letzshop-import
```
## Verification
### 1. Check Application Health
```bash
curl http://localhost:8000/health
```
Expected response:
```json
{
"status": "healthy",
"database": "connected",
"version": "1.0.0"
}
```
### 2. Run Tests
```bash
# Run all tests
pytest
# Run specific test types
pytest -m unit
pytest -m integration
```
### 3. Access Documentation
- **Swagger UI**: http://localhost:8000/docs
- **ReDoc**: http://localhost:8000/redoc
- **This Documentation** (if running MkDocs): http://localhost:8001
## Environment Variables
| Variable | Description | Default | Required |
|----------|-------------|---------|----------|
| `DATABASE_URL` | PostgreSQL connection string | - | ✅ |
| `SECRET_KEY` | Application secret key | - | ✅ |
| `JWT_SECRET_KEY` | JWT token secret | - | ✅ |
| `ENVIRONMENT` | Environment (dev/staging/prod) | `development` | ❌ |
| `DEBUG` | Enable debug mode | `False` | ❌ |
| `LOG_LEVEL` | Logging level | `INFO` | ❌ |
| `CORS_ORIGINS` | Allowed CORS origins | `["*"]` | ❌ |
## Troubleshooting
### Common Issues
#### Database Connection Issues
```bash
# Check if PostgreSQL is running
pg_isready -h localhost -p 5432
# Check database connectivity
python -c "from app.core.database import engine; engine.connect()"
```
#### Port Already in Use
```bash
# Find process using port 8000
lsof -i :8000
# Kill the process
kill -9 <PID>
```
#### Permission Issues
```bash
# Fix file permissions
chmod +x scripts/*.py
# Fix virtual environment permissions
chmod -R 755 venv/
```
### Getting Help
If you encounter issues:
1. Check the [Troubleshooting Guide](../development/troubleshooting.md)
2. Review application logs: `docker-compose logs api`
3. Open an [issue on GitHub](https://github.com/yourusername/letzshop-import/issues)
## Next Steps
- **[Quick Start Guide](quickstart.md)** - Get familiar with basic operations
- **[Configuration Guide](configuration.md)** - Detailed configuration options
- **[API Documentation](../api/index.md)** - Explore the API endpoints

117
docs/index.md Normal file
View File

@@ -0,0 +1,117 @@
# Letzshop Import Documentation
Welcome to the complete documentation for the Letzshop Import application - a comprehensive marketplace product import and management system built with FastAPI.
## What is Letzshop Import?
Letzshop Import is a powerful web application that enables:
- **Product Management**: Create, update, and manage product catalogs
- **Shop Management**: Multi-shop support with individual configurations
- **CSV Import**: Bulk import products from various marketplace formats
- **Stock Management**: Track inventory across multiple locations
- **User Management**: Role-based access control for different user types
- **Marketplace Integration**: Import from various marketplace platforms
## Quick Navigation
### 🚀 Get Started
- [**Installation Guide**](getting-started/installation.md) - Set up the application
- [**Quick Start**](getting-started/quickstart.md) - Get running in minutes
- [**Configuration**](getting-started/configuration.md) - Environment setup
### 📚 API Documentation
- [**Interactive API Docs**](http://localhost:8000/docs) - Swagger UI for live testing
- [**Alternative API Docs**](http://localhost:8000/redoc) - ReDoc interface
- [**API Overview**](api/index.md) - High-level API concepts
- [**Authentication Guide**](api/authentication.md) - Security and auth flows
### 📖 User Guides
- [**User Management**](guides/user-management.md) - Managing users and roles
- [**Product Management**](guides/product-management.md) - Working with products
- [**CSV Import**](guides/csv-import.md) - Bulk import workflows
- [**Shop Setup**](guides/shop-setup.md) - Configuring shops
### 🧪 Testing
- [**Test Naming Conventions**](testing/test-naming-conventions.md) - Our testing standards
- [**Running Tests**](testing/running-tests.md) - How to run the test suite
### 🔧 Development
- [**Architecture**](development/architecture.md) - System design overview
- [**Database Schema**](development/database-schema.md) - Data model documentation
- [**Contributing**](development/contributing.md) - How to contribute
### 🚢 Deployment
- [**Docker Deployment**](deployment/docker.md) - Containerized deployment
- [**Production Setup**](deployment/production.md) - Production best practices
## Architecture Overview
```mermaid
graph TB
Client[Web Client/API Consumer]
API[FastAPI Application]
Auth[Authentication Service]
Products[Product Service]
Shops[Shop Service]
Import[Import Service]
DB[(PostgreSQL Database)]
Client --> API
API --> Auth
API --> Products
API --> Shops
API --> Import
Auth --> DB
Products --> DB
Shops --> DB
Import --> DB
```
## Key Features
=== "Product Management"
- CRUD operations for products
- GTIN validation and normalization
- Price management with currency support
- Category and attribute management
- Bulk operations support
=== "Import System"
- CSV file processing
- Multiple marketplace format support
- Validation and error reporting
- Batch processing for large files
- Import job tracking and status
=== "Multi-Shop Support"
- Independent shop configurations
- Shop-specific product associations
- Inventory tracking per shop
- Role-based shop access
=== "Security"
- JWT-based authentication
- Role-based access control (RBAC)
- API key management
- Input validation and sanitization
- Rate limiting
## Technology Stack
- **Backend**: FastAPI, Python 3.10+
- **Database**: PostgreSQL with SQLAlchemy ORM
- **Authentication**: JWT tokens
- **Testing**: pytest with comprehensive test suite
- **Documentation**: MkDocs Material + FastAPI auto-docs
- **Deployment**: Docker, Docker Compose
## Getting Help
- **Issues**: [GitHub Issues](https://github.com/yourusername/letzshop-import/issues)
- **Discussions**: [GitHub Discussions](https://github.com/yourusername/letzshop-import/discussions)
- **API Testing**: Use the [Swagger UI](http://localhost:8000/docs) for interactive testing
---
Ready to get started? Head over to the [Installation Guide](getting-started/installation.md)!

View File

@@ -0,0 +1,383 @@
# Test Naming Conventions
This document outlines the naming conventions used in our test suite to ensure consistency, clarity, and maintainability across the project.
## Overview
Our test suite follows a hierarchical structure organized by test type and component, with clear naming patterns that make it easy to locate and understand test purposes.
## Directory Structure
```
tests/
├── conftest.py # Core test configuration and fixtures
├── pytest.ini # Pytest configuration
├── fixtures/ # Shared test fixtures organized by domain
├── unit/ # Fast, isolated component tests
├── integration/ # Multi-component interaction tests
├── performance/ # Performance and load tests
├── system/ # End-to-end system behavior tests
└── test_data/ # Test data files (CSV, JSON, etc.)
```
## File Naming Conventions
### General Rule
All test files must start with `test_` prefix for pytest auto-discovery.
**Pattern:** `test_{component/feature}.py`
### Unit Tests (`tests/unit/`)
Focus on testing individual components in isolation.
```
tests/unit/
├── models/
│ ├── test_database_models.py # Database model tests
│ ├── test_api_models.py # API model validation
│ └── test_model_relationships.py # Model relationship tests
├── utils/
│ ├── test_data_processing.py # Data processing utilities
│ ├── test_csv_processor.py # CSV processing utilities
│ ├── test_validators.py # Validation utilities
│ └── test_formatters.py # Data formatting utilities
├── services/
│ ├── test_admin_service.py # Admin service business logic
│ ├── test_auth_service.py # Authentication service
│ ├── test_product_service.py # Product management service
│ ├── test_shop_service.py # Shop management service
│ ├── test_stock_service.py # Stock management service
│ ├── test_marketplace_service.py # Marketplace import service
│ └── test_stats_service.py # Statistics service
└── core/
├── test_config.py # Configuration management
├── test_database.py # Database utilities
└── test_logging.py # Logging functionality
```
### Integration Tests (`tests/integration/`)
Focus on testing interactions between multiple components.
```
tests/integration/
├── api/v1/
│ ├── test_auth_endpoints.py # Authentication API endpoints
│ ├── test_admin_endpoints.py # Admin API endpoints
│ ├── test_product_endpoints.py # Product CRUD endpoints
│ ├── test_shop_endpoints.py # Shop management endpoints
│ ├── test_stock_endpoints.py # Stock management endpoints
│ ├── test_marketplace_endpoints.py # Import endpoints
│ ├── test_stats_endpoints.py # Statistics endpoints
│ └── test_pagination.py # Pagination functionality
├── database/
│ ├── test_migrations.py # Database migration tests
│ ├── test_transactions.py # Transaction handling
│ └── test_constraints.py # Database constraints
├── security/
│ ├── test_authentication.py # Authentication mechanisms
│ ├── test_authorization.py # Permission and role tests
│ ├── test_input_validation.py # Input security validation
│ ├── test_rate_limiting.py # Rate limiting middleware
│ └── test_cors.py # CORS configuration
└── workflows/
├── test_product_import_workflow.py # Complete import process
├── test_user_registration_flow.py # User registration process
└── test_shop_setup_flow.py # Shop creation workflow
```
### System Tests (`tests/system/`)
Focus on end-to-end application behavior.
```
tests/system/
├── test_application_startup.py # Application initialization
├── test_error_handling.py # Global error handling
├── test_health_checks.py # Health endpoint tests
├── test_database_connectivity.py # Database connection tests
└── test_external_dependencies.py # Third-party service tests
```
### Performance Tests (`tests/performance/`)
Focus on performance benchmarks and load testing.
```
tests/performance/
├── test_api_performance.py # API endpoint performance
├── test_database_performance.py # Database query performance
├── test_import_performance.py # Large file import tests
└── test_concurrent_users.py # Multi-user scenarios
```
## Class Naming Conventions
Use descriptive class names that clearly indicate what is being tested:
### Pattern: `Test{ComponentName}{TestType}`
```python
# Good examples
class TestProductService: # Testing ProductService class
class TestProductModel: # Testing Product model
class TestProductEndpoints: # Testing product API endpoints
class TestProductValidation: # Testing product validation logic
class TestProductPermissions: # Testing product access control
# Avoid generic names
class TestProduct: # Too vague - what aspect of Product?
class Tests: # Too generic
```
### Specialized Class Naming
```python
class TestProductCRUD: # CRUD operations
class TestProductSecurity: # Security-related tests
class TestProductErrorHandling: # Error scenario tests
class TestProductEdgeCases: # Boundary condition tests
```
## Method Naming Conventions
Test method names should be descriptive and follow a clear pattern that explains:
1. What is being tested
2. The scenario/condition
3. Expected outcome
### Pattern: `test_{action}_{scenario}_{expected_outcome}`
```python
# Good examples - Clear and descriptive
def test_create_product_with_valid_data_returns_product():
def test_create_product_with_invalid_gtin_raises_validation_error():
def test_get_product_by_id_when_not_found_returns_404():
def test_update_product_without_permission_raises_forbidden():
def test_delete_product_with_existing_stock_prevents_deletion():
# Acceptable shorter versions
def test_create_product_success():
def test_create_product_invalid_data():
def test_create_product_unauthorized():
def test_get_product_not_found():
```
### Method Naming Patterns by Scenario
**Happy Path Tests:**
```python
def test_create_user_success():
def test_login_valid_credentials():
def test_import_csv_valid_format():
```
**Error/Edge Case Tests:**
```python
def test_create_user_duplicate_email_fails():
def test_login_invalid_credentials_rejected():
def test_import_csv_malformed_data_raises_error():
```
**Permission/Security Tests:**
```python
def test_admin_endpoint_requires_admin_role():
def test_user_cannot_access_other_user_data():
def test_api_key_required_for_marketplace_import():
```
**Boundary/Edge Cases:**
```python
def test_pagination_with_zero_items():
def test_price_with_maximum_decimal_places():
def test_gtin_with_minimum_valid_length():
```
## Marker Usage
Use pytest markers to categorize and run specific test types:
```python
@pytest.mark.unit
class TestProductService:
"""Unit tests for ProductService business logic"""
@pytest.mark.integration
@pytest.mark.api
class TestProductEndpoints:
"""Integration tests for Product API endpoints"""
@pytest.mark.slow
@pytest.mark.performance
class TestImportPerformance:
"""Performance tests for large CSV imports"""
```
### Available Markers
| Marker | Purpose |
|--------|---------|
| `@pytest.mark.unit` | Fast, isolated component tests |
| `@pytest.mark.integration` | Multi-component interaction tests |
| `@pytest.mark.system` | End-to-end system tests |
| `@pytest.mark.performance` | Performance and load tests |
| `@pytest.mark.slow` | Long-running tests |
| `@pytest.mark.api` | API endpoint tests |
| `@pytest.mark.database` | Tests requiring database |
| `@pytest.mark.auth` | Authentication/authorization tests |
| `@pytest.mark.admin` | Admin functionality tests |
## File Organization Best Practices
### Mirror Source Structure
Test files should mirror the source code structure:
```
app/services/product_service.py → tests/unit/services/test_product_service.py
app/api/v1/admin.py → tests/integration/api/v1/test_admin_endpoints.py
```
### Group Related Tests
Keep related tests in the same file:
```python
# test_product_service.py
class TestProductCreation: # All product creation scenarios
class TestProductValidation: # All validation scenarios
class TestProductQueries: # All query scenarios
```
### Separate Complex Workflows
Break complex workflows into separate files:
```
test_user_registration_flow.py # Complete registration process
test_shop_setup_flow.py # Shop creation workflow
test_product_import_workflow.py # CSV import end-to-end
```
## Running Tests by Name Pattern
Use pytest's flexible test discovery:
```bash
# Run all unit tests
pytest tests/unit/ -v
# Run specific component tests
pytest tests/ -k "product" -v
# Run by marker
pytest -m "unit and not slow" -v
# Run specific test class
pytest tests/unit/services/test_product_service.py::TestProductService -v
# Run specific test method
pytest tests/unit/services/test_product_service.py::TestProductService::test_create_product_success -v
```
## Examples
### Complete Test File Example
```python
# tests/unit/services/test_product_service.py
import pytest
from unittest.mock import Mock, patch
from app.services.product_service import ProductService
from app.models.database_models import Product
@pytest.mark.unit
class TestProductService:
"""Unit tests for ProductService business logic"""
def setup_method(self):
"""Setup run before each test method"""
self.service = ProductService()
self.mock_db = Mock()
def test_create_product_with_valid_data_returns_product(self):
"""Test successful product creation with valid input data"""
# Arrange
product_data = {
"name": "Test Product",
"gtin": "1234567890123",
"price": "19.99"
}
# Act
result = self.service.create_product(product_data)
# Assert
assert result is not None
assert result.name == "Test Product"
def test_create_product_with_invalid_gtin_raises_validation_error(self):
"""Test product creation fails with invalid GTIN format"""
# Arrange
product_data = {
"name": "Test Product",
"gtin": "invalid_gtin",
"price": "19.99"
}
# Act & Assert
with pytest.raises(ValidationError, match="Invalid GTIN format"):
self.service.create_product(product_data)
@pytest.mark.unit
class TestProductValidation:
"""Unit tests for product validation logic"""
def test_validate_gtin_with_valid_format_returns_true(self):
"""Test GTIN validation accepts valid 13-digit GTIN"""
assert ProductService.validate_gtin("1234567890123") is True
def test_validate_gtin_with_invalid_format_returns_false(self):
"""Test GTIN validation rejects invalid format"""
assert ProductService.validate_gtin("invalid") is False
```
## Naming Anti-Patterns to Avoid
**Avoid these patterns:**
```python
# Too generic
def test_product():
def test_user():
def test_api():
# Unclear purpose
def test_function():
def test_method():
def test_endpoint():
# Non-descriptive
def test_1():
def test_a():
def test_scenario():
# Inconsistent naming
def testProductCreation(): # Wrong case
def test_product_creation(): # Good
def TestProductCreation(): # Wrong - this is for classes
```
**Use these patterns instead:**
```python
# Clear, descriptive, consistent
def test_create_product_with_valid_data_succeeds():
def test_authenticate_user_with_invalid_token_fails():
def test_get_products_endpoint_returns_paginated_results():
```
---
Following these naming conventions will help maintain a clean, understandable, and maintainable test suite that scales with your project.

133
main.py
View File

@@ -2,6 +2,7 @@ import logging
from datetime import datetime
from fastapi import Depends, FastAPI, HTTPException
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.middleware.cors import CORSMiddleware
from sqlalchemy import text
from sqlalchemy.orm import Session
@@ -36,28 +37,10 @@ app.include_router(api_router, prefix="/api/v1")
# Public Routes (no authentication required)
# Core application endpoints (Public Routes, no authentication required)
@app.get("/")
def root():
return {
"message": f"{settings.project_name} v{settings.version}",
"status": "operational",
"docs": "/docs",
"features": [
"JWT Authentication",
"Marketplace-aware product import",
"Multi-shop product management",
"Stock management with location tracking",
],
"supported_marketplaces": [
"Letzshop",
"Amazon",
"eBay",
"Etsy",
"Shopify",
"Other",
],
"auth_required": "Most endpoints require Bearer token authentication",
}
@app.get("/", include_in_schema=False)
async def root():
"""Redirect root to documentation"""
return RedirectResponse(url="/documentation")
@app.get("/health")
@@ -66,7 +49,25 @@ def health_check(db: Session = Depends(get_db)):
try:
# Test database connection
db.execute(text("SELECT 1"))
return {"status": "healthy", "timestamp": datetime.utcnow()}
return {"status": "healthy",
"timestamp": datetime.utcnow(),
"message": f"{settings.project_name} v{settings.version}",
"docs": {
"swagger": "/docs",
"redoc": "/redoc",
"openapi": "/openapi.json",
"complete": "Documentation site URL here"
},
"features": [
"JWT Authentication",
"Marketplace-aware product import",
"Multi-shop product management",
"Stock management with location tracking",
],
"supported_marketplaces": [
"Letzshop",
],
"auth_required": "Most endpoints require Bearer token authentication", }
except Exception as e:
logger.error(f"Health check failed: {e}")
raise HTTPException(status_code=503, detail="Service unhealthy")
@@ -74,6 +75,92 @@ def health_check(db: Session = Depends(get_db)):
# Add this temporary endpoint to your router:
# Documentation redirect endpoints
@app.get("/documentation", response_class=HTMLResponse, include_in_schema=False)
async def documentation_page():
"""Enhanced documentation hub page"""
return """
<!DOCTYPE html>
<html>
<head>
<title>Letzshop Import - Documentation</title>
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
max-width: 800px;
margin: 40px auto;
padding: 20px;
line-height: 1.6;
}
.header { text-align: center; margin-bottom: 40px; }
.logo { font-size: 2em; margin-bottom: 10px; }
.cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px; margin: 30px 0; }
.card {
border: 1px solid #e1e5e9;
border-radius: 8px;
padding: 20px;
transition: box-shadow 0.2s;
text-decoration: none;
color: inherit;
}
.card:hover { box-shadow: 0 4px 12px rgba(0,0,0,0.1); }
.card h3 { margin-top: 0; color: #1976d2; }
.badge {
display: inline-block;
background: #1976d2;
color: white;
padding: 4px 8px;
border-radius: 4px;
font-size: 0.8em;
margin-left: 10px;
}
</style>
</head>
<body>
<div class="header">
<div class="logo">📚 Letzshop Import Documentation</div>
<p>Choose your documentation experience</p>
</div>
<div class="cards">
<a href="/docs" class="card">
<h3>🔧 Interactive API Docs <span class="badge">LIVE</span></h3>
<p>Swagger UI interface for testing API endpoints directly in your browser. Perfect for development and API exploration.</p>
</a>
<a href="/redoc" class="card">
<h3>📖 API Reference</h3>
<p>Clean, readable API documentation with ReDoc. Great for understanding API structure and parameters.</p>
</a>
<a href="#" class="card">
<h3>📚 Complete Documentation</h3>
<p>Comprehensive project documentation with guides, tutorials, architecture, and development info.</p>
</a>
<a href="#" class="card">
<h3>🚀 Getting Started</h3>
<p>Step-by-step installation and setup guide to get you up and running quickly.</p>
</a>
<a href="#" class="card">
<h3>🧪 Testing Guide</h3>
<p>Testing conventions, how to run tests, and contribute to the test suite.</p>
</a>
<a href="/health" class="card">
<h3>💚 System Health</h3>
<p>Check the current status and health of the API and its dependencies.</p>
</a>
</div>
<div style="text-align: center; margin-top: 40px; color: #666;">
<p>Need help? Check our <a href="https://github.com/yourusername/letzshop-import/issues">GitHub Issues</a></p>
</div>
</body>
</html>
"""
if __name__ == "__main__":
import uvicorn

158
mkdocs.yml Normal file
View File

@@ -0,0 +1,158 @@
site_name: Letzshop Import Documentation
site_description: Complete documentation for the Letzshop Import application
site_author: Letzshop Team
site_url: https://yourusername.github.io/letzshop-import/
repo_name: letzshop-import
repo_url: https://github.com/yourusername/letzshop-import
edit_uri: edit/main/docs/
# Navigation structure
nav:
- Home: index.md
- Getting Started:
- Installation: getting-started/installation.md
- Quick Start: getting-started/quickstart.md
- Configuration: getting-started/configuration.md
- API:
- Overview: api/index.md
- Authentication: api/authentication.md
- Error Handling: api/error-handling.md
- Rate Limiting: api/rate-limiting.md
- User Guides:
- User Management: guides/user-management.md
- Product Management: guides/product-management.md
- Shop Setup: guides/shop-setup.md
- CSV Import: guides/csv-import.md
- Marketplace Integration: guides/marketplace-integration.md
- Testing:
- Overview: testing/index.md
- Naming Conventions: testing/test-naming-conventions.md
- Running Tests: testing/running-tests.md
- Test Data: testing/test-data.md
- Development:
- Architecture: development/architecture.md
- Database Schema: development/database-schema.md
- Services: development/services.md
- Contributing: development/contributing.md
- Deployment:
- Overview: deployment/index.md
- Docker: deployment/docker.md
- Production: deployment/production.md
- Environment Variables: deployment/environment.md
# Theme configuration
theme:
name: material
palette:
# Palette toggle for automatic mode
- media: "(prefers-color-scheme)"
toggle:
icon: material/brightness-auto
name: Switch to light mode
# Palette toggle for light mode
- media: "(prefers-color-scheme: light)"
scheme: default
primary: blue
accent: blue
toggle:
icon: material/brightness-7
name: Switch to dark mode
# Palette toggle for dark mode
- media: "(prefers-color-scheme: dark)"
scheme: slate
primary: blue
accent: blue
toggle:
icon: material/brightness-4
name: Switch to system preference
features:
- navigation.tabs
- navigation.tabs.sticky
- navigation.sections
- navigation.expand
- navigation.path
- navigation.indexes
- toc.follow
- navigation.top
- search.suggest
- search.highlight
- content.tabs.link
- content.code.annotation
- content.code.copy
- content.action.edit
- content.action.view
icon:
repo: fontawesome/brands/github
# Plugins
plugins:
- search:
separator: '[\s\-,:!=\[\]()"`/]+|\.(?!\d)|&[lg]t;|(?!\b)(?=[A-Z][a-z])'
- mkdocstrings:
handlers:
python:
options:
docstring_style: google
show_source: true
show_root_heading: true
show_root_toc_entry: false
merge_init_into_class: true
# Markdown extensions
markdown_extensions:
- abbr
- admonition
- attr_list
- def_list
- footnotes
- md_in_html
- toc:
permalink: true
- pymdownx.arithmatex:
generic: true
- pymdownx.betterem:
smart_enable: all
- pymdownx.caret
- pymdownx.details
- pymdownx.emoji:
emoji_generator: !!python/name:material.extensions.emoji.to_svg
emoji_index: !!python/name:material.extensions.emoji.twemoji
- pymdownx.highlight:
anchor_linenums: true
line_spans: __span
pygments_lang_class: true
- pymdownx.inlinehilite
- pymdownx.keys
- pymdownx.magiclink:
normalize_issue_symbols: true
repo_url_shorthand: true
user: yourusername
repo: letzshop-import
- pymdownx.mark
- pymdownx.smartsymbols
- pymdownx.snippets
- pymdownx.superfences:
custom_fences:
- name: mermaid
class: mermaid
format: !!python/name:pymdownx.superfences.fence_code_format
- pymdownx.tabbed:
alternate_style: true
combine_header_slug: true
- pymdownx.tasklist:
custom_checkbox: true
- pymdownx.tilde
# Footer
extra:
social:
- icon: fontawesome/brands/github
link: https://github.com/yourusername
# Copyright
copyright: Copyright &copy; 2024 Letzshop Team

7
requirements-docs.txt Normal file
View File

@@ -0,0 +1,7 @@
# requirements-docs.txt
# Documentation dependencies
mkdocs>=1.5.0
mkdocs-material>=9.4.0
mkdocstrings[python]>=0.24.0
mkdocs-swagger-ui-tag>=0.6.0
pymdown-extensions>=10.4.0