[INIT-001] Initial project setup with Clean Architecture (feat)
Some checks failed
CD - Build & Deploy / build-and-push (push) Has been cancelled
CD - Build & Deploy / package-helm (push) Has been cancelled
CD - Build & Deploy / deploy-staging (push) Has been cancelled
CD - Build & Deploy / deploy-production (push) Has been cancelled
CD - Build & Deploy / release (push) Has been cancelled
CI / test (3.11) (push) Has been cancelled
CI / test (3.12) (push) Has been cancelled
CI / security (push) Has been cancelled

- Implemented Clean Architecture with Domain, Application, Infrastructure, Presentation layers
- Added comprehensive project structure following SOLID principles
- Created Kubernetes deployment with Helm charts (HPA, PDB, NetworkPolicy)
- Configured ArgoCD for automated deployment (production + staging)
- Implemented CI/CD pipeline with GitHub Actions
- Added comprehensive documentation (handbook, architecture, coding standards)
- Configured PostgreSQL, Redis, Celery for backend services
- Created modern landing page with Persian fonts (Vazirmatn)
- Added Docker multi-stage build for production
- Configured development tools (pytest, black, flake8, mypy, isort)
- Added pre-commit hooks for code quality
- Implemented Makefile for common operations
This commit is contained in:
Ehsan.Asadi
2025-12-26 15:52:50 +03:30
commit 8a924f6091
135 changed files with 8637 additions and 0 deletions

View File

@@ -0,0 +1,386 @@
# استانداردهای کدنویسی
## اصول کلی
### 1. کد تمیز (Clean Code)
کد باید:
- خوانا باشد
- ساده باشد
- قابل فهم باشد
- قابل نگهداری باشد
### 2. PEP 8 Compliance
**الزامی**: تمام کدها باید با PEP 8 مطابقت داشته باشند.
استفاده از ابزارها:
```bash
black src/ # Auto-formatting
flake8 src/ # Linting
isort src/ # Import sorting
```
## قوانین Naming
### Classes
```python
# ✅ GOOD: PascalCase
class UserService:
pass
class PaymentGateway:
pass
class DatabaseConnection:
pass
# ❌ BAD
class user_service: # Wrong case
class payment_gateway_service: # Too long
class UServ: # Unclear abbreviation
```
### Functions & Methods
```python
# ✅ GOOD: snake_case, descriptive
def calculate_total_price(items: List[Item]) -> Decimal:
pass
def send_welcome_email(user: User) -> bool:
pass
# ❌ BAD
def calcTotPrice(): # Mixed case
def cp(): # Not descriptive
def calculate(): # Too vague
```
### Variables
```python
# ✅ GOOD
user_email = "test@example.com"
total_amount = Decimal("100.00")
is_active = True
MAX_ATTEMPTS = 3 # Constant
# ❌ BAD
e = "test@example.com" # Too short
userEmail = "test@example.com" # camelCase
TOTAL = 100 # Constant style for variable
```
## Type Hints
**الزامی**: همه function signatures باید type hints داشته باشند.
```python
from typing import Optional, List, Dict, Any
from decimal import Decimal
# ✅ GOOD
def get_user(user_id: int) -> Optional[User]:
pass
def create_invoice(
user_id: int,
amount: Decimal,
items: List[InvoiceItem]
) -> Invoice:
pass
# ❌ BAD
def get_user(user_id): # No types
pass
def create_invoice(user_id, amount, items): # No types
pass
```
## Docstrings
**الزامی**: همه public functions, classes, و methods باید docstring داشته باشند.
### Google Style (استاندارد پروژه)
```python
def create_user(
email: str,
password: str,
full_name: str
) -> User:
"""Create a new user account.
Args:
email: User's email address
password: Plain text password
full_name: User's full name
Returns:
User: Created user object
Raises:
EmailAlreadyExistsException: If email exists
WeakPasswordException: If password is weak
Example:
>>> user = create_user(
... email="test@example.com",
... password="SecurePass123!",
... full_name="John Doe"
... )
"""
pass
```
## Error Handling
### Use Specific Exceptions
```python
# ✅ GOOD
try:
user = user_repository.get_by_id(user_id)
if not user:
raise UserNotFoundException(f"User {user_id} not found")
except DatabaseException as e:
logger.error("database_error", error=str(e))
raise
except Exception as e:
logger.critical("unexpected_error", error=str(e))
raise
# ❌ BAD
try:
user = get_user(user_id)
except: # Never use bare except!
pass
try:
user = get_user(user_id)
except Exception: # Too broad
pass
```
### Custom Exception Hierarchy
```python
class PeikarbandException(Exception):
"""Base exception."""
pass
class DomainException(PeikarbandException):
"""Domain layer exceptions."""
pass
class UserNotFoundException(DomainException):
"""User not found."""
pass
```
## Code Organization
### Imports
```python
# 1. Standard library
import os
import sys
from typing import Optional, List
from decimal import Decimal
# 2. Third-party
import redis
from sqlalchemy import Column, Integer
from pydantic import BaseModel
# 3. Local
from src.config.settings import settings
from src.core.domain.entities.user import User
```
### Function Length
**Max 50 lines per function** (توصیه: 20-30 lines)
```python
# ✅ GOOD: Short and focused
def calculate_discount(amount: Decimal, user: User) -> Decimal:
"""Calculate user discount."""
if user.is_premium:
return amount * Decimal("0.10")
return Decimal("0.00")
# ❌ BAD: Too long (100+ lines)
def process_order(order_data):
# 100+ lines of code
pass
```
### Class Length
**Max 300 lines per class** (توصیه: 100-200 lines)
اگر class بزرگ شد، به چند class کوچکتر تقسیم کنید.
## Comments
### When to Comment
```python
# ✅ GOOD: Explain WHY, not WHAT
def calculate_tax(amount: Decimal) -> Decimal:
# Iranian tax rate is 9% as of 2024
TAX_RATE = Decimal("0.09")
return amount * TAX_RATE
# ❌ BAD: States the obvious
def add(a, b):
# Add two numbers
return a + b
```
### TODO Comments
```python
# TODO(username): Description of what needs to be done
# TODO(john): Implement caching for this query
# FIXME(jane): This breaks when amount is negative
# HACK(bob): Temporary workaround until API is fixed
```
## Best Practices
### 1. Single Responsibility
```python
# ✅ GOOD
class UserRepository:
def save(self, user: User) -> User:
pass
class EmailService:
def send_email(self, to: str, subject: str) -> bool:
pass
# ❌ BAD
class UserManager:
def save_user(self, user):
pass
def send_email(self, user):
pass
def log_activity(self, user):
pass
```
### 2. DRY (Don't Repeat Yourself)
```python
# ❌ BAD
def get_user_name(user_id):
db = connect_db()
user = db.query(User).filter_by(id=user_id).first()
db.close()
return user.name
def get_user_email(user_id):
db = connect_db()
user = db.query(User).filter_by(id=user_id).first()
db.close()
return user.email
# ✅ GOOD
def get_user(user_id: int) -> Optional[User]:
with get_db_context() as db:
return db.query(User).filter_by(id=user_id).first()
def get_user_name(user_id: int) -> Optional[str]:
user = get_user(user_id)
return user.name if user else None
```
### 3. Early Return
```python
# ✅ GOOD: Early return
def process_payment(amount: Decimal) -> bool:
if amount <= 0:
return False
if not user.has_sufficient_balance(amount):
return False
# Process payment
return True
# ❌ BAD: Nested conditions
def process_payment(amount):
if amount > 0:
if user.has_sufficient_balance(amount):
# Process payment
return True
return False
```
### 4. Use Constants
```python
# ✅ GOOD
MAX_LOGIN_ATTEMPTS = 3
PASSWORD_MIN_LENGTH = 8
SESSION_TIMEOUT_MINUTES = 30
if attempts >= MAX_LOGIN_ATTEMPTS:
lock_account()
# ❌ BAD: Magic numbers
if attempts >= 3: # What's 3?
lock_account()
```
### 5. Avoid Deep Nesting
```python
# ✅ GOOD: Max 2-3 levels
def process_order(order: Order) -> bool:
if not order.is_valid():
return False
if not user.can_order():
return False
return save_order(order)
# ❌ BAD: Too nested
def process_order(order):
if order:
if order.is_valid():
if user:
if user.can_order():
if save_order(order):
return True
return False
```
## Code Review Checklist
قبل از ارسال PR، این موارد را بررسی کنید:
- [ ] همه تست‌ها pass می‌شوند
- [ ] Code coverage کافی است (>80%)
- [ ] تمام functions دارای type hints هستند
- [ ] تمام public functions دارای docstring هستند
- [ ] black, flake8, mypy بدون error
- [ ] هیچ TODO/FIXME جدید بدون توضیح نیست
- [ ] تغییرات در CHANGELOG.md ثبت شده
- [ ] مستندات به‌روز شده
---
**الزامات**: این استانداردها الزامی هستند و در code review بررسی می‌شوند.

View File

@@ -0,0 +1,433 @@
# Git Workflow
## Branch Strategy
### Main Branches
```
main (production)
└── develop (staging)
```
- **main**: Production-ready code
- **develop**: Integration branch for features
### Supporting Branches
```
develop
├── feature/user-authentication
├── feature/billing-system
├── bugfix/payment-timeout
└── hotfix/security-patch
```
## Branch Naming Convention
### Feature Branches
```
feature/short-description
feature/user-auth
feature/payment-gateway
```
### Bugfix Branches
```
bugfix/issue-description
bugfix/payment-timeout
bugfix/email-sending
```
### Hotfix Branches
```
hotfix/critical-issue
hotfix/security-vuln
hotfix/data-loss
```
## Commit Message Format
### Structure
```
<type>(<scope>): <subject>
<body>
<footer>
```
### Type
- `feat`: ویژگی جدید
- `fix`: رفع باگ
- `docs`: تغییرات مستندات
- `style`: فرمت‌بندی، فاصله‌گذاری
- `refactor`: بازنویسی کد
- `perf`: بهبود performance
- `test`: اضافه/اصلاح تست
- `chore`: کارهای نگهداری
- `build`: تغییرات build system
- `ci`: تغییرات CI/CD
### Scope
بخشی از کد که تغییر کرده:
- `auth`
- `billing`
- `api`
- `database`
- `ui`
### Examples
```bash
feat(auth): add two-factor authentication
- Implement TOTP-based 2FA
- Add QR code generation
- Add backup codes
Closes #123
```
```bash
fix(payment): resolve timeout issue with zarinpal
The payment gateway was timing out due to long response time.
Added retry logic with exponential backoff.
Fixes #456
```
```bash
docs(api): update authentication endpoints
Added examples for JWT token usage and refresh flow.
```
## Workflow Steps
### 1. شروع کار روی Feature جدید
```bash
# بروزرسانی develop
git checkout develop
git pull origin develop
# ایجاد branch جدید
git checkout -b feature/my-feature
# شروع کدنویسی...
```
### 2. Commit های منظم
```bash
# بررسی تغییرات
git status
git diff
# Stage کردن
git add src/specific/file.py
# یا
git add .
# Commit
git commit -m "feat(scope): description"
# Push (اولین بار)
git push -u origin feature/my-feature
# Push های بعدی
git push
```
### 3. نگهداری Branch به‌روز
```bash
# بروزرسانی از develop
git checkout develop
git pull origin develop
git checkout feature/my-feature
git merge develop
# حل conflict ها (در صورت وجود)
# ... edit files ...
git add .
git commit -m "merge: resolve conflicts with develop"
```
### 4. ایجاد Pull Request
1. Push کردن همه commits
2. رفتن به GitHub/GitLab
3. Create Pull Request
4. انتخاب base: `develop`, compare: `feature/my-feature`
5. عنوان و توضیحات
6. Request reviewers
7. Link کردن issues
### 5. Code Review Process
**برای نویسنده**:
- پاسخ به comments
- انجام تغییرات درخواستی
- Push کردن updates
- Request re-review
**برای Reviewer**:
- بررسی کد با دقت
- Check کردن tests
- بررسی code quality
- Approve یا Request Changes
### 6. Merge
پس از approval:
```bash
# Squash and Merge (توصیه می‌شود)
# یا
# Merge Commit
# یا
# Rebase and Merge
```
### 7. پاک کردن Branch
```bash
# Local
git branch -d feature/my-feature
# Remote (معمولا automatic)
git push origin --delete feature/my-feature
```
## Best Practices
### Commit های کوچک و مشخص
```bash
# ✅ GOOD: Small, focused commits
git commit -m "feat(auth): add email validation"
git commit -m "test(auth): add tests for email validation"
git commit -m "docs(auth): document email validation"
# ❌ BAD: Large, vague commit
git commit -m "add stuff"
```
### Commit منظم
```bash
# Commit هر چند ساعت یکبار
# نه خیلی کم (هر خط کد)
# نه خیلی زیاد (روزی یک commit)
```
### Push روزانه
```bash
# حداقل یکبار در روز push کنید
# از دست رفتن کد جلوگیری می‌کند
```
### استفاده از .gitignore
```bash
# اضافه نکردن فایل‌های غیرضروری
# - __pycache__
# - .env
# - venv/
# - *.pyc
```
## Git Commands Reference
### Basic
```bash
# Status
git status
# Log
git log
git log --oneline
git log --graph
# Diff
git diff
git diff --staged
```
### Branching
```bash
# لیست branches
git branch
git branch -a # با remote
# ایجاد branch
git branch feature/new-feature
git checkout -b feature/new-feature # ایجاد + checkout
# تغییر branch
git checkout develop
# حذف branch
git branch -d feature/old-feature
git branch -D feature/force-delete # Force
```
### Stashing
```bash
# ذخیره تغییرات موقت
git stash
# با پیام
git stash save "work in progress"
# لیست stash ها
git stash list
# برگرداندن stash
git stash apply
git stash pop # apply + delete
# حذف stash
git stash drop
git stash clear # همه
```
### Undoing Changes
```bash
# Unstage file
git reset HEAD file.py
# Discard changes
git checkout -- file.py
# Undo last commit (keep changes)
git reset --soft HEAD~1
# Undo last commit (discard changes)
git reset --hard HEAD~1
# Revert commit (safe)
git revert <commit-hash>
```
### Rebasing
```bash
# Rebase on develop
git checkout feature/my-feature
git rebase develop
# Interactive rebase
git rebase -i HEAD~3 # آخرین 3 commits
# Abort rebase
git rebase --abort
# Continue after resolving conflicts
git rebase --continue
```
### Tags
```bash
# ایجاد tag
git tag v1.0.0
# با پیام
git tag -a v1.0.0 -m "Release version 1.0.0"
# Push tags
git push origin v1.0.0
git push origin --tags # همه tags
# حذف tag
git tag -d v1.0.0
git push origin --delete v1.0.0
```
## Merge Conflicts
### حل Conflict
```bash
# 1. مشاهده conflicts
git status
# 2. باز کردن فایل و حل conflict
# <<<<<<< HEAD
# کد شما
# =======
# کد دیگران
# >>>>>>> branch-name
# 3. Stage کردن
git add resolved-file.py
# 4. Commit
git commit -m "merge: resolve conflicts"
```
### ابزارهای کمکی
```bash
# استفاده از merge tool
git mergetool
# استفاده از --ours یا --theirs
git checkout --ours file.py
git checkout --theirs file.py
```
## Tips & Tricks
### Aliases
```bash
# در ~/.gitconfig
[alias]
co = checkout
br = branch
ci = commit
st = status
lg = log --oneline --graph --decorate
```
### Commit Templates
```bash
# در ~/.gitmessage
<type>(<scope>): <subject>
<body>
<footer>
```
```bash
git config --global commit.template ~/.gitmessage
```
### Auto-completion
```bash
# Bash
source /usr/share/bash-completion/completions/git
# Zsh
autoload -Uz compinit && compinit
```
---
**مهم**: این workflow الزامی است و در code review بررسی می‌شود.

371
docs/development/setup.md Normal file
View File

@@ -0,0 +1,371 @@
# راهنمای راه‌اندازی محیط توسعه
## پیش‌نیازها
### نرم‌افزارهای مورد نیاز
| نرم‌افزار | نسخه مورد نیاز | لینک نصب |
|-----------|----------------|----------|
| Python | 3.11+ | [python.org](https://python.org) |
| PostgreSQL | 14+ | [postgresql.org](https://postgresql.org) |
| Redis | 7+ | [redis.io](https://redis.io) |
| Node.js | 18+ | [nodejs.org](https://nodejs.org) |
| Git | 2.x+ | [git-scm.com](https://git-scm.com) |
### بررسی نسخه‌ها
```bash
python --version # باید 3.11 یا بالاتر
psql --version # باید 14 یا بالاتر
redis-cli --version # باید 7 یا بالاتر
node --version # باید 18 یا بالاتر
git --version
```
## نصب
### 1. Clone Repository
```bash
git clone https://github.com/yourusername/peikarband.git
cd peikarband
```
### 2. Virtual Environment
```bash
# ایجاد virtual environment
python -m venv venv
# فعال‌سازی
# Linux/Mac:
source venv/bin/activate
# Windows:
venv\Scripts\activate
```
### 3. نصب Dependencies
```bash
# Core dependencies
pip install -r requirements.txt
# Development dependencies
pip install -r requirements-dev.txt
# تایید نصب
pip list
```
### 4. Pre-commit Hooks
```bash
# نصب pre-commit hooks
pre-commit install
# تست (اختیاری)
pre-commit run --all-files
```
## تنظیمات
### 1. Environment Variables
```bash
# کپی فایل example
cp .env.example .env
# ویرایش .env
nano .env
```
**متغیرهای ضروری**:
```env
# Database
DATABASE_URL=postgresql://username:password@localhost:5432/peikarband
# Redis
REDIS_URL=redis://localhost:6379/0
# Security
SECRET_KEY=generate-a-secure-random-key
JWT_SECRET_KEY=generate-another-secure-random-key
# Celery
CELERY_BROKER_URL=redis://localhost:6379/1
CELERY_RESULT_BACKEND=redis://localhost:6379/2
```
**تولید Secret Key**:
```bash
python -c "import secrets; print(secrets.token_urlsafe(32))"
```
### 2. PostgreSQL Setup
```bash
# ایجاد دیتابیس
createdb peikarband
# یا با psql
psql -U postgres
CREATE DATABASE peikarband;
CREATE USER peikarband_user WITH PASSWORD 'your_password';
GRANT ALL PRIVILEGES ON DATABASE peikarband TO peikarband_user;
\q
```
### 3. Redis Setup
```bash
# شروع Redis
redis-server
# تست
redis-cli ping
# باید "PONG" برگرداند
```
### 4. Database Migrations
```bash
# اجرای migrations
alembic upgrade head
# بررسی
alembic current
```
### 5. Seed Database (اختیاری)
```bash
python scripts/seed_database.py
```
## اجرای پروژه
### Development Mode
```bash
# روش 1: با Reflex
python -m reflex run
# روش 2: با auto-reload
python -m reflex run --reload
# روش 3: با loglevel
python -m reflex run --loglevel debug
```
### Background Services
**Terminal 1**: Celery Worker
```bash
celery -A src.infrastructure.tasks.celery_app worker -l info
```
**Terminal 2**: Celery Beat (برای scheduled tasks)
```bash
celery -A src.infrastructure.tasks.celery_app beat -l info
```
**Terminal 3**: Flower (Celery monitoring)
```bash
celery -A src.infrastructure.tasks.celery_app flower
# دسترسی: http://localhost:5555
```
### دسترسی به Application
- **Frontend**: http://localhost:3000
- **Backend API**: http://localhost:8000
- **Flower (Celery)**: http://localhost:5555
## Development Workflow
### 1. Branch جدید
```bash
git checkout develop
git pull origin develop
git checkout -b feature/your-feature-name
```
### 2. کدنویسی
```bash
# قبل از commit
black src/
isort src/
flake8 src/
mypy src/
# یا با pre-commit
pre-commit run --all-files
```
### 3. Testing
```bash
# همه تست‌ها
pytest
# با coverage
pytest --cov=src tests/
# تست‌های خاص
pytest tests/unit/
pytest tests/integration/
# تست یک فایل
pytest tests/unit/test_user.py
# تست یک function
pytest tests/unit/test_user.py::test_create_user
```
### 4. Commit
```bash
git add .
git commit -m "feat(scope): description"
git push origin feature/your-feature-name
```
### 5. Pull Request
1. Create PR از feature branch به develop
2. منتظر code review باشید
3. اصلاحات لازم را انجام دهید
4. Merge
## Troubleshooting
### مشکل: ModuleNotFoundError
```bash
# مطمئن شوید که در virtual environment هستید
which python
# باید به venv اشاره کند
# نصب مجدد
pip install -r requirements.txt
```
### مشکل: Database Connection
```bash
# بررسی PostgreSQL
sudo systemctl status postgresql
# شروع PostgreSQL
sudo systemctl start postgresql
# تست connection
psql -U username -d peikarband
```
### مشکل: Redis Connection
```bash
# بررسی Redis
redis-cli ping
# شروع Redis
redis-server
# بررسی port
netstat -an | grep 6379
```
### مشکل: Port Already in Use
```bash
# پیدا کردن process
lsof -i :3000
lsof -i :8000
# Kill process
kill -9 <PID>
```
## ابزارهای مفید
### IDE Setup
**VS Code Extensions**:
- Python
- Pylance
- Python Test Explorer
- GitLens
- Better Comments
**PyCharm**: تنظیمات پیشنهادی در `.idea/` موجود است.
### Database Tools
- **pgAdmin**: GUI برای PostgreSQL
- **DBeaver**: Multi-database tool
- **TablePlus**: Modern database GUI
### API Testing
- **httpie**: `pip install httpie`
- **Postman**: Desktop app
- **Insomnia**: Alternative to Postman
## بروزرسانی Dependencies
```bash
# بررسی dependencies قدیمی
pip list --outdated
# بروزرسانی یک package
pip install --upgrade package-name
# بروزرسانی همه (با دقت!)
pip install --upgrade -r requirements.txt
# ذخیره نسخه‌های جدید
pip freeze > requirements.txt
```
## مشکلات رایج
### Import Error
اطمینان حاصل کنید که:
- Virtual environment فعال است
- `PYTHONPATH` صحیح است
- همه `__init__.py` ها موجودند
### Alembic Migration Error
```bash
# Reset alembic
alembic downgrade base
alembic upgrade head
# ایجاد migration جدید
alembic revision --autogenerate -m "description"
```
### Test Failures
```bash
# پاک کردن cache
pytest --cache-clear
# اجرا با verbose
pytest -vv
# اجرا با output کامل
pytest -s
```
---
**نکته**: این راهنما همیشه به‌روز نگه داشته می‌شود. در صورت مشکل به team lead مراجعه کنید.