Files
CMS/docs/monitoring-alerts-implementation-report.md

334 lines
8.3 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 📊 Monitoring & Alerts System - Implementation Report
**Date**: 2025-11-30
**Status**: ✅ Skeleton Implemented
**Completion**: 30% (Structure ready, integrations pending)
---
## 🎯 Overview
اسکلت سیستم **Monitoring & Alerts** برای پروژه CMS پیاده‌سازی شد. این سیستم به دو بخش اصلی تقسیم می‌شود:
1. **Alert System**: برای ارسال اعلان‌های مدیریتی (Critical Errors, Warnings, Success)
2. **User Notification System**: برای ارسال پیام به کاربران (کمیسیون، پرداخت، فعال‌سازی باشگاه)
---
## 📦 Files Created/Modified
### ✨ New Files:
1. **`IAlertService.cs`** (Interface)
- `SendCriticalAlertAsync()` - برای خطاهای Critical
- `SendWarningAlertAsync()` - برای Warning ها
- `SendSuccessNotificationAsync()` - برای موفقیت‌ها
2. **`IUserNotificationService.cs`** (Interface)
- `SendCommissionReceivedNotificationAsync()` - اعلان دریافت کمیسیون
- `SendClubActivationNotificationAsync()` - اعلان فعال‌سازی باشگاه
- `SendPayoutErrorNotificationAsync()` - اعلان خطا در پرداخت
3. **`AlertService.cs`** (Implementation - Skeleton)
- ✅ Logging به Console
- ⏳ TODO: Sentry Integration
- ⏳ TODO: Slack Integration
- ⏳ TODO: Email Integration
4. **`UserNotificationService.cs`** (Implementation - Skeleton)
- ✅ Logging به Console
- ⏳ TODO: SMS Gateway Integration
- ⏳ TODO: Email Service Integration
- ⏳ TODO: Push Notification Integration
5. **`MonitoringSettings.cs`** (Configuration Model)
- تنظیمات Sentry, Slack, Email, SMS
- قابل تنظیم از طریق `appsettings.json`
---
### ✏️ Modified Files:
1. **`ConfigureServices.cs`**
```csharp
services.AddScoped<IAlertService, AlertService>();
services.AddScoped<IUserNotificationService, UserNotificationService>();
```
2. **`WeeklyNetworkCommissionWorker.cs`**
- ✅ Integration با `IAlertService`
- ✅ ارسال Critical Alert در صورت خطا
- ✅ ارسال Success Notification پس از اتمام موفق
3. **`appsettings.json`**
- اضافه شدن بخش `Monitoring` با تنظیمات پیش‌فرض
---
## 🔧 Current Implementation
### Alert System Usage:
```csharp
// در Worker یا هر Handler دیگر:
try
{
// عملیات خطرناک
}
catch (Exception ex)
{
await _alertService.SendCriticalAlertAsync(
"Operation Failed",
"Description of what went wrong",
ex);
}
```
### Current Output:
```
🚨 CRITICAL ALERT: Weekly Commission Worker Failed - Worker execution abc-123 failed for week 2025-W48
```
---
## ⏳ Pending Integrations (TODO)
### 1. Sentry Integration
```csharp
// در AlertService.SendCriticalAlertAsync():
if (_settings.SentryEnabled)
{
SentrySdk.CaptureException(exception);
}
```
**Steps**:
- Install NuGet: `Sentry.AspNetCore`
- Configure DSN in `appsettings.json`
- Add to `Program.cs`: `builder.WebHost.UseSentry()`
---
### 2. Slack Integration
```csharp
// در AlertService:
if (_settings.SlackEnabled)
{
var payload = new
{
text = $"🚨 {title}",
attachments = new[]
{
new { text = message, color = "danger" }
}
};
await _httpClient.PostAsJsonAsync(_settings.SlackWebhookUrl, payload);
}
```
**Steps**:
- Create Slack Incoming Webhook
- Add URL to `appsettings.json`
- Install NuGet: `System.Net.Http.Json`
---
### 3. Email Alerts (برای Admin)
```csharp
// در AlertService:
if (_settings.EmailAlertsEnabled)
{
foreach (var email in _settings.AdminEmails)
{
await _emailService.SendAsync(
to: email,
subject: $"[ALERT] {title}",
body: message);
}
}
```
**Steps**:
- Configure SMTP settings
- Install NuGet: `MailKit` or use existing email service
- Add admin emails to config
---
### 4. SMS Notifications (برای کاربران)
```csharp
// در UserNotificationService.SendCommissionReceivedNotificationAsync():
var user = await _context.Users.FindAsync(userId);
if (user.SmsNotifications && _settings.SmsNotificationsEnabled)
{
var message = $"کمیسیون شما: {amount:N0} ریال برای هفته {weekNumber} واریز شد.";
await _smsGateway.SendAsync(user.Mobile, message);
}
```
**Steps**:
- Choose SMS provider (Kavenegar, Ghasedak, etc.)
- Get API Key
- Implement `ISmsGatewayService`
---
### 5. Retry Logic با Exponential Backoff
```csharp
// در Worker:
private async Task<T> RetryWithExponentialBackoff<T>(
Func<Task<T>> operation,
int maxRetries = 3)
{
for (int i = 0; i < maxRetries; i++)
{
try
{
return await operation();
}
catch (Exception ex) when (i < maxRetries - 1)
{
var delay = TimeSpan.FromSeconds(Math.Pow(2, i)); // 2^i seconds
_logger.LogWarning("Retry {Attempt}/{Max} after {Delay}s",
i + 1, maxRetries, delay.TotalSeconds);
await Task.Delay(delay);
}
}
}
```
---
## 📋 Configuration Example
در `appsettings.Production.json`:
```json
{
"Monitoring": {
"SentryEnabled": true,
"SentryDsn": "https://xxxxx@sentry.io/12345",
"SlackEnabled": true,
"SlackWebhookUrl": "https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXX",
"EmailAlertsEnabled": true,
"AdminEmails": [
"admin@foursat.ir",
"devops@foursat.ir"
],
"SmsNotificationsEnabled": true,
"SmsApiKey": "your-kavenegar-api-key",
"SmsGatewayUrl": "https://api.kavenegar.com/v1/{apikey}/sms/send.json"
}
}
```
---
## 🧪 Testing
### Test 1: Alert Service
```csharp
var alertService = serviceProvider.GetRequiredService<IAlertService>();
await alertService.SendCriticalAlertAsync(
"Test Alert",
"This is a test critical alert");
```
**Expected**: Log در Console + (در Production) Sentry + Slack
---
### Test 2: User Notification
```csharp
var notificationService = serviceProvider.GetRequiredService<IUserNotificationService>();
await notificationService.SendCommissionReceivedNotificationAsync(
userId: 123,
amount: 500_000,
weekNumber: 48);
```
**Expected**: Log در Console + (در Production) SMS + Email
---
## 📊 Integration Priority
| Priority | Integration | Effort | Impact |
|----------|------------|--------|--------|
| 🔴 High | Sentry | 1 hour | Critical error tracking |
| 🟡 Medium | Slack | 2 hours | Real-time admin alerts |
| 🟡 Medium | SMS (Kavenegar) | 3 hours | User notifications |
| 🟢 Low | Email Alerts | 2 hours | Backup notification channel |
| 🟢 Low | Retry Logic | 1 hour | Reliability improvement |
---
## ✅ Current Status Summary
### Completed (30%):
- ✅ Interface definitions
- ✅ Skeleton implementations with Logging
- ✅ DI registration
- ✅ Worker integration
- ✅ Configuration model
- ✅ appsettings structure
### Pending (70%):
- ⏳ Sentry integration (5%)
- ⏳ Slack webhook (10%)
- ⏳ Email service (10%)
- ⏳ SMS gateway (15%)
- ⏳ Push notifications (10%)
- ⏳ Retry logic (5%)
- ⏳ Testing (10%)
- ⏳ Documentation (5%)
---
## 🚀 Next Steps
1. **Immediate** (در صورت نیاز):
- Enable Sentry for error tracking
- Setup Slack webhook for critical alerts
2. **Short-term** (هفته آینده):
- Integrate SMS gateway (Kavenegar)
- Test User notifications
3. **Long-term** (ماه آینده):
- Add Email service
- Implement Retry logic
- Push notification service
---
## 📝 Notes
- تمام TODO ها در کد با comment مشخص شده‌اند
- فعلاً فقط Logging فعال است
- برای Production باید حتماً یکی از Integration ها (Sentry/Slack) فعال شود
- SMS Gateway باید بر اساس پروژه انتخاب شود (Kavenegar, Ghasedak, etc.)
---
## 🔗 Related Files
- **Interfaces**: `CMSMicroservice.Application/Common/Interfaces/IAlertService.cs`
- **Implementations**: `CMSMicroservice.Infrastructure/Services/Monitoring/`
- **Worker**: `CMSMicroservice.Infrastructure/BackgroundJobs/WeeklyNetworkCommissionWorker.cs`
- **Config**: `CMSMicroservice.WebApi/appsettings.json`
---
**Report generated**: 2025-11-30
**Build Status**: ✅ Success
**Ready for**: Development continuation / Integration implementation