# 🏢 CMS Microservice Documentation

> **آخرین بروزرسانی**: January 3, 2026  
> **Framework**: .NET 9.0 + Clean Architecture + CQRS  
> **Database**: PostgreSQL  
> **Build Status**: ✅ SUCCESS

---

## 📊 وضعیت کلی

| سیستم | پیشرفت | وضعیت |
|-------|--------|--------|
| Commission System | 85% | ✅ Production Ready |
| Network System | 90% | ✅ Production Ready |
| Club Membership | 95% | ✅ Production Ready |
| Inventory System | 80% | ✅ Phase 2 Complete |
| Email/SMS | 100% | ✅ Complete |

---

## 🏗️ معماری

### Clean Architecture (4 لایه)

```
CMSMicroservice/
├── CMSMicroservice.Domain/           # Entities, Enums, Interfaces
├── CMSMicroservice.Application/      # CQRS Commands/Queries, MediatR
├── CMSMicroservice.Infrastructure/   # DbContext, Services, Repositories
└── CMSMicroservice.WebApi/           # Controllers, gRPC Services
```

### الگوی استاندارد

- ✅ **CQRS** با MediatR
- ✅ **IApplicationDbContext** برای دسترسی به DB (بدون Repository Pattern)
- ✅ **Mapster** برای mapping
- ✅ **FluentValidation** برای validation

---

## 💼 Commission System

### ویژگی‌های اصلی:
- ✅ Binary network tree با placement خودکار
- ✅ عضویت باشگاه (Member/Trial) با نرخ‌های کمیسیون
- ✅ محاسبه کمیسیون هفتگی (الگوریتم Lesser Leg)
- ✅ Background worker با Hangfire
- ✅ Health check endpoints

### الگوریتم محاسبه:

```
Weekly Commission = (Lesser Leg Balance × Rate) / Total Balances
```

**نرخ‌ها**:
| عضویت | نرخ |
|-------|-----|
| Member | 10% |
| Trial | 5% |

---

## 🏪 Inventory System

### Domain Layer:

| Entity | توضیحات |
|--------|---------|
| `InventoryItem` | ردیابی موجودی محصول در هر انبار |
| `StockMovement` | تاریخچه حرکات موجودی |
| `Warehouse` | مدیریت انبارها |

### StockMovementType:

| Type | Code | توضیحات |
|------|------|---------|
| `MovementTypeUnspecified` | 0 | نامشخص |
| `InitialStock` | 10 | موجودی اولیه |
| `Purchase` | 20 | خرید از تامین‌کننده |
| `Sale` | 30 | فروش به مشتری |
| `Return` | 40 | برگشت از فروش |
| `Adjustment` | 50 | تنظیم موجودی |
| `Loss` | 60 | ضایعات/خسارت |
| `Transfer` | 70 | انتقال بین انبار |
| `Reservation` | 80 | رزرو برای سفارش |

### CQRS Commands (17):

**Inventory:**
- `CreateInventoryItem`
- `UpdateInventoryItem`
- `DeleteInventoryItem`
- `UpdateInventoryQuantity`
- `ReserveInventory`
- `ReleaseReservedInventory`
- `ReduceInventory`
- `IncreaseInventory`

**Movement:**
- `CreateStockMovement`
- `BulkCreateStockMovement`
- `DeleteStockMovement`

**Warehouse:**
- `CreateWarehouse`
- `UpdateWarehouse`
- `DeleteWarehouse`
- `SetDefaultWarehouse`
- `ActivateWarehouse`
- `BulkCreateWarehouse`

### CQRS Queries (35):

**Inventory:**
- `GetInventoryItem`
- `GetInventoryByProduct`
- `GetAllInventoryItems`
- `GetLowStockItems`
- `GetOutOfStockItems`
- `CheckAvailability`
- `SearchInventory`

**Movement:**
- `GetStockMovements`
- `GetStockMovementsByInventoryItem`
- `GetMovementHistory`
- `GetDailyVolume`
- `GetTopMovingProducts`
- `SearchStockMovements`

**Warehouse:**
- `GetWarehouse`
- `GetAllWarehouses`
- `GetWarehouseStats`
- `GetWarehouseLowStock`
- `SearchWarehouses`

---

## 📧 Email & SMS Notifications

### پیکربندی:

**Email (MailKit 4.14.1)**:
```json
{
  "Email": {
    "Host": "smtp.example.com",
    "Port": 587,
    "Username": "noreply@foursat.com",
    "Password": "xxx",
    "SenderName": "FourSat System"
  }
}
```

**SMS (Kavenegar 1.2.5)**:
```json
{
  "Kavenegar": {
    "ApiKey": "xxx",
    "Sender": "10008663"
  }
}
```

### انواع نوتیفیکیشن:
- ✅ Commission notification (هفتگی)
- ✅ Club activation notification
- ✅ Error alerts

---

## ⏰ Hangfire Job Scheduling

### داشبورد:
```
URL: https://cms.se.kbs1.ir/hangfire
```

### Job های زمان‌بندی شده:

| Job | Schedule | توضیحات |
|-----|----------|---------|
| WeeklyCommissionCalculation | یکشنبه 00:05 UTC | محاسبه کمیسیون هفتگی |

### API های Manual Trigger:
```
POST /api/commission/calculate
POST /api/commission/process-week?weekNumber=2026-W01
```

---

## 🏥 Health Checks

### Endpoints:

| Endpoint | استفاده |
|----------|---------|
| `/health` | وضعیت کلی |
| `/health/ready` | Readiness probe (K8s) |
| `/health/live` | Liveness probe (K8s) |

### Example Response:
```json
{
  "status": "Healthy",
  "checks": [
    { "name": "database", "status": "Healthy" },
    { "name": "redis", "status": "Healthy" }
  ]
}
```

---

## 🔧 Proto Sync (January 3, 2026)

### تغییرات enum در Inventory:

| آیتم | قبل | بعد |
|------|-----|-----|
| ProductType | `REGULAR`, `DISCOUNT` | `REGULAR_PRODUCT`, `DISCOUNT_PRODUCT` |
| StockMovementType | Sequential (0-9) | Grouped (10, 20, 30...) |

### تغییرات فیلد:

| قبل | بعد |
|-----|-----|
| `page_index` | `page` |
| `search_term` | `search` |
| `product_name` | `product_title` |
| `active_only` | `is_active` |
| `created_at` | `created` |

---

## 🚀 Build & Run

### Local Development:
```bash
cd CMS/src
dotnet build CMS.sln
dotnet run --project CMSMicroservice.WebApi
```

### Docker:
```bash
cd CMS
docker build -t cms:latest .
docker run -p 5000:80 cms:latest
```

### Environment Variables:
```bash
ASPNETCORE_ENVIRONMENT=Staging
ConnectionStrings__DefaultConnection=Host=...;Database=...
```

---

## 📚 مستندات مرتبط

- [BackOffice Documentation](./01-BACKOFFICE.md)
- [Proto Guide](./02-PROTO-GUIDE.md)
- [Deployment Guide](./05-DEPLOYMENT.md)
