revamping documentation

This commit is contained in:
2025-11-17 22:59:42 +01:00
parent bbd64a6f21
commit 807033be16
107 changed files with 11973 additions and 28413 deletions

View File

@@ -324,5 +324,5 @@ Migration failures will halt deployment to prevent data corruption.
## Further Reading
- [Alembic Official Documentation](https://alembic.sqlalchemy.org/)
- [Database Schema Documentation](database-schema.md)
- [Database Setup Guide](../getting-started/DATABASE_SETUP_GUIDE.md)
- [Deployment Guide](../deployment/production.md)

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,247 @@
# Database Commands - Quick Reference
## 🚀 Common Workflows
### First-Time Development Setup
```bash
make migrate-up # Apply migrations
make init-prod # Create admin user
make seed-demo # Add demo data
make dev # Start developing
```
### First-Time Production Setup
```bash
# 1. Configure .env
ENVIRONMENT=production
ADMIN_EMAIL=admin@yourcompany.com
ADMIN_PASSWORD=SecurePassword123!
# 2. Initialize
make migrate-up
make init-prod
# 3. Create vendors via admin panel
```
### Daily Development
```bash
make dev # Start server
make seed-demo-reset # Fresh demo data
make test # Run tests
```
---
## 📋 Command Reference
### Database Migrations
```bash
make migrate-create message="add_feature" # Create migration
make migrate-up # Apply migrations
make migrate-down # Rollback last
make migrate-status # Check status
```
### Initialization
```bash
make init-prod # Create admin + settings (SAFE for production)
```
### Demo Data (Development Only)
```bash
make seed-demo # 3 vendors + data
make seed-demo-minimal # 1 vendor only
make seed-demo-reset # DELETE ALL + reseed (DANGEROUS!)
```
### Complete Workflows
```bash
make db-setup # migrate + init + seed
make db-reset # rollback + migrate + reset
```
---
## ⚙️ Configuration (.env)
### Required Settings
```bash
ENVIRONMENT=development # development/staging/production
DATABASE_URL=sqlite:///./wizamart.db
# Admin credentials (CHANGE IN PRODUCTION!)
ADMIN_EMAIL=admin@wizamart.com
ADMIN_USERNAME=admin
ADMIN_PASSWORD=admin123
```
### Demo Data Controls
```bash
SEED_DEMO_VENDORS=3 # How many vendors
SEED_CUSTOMERS_PER_VENDOR=15 # Customers per vendor
SEED_PRODUCTS_PER_VENDOR=20 # Products per vendor
```
### Using Settings in Code
```python
from app.core.config import settings
# Environment checks
if settings.is_production:
# Production code
# Access configuration
email = settings.admin_email
db_url = settings.database_url
```
---
## 🔐 Default Credentials
### Admin (After init-prod)
```
URL: http://localhost:8000/admin/login
Username: admin
Password: admin123 (CHANGE IN PRODUCTION!)
```
### Demo Vendors (After seed-demo)
```
Vendor 1: vendor1@example.com / password123
Vendor 2: vendor2@example.com / password123
Vendor 3: vendor3@example.com / password123
```
⚠️ **All demo passwords are INSECURE - for development only!**
---
## 📊 What Each Command Creates
### `make init-prod`
✅ Platform admin user
✅ Admin settings
✅ Role templates
✅ RBAC schema verification
**Safe for production**: YES
**Contains fake data**: NO
### `make seed-demo`
✅ 3 demo vendors
✅ Demo vendor users
✅ ~45 customers (15 per vendor)
✅ ~60 products (20 per vendor)
✅ Vendor themes
✅ Custom domains
**Safe for production**: NO
**Contains fake data**: YES - ALL OF IT
### `make seed-demo-minimal`
✅ 1 demo vendor
✅ 1 demo vendor user
✅ ~15 customers
✅ ~20 products
✅ Vendor theme
✅ Custom domain
**Safe for production**: NO
**Contains fake data**: YES
---
## 🚨 Safety Features
### Production Warnings
```bash
# Automatically warns if:
⚠️ Using default admin password
⚠️ Using default JWT secret
⚠️ Debug mode enabled in production
⚠️ ALLOWED_HOSTS is wildcard
```
### Environment Protection
```bash
# seed_demo.py refuses to run if:
ENVIRONMENT=production
Error: Cannot run demo seeding in production!
```
### Reset Confirmation
```bash
make seed-demo-reset
# Requires typing: DELETE ALL DATA
```
---
## 🔍 Verification Commands
### Check Database State
```python
# Quick check
python -c "
from app.core.database import SessionLocal
from models.database.vendor import Vendor
db = SessionLocal()
print(f'Vendors: {db.query(Vendor).count()}')
db.close()
"
```
### View Settings
```python
# Check configuration
python -c "
from app.core.config import settings, print_environment_info
print_environment_info()
"
```
### Validate Production
```python
# Check production security
python -c "
from app.core.config import validate_production_settings
warnings = validate_production_settings()
if warnings:
for w in warnings: print(w)
else:
print('✅ Production configuration is secure')
"
```
---
## 🆘 Common Issues
### "Admin already exists"
**Normal!** init_production.py is idempotent (safe to run multiple times)
### "Table doesn't exist"
❌ Run migrations first: `make migrate-up`
### "Cannot run in production"
**Correct behavior!** seed_demo.py blocks production usage
### "Default password warning"
⚠️ Update `.env` with secure password in production
---
## 📚 More Help
```bash
make help # All commands
make help-db # Database-specific help
```
**Documentation**:
- `DATABASE_INIT_GUIDE.md` - Detailed guide
- `MIGRATION_GUIDE.md` - Migration from old system
- `README.md` - Project overview

View File

@@ -0,0 +1,380 @@
# Enhanced Database Seeder - Implementation Guide
## Overview
I've created a comprehensive database seeder for your Wizamart platform that significantly expands coverage beyond your original implementation. The new seeder creates realistic test data across all your database models.
## What's New
### Original Seeder Coverage
- ✓ Admin user
- ✓ 2 Vendors (TESTVENDOR, WIZAMART)
### Enhanced Seeder Coverage
- ✓ Admin user + multiple test users (vendors, customers)
- ✓ 3 Vendors with different themes and configurations
- ✓ Custom domains for vendors
- ✓ Vendor themes with different presets (modern, classic, vibrant)
- ✓ 5 Sample marketplace products
- ✓ Vendor-product relationships
- ✓ Multiple customers with addresses
- ✓ Sample orders with order items
- ✓ Import jobs
- ✓ Admin settings (platform configuration)
- ✓ Platform alerts (system monitoring)
## Files Created
1. **seed_database.py** - Enhanced seeder script (placed in /mnt/user-data/outputs/)
2. **makefile_additions.txt** - Commands to add to your Makefile
## Makefile Integration
Add these commands to your Makefile in the DATABASE section (after backup-db):
```makefile
seed:
@echo Seeding database with comprehensive test data...
$(PYTHON) scripts/seed_database.py
@echo Seeding completed successfully
seed-minimal:
@echo Seeding database with minimal data (admin + 1 vendor)...
$(PYTHON) scripts/seed_database.py --minimal
@echo Minimal seeding completed
seed-reset:
@echo WARNING: This will DELETE ALL existing data!
$(PYTHON) scripts/seed_database.py --reset
@echo Database reset and seeded
# Complete database setup (migrate + seed)
db-setup: migrate-up seed
@echo Database setup complete!
@echo Run 'make dev' to start development server
db-reset: migrate-down migrate-up seed-reset
@echo Database completely reset!
```
Add these help entries to the help section (under === DATABASE ===):
```makefile
@echo seed - Seed database with comprehensive test data
@echo seed-minimal - Seed minimal data (admin + 1 vendor)
@echo seed-reset - Reset and seed database (destructive!)
@echo db-setup - Complete database setup (migrate + seed)
@echo db-reset - Complete database reset
```
## Usage
### 1. Install the Seeder
Copy the seed_database.py file to your scripts directory:
```bash
cp seed_database.py scripts/seed_database.py
```
### 2. Run Seeding Commands
#### Option A: Full Comprehensive Seeding (Recommended for Development)
```bash
make seed
# or
python scripts/seed_database.py
```
This creates:
- 1 admin user
- 3 test users (2 vendors, 1 customer)
- 3 vendors (WIZAMART, FASHIONHUB, BOOKSTORE)
- 5 marketplace products
- 10 vendor-product links
- 4 customers
- 8 addresses
- 2 orders
- 2 import jobs
- 4 admin settings
- 2 platform alerts
#### Option B: Minimal Seeding (Quick Setup)
```bash
make seed-minimal
# or
python scripts/seed_database.py --minimal
```
This creates only:
- 1 admin user
- 1 vendor (WIZAMART)
#### Option C: Reset and Seed (Fresh Start)
```bash
make seed-reset
# or
python scripts/seed_database.py --reset
```
⚠️ **WARNING**: This DELETES ALL existing data!
#### Option D: Complete Database Setup (Migration + Seed)
```bash
make db-setup
```
This runs:
1. `make migrate-up` (apply migrations)
2. `make seed` (seed data)
## Test Data Details
### Users Created
| Username | Email | Password | Role |
|----------|-------|----------|------|
| admin | admin@wizamart.com | admin123 | admin |
| vendor1 | vendor1@example.com | password123 | vendor |
| vendor2 | vendor2@example.com | password123 | vendor |
| customer1 | customer1@example.com | password123 | customer |
### Vendors Created
| Code | Name | Subdomain | Theme | Custom Domain |
|------|------|-----------|-------|---------------|
| WIZAMART | WizaMart | wizamart | modern | wizamart.shop |
| FASHIONHUB | Fashion Hub | fashionhub | vibrant | fashionhub.store |
| BOOKSTORE | The Book Store | bookstore | classic | (none) |
### Products Created
1. **Wireless Bluetooth Headphones** - $149.99
- Brand: AudioTech
- GTIN: 1234567890123
2. **Smart Watch Pro** - $299.99
- Brand: TechWear
- GTIN: 1234567890124
3. **Portable Bluetooth Speaker** - $79.99
- Brand: AudioTech
- GTIN: 1234567890125
4. **Wireless Charging Pad** - $39.99
- Brand: ChargeMax
- GTIN: 1234567890126
5. **4K Webcam** - $129.99
- Brand: VisionTech
- GTIN: 1234567890127
### Theme Presets Available
The seeder includes 5 built-in theme presets:
1. **default** - Indigo and purple, Inter font
2. **modern** - Blue and cyan, Poppins font, transparent header
3. **classic** - Deep blue and purple, Georgia serif font
4. **vibrant** - Pink and orange, colorful background
5. **minimal** - Black and white, Helvetica font
## Features
### 1. Idempotent Operations
- Safe to run multiple times without --reset flag
- Checks for existing records before creating
- Reports what was created vs. what already existed
### 2. Comprehensive Coverage
- Tests all major database models
- Creates realistic relationships between entities
- Includes edge cases (pending orders, completed orders, etc.)
### 3. Better Output
- Beautiful formatted output with boxes and sections
- Color-coded success/info/error messages
- Detailed summary with database statistics
- Quick reference for login credentials and URLs
### 4. Command-Line Arguments
```bash
python scripts/seed_database.py [--reset] [--minimal]
--reset : Drop all data before seeding (destructive!)
--minimal : Create only essential data (admin + 1 vendor)
```
### 5. Proper Error Handling
- Verifies database is ready before seeding
- Rolls back on errors
- Provides helpful error messages
- Suggests solutions for common issues
## Testing Access
### Admin Panel
- URL: `http://localhost:8000/admin/login`
- Username: `admin`
- Password: `admin123`
### Vendor Shops
- WIZAMART: `http://localhost:8000/shop/WIZAMART`
- FASHIONHUB: `http://localhost:8000/shop/FASHIONHUB`
- BOOKSTORE: `http://localhost:8000/shop/BOOKSTORE`
### Theme Editors
- WIZAMART Theme: `http://localhost:8000/admin/vendors/WIZAMART/theme`
- FASHIONHUB Theme: `http://localhost:8000/admin/vendors/FASHIONHUB/theme`
- BOOKSTORE Theme: `http://localhost:8000/admin/vendors/BOOKSTORE/theme`
## Example Output
```
╔════════════════════════════════════════════════════════════════════╗
║ WIZAMART DATABASE SEEDER ║
╚════════════════════════════════════════════════════════════════════╝
STEP 1: Verifying database...
✓ Database tables verified
════════════════════════════════════════════════════════════════════════
COMPREHENSIVE SEEDING
════════════════════════════════════════════════════════════════════════
STEP 1: Creating users...
✓ Admin user created (ID: 1)
✓ User 'vendor1' created (ID: 2)
✓ User 'vendor2' created (ID: 3)
✓ User 'customer1' created (ID: 4)
STEP 2: Creating vendors...
✓ WIZAMART created (ID: 1)
✓ Theme 'modern' applied
✓ Custom domain 'wizamart.shop' added
✓ FASHIONHUB created (ID: 2)
✓ Theme 'vibrant' applied
✓ Custom domain 'fashionhub.store' added
✓ BOOKSTORE created (ID: 3)
✓ Theme 'classic' applied
...
════════════════════════════════════════════════════════════════════════
SEEDING SUMMARY
════════════════════════════════════════════════════════════════════════
📊 Database Statistics:
Users: 4
Vendors: 3
Vendor Themes: 3
Custom Domains: 2
Marketplace Products: 5
Vendor Products: 10
Customers: 4
Addresses: 8
Orders: 2
Order Items: 4
Import Jobs: 2
Admin Settings: 4
Platform Alerts: 2
```
## Configuration
You can customize the seeder by editing the configuration constants at the top of the file:
```python
# Admin credentials
DEFAULT_ADMIN_EMAIL = "admin@wizamart.com"
DEFAULT_ADMIN_USERNAME = "admin"
DEFAULT_ADMIN_PASSWORD = "admin123"
# Vendor configurations
VENDOR_CONFIGS = [...]
# Test users
TEST_USERS = [...]
# Sample products
SAMPLE_PRODUCTS = [...]
# Theme presets
THEME_PRESETS = {...}
```
## Migration Path from Old Seeder
If you're currently using the old seed_database.py:
1. Backup your current seeder:
```bash
mv scripts/seed_database.py scripts/seed_database.old.py
```
2. Install new seeder:
```bash
cp seed_database.py scripts/seed_database.py
```
3. Run with minimal flag first to test:
```bash
make seed-minimal
```
4. If satisfied, run full seeding:
```bash
make seed
```
## Troubleshooting
### Error: "Database not ready"
**Solution**: Run migrations first
```bash
make migrate-up
```
### Error: "Table doesn't exist"
**Solution**: Make sure all migrations are applied
```bash
alembic upgrade head
```
### Error: "Foreign key constraint failed"
**Solution**: Reset database and try again
```bash
make seed-reset
```
### Error: Import errors
**Solution**: Make sure you're in the project root and virtual environment is activated
```bash
source venv/bin/activate # Linux/Mac
venv\Scripts\activate # Windows
```
## Best Practices
1. **Development**: Use `make seed` for full test data
2. **Quick Testing**: Use `make seed-minimal` for fast setup
3. **Fresh Start**: Use `make seed-reset` when testing migrations
4. **Production**: Never run the seeder in production!
## Security Notes
⚠️ **IMPORTANT**:
- Default passwords are simple for development convenience
- Change ALL default passwords in production environments
- The admin password is intentionally weak for local development
- Never commit sensitive credentials to version control
## Future Enhancements
Consider adding:
- More diverse product categories
- Different vendor statuses (pending, suspended)
- Customer order history variations
- Failed import jobs
- More complex inventory scenarios
- Payment transactions
- Vendor subscriptions
- Product reviews and ratings

View File

@@ -0,0 +1,198 @@
# Makefile Changes - Quick Reference
## Location 1: DATABASE Section (After line 78 - after backup-db)
Add these targets:
```makefile
seed:
@echo Seeding database with comprehensive test data...
$(PYTHON) scripts/seed_database.py
@echo Seeding completed successfully
seed-minimal:
@echo Seeding database with minimal data (admin + 1 vendor)...
$(PYTHON) scripts/seed_database.py --minimal
@echo Minimal seeding completed
seed-reset:
@echo WARNING: This will DELETE ALL existing data!
$(PYTHON) scripts/seed_database.py --reset
@echo Database reset and seeded
# Complete database setup (migrate + seed)
db-setup: migrate-up seed
@echo Database setup complete!
@echo Run 'make dev' to start development server
db-reset: migrate-down migrate-up seed-reset
@echo Database completely reset!
```
## Location 2: HELP Section (Around line 270 - in DATABASE help)
Replace:
```makefile
@echo === DATABASE ===
@echo migrate-create message="msg" - Create new migration
@echo migrate-up - Apply pending migrations
@echo migrate-down - Rollback last migration
@echo migrate-status - Show migration status
@echo backup-db - Backup database
@echo.
```
With:
```makefile
@echo === DATABASE ===
@echo migrate-create message="msg" - Create new migration
@echo migrate-up - Apply pending migrations
@echo migrate-down - Rollback last migration
@echo migrate-status - Show migration status
@echo backup-db - Backup database
@echo seed - Seed database with comprehensive test data
@echo seed-minimal - Seed minimal data (admin + 1 vendor)
@echo seed-reset - Reset and seed database (destructive!)
@echo db-setup - Complete database setup (migrate + seed)
@echo db-reset - Complete database reset
@echo.
```
## Location 3: DAILY WORKFLOW Help Section (Around line 305)
Replace:
```makefile
@echo === DAILY WORKFLOW ===
@echo make dev # Start development
@echo make migrate-create message="feature" # Create migration
@echo make migrate-up # Apply migration
@echo make test # Run tests
```
With:
```makefile
@echo === DAILY WORKFLOW ===
@echo make db-setup # Setup database with data
@echo make dev # Start development
@echo make migrate-create message="feature" # Create migration
@echo make migrate-up # Apply migration
@echo make seed # Seed test data
@echo make test # Run tests
```
## Location 4: help-db target (Around line 310)
Replace:
```makefile
help-db:
@echo === DATABASE COMMANDS ===
@echo migrate-create message="description" - Create auto-generated migration
@echo migrate-create-manual message="desc" - Create empty migration template
@echo migrate-up - Apply all pending migrations
@echo migrate-down - Rollback last migration
@echo migrate-status - Show current status and history
@echo backup-db - Create database backup
@echo.
@echo TYPICAL WORKFLOW:
@echo 1. Edit your SQLAlchemy models
@echo 2. make migrate-create message="add_new_feature"
@echo 3. Review the generated migration file
@echo 4. make migrate-up
```
With:
```makefile
help-db:
@echo === DATABASE COMMANDS ===
@echo migrate-create message="description" - Create auto-generated migration
@echo migrate-create-manual message="desc" - Create empty migration template
@echo migrate-up - Apply all pending migrations
@echo migrate-down - Rollback last migration
@echo migrate-status - Show current status and history
@echo backup-db - Create database backup
@echo seed - Seed comprehensive test data
@echo seed-minimal - Seed minimal data (admin + 1 vendor)
@echo seed-reset - Reset and seed (destructive!)
@echo db-setup - Complete database setup
@echo db-reset - Complete database reset
@echo.
@echo TYPICAL WORKFLOW:
@echo 1. make db-setup # First time setup
@echo 2. Edit your SQLAlchemy models
@echo 3. make migrate-create message="add_new_feature"
@echo 4. Review the generated migration file
@echo 5. make migrate-up
@echo 6. make seed # Refresh test data if needed
```
## Update .PHONY targets (Around line 2)
Replace:
```makefile
.PHONY: install install-dev install-docs install-all dev test test-coverage lint format check docker-build docker-up docker-down clean help
```
With:
```makefile
.PHONY: install install-dev install-docs install-all dev test test-coverage lint format check docker-build docker-up docker-down clean help seed seed-minimal seed-reset db-setup db-reset
```
## Quick Copy-Paste Version
If you want to add all commands at once, here's the complete DATABASE section replacement:
```makefile
# =============================================================================
# DATABASE MIGRATIONS
# =============================================================================
migrate-create:
@if "$(message)"=="" (echo Error: Please provide a message. Usage: make migrate-create message="your_description") else ($(PYTHON) -m alembic revision --autogenerate -m "$(message)")
migrate-create-manual:
@if "$(message)"=="" (echo Error: Please provide a message. Usage: make migrate-create-manual message="your_description") else ($(PYTHON) -m alembic revision -m "$(message)")
migrate-up:
@echo Running database migrations...
$(PYTHON) -m alembic upgrade head
@echo Migrations completed successfully
migrate-down:
@echo Rolling back last migration...
$(PYTHON) -m alembic downgrade -1
@echo Rollback completed
migrate-status:
@echo Current migration status:
$(PYTHON) -m alembic current
@echo.
@echo Migration history:
$(PYTHON) -m alembic history --verbose
backup-db:
@echo Creating database backup...
@$(PYTHON) scripts/backup_database.py
seed:
@echo Seeding database with comprehensive test data...
$(PYTHON) scripts/seed_database.py
@echo Seeding completed successfully
seed-minimal:
@echo Seeding database with minimal data (admin + 1 vendor)...
$(PYTHON) scripts/seed_database.py --minimal
@echo Minimal seeding completed
seed-reset:
@echo WARNING: This will DELETE ALL existing data!
$(PYTHON) scripts/seed_database.py --reset
@echo Database reset and seeded
# Complete database setup (migrate + seed)
db-setup: migrate-up seed
@echo Database setup complete!
@echo Run 'make dev' to start development server
db-reset: migrate-down migrate-up seed-reset
@echo Database completely reset!
```

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,315 @@
# Error Handling System - Flow Diagram
## Request Processing Flow
```
┌─────────────────────────────────────────────────────────────────┐
│ Incoming HTTP Request │
└─────────────────────────────────┬───────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ Vendor Context Middleware (FIRST) │
│ - Detects vendor from domain/subdomain/path │
│ - Sets request.state.vendor │
│ - Sets request.state.vendor_context │
└─────────────────────────────────┬───────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ Context Detection Middleware (NEW) │
│ - Detects request context type │
│ - Sets request.state.context_type │
│ • API, ADMIN, VENDOR_DASHBOARD, SHOP, FALLBACK │
└─────────────────────────────────┬───────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ Route Handler Execution │
│ - Process business logic │
│ - May throw exceptions │
└─────────────────────────────────┬───────────────────────────────┘
┌─────────────┴─────────────┐
│ │
▼ ▼
┌──────────────┐ ┌──────────────┐
│ Success │ │ Exception │
│ Response │ │ Raised │
└──────────────┘ └──────┬───────┘
┌────────────────────────────────────────────────────────┐
│ Exception Handler │
│ - WizamartException │
│ - HTTPException │
│ - RequestValidationError │
│ - Generic Exception │
│ - 404 Not Found │
└────────────────────┬───────────────────────────────────┘
┌─────────────┴────────────┐
│ │
▼ ▼
┌──────────────────┐ ┌──────────────────┐
│ Special Case: │ │ General Error │
│ 401 on HTML │ │ Handling │
│ → Redirect to │ │ │
│ Login │ │ │
└──────────────────┘ └─────────┬────────┘
┌─────────────┴─────────────┐
│ │
▼ ▼
┌──────────────────┐ ┌──────────────────┐
│ API Request? │ │ HTML Request? │
│ /api/* path │ │ GET + text/html │
└────────┬─────────┘ └─────────┬────────┘
│ │
▼ ▼
┌──────────────────┐ ┌──────────────────────────┐
│ Return JSON │ │ Error Page Renderer │
│ Response │ │ │
│ { │ │ - Detect context type │
│ error_code, │ │ - Select template │
│ message, │ │ - Prepare data │
│ status_code │ │ - Render HTML │
│ } │ └──────────┬───────────────┘
└──────────────────┘ │
┌──────────────────────────────┐
│ Template Selection │
│ │
│ Priority: │
│ 1. {context}/errors/{code} │
│ 2. {context}/errors/generic│
│ 3. fallback/{code}.html │
│ 4. fallback/generic.html │
└──────────┬───────────────────┘
┌──────────────┼──────────────┐
│ │ │
▼ ▼ ▼
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Admin │ │ Vendor │ │ Shop │
│ Error │ │ Error │ │ Error │
│ Page │ │ Page │ │ Page │
│ │ │ │ │ (Themed) │
└─────────────┘ └─────────────┘ └─────────────┘
```
---
## Context Detection Logic
```
┌──────────────────────────────────────────────────────────────────┐
│ Request Arrives │
│ (host + path) │
└────────────────────────────┬─────────────────────────────────────┘
┌──────────────────┐
│ Path starts │───YES───→ API Context
│ with /api/ ? │ (Always JSON)
└────────┬─────────┘
│ NO
┌──────────────────┐
│ Host starts │───YES───→ ADMIN Context
│ with admin. │ (Admin Portal)
│ OR path starts │
│ with /admin ? │
└────────┬─────────┘
│ NO
┌──────────────────┐
│ Path starts │───YES───→ VENDOR_DASHBOARD Context
│ with /vendor/ ? │ (Vendor Management)
└────────┬─────────┘
│ NO
┌──────────────────┐
│ Vendor object │───YES───→ SHOP Context
│ in request │ (Customer Storefront)
│ state? │
└────────┬─────────┘
│ NO
┌──────────────────┐
│ FALLBACK │
│ Context │
│ (Unknown) │
└──────────────────┘
```
---
## Template Selection Example
For a 404 error in ADMIN context:
```
1. Check: app/templates/admin/errors/404.html ✓ EXISTS → USE THIS
2. Check: app/templates/admin/errors/generic.html (skipped)
3. Check: app/templates/fallback/404.html (skipped)
4. Check: app/templates/fallback/generic.html (skipped)
```
For a 429 error in SHOP context (not created yet):
```
1. Check: app/templates/shop/errors/429.html ✗ Missing
2. Check: app/templates/shop/errors/generic.html ✗ Missing
3. Check: app/templates/fallback/429.html ✗ Missing
4. Check: app/templates/fallback/generic.html ✓ EXISTS → USE THIS
```
---
## Error Response Types
```
┌──────────────────────────────────────────────────────────────────┐
│ Request Type │
└───────────┬─────────────┬───────────────────┬─────────────────────┘
│ │ │
▼ ▼ ▼
┌────────────┐ ┌────────────┐ ┌──────────────┐
│ API │ │ HTML Page │ │ 401 on HTML │
│ Request │ │ Request │ │ Page │
└──────┬─────┘ └──────┬─────┘ └──────┬───────┘
│ │ │
▼ ▼ ▼
┌────────────┐ ┌────────────┐ ┌──────────────┐
│ JSON │ │ Rendered │ │ Redirect │
│ Response │ │ HTML │ │ to Login │
│ │ │ Error │ │ │
│ { │ │ Page │ │ 302 Found │
│ error_code│ │ │ │ Location: │
│ message │ │ Context- │ │ /admin/login│
│ status │ │ aware │ │ /vendor/login│
│ details │ │ template │ │ /shop/login │
│ } │ │ │ │ │
└────────────┘ └────────────┘ └──────────────┘
```
---
## Example Scenarios
### Scenario 1: API 404 Error
```
Request: GET /api/v1/admin/vendors/999
Context: API
Result: JSON { "error_code": "VENDOR_NOT_FOUND", ... }
```
### Scenario 2: Admin Page 404 Error
```
Request: GET /admin/nonexistent
Accept: text/html
Context: ADMIN
Result: HTML admin/errors/404.html
```
### Scenario 3: Shop Page 500 Error
```
Request: GET /products/123 (on vendor1.platform.com)
Accept: text/html
Context: SHOP (vendor detected)
Result: HTML shop/errors/500.html (with vendor theme)
```
### Scenario 4: Unauthorized Access to Admin
```
Request: GET /admin/settings
Accept: text/html
No valid session
Context: ADMIN
Result: 302 Redirect to /admin/login
```
---
## Debug Information Display
```
┌──────────────────────────────────────────────────────────────┐
│ Error Page Display │
└──────────────────────┬───────────────────────────────────────┘
┌───────────┴───────────┐
│ │
▼ ▼
┌──────────────┐ ┌──────────────┐
│ Admin User │ │ Other Users │
│ (Context: │ │ (Vendor, │
│ ADMIN) │ │ Shop) │
└──────┬───────┘ └──────┬───────┘
│ │
▼ ▼
┌──────────────┐ ┌──────────────┐
│ Debug Info │ │ No Debug │
│ SHOWN: │ │ Info: │
│ • Path │ │ │
│ • Error code │ │ Only user- │
│ • Details │ │ friendly │
│ • Stack │ │ message │
└──────────────┘ └──────────────┘
```
---
## File Organization
```
app/
├── exceptions/
│ ├── handler.py # Exception handlers (refactored)
│ ├── error_renderer.py # NEW: Renders error pages
│ └── base.py # Base exceptions
├── templates/
│ ├── admin/
│ │ └── errors/ # NEW: Admin error pages
│ │ ├── base.html # Base template
│ │ ├── 404.html # Specific errors
│ │ └── generic.html # Catch-all
│ │
│ ├── vendor/
│ │ └── errors/ # TODO: Vendor error pages
│ │
│ ├── shop/
│ │ └── errors/ # TODO: Shop error pages (themed)
│ │
│ └── fallback/
│ └── (minimal pages) # NEW: Unknown context fallback
middleware/
├── vendor_context.py # Vendor detection (existing)
├── context_middleware.py # NEW: Context detection
└── theme_context.py # Theme loading (existing)
```
---
## Benefits Summary
**Separation of Concerns**: HTML templates separate from handler logic
**Context-Aware**: Different error pages for different areas
**Maintainable**: Easy to update individual error pages
**Scalable**: Easy to add new contexts or error types
**Professional**: Polished error pages matching area design
**Flexible**: Fallback mechanism ensures errors always render
**Secure**: Debug info only shown to admins
**Themed**: Shop errors can use vendor branding (Phase 3)
---
This flow ensures that:
1. API calls ALWAYS get JSON responses
2. HTML page requests get appropriate error pages
3. Each context (admin/vendor/shop) has its own error design
4. Fallback mechanism prevents broken error pages
5. 401 errors redirect to appropriate login pages

View File

@@ -0,0 +1,423 @@
# Naming Conventions
**Version:** 1.0
**Last Updated:** November 2025
**Audience:** Development Team
---
## Overview
This document establishes consistent naming conventions across the entire Wizamart multi-tenant ecommerce platform. Consistent naming improves code readability, reduces developer confusion, and ensures maintainable architecture.
## Core Principles
### 1. Context-Based Naming
- **Collections/Endpoints**: Use PLURAL (handle multiple items)
- **Entities/Models**: Use SINGULAR (represent individual items)
- **Domains/Services**: Use SINGULAR (focus on one domain area)
### 2. Terminology Standardization
- Use **"inventory"** not "stock" (more business-friendly)
- Use **"vendor"** not "shop" (multi-tenant architecture)
- Use **"customer"** not "user" for end customers (clarity)
### 3. File Naming Patterns
- **API files**: `entities.py` (plural)
- **Model files**: `entity.py` (singular)
- **Service files**: `entity_service.py` (singular + service)
- **Exception files**: `entity.py` (singular domain)
---
## Detailed Naming Rules
### API Endpoint Files (PLURAL)
**Rule**: API files handle collections of resources, so use plural names.
**Location**: `app/api/v1/*/`
**Examples**:
```
app/api/v1/admin/
├── vendors.py # Handles multiple vendors
├── users.py # Handles multiple users
└── dashboard.py # Exception: not a resource collection
app/api/v1/vendor/
├── products.py # Handles vendor's products
├── orders.py # Handles vendor's orders
├── customers.py # Handles vendor's customers
├── teams.py # Handles team members
├── inventory.py # Handles inventory items
└── settings.py # Exception: not a resource collection
app/api/v1/public/vendors/
├── products.py # Public product catalog
├── orders.py # Order placement
└── auth.py # Exception: authentication service
```
**Rationale**: REST endpoints typically operate on collections (`GET /products`, `POST /orders`).
### Database Model Files (SINGULAR)
**Rule**: Model files represent individual entity definitions, so use singular names.
**Location**: `models/database/`
**Examples**:
```
models/database/
├── user.py # User, UserProfile classes
├── vendor.py # Vendor, VendorUser, Role classes
├── customer.py # Customer, CustomerAddress classes
├── product.py # Product, ProductVariant classes
├── order.py # Order, OrderItem classes
├── inventory.py # Inventory, InventoryMovement classes
├── marketplace.py # MarketplaceImportJob class
└── admin.py # Admin-specific models
```
**Class Names Within Files**:
```python
# models/database/product.py
class Product(Base): # Singular
class ProductVariant(Base): # Singular
# models/database/inventory.py
class Inventory(Base): # Singular
class InventoryMovement(Base): # Singular
```
**Rationale**: Each model class represents a single entity instance in the database.
### Schema/Pydantic Model Files (SINGULAR)
**Rule**: Schema files define validation for individual entities, so use singular names.
**Location**: `models/schema/`
**Examples**:
```
models/schema/
├── user.py # UserCreate, UserResponse classes
├── vendor.py # VendorCreate, VendorResponse classes
├── customer.py # CustomerCreate, CustomerResponse classes
├── product.py # ProductCreate, ProductResponse classes
├── order.py # OrderCreate, OrderResponse classes
├── inventory.py # InventoryCreate, InventoryResponse classes
├── marketplace.py # MarketplaceImportRequest class
└── admin.py # Admin operation schemas
```
**Class Names Within Files**:
```python
# models/schema/product.py
class ProductCreate(BaseModel): # Singular entity
class ProductUpdate(BaseModel): # Singular entity
class ProductResponse(BaseModel): # Singular entity
```
**Rationale**: Schema models validate individual entity data structures.
### Service Files (SINGULAR + "service")
**Rule**: Service files handle business logic for one domain area, so use singular + "service".
**Location**: `services/`
**Examples**:
```
services/
├── auth_service.py # Authentication domain
├── admin_service.py # Admin operations domain
├── vendor_service.py # Vendor management domain
├── customer_service.py # Customer operations domain
├── team_service.py # Team management domain
├── product_service.py # Product operations domain
├── order_service.py # Order operations domain
├── inventory_service.py # Inventory operations domain
├── marketplace_service.py # Marketplace integration domain
└── stats_service.py # Statistics domain
```
**Class Names Within Files**:
```python
# services/product_service.py
class ProductService: # Singular domain focus
def create_product() # Operates on single product
def get_products() # Can return multiple, but service is singular
```
**Rationale**: Each service focuses on one business domain area.
### Exception Files (SINGULAR)
**Rule**: Exception files handle errors for one domain area, so use singular names.
**Location**: `app/exceptions/`
**Examples**:
```
app/exceptions/
├── base.py # Base exception classes
├── handler.py # Exception handlers
├── auth.py # Authentication domain exceptions
├── admin.py # Admin domain exceptions
├── vendor.py # Vendor domain exceptions
├── customer.py # Customer domain exceptions
├── product.py # Product domain exceptions
├── order.py # Order domain exceptions
├── inventory.py # Inventory domain exceptions
└── marketplace.py # Marketplace domain exceptions
```
**Class Names Within Files**:
```python
# app/exceptions/product.py
class ProductNotFoundException(ResourceNotFoundException):
class ProductAlreadyExistsException(ConflictException):
class ProductValidationException(ValidationException):
```
**Rationale**: Exception files are domain-focused, not collection-focused.
### Middleware Files (DESCRIPTIVE)
**Rule**: Middleware files use descriptive names based on their function.
**Location**: `middleware/`
**Examples**:
```
middleware/
├── auth.py # Authentication middleware
├── vendor_context.py # Vendor context detection
├── rate_limiter.py # Rate limiting functionality
├── logging_middleware.py # Request logging
└── decorators.py # Cross-cutting decorators
```
**Rationale**: Middleware serves specific cross-cutting functions.
### Frontend Files
**Rule**: Frontend files use context-appropriate naming.
**Location**: `frontend/`
**Examples**:
```
frontend/
├── admin/
│ ├── vendors.html # PLURAL - lists multiple vendors
│ ├── users.html # PLURAL - lists multiple users
│ └── dashboard.html # SINGULAR - one dashboard
├── vendor/admin/
│ ├── products.html # PLURAL - lists multiple products
│ ├── orders.html # PLURAL - lists multiple orders
│ ├── teams.html # PLURAL - lists team members
│ └── dashboard.html # SINGULAR - one dashboard
└── shop/
├── products.html # PLURAL - product catalog
├── product.html # SINGULAR - single product detail
├── orders.html # PLURAL - order history
└── cart.html # SINGULAR - one shopping cart
```
**Rationale**:
- List views are plural (show collections)
- Detail views are singular (show individual items)
- Functional views use descriptive names
---
## Terminology Standards
### Core Business Terms
| Use This | Not This | Context |
|----------|----------|---------|
| inventory | stock | All inventory management |
| vendor | shop | Multi-tenant architecture |
| customer | user | End customers (buyers) |
| user | member | Platform/vendor team members |
| team | staff | Vendor team members |
| order | purchase | Customer orders |
| product | item | Catalog products |
### Database Naming
**Table Names**: Use singular, lowercase with underscores
```sql
-- ✅ Correct
inventory
inventory_movements
vendor_users
-- ❌ Incorrect
inventories
inventory_movement
vendorusers
```
**Column Names**: Use singular, descriptive names
```sql
-- ✅ Correct
vendor_id
inventory_level
created_at
-- ❌ Incorrect
vendors_id
inventory_levels
creation_time
```
### API Endpoint Patterns
**Resource Collections**: Use plural nouns
```
GET /api/v1/vendor/products # List products
POST /api/v1/vendor/products # Create product
GET /api/v1/vendor/orders # List orders
POST /api/v1/vendor/orders # Create order
```
**Individual Resources**: Use singular in URL structure
```
GET /api/v1/vendor/products/{id} # Get single product
PUT /api/v1/vendor/products/{id} # Update single product
DELETE /api/v1/vendor/products/{id} # Delete single product
```
**Non-Resource Endpoints**: Use descriptive names
```
GET /api/v1/vendor/dashboard/stats # Dashboard statistics
POST /api/v1/vendor/auth/login # Authentication
GET /api/v1/vendor/settings # Vendor settings
```
---
## Variable and Function Naming
### Function Names
```python
# ✅ Correct - verb + singular object
def create_product()
def get_customer()
def update_order()
def delete_inventory_item()
# ✅ Correct - verb + plural when operating on collections
def get_products()
def list_customers()
def bulk_update_orders()
# ❌ Incorrect
def create_products() # Creates one product
def get_customers() # Gets one customer
```
### Variable Names
```python
# ✅ Correct - context-appropriate singular/plural
product = get_product(id)
products = get_products()
customer_list = get_all_customers()
inventory_count = len(inventory_items)
# ❌ Incorrect
products = get_product(id) # Single item, should be singular
product = get_products() # Multiple items, should be plural
```
### Class Attributes
```python
# ✅ Correct - descriptive and consistent
class Vendor:
id: int
name: str
subdomain: str
owner_user_id: int # Singular reference
created_at: datetime
class Customer:
vendor_id: int # Belongs to one vendor
total_orders: int # Aggregate count
last_order_date: datetime # Most recent
```
---
## Benefits of Consistent Naming
1. **Developer Productivity**: Predictable file locations and naming patterns
2. **Code Readability**: Clear understanding of file purposes and contents
3. **Team Communication**: Shared vocabulary and terminology
4. **Maintenance**: Easier to locate and update related functionality
5. **Onboarding**: New developers quickly understand the codebase structure
6. **Documentation**: Consistent terminology across all documentation
7. **API Usability**: Predictable and intuitive API endpoint structures
---
## Enforcement
### Code Review Checklist
- [ ] File names follow singular/plural conventions
- [ ] Class names use appropriate terminology (inventory vs stock)
- [ ] API endpoints use plural resource names
- [ ] Database models use singular names
- [ ] Variables names match their content (singular vs plural)
### Automated Checks
Consider implementing linting rules or pre-commit hooks to enforce:
- File naming patterns
- Import statement consistency
- Variable naming conventions
- API endpoint patterns
---
## Quick Reference Table
| Component | Naming | Example |
|-----------|--------|---------|
| API Endpoint Files | PLURAL | `products.py`, `orders.py` |
| Database Models | SINGULAR | `product.py`, `order.py` |
| Schema/Pydantic | SINGULAR | `product.py`, `order.py` |
| Services | SINGULAR + service | `product_service.py` |
| Exceptions | SINGULAR | `product.py`, `order.py` |
| Middleware | DESCRIPTIVE | `auth.py`, `rate_limiter.py` |
| Database Tables | SINGULAR | `product`, `inventory` |
| Database Columns | SINGULAR | `vendor_id`, `created_at` |
| API Endpoints | PLURAL | `/products`, `/orders` |
| Functions (single) | SINGULAR | `create_product()` |
| Functions (multiple) | PLURAL | `get_products()` |
| Variables (single) | SINGULAR | `product = ...` |
| Variables (multiple) | PLURAL | `products = ...` |
---
## Related Documentation
- [Contributing Guide](contributing.md) - Development workflow
- [Backend Development](../backend/overview.md) - Backend development guide
- [Architecture Overview](../architecture/overview.md) - System architecture
---
**Document Version:** 1.0
**Last Updated:** November 2025
**Maintained By:** Backend Team
This naming convention guide ensures consistent, maintainable, and intuitive code across the entire Wizamart multi-tenant ecommerce platform.

View File

@@ -1 +1,398 @@
*This documentation is under development.*
# PyCharm Troubleshooting Guide
Common PyCharm issues and their solutions for the development team.
---
## Table of Contents
- [Go to Declaration Not Working (Ctrl+B)](#go-to-declaration-not-working-ctrlb)
- [Import Errors and Red Underlines](#import-errors-and-red-underlines)
- [Python Interpreter Issues](#python-interpreter-issues)
- [Debugging Not Working](#debugging-not-working)
- [Performance Issues](#performance-issues)
- [Git Integration Issues](#git-integration-issues)
- [Database Tool Issues](#database-tool-issues)
---
## Go to Declaration Not Working (Ctrl+B)
### Problem
When you press **Ctrl+B** (or Cmd+B on Mac) on a function, class, or variable, PyCharm shows:
- "Cannot find declaration to go to"
- No navigation occurs
- Imports are marked as unresolved even though code runs fine
**Example:**
```python
from app.services.admin_audit_service import admin_audit_service
# Ctrl+B on get_audit_logs doesn't work
logs = admin_audit_service.get_audit_logs(db, filters)
```
### Solution 1: Configure Source Roots (Most Common Fix)
PyCharm needs to know your project structure:
1. **Mark project root as Sources Root:**
- Right-click on project root folder (`letzshop-product-import`)
- Select **"Mark Directory as"** → **"Sources Root"**
- The folder icon should turn blue
2. **Via Project Structure settings:**
- **File** → **Settings** (Ctrl+Alt+S)
- Navigate to **Project: letzshop-product-import****Project Structure**
- Select your project root directory
- Click the **"Sources"** button at the top
- Click **Apply****OK**
3. **Verify the change:**
- Your project root should now have a blue folder icon
- The `.idea` folder should show the source root is configured
### Solution 2: Verify Python Interpreter
Ensure PyCharm is using the correct virtual environment:
1. **Check current interpreter:**
- **File** → **Settings****Project****Python Interpreter**
- Should show: `/home/samir/PycharmProjects/letzshop-product-import/.venv/bin/python`
2. **If wrong interpreter:**
- Click the gear icon → **Add**
- Select **"Existing environment"**
- Navigate to: `[PROJECT_ROOT]/.venv/bin/python`
- Click **OK**
3. **Wait for indexing:**
- Bottom right corner will show "Indexing..."
- Wait for it to complete before testing
### Solution 3: Invalidate Caches
PyCharm's index might be corrupted:
1. **File****Invalidate Caches...**
2. Select all checkboxes:
- ✅ Invalidate and Restart
- ✅ Clear file system cache and Local History
- ✅ Clear downloaded shared indexes
3. Click **"Invalidate and Restart"**
4. **Wait 2-5 minutes** for re-indexing after restart
### Solution 4: Reimport Project
If nothing else works, rebuild the project structure:
1. **Close PyCharm**
2. **Delete PyCharm's cache folder:**
```bash
rm -rf .idea/
```
3. **Reopen project in PyCharm:**
- **File** → **Open**
- Select project folder
- Let PyCharm recreate `.idea/` folder
4. **Reconfigure:**
- Set Python interpreter
- Mark source roots
- Wait for indexing
### Solution 5: Check .idea/workspace.xml
Sometimes workspace configuration gets corrupted:
```bash
# Close PyCharm first
rm .idea/workspace.xml
# Reopen PyCharm - it will regenerate this file
```
---
## Import Errors and Red Underlines
### Problem
Imports show red underlines and errors like:
- "Unresolved reference"
- "No module named 'app'"
- Code runs fine but PyCharm shows errors
### Solution
1. **Check Sources Root** (see above)
2. **Verify `__init__.py` files exist:**
```bash
# All package directories need __init__.py
ls -la app/__init__.py
ls -la app/services/__init__.py
ls -la app/api/__init__.py
```
3. **Add project root to PYTHONPATH:**
- **File** → **Settings** → **Project** → **Project Structure**
- Right-click project root → **"Mark as Sources Root"**
4. **Enable namespace packages** (if using PEP 420):
- **File** → **Settings** → **Editor** → **Code Style** → **Python**
- Check "Support namespace packages"
---
## Python Interpreter Issues
### Problem
- "No Python interpreter configured"
- Wrong Python version
- Missing packages even though they're installed
### Solution
1. **Verify virtual environment:**
```bash
# In terminal
which python # Should show .venv/bin/python
python --version # Should show Python 3.13.x
```
2. **Configure in PyCharm:**
- **File** → **Settings** → **Project** → **Python Interpreter**
- Click gear icon → **Add**
- Select **"Existing Environment"**
- Choose: `[PROJECT_ROOT]/.venv/bin/python`
3. **Refresh interpreter packages:**
- In Python Interpreter settings
- Click refresh icon (⟳)
- Wait for packages to reload
4. **Reinstall packages if needed:**
```bash
source .venv/bin/activate
pip install -r requirements.txt
pip install -r requirements-dev.txt
```
---
## Debugging Not Working
### Problem
- Breakpoints are grayed out
- Debugger doesn't stop at breakpoints
- "Debugger is not attached"
### Solution 1: Check Run Configuration
1. **Edit configuration:**
- Top right → Edit Configurations
- Should use "Python" configuration type
- Script path should point to your main file
- Interpreter should be your virtual environment
2. **For FastAPI/Uvicorn:**
- Module: `uvicorn`
- Parameters: `main:app --reload`
- Working directory: Project root
### Solution 2: Enable Gevent/Asyncio Support
For async code (FastAPI):
1. **File** → **Settings** → **Build, Execution, Deployment** → **Python Debugger**
2. Check **"Gevent compatible"** or **"Asyncio compatible"**
3. Restart debugger
### Solution 3: Check Breakpoint Settings
Right-click on breakpoint (red dot):
- Ensure "Enabled" is checked
- Check "Suspend" is set to "All"
- Remove any conditions if not needed
---
## Performance Issues
### Problem
- PyCharm is slow or freezing
- High CPU/memory usage
- Indexing takes forever
### Solution 1: Exclude Unnecessary Directories
Exclude directories PyCharm doesn't need to index:
1. **File** → **Settings** → **Project** → **Project Structure**
2. **Mark as "Excluded":**
- `.venv` (if not already)
- `node_modules`
- `.pytest_cache`
- `__pycache__`
- `htmlcov`
- `site` (mkdocs build output)
3. **Right-click these folders in Project view:**
- **Mark Directory as** → **Excluded**
### Solution 2: Increase Memory
1. **Help** → **Change Memory Settings**
2. Increase heap size to **2048 MB** or higher
3. Restart PyCharm
### Solution 3: Disable Unused Plugins
1. **File** → **Settings** → **Plugins**
2. Disable plugins you don't use
3. Keep essential: Python, Git, Database, Markdown
4. Restart PyCharm
### Solution 4: Pause Indexing
If you need to work immediately:
1. **File** → **Pause Indexing**
2. Do your work
3. **Resume Indexing** when convenient
---
## Git Integration Issues
### Problem
- Git operations fail
- "Cannot run git" errors
- Changes not detected
### Solution 1: Configure Git Executable
1. **File** → **Settings** → **Version Control** → **Git**
2. **Path to Git executable:**
- Linux/Mac: `/usr/bin/git`
- Windows: `C:\Program Files\Git\bin\git.exe`
3. Click **"Test"** to verify
4. Click **OK**
### Solution 2: Check Git Root
1. **File** → **Settings** → **Version Control**
2. Verify your project root is listed
3. If missing, click **+** and add it
### Solution 3: Refresh VCS
1. **VCS** → **Refresh File Status**
2. Or: **Git** → **Refresh**
3. Or press: **Ctrl+F5**
---
## Database Tool Issues
### Problem
- Can't connect to PostgreSQL database
- "Connection refused" errors
- Tables not showing
### Solution 1: Verify Database Connection
1. **Database** tool window (usually right side)
2. Click **+** → **Data Source** → **PostgreSQL**
3. **Configure:**
```
Host: localhost
Port: 5432
Database: letzshop_db
User: [from .env file]
Password: [from .env file]
```
4. Click **"Test Connection"**
5. Download drivers if prompted
### Solution 2: Check Database is Running
```bash
# Check if PostgreSQL is running
sudo systemctl status postgresql
# Start if not running
sudo systemctl start postgresql
```
### Solution 3: Verify .env Configuration
```bash
# Check your .env file
cat .env | grep DATABASE
# Should show something like:
DATABASE_URL=postgresql://user:password@localhost:5432/letzshop_db
```
---
## Quick Checklist for New Developers
When setting up PyCharm for the first time:
- [ ] Clone repository
- [ ] Create virtual environment: `python -m venv .venv`
- [ ] Activate: `source .venv/bin/activate`
- [ ] Install dependencies: `pip install -r requirements.txt`
- [ ] Open project in PyCharm
- [ ] Configure Python interpreter (`.venv/bin/python`)
- [ ] Mark project root as Sources Root
- [ ] Exclude `.venv`, `.pytest_cache`, `__pycache__` directories
- [ ] Configure Git executable
- [ ] Configure database connection
- [ ] Wait for indexing to complete
- [ ] Test: Ctrl+B on an import should work
---
## Still Having Issues?
### Check PyCharm Logs
1. **Help** → **Show Log in Explorer/Finder**
2. Look for errors in `idea.log`
3. Search for "ERROR" or "Exception"
### Enable Debug Logging
1. **Help** → **Diagnostic Tools** → **Debug Log Settings**
2. Add: `#com.intellij.python`
3. Reproduce the issue
4. Check logs
### Report to Team
If the issue persists:
1. Screenshot the error
2. Share PyCharm version: **Help** → **About**
3. Share Python version: `python --version`
4. Share OS: `uname -a` (Linux/Mac) or `ver` (Windows)
5. Post in team chat with:
- What you were trying to do
- What error you got
- What you've tried so far
---
## Related Documentation
- [PyCharm Make Configuration](pycharm-configuration-make.md) - Configure Make with virtual environment
- [Contributing Guide](contributing.md) - Development workflow
- [Database Migrations](database-migrations.md) - Working with Alembic