Refactor code structure for improved readability and maintainability

This commit is contained in:
masoodafar-web
2026-02-10 22:06:46 +03:30
parent 8f02cec22f
commit 5149b9a89c
182 changed files with 7305 additions and 243980 deletions
+483
View File
@@ -0,0 +1,483 @@
# 📋 لیست کامل جداول و Mapping ها
## تعداد کل: 33 جدول
### جداول با تغییر نام (10 جدول)
این جداول در دیتابیس قدیمی نام‌گذاری اشتباه دارند و در دیتابیس جدید اصلاح می‌شوند:
| # | نام قدیمی (Source) | نام جدید (Target) | دلیل تغییر |
|---|-------------------|-------------------|-----------|
| 1 | `Categorys` | `Categories` | جمع صحیح Category |
| 2 | `FactorDetailss` | `FactorDetails` | Detail تکی نیست، s اضافی |
| 3 | `ProductGalleryss` | `ProductGalleries` | Gallery → Galleries، s اضافی |
| 4 | `ProductImagess` | `ProductImages` | Image → Images، s اضافی |
| 5 | `Productss` | `Products` | s اضافی |
| 6 | `PruductCategorys` | `ProductCategories` | Pruduct → Product + جمع صحیح |
| 7 | `PruductTags` | `ProductTags` | Pruduct → Product |
| 8 | `Transactionss` | `Transactions` | s اضافی |
| 9 | `UserAddresss` | `UserAddresses` | Address → Addresses، s اضافی |
| 10 | `UserCartss` | `UserCarts` | s اضافی |
---
### جداول بدون تغییر نام (23 جدول)
این جداول نام‌گذاری صحیحی دارند:
| # | نام جدول |
|---|----------|
| 1 | `ClubFeatures` |
| 2 | `ClubMembershipHistories` |
| 3 | `ClubMemberships` |
| 4 | `CommissionPayoutHistories` |
| 5 | `Contracts` |
| 6 | `NetworkMembershipHistories` |
| 7 | `NetworkWeeklyBalances` |
| 8 | `OtpTokens` |
| 9 | `Packages` |
| 10 | `Roles` |
| 11 | `SystemConfigurationHistories` |
| 12 | `SystemConfigurations` |
| 13 | `Tags` |
| 14 | `UserClubFeatures` |
| 15 | `UserCommissionPayouts` |
| 16 | `UserContracts` |
| 17 | `UserOrders` |
| 18 | `UserRoles` |
| 19 | `Users` |
| 20 | `UserWalletChangeLogs` |
| 21 | `UserWallets` |
| 22 | `WeeklyCommissionPools` |
| 23 | `WorkerExecutionLogs` |
---
## ترتیب پیشنهادی برای Migration
### مرحله 1: جداول پایه (Independent Tables)
بدون FK، می‌توانند اول migrate شوند:
1. `Roles`
2. `Tags`
3. `SystemConfigurations`
4. `ClubFeatures`
5. `Packages`
### مرحله 2: جداول کاربری
FK به Users:
6. `Users` ⚠️ **مهم**: پس از migration → Post-Migration Transformation
7. `OtpTokens`
8. `UserRoles`
9. `UserWallets`
10. `UserWalletChangeLogs`
11. `UserAddresses`
12. `UserCarts`
### مرحله 3: جداول محصولات
FK به Categories و Products:
13. `Categories`
14. `Products`
15. `ProductImages`
16. `ProductGalleries`
17. `ProductCategories`
18. `ProductTags`
### مرحله 4: جداول عضویت و کمیسیون
19. `ClubMemberships`
20. `ClubMembershipHistories`
21. `NetworkWeeklyBalances`
22. `NetworkMembershipHistories`
23. `CommissionPayoutHistories`
24. `UserCommissionPayouts`
25. `WeeklyCommissionPools`
### مرحله 5: جداول قراردادها و تراکنش‌ها
26. `Contracts`
27. `UserContracts`
28. `Transactions`
29. `FactorDetails`
### مرحله 6: جداول کاربری پیشرفته
30. `UserOrders`
31. `UserClubFeatures`
### مرحله 7: جداول سیستمی
32. `SystemConfigurationHistories`
33. `WorkerExecutionLogs`
---
## تغییرات ساختاری مهم
### 1. Users Table
**تبدیل Binary Tree:**
- **قدیمی**: `ParentId` (یک Parent ساده)
- **جدید**: `NetworkParentId` + `LegPosition` (Binary Tree)
**Post-Migration Script:**
```sql
-- Script: Scripts/PostMigration_DataTransformation.sql
-- اجرا: خودکار بعد از migration (اگر RunPostMigrationTransformation=true)
```
**چه کاری انجام می‌دهد:**
1. ✅ بررسی: آیا Parent ها بیشتر از 2 فرزند دارند؟ (ROLLBACK اگر دارند)
2. ✅ کپی: `ParentId``NetworkParentId`
3. ✅ تخصیص: `LegPosition` (فرزند اول=Left, فرزند دوم=Right)
4. ✅ حل Orphan ها: Parent نداشته → `NetworkParentId=NULL`
5. ✅ Validation نهایی: Binary Tree درست است؟
6. ✅ آمار: تعداد کل، Left/Right distribution
---
## Configuration در appsettings.json
```json
{
"TableMappings": {
"Categorys": "Categories",
"ClubFeatures": "ClubFeatures",
"ClubMembershipHistories": "ClubMembershipHistories",
"ClubMemberships": "ClubMemberships",
"CommissionPayoutHistories": "CommissionPayoutHistories",
"Contracts": "Contracts",
"FactorDetailss": "FactorDetails",
"NetworkMembershipHistories": "NetworkMembershipHistories",
"NetworkWeeklyBalances": "NetworkWeeklyBalances",
"OtpTokens": "OtpTokens",
"Packages": "Packages",
"ProductGalleryss": "ProductGalleries",
"ProductImagess": "ProductImages",
"Productss": "Products",
"PruductCategorys": "ProductCategories",
"PruductTags": "ProductTags",
"Roles": "Roles",
"SystemConfigurationHistories": "SystemConfigurationHistories",
"SystemConfigurations": "SystemConfigurations",
"Tags": "Tags",
"Transactionss": "Transactions",
"UserAddresss": "UserAddresses",
"UserCartss": "UserCarts",
"UserClubFeatures": "UserClubFeatures",
"UserCommissionPayouts": "UserCommissionPayouts",
"UserContracts": "UserContracts",
"UserOrders": "UserOrders",
"UserRoles": "UserRoles",
"Users": "Users",
"UserWalletChangeLogs": "UserWalletChangeLogs",
"UserWallets": "UserWallets",
"WeeklyCommissionPools": "WeeklyCommissionPools",
"WorkerExecutionLogs": "WorkerExecutionLogs"
}
}
```
---
## چک‌لیست قبل از Migration
### 1. ساختار Target Database
- [ ] همه 33 جدول در Target ایجاد شده‌اند
- [ ] Schema صحیح است: `[CMS].[TableName]`
- [ ] Column ها مطابقت دارند
- [ ] `Users` دارای `NetworkParentId` و `LegPosition` است
### 2. Connection Strings
- [ ] `SourceDatabase`: IP, Port, Username, Password صحیح
- [ ] `TargetDatabase`: IP, Port, Username, Password صحیح
- [ ] Firewall: IP شما مجاز است
- [ ] SQL User دسترسی `db_datareader` (Source) دارد
- [ ] SQL User دسترسی `db_datawriter` (Target) دارد
### 3. تنظیمات Migration
- [ ] `BatchSize`: مناسب با Network شما
- [ ] `MaxConcurrentTables`: 3 (پیشنهادی)
- [ ] `RunPostMigrationTransformation`: true
- [ ] `TableMappings`: همه 33 جدول لیست شده
### 4. Backup
- [ ] ⚠️ **حتماً** Target Database را Backup بگیرید
- [ ] فضای کافی روی Disk دارید
---
## آمار تخمینی
بر اساس backup file (`dbbkup/CMS.sql`):
| دسته | تعداد جداول | تخمین رکوردها |
|------|------------|---------------|
| **Core** (Users, Roles, etc.) | 5 | ~2,000 |
| **Products** (Categories, Products, etc.) | 8 | ~5,000 |
| **Club & Network** | 7 | ~10,000 |
| **Transactions & Orders** | 6 | ~20,000 |
| **System & Logs** | 7 | ~15,000 |
| **جمع کل** | **33** | **~50,000+** |
**زمان تخمینی:** 5-10 دقیقه (بسته به Network)
---
**نسخه:** 1.0
**تاریخ:** December 6, 2025
**وضعیت:** ✅ آماده برای Production
---
## Post-Migration Binary Tree Transformation
> Merged from `DataMigration/POST-MIGRATION-TRANSFORMATION.md`
## تغییرات اعمال شده
### 1. اضافه شدن SQL Script
**فایل**: `Scripts/PostMigration_DataTransformation.sql`
این اسکریپت **بعد از migration داده‌ها** اجرا می‌شود و تبدیلات زیر را انجام می‌دهد:
#### تبدیل Users Table: `ParentId` → `NetworkParentId + LegPosition`
**مراحل:**
1. **Validation**: بررسی کاربرانی که بیشتر از 2 فرزند دارند (❌ برای binary tree نامعتبر)
2. **Copy**: کپی `ParentId` به `NetworkParentId`
3. **Assign LegPosition**:
- فرزند اول → Left (0)
- فرزند دوم → Right (1)
4. **Orphan Detection**: پیدا کردن کاربرانی که Parent آنها وجود ندارد
5. **Final Validation**: تایید یکپارچگی binary tree (هر Parent حداکثر 2 فرزند)
6. **Statistics**: آمار نهایی
---
## جریان کار Migration (بروزرسانی شده)
```
1. خواندن تنظیمات
2. اتصال به Source و Target databases
3. کشف و نگاشت جداول (Table Mappings)
4. Migration داده‌ها (Batch Processing + Retry)
5. گزارش نتایج Migration
6. ✨ Post-Migration Transformation (جدید!)
├─ اجرای Scripts/PostMigration_DataTransformation.sql
├─ تبدیل ParentId → NetworkParentId
├─ تخصیص LegPosition
├─ Validation
└─ Log نتایج
7. پایان
```
---
## تنظیمات جدید
### `appsettings.json`
```json
{
"MigrationSettings": {
...
"RunPostMigrationTransformation": true // ✨ جدید
}
}
```
**گزینه‌ها:**
- `true` (پیشفرض): اسکریپت تبدیل بعد از migration اجرا می‌شود
- `false`: فقط migration داده‌ها انجام می‌شود (تبدیل دستی)
---
## خروجی Migration
### قبل:
```
[12:35:42 INF] === Migration Complete ===
[12:35:42 INF] Success: 33 tables, 50,000+ records
[12:35:42 INF] Failed: 0 tables
[12:35:42 INF] Duration: 00:05:27
```
### بعد (با Transformation):
```
[12:35:42 INF] === Migration Complete ===
[12:35:42 INF] Success: 33 tables, 50,000+ records
[12:35:42 INF] Failed: 0 tables
[12:35:42 INF] Duration: 00:05:27
[12:35:42 INF] === Starting Post-Migration Data Transformation ===
[12:35:43 INF] Executing post-migration transformation script...
[12:35:43 INF] SQL: === Starting Post-Migration Data Transformation ===
[12:35:43 INF] SQL: Step 1: Validating Users for binary tree conversion...
[12:35:44 INF] SQL: Step 2: Copying ParentId → NetworkParentId...
[12:35:44 INF] SQL: - Updated: 1,250 users
[12:35:44 INF] SQL: Step 3: Assigning LegPosition (Left/Right)...
[12:35:45 INF] SQL: - Updated: 1,250 users
[12:35:45 INF] SQL: Step 4: Checking for orphaned nodes...
[12:35:45 INF] SQL: - No orphaned nodes found
[12:35:45 INF] SQL: Step 5: Verifying binary tree integrity...
[12:35:45 INF] SQL: - Binary tree integrity: OK
[12:35:45 INF] SQL: Step 6: Migration Statistics:
[12:35:46 INF] SQL: === Post-Migration Data Transformation Complete ===
[12:35:46 INF] Post-migration transformation completed successfully
```
---
## Validation Checks
### 1. Binary Tree Violation Check
اگر کاربری بیشتر از 2 فرزند داشته باشد:
```
ERROR: Cannot proceed with binary tree migration. Please resolve manually.
ParentId ChildCount ChildIds
-------- ---------- ----------
12345 3 67890, 67891, 67892
```
**راه حل دستی:**
1. تصمیم بگیرید کدام 2 فرزند در binary tree بمانند
2. فرزند سوم را به Parent دیگری منتقل کنید
3. Migration را دوباره اجرا کنید
### 2. Orphaned Nodes Detection
اگر Parent کاربر وجود نداشته باشد:
```
WARNING: Found orphaned nodes (parent does not exist)!
Id NetworkParentId Issue
----- --------------- -----------------------------
99999 88888 Orphaned: Parent does not exist
```
**راه حل خودکار:**
- اسکریپت این کاربران را به `NetworkParentId = NULL` تبدیل می‌کند (root level)
---
## خطاها و عیب‌یابی
### خطا: "Post-migration script not found"
```
[12:35:46 WRN] Post-migration script not found: /path/to/Scripts/PostMigration_DataTransformation.sql
[12:35:46 INF] Skipping data transformation. Users table will need manual ParentId→NetworkParentId migration.
```
**راه حل:**
- Script را manually اجرا کنید از SQL Server Management Studio
- یا فایل را در مسیر `Scripts/` قرار دهید و دوباره اجرا کنید
### خطا: "Binary tree integrity violation"
```
ERROR: Binary tree integrity violation! Some parents have more than 2 children.
```
**راه حل:**
1. Query زیر را اجرا کنید تا والدین مشکل‌دار را ببینید:
```sql
SELECT
ParentId,
COUNT(*) as ChildCount,
STRING_AGG(CAST(Id AS VARCHAR), ', ') as ChildIds
FROM [CMS].[Users]
WHERE ParentId IS NOT NULL
GROUP BY ParentId
HAVING COUNT(*) > 2;
```
2. فرزندان اضافی را دستی حل کنید
3. Migration را دوباره اجرا کنید
---
## غیرفعال کردن Transformation
اگر می‌خواهید فقط داده‌ها migrate شوند بدون تبدیل:
```json
{
"MigrationSettings": {
"RunPostMigrationTransformation": false
}
}
```
سپس می‌توانید اسکریپت را **دستی** از SSMS اجرا کنید:
```sql
-- فایل: Scripts/PostMigration_DataTransformation.sql
-- اجرا در: Target Database
```
---
## آمار نهایی
بعد از transformation، این آمار نمایش داده می‌شود:
| Metric | Count |
|--------|-------|
| Total Users | 2,500 |
| Users with NetworkParentId | 1,250 |
| Users with LegPosition Left | 625 |
| Users with LegPosition Right | 625 |
| Root users (no parent) | 1,250 |
---
## تغییرات کد
### `MigrationService.cs`
**متد جدید:**
```csharp
private async Task RunPostMigrationTransformationAsync(string targetConn, CancellationToken cancellationToken)
{
// 1. خواندن SQL script
// 2. اتصال به Target database
// 3. اجرای script با handling PRINT messages
// 4. Log کردن نتایج
}
```
**Integration:**
- بعد از اتمام موفق migration، اگر `RunPostMigrationTransformation = true` باشد، این متد اجرا می‌شود
- اگر script یافت نشود، فقط یک warning نمایش داده می‌شود (Migration fail نمی‌شود)
- اگر transformation fail شود، Migration موفق تلقی می‌شود ولی warning نمایش داده می‌شود
---
## مزایا
**خودکار**: نیازی به اجرای دستی script نیست
**Safe**: اگر fail شود، Migration rollback نمی‌شود
**Logged**: تمام مراحل در console و file log می‌شود
**Configurable**: می‌توان غیرفعال کرد
**Validated**: قبل از commit، تمام validationها انجام می‌شود
---
**نسخه:** 1.1
**تاریخ:** December 6, 2025
**وضعیت:** ✅ Build موفق