# CMS Microservice - Network & Club Commission + Inventory Management System

[![Status](https://img.shields.io/badge/Status-Active%20Development-success)]()
[![Progress](https://img.shields.io/badge/Inventory%20System-Phase%202%20Complete-blue)]()
[![Phase](https://img.shields.io/badge/Next-Business%20Services-orange)]()

## 📊 Project Status (January 2026)

### 🏪 Inventory Management System - NEW!
**Progress**: Phase 2 Complete (50%)  
**Architecture**: Clean Architecture + CQRS + Repository Pattern

#### ✅ Completed Phases
1. ✅ **Phase 1: Infrastructure & Domain Layer**
   - Domain Entities: `InventoryItem`, `StockMovement`, `Warehouse`
   - Domain Enums: `StockMovementType`
   - EF Core Configurations with proper indexing
   - Database migration applied

2. ✅ **Phase 2: Repository Pattern & CQRS**
   - Repository Interfaces & Implementations
   - CQRS Commands (17 commands)
   - CQRS Queries (35 queries)
   - MediatR Handlers (52 handlers)

#### 🔄 In Progress
3. 🔄 **Phase 3: Business Services Layer**
4. ⏳ **Phase 4: DTOs & AutoMapper**
5. ⏳ **Phase 5: API Controllers**

---

### 💼 Commission System - Production Ready
**Progress**: 85% Complete  
**MVP Status**: ✅ 100% Complete

#### ✅ Completed Features
- ✅ Binary network tree with automatic placement
- ✅ Club membership (Member/Trial) with commission rates
- ✅ Weekly commission calculation (Lesser Leg algorithm)
- ✅ Background worker with Hangfire
- ✅ Email + SMS notifications (MailKit + Kavenegar)
- ✅ Health check endpoints (Kubernetes-ready)

### 🟡 Partially Complete
- Phase 10: Withdrawal & Settlement (40%)
  - ✅ Commands & Database
  - ❌ Payment Gateway Integration

### ❌ Not Started
- Phase 9: Club Shop & Product Integration (0%)

---

## 🚀 Recent Updates (January 2026)

### 🏪 Inventory Management System - NEW! ✅
**Complete CQRS-based inventory management with:**

#### Domain Layer:
- ✅ `InventoryItem` - Multi-warehouse product tracking with min/max thresholds
- ✅ `StockMovement` - Complete audit trail with 8 movement types
- ✅ `Warehouse` - Multi-location support with default warehouse

#### Repository Pattern:
- ✅ `IInventoryItemRepository` - 25+ methods for inventory operations
- ✅ `IStockMovementRepository` - Movement tracking & analytics
- ✅ `IWarehouseRepository` - Warehouse management & statistics

#### CQRS Commands (17 total):
- **Inventory:** Create, Update, Delete, Reserve, Release, Reduce, Increase
- **Movement:** Create, BulkCreate, Delete  
- **Warehouse:** Create, Update, Delete, SetDefault, Activate, BulkCreate

#### CQRS Queries (35 total):
- **Inventory:** GetById, Search, LowStock, OutOfStock, CheckAvailability
- **Movement:** GetHistory, GetByOrder, Search, Analytics, DailyVolume, TopMoving
- **Warehouse:** GetById, Search, GetStats, GetLowStock, GetAllStats

#### Business Features:
- ✅ Multi-warehouse inventory management
- ✅ Stock reservation system for orders
- ✅ Automatic movement tracking
- ✅ Low stock & out-of-stock alerts
- ✅ Advanced analytics & reporting
- ✅ Bulk operations support
- ✅ Transaction-safe operations

---

### Email & SMS Notifications - COMPLETED ✅
- ✅ **MailKit 4.14.1** for Email (SMTP with HTML templates)
- ✅ **Kavenegar 1.2.5** for SMS (Iranian SMS gateway)
- ✅ User.Email field added with migration
- ✅ 3 notification types: Commission, Club activation, Errors
- ✅ Persian RTL templates with rich formatting
- ✅ Production configuration guide created

### Hangfire Job Scheduling - COMPLETED ✅
- ✅ Dashboard UI at `/hangfire`
- ✅ Cron schedule: Sunday 00:05 UTC
- ✅ SQL Server persistence
- ✅ Manual trigger API endpoints
- ✅ Distributed execution support

### Infrastructure Enhancements - COMPLETED ✅
- ✅ Health Check endpoints (`/health`, `/health/ready`, `/health/live`)
- ✅ AlertService (structured logging for Sentry/Slack)
- ✅ Retry logic (Polly 8.5.0 with exponential backoff)
- ✅ WorkerExecutionLog (database audit trail)
- ✅ CurrentUserService (JWT authentication context)

---

## 🏗️ Architecture

**Clean Architecture** with 4 layers:
```
CMSMicroservice.Domain/          # Entities, Enums, Interfaces
├── Entities/
│   ├── InventoryItem.cs        # NEW: Inventory tracking
│   ├── StockMovement.cs        # NEW: Movement audit
│   └── Warehouse.cs            # NEW: Multi-warehouse
├── Enums/
│   └── StockMovementType.cs    # NEW: Movement types

CMSMicroservice.Application/     # CQRS (Commands, Queries, MediatR)
├── Features/
│   ├── InventoryItems/         # NEW: Inventory CQRS
│   │   ├── Commands/
│   │   ├── Queries/
│   │   └── Handlers/
│   ├── StockMovements/         # NEW: Movement CQRS
│   │   ├── Commands/
│   │   ├── Queries/
│   │   └── Handlers/
│   └── Warehouses/             # NEW: Warehouse CQRS
│       ├── Commands/
│       ├── Queries/
│       └── Handlers/
└── Common/Interfaces/
    └── Repositories/           # NEW: Repository interfaces

CMSMicroservice.Infrastructure/  # DbContext, Services, Background Jobs
├── Persistence/
│   ├── Context/
│   ├── Configurations/         # NEW: EF Core configs
│   ├── Repositories/           # NEW: Repository implementations
│   └── Migrations/
└── DependencyInjection.cs      # NEW: DI setup

CMSMicroservice.WebApi/          # gRPC Services, Controllers
CMSMicroservice.Protobuf/        # Protocol Buffers definitions
```

**Technology Stack**:
- .NET 9.0
- Entity Framework Core 9.0.11
- gRPC + JSON Transcoding
- Hangfire 1.8.22 (Job Scheduling)
- MediatR 13.0.0 (CQRS)
- Polly 8.5.0 (Resilience)
- MailKit 4.14.1 (Email)
- Kavenegar 1.2.5 (SMS)
- SQL Server

---

## 📖 Documentation

- **[Development Plan](docs/development-plan.md)** - NEW: Inventory system roadmap
- **[Implementation Progress](docs/implementation-progress.md)** - Detailed phase-by-phase progress
- **[Email/SMS Configuration Guide](docs/email-sms-configuration-guide.md)** - Production setup instructions
- **[Balance Calculation Logic](docs/balance-calculation-carryover-logic.md)** - Commission algorithm details
- **[Binary Tree Registration](docs/binary-tree-registration-guide.md)** - Network tree guide
- **[Network Club Commission System](docs/network-club-commission-system-v1.1.md)** - Full system specification

---

## 🏪 Inventory System Usage

### Create Warehouse
```csharp
await mediator.Send(new CreateWarehouseCommand 
{
    Name = "Main Warehouse",
    Code = "WH-001",
    IsDefault = true,
    IsActive = true
});
```

### Create Inventory Item
```csharp
await mediator.Send(new CreateInventoryItemCommand 
{
    ProductId = 1,
    WarehouseId = 1,
    Quantity = 100,
    MinQuantity = 10,
    MaxQuantity = 1000
});
```

### Reserve Stock for Order
```csharp
await mediator.Send(new ReserveInventoryCommand 
{
    Id = inventoryId,
    Quantity = 5,
    OrderId = 12345
});
```

### Check Availability
```csharp
bool available = await mediator.Send(
    new CheckInventoryAvailabilityQuery(inventoryId, 10));
```

### Get Low Stock Alerts
```csharp
var lowStock = await mediator.Send(new GetLowStockItemsQuery 
{
    WarehouseId = 1,
    Count = 50
});
```

### Get Movement Analytics
```csharp
var summary = await mediator.Send(new GetMovementSummaryQuery 
{
    FromDate = DateTime.Now.AddDays(-7),
    ToDate = DateTime.Now
});

var topProducts = await mediator.Send(new GetTopMovingProductsQuery 
{
    FromDate = DateTime.Now.AddDays(-30),
    ToDate = DateTime.Now,
    Count = 10
});
```

---

## 🚀 Quick Start

### Prerequisites
- .NET 9.0 SDK
- SQL Server (local or remote)
- (Optional) Gmail account for Email
- (Optional) Kavenegar account for SMS

### 1. Clone & Build
```bash
cd /home/masoud/Apps/project/FourSat/CMS/src
dotnet build
```

### 2. Configure Database
Update `appsettings.json` with your SQL Server connection:
```json
"ConnectionStrings": {
  "DefaultConnection": "Server=YOUR_SERVER;Database=Foursat_CMS;..."
}
```

### 3. Apply Migrations
```bash
cd CMSMicroservice.WebApi
dotnet ef database update
```

### 4. Configure Notifications (Optional)
See [Email/SMS Configuration Guide](docs/email-sms-configuration-guide.md)

### 5. Run
```bash
dotnet run --urls="http://localhost:5133"
```

### 6. Access Endpoints
- **Health**: http://localhost:5133/health
- **Hangfire Dashboard**: http://localhost:5133/hangfire
- **gRPC**: localhost:5133 (HTTP/2)

---

## 🔧 Configuration

### Email (SMTP)
```json
"Email": {
  "Enabled": true,
  "SmtpHost": "smtp.gmail.com",
  "SmtpPort": 587,
  "SmtpUsername": "your-email@gmail.com",
  "SmtpPassword": "your-gmail-app-password",
  "FromEmail": "noreply@foursat.com",
  "FromName": "FourSat CMS",
  "EnableSsl": true
}
```

### SMS (Kavenegar)
```json
"Sms": {
  "Enabled": true,
  "Provider": "Kavenegar",
  "KavenegarApiKey": "YOUR_API_KEY",
  "Sender": "10008663"
}
```

### Background Worker
```csharp
// Cron: "5 0 * * 0" = Every Sunday at 00:05 UTC
RecurringJob.AddOrUpdate<WeeklyCommissionJob>(
    "weekly-commission-calculation",
    job => job.ExecuteAsync(CancellationToken.None),
    "5 0 * * 0");
```

---

## 🧪 Testing

### Manual Trigger (via API)
```bash
# Trigger weekly calculation immediately
curl -X POST http://localhost:5133/api/admin/trigger-weekly-calculation

# Trigger recurring job now
curl -X POST http://localhost:5133/api/admin/trigger-recurring-job-now

# Get recurring jobs status
curl http://localhost:5133/api/admin/recurring-jobs-status
```

### Health Checks
```bash
curl http://localhost:5133/health         # Overall health
curl http://localhost:5133/health/ready   # Readiness probe (K8s)
curl http://localhost:5133/health/live    # Liveness probe (K8s)
```

---

## 📊 What's Remaining?

### 🏪 Inventory System (Current Focus)
1. **Phase 3: Business Services** (In Progress)
   - `IInventoryManagementService` - High-level operations
   - `IStockMovementService` - Movement orchestration
   - `IWarehouseService` - Warehouse business logic
   - `IInventoryReportingService` - Advanced reporting

2. **Phase 4: DTOs & AutoMapper** (Next)
   - Request/Response DTOs
   - AutoMapper profiles
   - Validation rules

3. **Phase 5: API Controllers** (Planned)
   - `InventoryController` - REST API
   - `WarehouseController` - Warehouse management
   - `StockMovementController` - Movement tracking
   - Swagger documentation

### 💼 Commission System
1. **Payment Gateway Integration** (Phase 10 - 1 week)
   - Daya or Bank Mellat API integration
   - IBAN transfer automation
   - Admin approval UI in BackOffice

2. **Production Configuration** (30 minutes)
   - Gmail App Password setup
   - Kavenegar API key registration
   - Update `appsettings.Production.json`

### Medium Priority
3. **Club Shop Integration** (Phase 9 - 2 weeks)
   - Product catalog for club memberships
   - Shopping cart integration
   - Auto-activation on purchase

### Low Priority
4. **Testing** (Phase 7 - Postponed)
   - Unit tests for business logic
   - Integration tests for API
   - Load testing for background worker

### Optional Enhancements
- Redis distributed locks (multi-server deployment)
- Sentry error tracking (API key needed)
- Slack notifications (webhook needed)
- FCM push notifications

---

## 🎯 MVP Features (100% Complete)

### 💼 Commission System:
✅ Binary network tree with automatic placement  
✅ Club membership (Member/Trial) with different commission rates  
✅ Weekly commission calculation (Lesser Leg algorithm)  
✅ Background worker with Hangfire (cron scheduling)  
✅ Balance carryover logic (rollover unused volumes)  
✅ MaxWeeklyBalances cap enforcement  
✅ Health check endpoints (Kubernetes-ready)  
✅ Manual trigger API (admin control)  
✅ Email + SMS notifications (MailKit + Kavenegar)  
✅ Retry logic with exponential backoff (Polly)  
✅ Audit trail (WorkerExecutionLog, History tables)  
✅ Structured logging (AlertService for Sentry/Slack)  
✅ JWT authentication context (CurrentUserService)  

### 🏪 Inventory System (Phase 2 Complete):
✅ Domain entities (InventoryItem, StockMovement, Warehouse)  
✅ Multi-warehouse inventory management  
✅ Stock reservation system for orders  
✅ 8 movement types with complete audit trail  
✅ Repository pattern with 25+ methods per repository  
✅ CQRS with 17 commands and 35 queries  
✅ 52 MediatR handlers with business logic  
✅ Low stock and out-of-stock alerts  
✅ Advanced analytics (top products, daily volume)  
✅ Bulk operations support  
✅ Transaction-safe operations with rollback  
✅ DI container configuration  

---

## 👥 Team

**Development**: FourSat Team  
**Last Updated**: January 2026

---

## 📝 License

Proprietary - FourSat Company
# Multi-remote push enabled
