Merge branch 'kub-stage' into production
Build and Deploy to Production / build-and-deploy (push) Successful in 8m48s

# Conflicts:
#	.gitea/workflows/kub-deploy.yml
#	k8s/staging/cms-deployment.yaml
#	src/CMSMicroservice.Application/DiscountShopCQ/Commands/CompleteOrderPayment/CompleteOrderPaymentCommandHandler.cs
#	src/CMSMicroservice.Application/DiscountShopCQ/Commands/PlaceOrder/PlaceOrderCommandHandler.cs
#	src/CMSMicroservice.Application/WalletCQ/Commands/VerifyDiscountWalletCharge/VerifyDiscountWalletChargeCommandHandler.cs
#	src/CMSMicroservice.Application/WalletCQ/Commands/VerifyMagicWalletCharge/VerifyMagicWalletChargeCommandHandler.cs
#	src/CMSMicroservice.Infrastructure/Services/Payment/ZarinPalPaymentService.cs
#	src/CMSMicroservice.WebApi/Controllers/PaymentCallbackController.cs
#	src/CMSMicroservice.WebApi/appsettings.Production.json
#	src/CMSMicroservice.WebApi/appsettings.Staging.json
#	src/CMSMicroservice.WebApi/appsettings.json
This commit is contained in:
masoodafar-web
2026-02-28 04:51:57 +03:30
209 changed files with 15064 additions and 2696 deletions
@@ -0,0 +1,288 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using CMSMicroservice.Application.Common.Interfaces;
namespace CMSMicroservice.Infrastructure.BackgroundServices;
/// <summary>
/// سرویس دیپلوی خودکار Stored Procedureها در استارتاپ (Q26).
/// فایل‌های .sql از EmbeddedResource خوانده شده، SHA256 محاسبه و با جدول
/// [CMS].[__StoredProcedureVersions] مقایسه می‌شود.
/// اگر checksum تغییر کرده باشد، SP دوباره اجرا (CREATE OR ALTER) می‌شود.
/// این سرویس فقط یکبار در استارتاپ اجرا شده و سپس متوقف می‌شود.
/// </summary>
public class StoredProcedureDeploymentService : BackgroundService
{
private readonly IServiceScopeFactory _scopeFactory;
private readonly ILogger<StoredProcedureDeploymentService> _logger;
/// <summary>
/// پیشوند نام‌فضای EmbeddedResource — فقط فایل‌های .sql واقعی (بدون README)
/// </summary>
private const string ResourcePrefix = "CMSMicroservice.Infrastructure.Persistence.StoredProcedures.";
public StoredProcedureDeploymentService(
IServiceScopeFactory scopeFactory,
ILogger<StoredProcedureDeploymentService> logger)
{
_scopeFactory = scopeFactory;
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
// صبر برای آماده شدن دیتابیس و اتمام Migrationها
await Task.Delay(TimeSpan.FromSeconds(15), stoppingToken);
_logger.LogInformation("StoredProcedureDeploymentService started — checking stored procedures...");
try
{
using var scope = _scopeFactory.CreateScope();
var context = scope.ServiceProvider.GetRequiredService<IApplicationDbContext>();
var connection = context.Database.GetDbConnection();
await connection.OpenAsync(stoppingToken);
// ── ساخت جدول ورژن اگر وجود ندارد ──
await EnsureVersionTableAsync(connection, stoppingToken);
// ── خواندن فایل‌های SP از Embedded Resources ──
var assembly = Assembly.GetExecutingAssembly();
var resourceNames = assembly.GetManifestResourceNames()
.Where(r => r.StartsWith(ResourcePrefix, StringComparison.OrdinalIgnoreCase)
&& r.EndsWith(".sql", StringComparison.OrdinalIgnoreCase)
&& !r.Contains("README", StringComparison.OrdinalIgnoreCase))
.OrderBy(r => r)
.ToList();
_logger.LogInformation("Found {Count} SQL resources to check", resourceNames.Count);
var deployed = 0;
var skipped = 0;
foreach (var resourceName in resourceNames)
{
if (stoppingToken.IsCancellationRequested) break;
var fileName = resourceName[ResourcePrefix.Length..]; // e.g. "sp_CalculateWeeklyBalances.sql"
var sqlContent = await ReadResourceAsync(assembly, resourceName);
var checksum = ComputeSha256(sqlContent);
var existingChecksum = await GetStoredChecksumAsync(connection, fileName, stoppingToken);
if (string.Equals(existingChecksum, checksum, StringComparison.OrdinalIgnoreCase))
{
_logger.LogDebug("SP '{FileName}' is up-to-date (checksum match), skipping", fileName);
skipped++;
continue;
}
// ── اجرای SP (CREATE OR ALTER) ──
_logger.LogInformation("Deploying SP '{FileName}' (checksum changed: {Old} → {New})",
fileName,
existingChecksum ?? "NEW",
checksum[..12]);
try
{
await ExecuteSqlAsync(connection, sqlContent, stoppingToken);
await UpsertChecksumAsync(connection, fileName, checksum, stoppingToken);
deployed++;
_logger.LogInformation("Successfully deployed SP '{FileName}'", fileName);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to deploy SP '{FileName}' — skipping", fileName);
}
}
_logger.LogInformation(
"StoredProcedureDeploymentService completed — deployed: {Deployed}, skipped: {Skipped}, total: {Total}",
deployed, skipped, resourceNames.Count);
}
catch (Exception ex)
{
_logger.LogError(ex, "StoredProcedureDeploymentService encountered a fatal error");
}
}
// ══════════════════════════════════════════════════════════════
// Helper Methods
// ══════════════════════════════════════════════════════════════
/// <summary>
/// ساخت جدول [CMS].[__StoredProcedureVersions] اگر وجود ندارد.
/// از Raw SQL استفاده می‌کنیم تا نیازی به Entity و Migration نباشد.
/// </summary>
private static async Task EnsureVersionTableAsync(
System.Data.Common.DbConnection connection,
CancellationToken ct)
{
const string sql = """
IF NOT EXISTS (
SELECT 1 FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'CMS' AND TABLE_NAME = '__StoredProcedureVersions'
)
BEGIN
CREATE TABLE [CMS].[__StoredProcedureVersions] (
[FileName] NVARCHAR(256) NOT NULL PRIMARY KEY,
[Checksum] NVARCHAR(64) NOT NULL,
[DeployedAt] DATETIME2 NOT NULL DEFAULT GETUTCDATE(),
[DeployCount] INT NOT NULL DEFAULT 1
);
END
""";
await using var cmd = connection.CreateCommand();
cmd.CommandText = sql;
await cmd.ExecuteNonQueryAsync(ct);
}
/// <summary>
/// خواندن checksum ذخیره‌شده برای یک فایل
/// </summary>
private static async Task<string?> GetStoredChecksumAsync(
System.Data.Common.DbConnection connection,
string fileName,
CancellationToken ct)
{
const string sql = "SELECT [Checksum] FROM [CMS].[__StoredProcedureVersions] WHERE [FileName] = @FileName";
await using var cmd = connection.CreateCommand();
cmd.CommandText = sql;
var param = cmd.CreateParameter();
param.ParameterName = "@FileName";
param.Value = fileName;
cmd.Parameters.Add(param);
var result = await cmd.ExecuteScalarAsync(ct);
return result as string;
}
/// <summary>
/// ذخیره/به‌روزرسانی checksum بعد از دیپلوی موفق
/// </summary>
private static async Task UpsertChecksumAsync(
System.Data.Common.DbConnection connection,
string fileName,
string checksum,
CancellationToken ct)
{
const string sql = """
MERGE [CMS].[__StoredProcedureVersions] AS target
USING (SELECT @FileName AS [FileName]) AS source
ON target.[FileName] = source.[FileName]
WHEN MATCHED THEN
UPDATE SET [Checksum] = @Checksum,
[DeployedAt] = GETUTCDATE(),
[DeployCount] = target.[DeployCount] + 1
WHEN NOT MATCHED THEN
INSERT ([FileName], [Checksum], [DeployedAt], [DeployCount])
VALUES (@FileName, @Checksum, GETUTCDATE(), 1);
""";
await using var cmd = connection.CreateCommand();
cmd.CommandText = sql;
var pFileName = cmd.CreateParameter();
pFileName.ParameterName = "@FileName";
pFileName.Value = fileName;
cmd.Parameters.Add(pFileName);
var pChecksum = cmd.CreateParameter();
pChecksum.ParameterName = "@Checksum";
pChecksum.Value = checksum;
cmd.Parameters.Add(pChecksum);
await cmd.ExecuteNonQueryAsync(ct);
}
/// <summary>
/// اجرای محتوای SQL روی کانکشن فعلی
/// </summary>
private static async Task ExecuteSqlAsync(
System.Data.Common.DbConnection connection,
string sqlContent,
CancellationToken ct)
{
// SP ها ممکن است GO separator داشته باشند — هر بلاک را جدا اجرا می‌کنیم
var batches = SplitBatches(sqlContent);
foreach (var batch in batches)
{
var trimmed = batch.Trim();
if (string.IsNullOrWhiteSpace(trimmed)) continue;
await using var cmd = connection.CreateCommand();
cmd.CommandText = trimmed;
cmd.CommandTimeout = 120; // SP های بزرگ ممکن است زمان ببرند
await cmd.ExecuteNonQueryAsync(ct);
}
}
/// <summary>
/// تقسیم SQL به بلاک‌ها بر اساس GO separator
/// </summary>
private static List<string> SplitBatches(string sql)
{
// GO باید تنها در خط خودش باشد (case-insensitive)
var lines = sql.Split('\n');
var batch = new StringBuilder();
var result = new List<string>();
foreach (var line in lines)
{
if (line.Trim().Equals("GO", StringComparison.OrdinalIgnoreCase))
{
if (batch.Length > 0)
{
result.Add(batch.ToString());
batch.Clear();
}
}
else
{
batch.AppendLine(line);
}
}
if (batch.Length > 0)
result.Add(batch.ToString());
return result;
}
/// <summary>
/// خواندن محتوای یک Embedded Resource
/// </summary>
private static async Task<string> ReadResourceAsync(Assembly assembly, string resourceName)
{
await using var stream = assembly.GetManifestResourceStream(resourceName)
?? throw new InvalidOperationException($"Embedded resource not found: {resourceName}");
using var reader = new StreamReader(stream, Encoding.UTF8);
return await reader.ReadToEndAsync();
}
/// <summary>
/// محاسبه SHA256 از محتوای SQL
/// </summary>
private static string ComputeSha256(string content)
{
var bytes = SHA256.HashData(Encoding.UTF8.GetBytes(content));
return Convert.ToHexString(bytes).ToLowerInvariant();
}
}
@@ -30,4 +30,8 @@
<ItemGroup>
<Folder Include="Persistence\Migrations\" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Persistence\StoredProcedures\*.sql" />
</ItemGroup>
</Project>
@@ -31,6 +31,7 @@ public static class ConfigureServices
services.Configure<SmsSettings>(configuration.GetSection(SmsSettings.SectionName));
services.AddScoped<AuditableEntitySaveChangesInterceptor>();
services.AddScoped<HistoryTrackingSaveChangesInterceptor>();
services.AddScoped<ApplicationDbContextInitialiser>();
services.AddScoped<IGenerateJwtToken, GenerateJwtTokenService>();
services.AddScoped<IHashService, HashService>();
@@ -130,6 +131,9 @@ public static class ConfigureServices
if (configuration.GetValue<bool>("SeedWorkers:MagicWalletCycleSeed:Enabled"))
services.AddHostedService<MagicWalletCycleSeedService>();
// Q26: Auto-deploy stored procedures on startup (checksum-based)
services.AddHostedService<StoredProcedureDeploymentService>();
if (configuration.GetValue<bool>("UseInMemoryDatabase"))
{
services.AddDbContext<ApplicationDbContext>(options =>
@@ -18,6 +18,7 @@ public class ApplicationDbContext : DbContext, IApplicationDbContext
{
private readonly IMediator? _mediator;
private readonly AuditableEntitySaveChangesInterceptor? _auditableEntitySaveChangesInterceptor;
private readonly HistoryTrackingSaveChangesInterceptor? _historyTrackingInterceptor;
/// <summary>
/// Constructor برای design-time (migrations)
@@ -33,11 +34,13 @@ public class ApplicationDbContext : DbContext, IApplicationDbContext
public ApplicationDbContext(
DbContextOptions<ApplicationDbContext> options,
IMediator mediator,
AuditableEntitySaveChangesInterceptor auditableEntitySaveChangesInterceptor)
AuditableEntitySaveChangesInterceptor auditableEntitySaveChangesInterceptor,
HistoryTrackingSaveChangesInterceptor historyTrackingInterceptor)
: base(options)
{
_mediator = mediator;
_auditableEntitySaveChangesInterceptor = auditableEntitySaveChangesInterceptor;
_historyTrackingInterceptor = historyTrackingInterceptor;
}
protected override void OnModelCreating(ModelBuilder builder)
{
@@ -57,6 +60,11 @@ public class ApplicationDbContext : DbContext, IApplicationDbContext
optionsBuilder.AddInterceptors(_auditableEntitySaveChangesInterceptor);
}
if (_historyTrackingInterceptor != null)
{
optionsBuilder.AddInterceptors(_historyTrackingInterceptor);
}
// Suppress PendingModelChangesWarning in EF Core 9
optionsBuilder.ConfigureWarnings(w => w.Ignore(RelationalEventId.PendingModelChangesWarning));
}
@@ -89,7 +97,7 @@ public class ApplicationDbContext : DbContext, IApplicationDbContext
public DbSet<OrderVAT> OrderVATs => Set<OrderVAT>();
public DbSet<UserPackagePurchase> UserPackagePurchases => Set<UserPackagePurchase>();
public DbSet<UserWallet> UserWallets => Set<UserWallet>();
public DbSet<UserWalletChangeLog> UserWalletChangeLogs => Set<UserWalletChangeLog>();
public DbSet<UserWalletHistory> UserWalletHistories => Set<UserWalletHistory>();
public DbSet<DayaLoanContract> DayaLoanContracts => Set<DayaLoanContract>();
// Payment
@@ -110,6 +118,9 @@ public class ApplicationDbContext : DbContext, IApplicationDbContext
public DbSet<UserClubFeature> UserClubFeatures => Set<UserClubFeature>();
public DbSet<ClubMembershipHistory> ClubMembershipHistories => Set<ClubMembershipHistory>();
public DbSet<ClubMembershipCycle> ClubMembershipCycles => Set<ClubMembershipCycle>();
public DbSet<ClubMembershipCycleHistory> ClubMembershipCycleHistories => Set<ClubMembershipCycleHistory>();
public DbSet<PackageHistory> PackageHistories => Set<PackageHistory>();
public DbSet<PackageFeature> PackageFeatures => Set<PackageFeature>();
// Network
public DbSet<NetworkWeeklyBalance> NetworkWeeklyBalances => Set<NetworkWeeklyBalance>();
@@ -23,12 +23,32 @@ public class ClubMembershipConfiguration : IEntityTypeConfiguration<ClubMembersh
builder.Property(entity => entity.GiftValue).IsRequired();
builder.Property(entity => entity.TotalEarned).IsRequired();
// فیلدهای جدید First/Last Activation
builder.Property(entity => entity.FirstActivationDate).IsRequired(false);
builder.Property(entity => entity.FirstPackageId).IsRequired(false);
builder.Property(entity => entity.LastActivationDate).IsRequired(false);
builder.Property(entity => entity.LastPackageId).IsRequired(false);
// رابطه یک‌به‌یک با User
builder.HasOne(entity => entity.User)
.WithOne(u => u.ClubMembership)
.HasForeignKey<ClubMembership>(entity => entity.UserId)
.OnDelete(DeleteBehavior.Restrict);
// رابطه با Package — اولین پکیج خریداری‌شده
builder.HasOne(entity => entity.FirstPackage)
.WithMany()
.HasForeignKey(entity => entity.FirstPackageId)
.IsRequired(false)
.OnDelete(DeleteBehavior.Restrict);
// رابطه با Package — آخرین پکیج خریداری‌شده
builder.HasOne(entity => entity.LastPackage)
.WithMany()
.HasForeignKey(entity => entity.LastPackageId)
.IsRequired(false)
.OnDelete(DeleteBehavior.Restrict);
// Index برای UserId (یونیک برای یک‌به‌یک)
builder.HasIndex(e => e.UserId)
.IsUnique()
@@ -37,5 +57,9 @@ public class ClubMembershipConfiguration : IEntityTypeConfiguration<ClubMembersh
// Index برای IsActive
builder.HasIndex(e => e.IsActive)
.HasDatabaseName("IX_ClubMembership_IsActive");
// Index برای LastActivationDate (تشخیص فعال‌سازی هفتگی Q22)
builder.HasIndex(e => e.LastActivationDate)
.HasDatabaseName("IX_ClubMembership_LastActivationDate");
}
}
@@ -21,6 +21,7 @@ public class ClubMembershipCycleConfiguration : IEntityTypeConfiguration<ClubMem
builder.Property(entity => entity.MagicCompletedAt).IsRequired(false);
builder.Property(entity => entity.PurchaseMethod).IsRequired();
builder.Property(entity => entity.PackageAmount).IsRequired();
builder.Property(entity => entity.PackageId).IsRequired();
builder.Property(entity => entity.IsCurrentCycle)
.IsRequired()
.HasDefaultValue(false);
@@ -36,6 +37,11 @@ public class ClubMembershipCycleConfiguration : IEntityTypeConfiguration<ClubMem
.HasForeignKey(entity => entity.ClubMembershipId)
.OnDelete(DeleteBehavior.Restrict);
builder.HasOne(entity => entity.Package)
.WithMany()
.HasForeignKey(entity => entity.PackageId)
.OnDelete(DeleteBehavior.Restrict);
// Indexes
builder.HasIndex(e => new { e.UserId, e.IsCurrentCycle })
.HasDatabaseName("IX_ClubMembershipCycle_UserId_IsCurrentCycle");
@@ -0,0 +1,51 @@
using CMSMicroservice.Domain.Entities.History;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace CMSMicroservice.Infrastructure.Persistence.Configurations;
/// <summary>
/// تاریخچه تغییرات دوره عضویت باشگاه (Q27)
/// </summary>
public class ClubMembershipCycleHistoryConfiguration : IEntityTypeConfiguration<ClubMembershipCycleHistory>
{
public void Configure(EntityTypeBuilder<ClubMembershipCycleHistory> builder)
{
builder.HasQueryFilter(p => !p.IsDeleted);
builder.Ignore(entity => entity.DomainEvents);
builder.HasKey(entity => entity.Id);
builder.Property(entity => entity.Id).UseIdentityColumn();
builder.Property(entity => entity.ClubMembershipCycleId).IsRequired();
builder.Property(entity => entity.UserId).IsRequired();
builder.Property(entity => entity.CycleNumber).IsRequired();
builder.Property(entity => entity.OldIsCurrentCycle).IsRequired();
builder.Property(entity => entity.NewIsCurrentCycle).IsRequired();
builder.Property(entity => entity.OldMagicStartedAt).IsRequired(false);
builder.Property(entity => entity.NewMagicStartedAt).IsRequired(false);
builder.Property(entity => entity.OldMagicCompletedAt).IsRequired(false);
builder.Property(entity => entity.NewMagicCompletedAt).IsRequired(false);
builder.Property(entity => entity.Action).IsRequired();
builder.Property(entity => entity.PerformedBy).IsRequired(false).HasMaxLength(100);
builder.Property(entity => entity.Reason).IsRequired(false).HasMaxLength(500);
// رابطه با ClubMembershipCycle
builder.HasOne(entity => entity.ClubMembershipCycle)
.WithMany(c => c.CycleHistories)
.HasForeignKey(entity => entity.ClubMembershipCycleId)
.OnDelete(DeleteBehavior.Restrict);
// Index برای UserId و Created
builder.HasIndex(e => new { e.UserId, e.Created })
.HasDatabaseName("IX_ClubMembershipCycleHistory_UserId_Created");
// Index برای ClubMembershipCycleId
builder.HasIndex(e => e.ClubMembershipCycleId)
.HasDatabaseName("IX_ClubMembershipCycleHistory_CycleId");
// Index برای Action
builder.HasIndex(e => e.Action)
.HasDatabaseName("IX_ClubMembershipCycleHistory_Action");
}
}
@@ -18,6 +18,7 @@ public class NetworkWeeklyBalanceConfiguration : IEntityTypeConfiguration<Networ
builder.Property(entity => entity.UserId).IsRequired();
builder.Property(entity => entity.WeekDefinitionId).IsRequired();
builder.Property(entity => entity.PackageId).IsRequired();
builder.Property(entity => entity.LeftLegBalances).IsRequired();
builder.Property(entity => entity.RightLegBalances).IsRequired();
builder.Property(entity => entity.TotalBalances).IsRequired();
@@ -37,10 +38,16 @@ public class NetworkWeeklyBalanceConfiguration : IEntityTypeConfiguration<Networ
.HasForeignKey(entity => entity.WeekDefinitionId)
.OnDelete(DeleteBehavior.Restrict);
// Composite Index برای UserId و WeekDefinitionId
builder.HasIndex(e => new { e.UserId, e.WeekDefinitionId })
// رابطه با Package
builder.HasOne(entity => entity.Package)
.WithMany()
.HasForeignKey(entity => entity.PackageId)
.OnDelete(DeleteBehavior.Restrict);
// Composite Index: هر کاربر × هر هفته × هر پکیج فقط یک رکورد
builder.HasIndex(e => new { e.UserId, e.WeekDefinitionId, e.PackageId })
.IsUnique()
.HasDatabaseName("IX_NetworkWeeklyBalance_UserId_WeekDefinitionId");
.HasDatabaseName("IX_NetworkWeeklyBalance_User_WeekDef_Package");
// Index برای WeekDefinitionId
builder.HasIndex(e => e.WeekDefinitionId)
@@ -15,6 +15,28 @@ public class PackageConfiguration : IEntityTypeConfiguration<Package>
builder.Property(entity => entity.Description).IsRequired(true);
builder.Property(entity => entity.ImagePath).IsRequired(true);
builder.Property(entity => entity.Price).IsRequired(true);
// فیلدهای جدید پکیج
builder.Property(entity => entity.SortOrder).IsRequired().HasDefaultValue(0);
builder.Property(entity => entity.IsActive).IsRequired().HasDefaultValue(true);
builder.Property(entity => entity.IsBasePackage).IsRequired().HasDefaultValue(false);
builder.Property(entity => entity.SupportsDayaPurchase).IsRequired().HasDefaultValue(false);
builder.Property(entity => entity.SupportsDirectPurchase).IsRequired().HasDefaultValue(true);
builder.Property(entity => entity.ActivationFee).IsRequired().HasDefaultValue(0L);
builder.Property(entity => entity.DiscountMultiplier).IsRequired().HasDefaultValue(2.0m)
.HasPrecision(18, 4);
builder.Property(entity => entity.MagicWalletMultiplier).IsRequired().HasDefaultValue(2.5m)
.HasPrecision(18, 4);
builder.Property(entity => entity.MaxBalancesPerLeg).IsRequired().HasDefaultValue(300);
builder.Property(entity => entity.MaxNetworkLevel).IsRequired().HasDefaultValue(15);
builder.Property(entity => entity.MagicWalletMaxDeposit).IsRequired().HasDefaultValue(1_000_000_000L);
builder.Property(entity => entity.MagicWalletMaxCredit).IsRequired().HasDefaultValue(2_500_000_000L);
// Indexes
builder.HasIndex(e => e.IsActive)
.HasDatabaseName("IX_Package_IsActive");
builder.HasIndex(e => e.SortOrder)
.HasDatabaseName("IX_Package_SortOrder");
}
}
@@ -0,0 +1,41 @@
using CMSMicroservice.Domain.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace CMSMicroservice.Infrastructure.Persistence.Configurations;
/// <summary>
/// EF Configuration — ارتباط پکیج–فیچر
/// </summary>
public class PackageFeatureConfiguration : IEntityTypeConfiguration<PackageFeature>
{
public void Configure(EntityTypeBuilder<PackageFeature> builder)
{
builder.HasQueryFilter(p => !p.IsDeleted);
builder.Ignore(entity => entity.DomainEvents);
builder.HasKey(entity => entity.Id);
builder.Property(entity => entity.Id).UseIdentityColumn();
builder.Property(entity => entity.PackageId).IsRequired();
builder.Property(entity => entity.ClubFeatureId).IsRequired();
builder.Property(entity => entity.IsIncluded).IsRequired().HasDefaultValue(true);
// رابطه با Package
builder.HasOne(entity => entity.Package)
.WithMany(p => p.PackageFeatures)
.HasForeignKey(entity => entity.PackageId)
.OnDelete(DeleteBehavior.Cascade);
// رابطه با ClubFeature
builder.HasOne(entity => entity.ClubFeature)
.WithMany()
.HasForeignKey(entity => entity.ClubFeatureId)
.OnDelete(DeleteBehavior.Restrict);
// Unique: هر فیچر فقط یک بار در هر پکیج
builder.HasIndex(e => new { e.PackageId, e.ClubFeatureId })
.IsUnique()
.HasDatabaseName("IX_PackageFeature_PackageId_ClubFeatureId");
}
}
@@ -0,0 +1,51 @@
using CMSMicroservice.Domain.Entities.History;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace CMSMicroservice.Infrastructure.Persistence.Configurations;
/// <summary>
/// تاریخچه تغییرات پکیج (Q27)
/// </summary>
public class PackageHistoryConfiguration : IEntityTypeConfiguration<PackageHistory>
{
public void Configure(EntityTypeBuilder<PackageHistory> builder)
{
builder.HasQueryFilter(p => !p.IsDeleted);
builder.Ignore(entity => entity.DomainEvents);
builder.HasKey(entity => entity.Id);
builder.Property(entity => entity.Id).UseIdentityColumn();
builder.Property(entity => entity.PackageId).IsRequired();
builder.Property(entity => entity.OldPrice).IsRequired(false);
builder.Property(entity => entity.NewPrice).IsRequired(false);
builder.Property(entity => entity.OldActivationFee).IsRequired(false);
builder.Property(entity => entity.NewActivationFee).IsRequired(false);
builder.Property(entity => entity.OldMagicMultiplier).IsRequired(false).HasPrecision(18, 4);
builder.Property(entity => entity.NewMagicMultiplier).IsRequired(false).HasPrecision(18, 4);
builder.Property(entity => entity.OldMagicMaxDeposit).IsRequired(false);
builder.Property(entity => entity.NewMagicMaxDeposit).IsRequired(false);
builder.Property(entity => entity.OldMaxBalancesPerLeg).IsRequired(false);
builder.Property(entity => entity.NewMaxBalancesPerLeg).IsRequired(false);
builder.Property(entity => entity.OldIsActive).IsRequired(false);
builder.Property(entity => entity.NewIsActive).IsRequired(false);
builder.Property(entity => entity.Action).IsRequired();
builder.Property(entity => entity.PerformedBy).IsRequired(false).HasMaxLength(100);
builder.Property(entity => entity.Reason).IsRequired(false).HasMaxLength(500);
// رابطه با Package
builder.HasOne(entity => entity.Package)
.WithMany(p => p.PackageHistories)
.HasForeignKey(entity => entity.PackageId)
.OnDelete(DeleteBehavior.Restrict);
// Index برای PackageId و Created
builder.HasIndex(e => new { e.PackageId, e.Created })
.HasDatabaseName("IX_PackageHistory_PackageId_Created");
// Index برای Action
builder.HasIndex(e => e.Action)
.HasDatabaseName("IX_PackageHistory_Action");
}
}
@@ -19,6 +19,7 @@ public class UserCommissionPayoutConfiguration : IEntityTypeConfiguration<UserCo
builder.Property(entity => entity.UserId).IsRequired();
builder.Property(entity => entity.WeekDefinitionId).IsRequired();
builder.Property(entity => entity.WeeklyPoolId).IsRequired();
builder.Property(entity => entity.PackageId).IsRequired();
builder.Property(entity => entity.BalancesEarned).IsRequired();
builder.Property(entity => entity.ValuePerBalance).IsRequired();
builder.Property(entity => entity.TotalAmount).IsRequired();
@@ -50,10 +51,16 @@ public class UserCommissionPayoutConfiguration : IEntityTypeConfiguration<UserCo
.IsRequired()
.OnDelete(DeleteBehavior.Restrict);
// Composite Index برای UserId و WeekDefinitionId
builder.HasIndex(e => new { e.UserId, e.WeekDefinitionId })
// رابطه با Package
builder.HasOne(entity => entity.Package)
.WithMany()
.HasForeignKey(entity => entity.PackageId)
.OnDelete(DeleteBehavior.Restrict);
// Composite Index برای UserId، WeekDefinitionId و PackageId
builder.HasIndex(e => new { e.UserId, e.WeekDefinitionId, e.PackageId })
.IsUnique()
.HasDatabaseName("IX_UserCommissionPayout_UserId_WeekDefinitionId");
.HasDatabaseName("IX_UserCommissionPayout_User_WeekDef_Package");
// Index برای WeeklyPoolId
builder.HasIndex(e => e.WeeklyPoolId)
@@ -33,7 +33,7 @@ public class UserPackagePurchaseConfiguration : IEntityTypeConfiguration<UserPac
// رابطه با Package
builder.HasOne(entity => entity.Package)
.WithMany()
.WithMany(p => p.Purchases)
.HasForeignKey(entity => entity.PackageId)
.OnDelete(DeleteBehavior.Restrict);
@@ -3,9 +3,9 @@ using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace CMSMicroservice.Infrastructure.Persistence.Configurations;
//آدرس کاربر
public class UserWalletChangeLogConfiguration : IEntityTypeConfiguration<UserWalletChangeLog>
public class UserWalletHistoryConfiguration : IEntityTypeConfiguration<UserWalletHistory>
{
public void Configure(EntityTypeBuilder<UserWalletChangeLog> builder)
public void Configure(EntityTypeBuilder<UserWalletHistory> builder)
{
builder.HasQueryFilter(p => !p.IsDeleted);
builder.Ignore(entity => entity.DomainEvents);
@@ -13,7 +13,7 @@ public class UserWalletChangeLogConfiguration : IEntityTypeConfiguration<UserWal
builder.Property(entity => entity.Id).UseIdentityColumn();
builder
.HasOne(entity => entity.Wallet)
.WithMany(entity => entity.UserWalletChangeLogs)
.WithMany(entity => entity.UserWalletHistories)
.HasForeignKey(entity => entity.WalletId)
.IsRequired(true);
builder.Property(entity => entity.CurrentBalance).IsRequired(true);
@@ -22,6 +22,14 @@ public class UserWalletChangeLogConfiguration : IEntityTypeConfiguration<UserWal
builder.Property(entity => entity.ChangeNerworkValue).IsRequired(true);
builder.Property(entity => entity.IsIncrease).IsRequired(true);
builder.Property(entity => entity.RefrenceId).IsRequired(false);
builder.Property(entity => entity.PackageId).IsRequired(false);
// رابطه با Package (nullable)
builder.HasOne(entity => entity.Package)
.WithMany()
.HasForeignKey(entity => entity.PackageId)
.IsRequired(false)
.OnDelete(DeleteBehavior.Restrict);
}
}
@@ -17,6 +17,7 @@ public class WeeklyCommissionPoolConfiguration : IEntityTypeConfiguration<Weekly
builder.Property(entity => entity.Id).UseIdentityColumn();
builder.Property(entity => entity.WeekDefinitionId).IsRequired();
builder.Property(entity => entity.PackageId).IsRequired();
builder.Property(entity => entity.TotalPoolAmount).IsRequired();
builder.Property(entity => entity.TotalBalances).IsRequired();
builder.Property(entity => entity.ValuePerBalance).IsRequired();
@@ -30,10 +31,16 @@ public class WeeklyCommissionPoolConfiguration : IEntityTypeConfiguration<Weekly
.IsRequired()
.OnDelete(DeleteBehavior.Restrict);
// Index یونیک برای WeekDefinitionId
builder.HasIndex(e => e.WeekDefinitionId)
// رابطه با Package
builder.HasOne(entity => entity.Package)
.WithMany()
.HasForeignKey(entity => entity.PackageId)
.OnDelete(DeleteBehavior.Restrict);
// Index یونیک ترکیبی: هر هفته × هر پکیج فقط یک استخر
builder.HasIndex(e => new { e.WeekDefinitionId, e.PackageId })
.IsUnique()
.HasDatabaseName("IX_WeeklyCommissionPool_WeekDefinitionId");
.HasDatabaseName("IX_WeeklyCommissionPool_WeekDef_Package");
// Index برای IsCalculated
builder.HasIndex(e => e.IsCalculated)
@@ -0,0 +1,150 @@
using System.Collections.Generic;
using System.Linq;
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Common;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.Logging;
namespace CMSMicroservice.Infrastructure.Persistence.Interceptors;
/// <summary>
/// Interceptor ثبت خودکار تاریخچه تغییرات (Q27).
/// هر entity که IHasHistory&lt;T&gt; رو implement کرده باشه،
/// هنگام Modified یا Added شدن یک رکورد history ثبت می‌شه.
/// </summary>
public class HistoryTrackingSaveChangesInterceptor : SaveChangesInterceptor
{
private readonly ICurrentUserService _currentUserService;
private readonly ILogger<HistoryTrackingSaveChangesInterceptor> _logger;
public HistoryTrackingSaveChangesInterceptor(
ICurrentUserService currentUserService,
ILogger<HistoryTrackingSaveChangesInterceptor> logger)
{
_currentUserService = currentUserService;
_logger = logger;
}
public override InterceptionResult<int> SavingChanges(
DbContextEventData eventData,
InterceptionResult<int> result)
{
TrackHistoryChanges(eventData.Context);
return base.SavingChanges(eventData, result);
}
public override ValueTask<InterceptionResult<int>> SavingChangesAsync(
DbContextEventData eventData,
InterceptionResult<int> result,
CancellationToken cancellationToken = default)
{
TrackHistoryChanges(eventData.Context);
return base.SavingChangesAsync(eventData, result, cancellationToken);
}
private void TrackHistoryChanges(DbContext? context)
{
if (context == null) return;
var performedBy = _currentUserService.GetPerformedBy();
var historyEntries = new List<object>();
foreach (var entry in context.ChangeTracker.Entries())
{
// فقط Modified و Added — Deleted رو ignore می‌کنیم (soft delete)
if (entry.State != EntityState.Modified && entry.State != EntityState.Added)
continue;
var entityType = entry.Entity.GetType();
// بررسی اینکه entity آیا IHasHistory<T> رو implement کرده
var historyInterface = entityType.GetInterfaces()
.FirstOrDefault(i => i.IsGenericType
&& i.GetGenericTypeDefinition() == typeof(IHasHistory<>));
if (historyInterface == null)
continue;
// تعیین نوع عملیات
var action = entry.State == EntityState.Added ? "Created" : "Updated";
try
{
// فراخوانی CreateHistorySnapshot از طریق reflection
var method = historyInterface.GetMethod("CreateHistorySnapshot");
if (method == null) continue;
var historyEntity = method.Invoke(entry.Entity, new object?[] { action, performedBy });
if (historyEntity == null) continue;
// برای Modified: مقادیر Original رو ست کنیم
if (entry.State == EntityState.Modified)
{
SetOriginalValues(entry, historyEntity);
}
historyEntries.Add(historyEntity);
}
catch (Exception ex)
{
_logger.LogWarning(ex,
"Failed to create history snapshot for {EntityType} (Id={Id})",
entityType.Name,
entry.Property("Id").CurrentValue);
}
}
// اضافه کردن history entities به context
foreach (var historyEntry in historyEntries)
{
context.Add(historyEntry);
}
if (historyEntries.Count > 0)
{
_logger.LogDebug("HistoryTrackingInterceptor: {Count} history records queued", historyEntries.Count);
}
}
/// <summary>
/// ست کردن مقادیر Original (قبل از تغییر) روی history entity.
/// از روی نام property: "OldX" ← OriginalValue("X"), "NewX" ← CurrentValue("X")
/// </summary>
private static void SetOriginalValues(
Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry entry,
object historyEntity)
{
var historyType = historyEntity.GetType();
var historyProps = historyType.GetProperties();
foreach (var historyProp in historyProps)
{
// الگو: OldPrice ← entry.OriginalValues["Price"]
if (!historyProp.Name.StartsWith("Old") || !historyProp.CanWrite)
continue;
var sourcePropertyName = historyProp.Name[3..]; // "OldPrice" → "Price"
try
{
var entryProperty = entry.Properties
.FirstOrDefault(p => p.Metadata.Name == sourcePropertyName);
if (entryProperty != null)
{
var originalValue = entryProperty.OriginalValue;
// تبدیل نوع اگه nullable باشه
if (originalValue != null || Nullable.GetUnderlyingType(historyProp.PropertyType) != null)
{
historyProp.SetValue(historyEntity, originalValue);
}
}
}
catch
{
// اگه property match نداشت، skip — ممکنه OldIsActive با bool? باشه
}
}
}
}
@@ -0,0 +1,683 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace CMSMicroservice.Infrastructure.Persistence.Migrations
{
/// <inheritdoc />
public partial class AddPackageBasedSystem : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_WeeklyCommissionPool_WeekDefinitionId",
schema: "CMS",
table: "WeeklyCommissionPools");
migrationBuilder.DropIndex(
name: "IX_UserCommissionPayout_UserId_WeekDefinitionId",
schema: "CMS",
table: "UserCommissionPayouts");
migrationBuilder.DropIndex(
name: "IX_NetworkWeeklyBalance_UserId_WeekDefinitionId",
schema: "CMS",
table: "NetworkWeeklyBalances");
migrationBuilder.AddColumn<long>(
name: "PackageId",
schema: "CMS",
table: "WeeklyCommissionPools",
type: "bigint",
nullable: false,
defaultValue: 0L);
migrationBuilder.AddColumn<long>(
name: "PackageId",
schema: "CMS",
table: "UserWalletChangeLogs",
type: "bigint",
nullable: true);
migrationBuilder.AddColumn<long>(
name: "PackageId",
schema: "CMS",
table: "UserCommissionPayouts",
type: "bigint",
nullable: false,
defaultValue: 0L);
migrationBuilder.AddColumn<long>(
name: "ActivationFee",
schema: "CMS",
table: "Packages",
type: "bigint",
nullable: false,
defaultValue: 0L);
migrationBuilder.AddColumn<decimal>(
name: "DiscountMultiplier",
schema: "CMS",
table: "Packages",
type: "decimal(18,4)",
precision: 18,
scale: 4,
nullable: false,
defaultValue: 2.0m);
migrationBuilder.AddColumn<bool>(
name: "IsActive",
schema: "CMS",
table: "Packages",
type: "bit",
nullable: false,
defaultValue: true);
migrationBuilder.AddColumn<bool>(
name: "IsBasePackage",
schema: "CMS",
table: "Packages",
type: "bit",
nullable: false,
defaultValue: false);
migrationBuilder.AddColumn<long>(
name: "MagicWalletMaxCredit",
schema: "CMS",
table: "Packages",
type: "bigint",
nullable: false,
defaultValue: 2500000000L);
migrationBuilder.AddColumn<long>(
name: "MagicWalletMaxDeposit",
schema: "CMS",
table: "Packages",
type: "bigint",
nullable: false,
defaultValue: 1000000000L);
migrationBuilder.AddColumn<decimal>(
name: "MagicWalletMultiplier",
schema: "CMS",
table: "Packages",
type: "decimal(18,4)",
precision: 18,
scale: 4,
nullable: false,
defaultValue: 2.5m);
migrationBuilder.AddColumn<int>(
name: "MaxBalancesPerLeg",
schema: "CMS",
table: "Packages",
type: "int",
nullable: false,
defaultValue: 300);
migrationBuilder.AddColumn<int>(
name: "MaxNetworkLevel",
schema: "CMS",
table: "Packages",
type: "int",
nullable: false,
defaultValue: 15);
migrationBuilder.AddColumn<int>(
name: "SortOrder",
schema: "CMS",
table: "Packages",
type: "int",
nullable: false,
defaultValue: 0);
migrationBuilder.AddColumn<bool>(
name: "SupportsDayaPurchase",
schema: "CMS",
table: "Packages",
type: "bit",
nullable: false,
defaultValue: false);
migrationBuilder.AddColumn<bool>(
name: "SupportsDirectPurchase",
schema: "CMS",
table: "Packages",
type: "bit",
nullable: false,
defaultValue: true);
migrationBuilder.AddColumn<long>(
name: "PackageId",
schema: "CMS",
table: "NetworkWeeklyBalances",
type: "bigint",
nullable: false,
defaultValue: 0L);
migrationBuilder.AddColumn<DateTime>(
name: "FirstActivationDate",
schema: "CMS",
table: "ClubMemberships",
type: "datetime2",
nullable: true);
migrationBuilder.AddColumn<long>(
name: "FirstPackageId",
schema: "CMS",
table: "ClubMemberships",
type: "bigint",
nullable: true);
migrationBuilder.AddColumn<DateTime>(
name: "LastActivationDate",
schema: "CMS",
table: "ClubMemberships",
type: "datetime2",
nullable: true);
migrationBuilder.AddColumn<long>(
name: "LastPackageId",
schema: "CMS",
table: "ClubMemberships",
type: "bigint",
nullable: true);
migrationBuilder.AddColumn<long>(
name: "PackageId",
schema: "CMS",
table: "ClubMembershipCycles",
type: "bigint",
nullable: false,
defaultValue: 0L);
migrationBuilder.CreateTable(
name: "PackageFeatures",
schema: "CMS",
columns: table => new
{
Id = table.Column<long>(type: "bigint", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
PackageId = table.Column<long>(type: "bigint", nullable: false),
ClubFeatureId = table.Column<long>(type: "bigint", nullable: false),
IsIncluded = table.Column<bool>(type: "bit", nullable: false, defaultValue: true),
Created = table.Column<DateTime>(type: "datetime2", nullable: false),
CreatedBy = table.Column<string>(type: "nvarchar(max)", nullable: true),
LastModified = table.Column<DateTime>(type: "datetime2", nullable: true),
LastModifiedBy = table.Column<string>(type: "nvarchar(max)", nullable: true),
IsDeleted = table.Column<bool>(type: "bit", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_PackageFeatures", x => x.Id);
table.ForeignKey(
name: "FK_PackageFeatures_ClubFeatures_ClubFeatureId",
column: x => x.ClubFeatureId,
principalSchema: "CMS",
principalTable: "ClubFeatures",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_PackageFeatures_Packages_PackageId",
column: x => x.PackageId,
principalSchema: "CMS",
principalTable: "Packages",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_WeeklyCommissionPool_WeekDef_Package",
schema: "CMS",
table: "WeeklyCommissionPools",
columns: new[] { "WeekDefinitionId", "PackageId" },
unique: true);
migrationBuilder.CreateIndex(
name: "IX_WeeklyCommissionPools_PackageId",
schema: "CMS",
table: "WeeklyCommissionPools",
column: "PackageId");
migrationBuilder.CreateIndex(
name: "IX_UserWalletChangeLogs_PackageId",
schema: "CMS",
table: "UserWalletChangeLogs",
column: "PackageId");
migrationBuilder.CreateIndex(
name: "IX_UserCommissionPayout_User_WeekDef_Package",
schema: "CMS",
table: "UserCommissionPayouts",
columns: new[] { "UserId", "WeekDefinitionId", "PackageId" },
unique: true);
migrationBuilder.CreateIndex(
name: "IX_UserCommissionPayouts_PackageId",
schema: "CMS",
table: "UserCommissionPayouts",
column: "PackageId");
migrationBuilder.CreateIndex(
name: "IX_Package_IsActive",
schema: "CMS",
table: "Packages",
column: "IsActive");
migrationBuilder.CreateIndex(
name: "IX_Package_SortOrder",
schema: "CMS",
table: "Packages",
column: "SortOrder");
migrationBuilder.CreateIndex(
name: "IX_NetworkWeeklyBalance_User_WeekDef_Package",
schema: "CMS",
table: "NetworkWeeklyBalances",
columns: new[] { "UserId", "WeekDefinitionId", "PackageId" },
unique: true);
migrationBuilder.CreateIndex(
name: "IX_NetworkWeeklyBalances_PackageId",
schema: "CMS",
table: "NetworkWeeklyBalances",
column: "PackageId");
migrationBuilder.CreateIndex(
name: "IX_ClubMembership_LastActivationDate",
schema: "CMS",
table: "ClubMemberships",
column: "LastActivationDate");
migrationBuilder.CreateIndex(
name: "IX_ClubMemberships_FirstPackageId",
schema: "CMS",
table: "ClubMemberships",
column: "FirstPackageId");
migrationBuilder.CreateIndex(
name: "IX_ClubMemberships_LastPackageId",
schema: "CMS",
table: "ClubMemberships",
column: "LastPackageId");
migrationBuilder.CreateIndex(
name: "IX_ClubMembershipCycles_PackageId",
schema: "CMS",
table: "ClubMembershipCycles",
column: "PackageId");
migrationBuilder.CreateIndex(
name: "IX_PackageFeature_PackageId_ClubFeatureId",
schema: "CMS",
table: "PackageFeatures",
columns: new[] { "PackageId", "ClubFeatureId" },
unique: true);
migrationBuilder.CreateIndex(
name: "IX_PackageFeatures_ClubFeatureId",
schema: "CMS",
table: "PackageFeatures",
column: "ClubFeatureId");
// === DATA MIGRATION: Seed golden package and backfill existing records ===
// 1. Ensure golden package exists with known Id
// Use IDENTITY_INSERT to guarantee Id=1 (if Package table uses identity)
migrationBuilder.Sql(@"
SET IDENTITY_INSERT [CMS].[Packages] ON;
IF NOT EXISTS (SELECT 1 FROM [CMS].[Packages] WHERE [Id] = 1)
BEGIN
INSERT INTO [CMS].[Packages]
([Id], [Title], [Description], [ImagePath], [Price],
[SortOrder], [IsActive], [IsBasePackage],
[SupportsDayaPurchase], [SupportsDirectPurchase],
[ActivationFee], [DiscountMultiplier], [MagicWalletMultiplier],
[MaxBalancesPerLeg], [MaxNetworkLevel],
[MagicWalletMaxDeposit], [MagicWalletMaxCredit],
[Created], [IsDeleted])
VALUES
(1, N'پکیج طلایی', N'پکیج اصلی باشگاه مشتریان کارا بازار سلامت',
N'/images/packages/golden.png', 56000000,
1, 1, 1,
1, 1,
25200000, 2.0, 2.5,
300, 15,
1000000000, 2500000000,
GETUTCDATE(), 0);
END
SET IDENTITY_INSERT [CMS].[Packages] OFF;
");
// 2. Backfill PackageId on existing records → point to golden package (Id=1)
migrationBuilder.Sql(@"
UPDATE [CMS].[WeeklyCommissionPools] SET [PackageId] = 1 WHERE [PackageId] = 0;
UPDATE [CMS].[UserCommissionPayouts] SET [PackageId] = 1 WHERE [PackageId] = 0;
UPDATE [CMS].[NetworkWeeklyBalances] SET [PackageId] = 1 WHERE [PackageId] = 0;
UPDATE [CMS].[ClubMembershipCycles] SET [PackageId] = 1 WHERE [PackageId] = 0;
");
// 3. Backfill ClubMembership First/Last fields from existing ActivatedAt
migrationBuilder.Sql(@"
UPDATE cm SET
cm.[FirstActivationDate] = cm.[ActivatedAt],
cm.[LastActivationDate] = cm.[ActivatedAt],
cm.[FirstPackageId] = 1,
cm.[LastPackageId] = 1
FROM [CMS].[ClubMemberships] cm
WHERE cm.[ActivatedAt] IS NOT NULL
AND cm.[FirstActivationDate] IS NULL;
");
// === END DATA MIGRATION ===
migrationBuilder.AddForeignKey(
name: "FK_ClubMembershipCycles_Packages_PackageId",
schema: "CMS",
table: "ClubMembershipCycles",
column: "PackageId",
principalSchema: "CMS",
principalTable: "Packages",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_ClubMemberships_Packages_FirstPackageId",
schema: "CMS",
table: "ClubMemberships",
column: "FirstPackageId",
principalSchema: "CMS",
principalTable: "Packages",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_ClubMemberships_Packages_LastPackageId",
schema: "CMS",
table: "ClubMemberships",
column: "LastPackageId",
principalSchema: "CMS",
principalTable: "Packages",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_NetworkWeeklyBalances_Packages_PackageId",
schema: "CMS",
table: "NetworkWeeklyBalances",
column: "PackageId",
principalSchema: "CMS",
principalTable: "Packages",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_UserCommissionPayouts_Packages_PackageId",
schema: "CMS",
table: "UserCommissionPayouts",
column: "PackageId",
principalSchema: "CMS",
principalTable: "Packages",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_UserWalletChangeLogs_Packages_PackageId",
schema: "CMS",
table: "UserWalletChangeLogs",
column: "PackageId",
principalSchema: "CMS",
principalTable: "Packages",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_WeeklyCommissionPools_Packages_PackageId",
schema: "CMS",
table: "WeeklyCommissionPools",
column: "PackageId",
principalSchema: "CMS",
principalTable: "Packages",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_ClubMembershipCycles_Packages_PackageId",
schema: "CMS",
table: "ClubMembershipCycles");
migrationBuilder.DropForeignKey(
name: "FK_ClubMemberships_Packages_FirstPackageId",
schema: "CMS",
table: "ClubMemberships");
migrationBuilder.DropForeignKey(
name: "FK_ClubMemberships_Packages_LastPackageId",
schema: "CMS",
table: "ClubMemberships");
migrationBuilder.DropForeignKey(
name: "FK_NetworkWeeklyBalances_Packages_PackageId",
schema: "CMS",
table: "NetworkWeeklyBalances");
migrationBuilder.DropForeignKey(
name: "FK_UserCommissionPayouts_Packages_PackageId",
schema: "CMS",
table: "UserCommissionPayouts");
migrationBuilder.DropForeignKey(
name: "FK_UserWalletChangeLogs_Packages_PackageId",
schema: "CMS",
table: "UserWalletChangeLogs");
migrationBuilder.DropForeignKey(
name: "FK_WeeklyCommissionPools_Packages_PackageId",
schema: "CMS",
table: "WeeklyCommissionPools");
migrationBuilder.DropTable(
name: "PackageFeatures",
schema: "CMS");
migrationBuilder.DropIndex(
name: "IX_WeeklyCommissionPool_WeekDef_Package",
schema: "CMS",
table: "WeeklyCommissionPools");
migrationBuilder.DropIndex(
name: "IX_WeeklyCommissionPools_PackageId",
schema: "CMS",
table: "WeeklyCommissionPools");
migrationBuilder.DropIndex(
name: "IX_UserWalletChangeLogs_PackageId",
schema: "CMS",
table: "UserWalletChangeLogs");
migrationBuilder.DropIndex(
name: "IX_UserCommissionPayout_User_WeekDef_Package",
schema: "CMS",
table: "UserCommissionPayouts");
migrationBuilder.DropIndex(
name: "IX_UserCommissionPayouts_PackageId",
schema: "CMS",
table: "UserCommissionPayouts");
migrationBuilder.DropIndex(
name: "IX_Package_IsActive",
schema: "CMS",
table: "Packages");
migrationBuilder.DropIndex(
name: "IX_Package_SortOrder",
schema: "CMS",
table: "Packages");
migrationBuilder.DropIndex(
name: "IX_NetworkWeeklyBalance_User_WeekDef_Package",
schema: "CMS",
table: "NetworkWeeklyBalances");
migrationBuilder.DropIndex(
name: "IX_NetworkWeeklyBalances_PackageId",
schema: "CMS",
table: "NetworkWeeklyBalances");
migrationBuilder.DropIndex(
name: "IX_ClubMembership_LastActivationDate",
schema: "CMS",
table: "ClubMemberships");
migrationBuilder.DropIndex(
name: "IX_ClubMemberships_FirstPackageId",
schema: "CMS",
table: "ClubMemberships");
migrationBuilder.DropIndex(
name: "IX_ClubMemberships_LastPackageId",
schema: "CMS",
table: "ClubMemberships");
migrationBuilder.DropIndex(
name: "IX_ClubMembershipCycles_PackageId",
schema: "CMS",
table: "ClubMembershipCycles");
migrationBuilder.DropColumn(
name: "PackageId",
schema: "CMS",
table: "WeeklyCommissionPools");
migrationBuilder.DropColumn(
name: "PackageId",
schema: "CMS",
table: "UserWalletChangeLogs");
migrationBuilder.DropColumn(
name: "PackageId",
schema: "CMS",
table: "UserCommissionPayouts");
migrationBuilder.DropColumn(
name: "ActivationFee",
schema: "CMS",
table: "Packages");
migrationBuilder.DropColumn(
name: "DiscountMultiplier",
schema: "CMS",
table: "Packages");
migrationBuilder.DropColumn(
name: "IsActive",
schema: "CMS",
table: "Packages");
migrationBuilder.DropColumn(
name: "IsBasePackage",
schema: "CMS",
table: "Packages");
migrationBuilder.DropColumn(
name: "MagicWalletMaxCredit",
schema: "CMS",
table: "Packages");
migrationBuilder.DropColumn(
name: "MagicWalletMaxDeposit",
schema: "CMS",
table: "Packages");
migrationBuilder.DropColumn(
name: "MagicWalletMultiplier",
schema: "CMS",
table: "Packages");
migrationBuilder.DropColumn(
name: "MaxBalancesPerLeg",
schema: "CMS",
table: "Packages");
migrationBuilder.DropColumn(
name: "MaxNetworkLevel",
schema: "CMS",
table: "Packages");
migrationBuilder.DropColumn(
name: "SortOrder",
schema: "CMS",
table: "Packages");
migrationBuilder.DropColumn(
name: "SupportsDayaPurchase",
schema: "CMS",
table: "Packages");
migrationBuilder.DropColumn(
name: "SupportsDirectPurchase",
schema: "CMS",
table: "Packages");
migrationBuilder.DropColumn(
name: "PackageId",
schema: "CMS",
table: "NetworkWeeklyBalances");
migrationBuilder.DropColumn(
name: "FirstActivationDate",
schema: "CMS",
table: "ClubMemberships");
migrationBuilder.DropColumn(
name: "FirstPackageId",
schema: "CMS",
table: "ClubMemberships");
migrationBuilder.DropColumn(
name: "LastActivationDate",
schema: "CMS",
table: "ClubMemberships");
migrationBuilder.DropColumn(
name: "LastPackageId",
schema: "CMS",
table: "ClubMemberships");
migrationBuilder.DropColumn(
name: "PackageId",
schema: "CMS",
table: "ClubMembershipCycles");
migrationBuilder.CreateIndex(
name: "IX_WeeklyCommissionPool_WeekDefinitionId",
schema: "CMS",
table: "WeeklyCommissionPools",
column: "WeekDefinitionId",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_UserCommissionPayout_UserId_WeekDefinitionId",
schema: "CMS",
table: "UserCommissionPayouts",
columns: new[] { "UserId", "WeekDefinitionId" },
unique: true);
migrationBuilder.CreateIndex(
name: "IX_NetworkWeeklyBalance_UserId_WeekDefinitionId",
schema: "CMS",
table: "NetworkWeeklyBalances",
columns: new[] { "UserId", "WeekDefinitionId" },
unique: true);
}
}
}
@@ -0,0 +1,190 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace CMSMicroservice.Infrastructure.Persistence.Migrations
{
/// <inheritdoc />
public partial class Q27_HistoryTables_And_RenameWalletHistory : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.RenameTable(
name: "UserWalletChangeLogs",
schema: "CMS",
newName: "UserWalletHistories",
newSchema: "CMS");
migrationBuilder.RenameIndex(
name: "IX_UserWalletChangeLogs_PackageId",
schema: "CMS",
table: "UserWalletHistories",
newName: "IX_UserWalletHistories_PackageId");
migrationBuilder.RenameIndex(
name: "IX_UserWalletChangeLogs_WalletId",
schema: "CMS",
table: "UserWalletHistories",
newName: "IX_UserWalletHistories_WalletId");
migrationBuilder.Sql(
"EXEC sp_rename N'CMS.PK_UserWalletChangeLogs', N'PK_UserWalletHistories', N'OBJECT'");
migrationBuilder.Sql(
"EXEC sp_rename N'CMS.FK_UserWalletChangeLogs_Packages_PackageId', N'FK_UserWalletHistories_Packages_PackageId', N'OBJECT'");
migrationBuilder.Sql(
"EXEC sp_rename N'CMS.FK_UserWalletChangeLogs_UserWallets_WalletId', N'FK_UserWalletHistories_UserWallets_WalletId', N'OBJECT'");
migrationBuilder.CreateTable(
name: "ClubMembershipCycleHistories",
schema: "CMS",
columns: table => new
{
Id = table.Column<long>(type: "bigint", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ClubMembershipCycleId = table.Column<long>(type: "bigint", nullable: false),
UserId = table.Column<long>(type: "bigint", nullable: false),
CycleNumber = table.Column<int>(type: "int", nullable: false),
OldIsCurrentCycle = table.Column<bool>(type: "bit", nullable: false),
NewIsCurrentCycle = table.Column<bool>(type: "bit", nullable: false),
OldMagicStartedAt = table.Column<DateTime>(type: "datetime2", nullable: true),
NewMagicStartedAt = table.Column<DateTime>(type: "datetime2", nullable: true),
OldMagicCompletedAt = table.Column<DateTime>(type: "datetime2", nullable: true),
NewMagicCompletedAt = table.Column<DateTime>(type: "datetime2", nullable: true),
Action = table.Column<int>(type: "int", nullable: false),
PerformedBy = table.Column<string>(type: "nvarchar(100)", maxLength: 100, nullable: true),
Reason = table.Column<string>(type: "nvarchar(500)", maxLength: 500, nullable: true),
Created = table.Column<DateTime>(type: "datetime2", nullable: false),
CreatedBy = table.Column<string>(type: "nvarchar(max)", nullable: true),
LastModified = table.Column<DateTime>(type: "datetime2", nullable: true),
LastModifiedBy = table.Column<string>(type: "nvarchar(max)", nullable: true),
IsDeleted = table.Column<bool>(type: "bit", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ClubMembershipCycleHistories", x => x.Id);
table.ForeignKey(
name: "FK_ClubMembershipCycleHistories_ClubMembershipCycles_ClubMembershipCycleId",
column: x => x.ClubMembershipCycleId,
principalSchema: "CMS",
principalTable: "ClubMembershipCycles",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "PackageHistories",
schema: "CMS",
columns: table => new
{
Id = table.Column<long>(type: "bigint", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
PackageId = table.Column<long>(type: "bigint", nullable: false),
OldPrice = table.Column<long>(type: "bigint", nullable: true),
NewPrice = table.Column<long>(type: "bigint", nullable: true),
OldActivationFee = table.Column<long>(type: "bigint", nullable: true),
NewActivationFee = table.Column<long>(type: "bigint", nullable: true),
OldMagicMultiplier = table.Column<decimal>(type: "decimal(18,4)", precision: 18, scale: 4, nullable: true),
NewMagicMultiplier = table.Column<decimal>(type: "decimal(18,4)", precision: 18, scale: 4, nullable: true),
OldMagicMaxDeposit = table.Column<long>(type: "bigint", nullable: true),
NewMagicMaxDeposit = table.Column<long>(type: "bigint", nullable: true),
OldMaxBalancesPerLeg = table.Column<int>(type: "int", nullable: true),
NewMaxBalancesPerLeg = table.Column<int>(type: "int", nullable: true),
OldIsActive = table.Column<bool>(type: "bit", nullable: true),
NewIsActive = table.Column<bool>(type: "bit", nullable: true),
Action = table.Column<int>(type: "int", nullable: false),
PerformedBy = table.Column<string>(type: "nvarchar(100)", maxLength: 100, nullable: true),
Reason = table.Column<string>(type: "nvarchar(500)", maxLength: 500, nullable: true),
Created = table.Column<DateTime>(type: "datetime2", nullable: false),
CreatedBy = table.Column<string>(type: "nvarchar(max)", nullable: true),
LastModified = table.Column<DateTime>(type: "datetime2", nullable: true),
LastModifiedBy = table.Column<string>(type: "nvarchar(max)", nullable: true),
IsDeleted = table.Column<bool>(type: "bit", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_PackageHistories", x => x.Id);
table.ForeignKey(
name: "FK_PackageHistories_Packages_PackageId",
column: x => x.PackageId,
principalSchema: "CMS",
principalTable: "Packages",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateIndex(
name: "IX_ClubMembershipCycleHistory_Action",
schema: "CMS",
table: "ClubMembershipCycleHistories",
column: "Action");
migrationBuilder.CreateIndex(
name: "IX_ClubMembershipCycleHistory_CycleId",
schema: "CMS",
table: "ClubMembershipCycleHistories",
column: "ClubMembershipCycleId");
migrationBuilder.CreateIndex(
name: "IX_ClubMembershipCycleHistory_UserId_Created",
schema: "CMS",
table: "ClubMembershipCycleHistories",
columns: new[] { "UserId", "Created" });
migrationBuilder.CreateIndex(
name: "IX_PackageHistory_Action",
schema: "CMS",
table: "PackageHistories",
column: "Action");
migrationBuilder.CreateIndex(
name: "IX_PackageHistory_PackageId_Created",
schema: "CMS",
table: "PackageHistories",
columns: new[] { "PackageId", "Created" });
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "ClubMembershipCycleHistories",
schema: "CMS");
migrationBuilder.DropTable(
name: "PackageHistories",
schema: "CMS");
migrationBuilder.RenameTable(
name: "UserWalletHistories",
schema: "CMS",
newName: "UserWalletChangeLogs",
newSchema: "CMS");
migrationBuilder.RenameIndex(
name: "IX_UserWalletHistories_PackageId",
schema: "CMS",
table: "UserWalletChangeLogs",
newName: "IX_UserWalletChangeLogs_PackageId");
migrationBuilder.RenameIndex(
name: "IX_UserWalletHistories_WalletId",
schema: "CMS",
table: "UserWalletChangeLogs",
newName: "IX_UserWalletChangeLogs_WalletId");
migrationBuilder.Sql(
"EXEC sp_rename N'CMS.PK_UserWalletHistories', N'PK_UserWalletChangeLogs', N'OBJECT'");
migrationBuilder.Sql(
"EXEC sp_rename N'CMS.FK_UserWalletHistories_Packages_PackageId', N'FK_UserWalletChangeLogs_Packages_PackageId', N'OBJECT'");
migrationBuilder.Sql(
"EXEC sp_rename N'CMS.FK_UserWalletHistories_UserWallets_WalletId', N'FK_UserWalletChangeLogs_UserWallets_WalletId', N'OBJECT'");
}
}
}
@@ -400,6 +400,12 @@ namespace CMSMicroservice.Infrastructure.Persistence.Migrations
b.Property<string>("CreatedBy")
.HasColumnType("nvarchar(max)");
b.Property<DateTime?>("FirstActivationDate")
.HasColumnType("datetime2");
b.Property<long?>("FirstPackageId")
.HasColumnType("bigint");
b.Property<long>("GiftValue")
.HasColumnType("bigint");
@@ -412,12 +418,18 @@ namespace CMSMicroservice.Infrastructure.Persistence.Migrations
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("LastActivationDate")
.HasColumnType("datetime2");
b.Property<DateTime?>("LastModified")
.HasColumnType("datetime2");
b.Property<string>("LastModifiedBy")
.HasColumnType("nvarchar(max)");
b.Property<long?>("LastPackageId")
.HasColumnType("bigint");
b.Property<int>("PurchaseMethod")
.HasColumnType("int");
@@ -429,9 +441,16 @@ namespace CMSMicroservice.Infrastructure.Persistence.Migrations
b.HasKey("Id");
b.HasIndex("FirstPackageId");
b.HasIndex("IsActive")
.HasDatabaseName("IX_ClubMembership_IsActive");
b.HasIndex("LastActivationDate")
.HasDatabaseName("IX_ClubMembership_LastActivationDate");
b.HasIndex("LastPackageId");
b.HasIndex("UserId")
.IsUnique()
.HasDatabaseName("IX_ClubMembership_UserId");
@@ -482,6 +501,9 @@ namespace CMSMicroservice.Infrastructure.Persistence.Migrations
b.Property<long>("PackageAmount")
.HasColumnType("bigint");
b.Property<long>("PackageId")
.HasColumnType("bigint");
b.Property<DateTime>("PackagePurchasedAt")
.HasColumnType("datetime2");
@@ -495,6 +517,8 @@ namespace CMSMicroservice.Infrastructure.Persistence.Migrations
b.HasIndex("ClubMembershipId");
b.HasIndex("PackageId");
b.HasIndex("PackagePurchasedAt")
.HasDatabaseName("IX_ClubMembershipCycle_PackagePurchasedAt");
@@ -598,6 +622,9 @@ namespace CMSMicroservice.Infrastructure.Persistence.Migrations
b.Property<string>("LastModifiedBy")
.HasColumnType("nvarchar(max)");
b.Property<long>("PackageId")
.HasColumnType("bigint");
b.Property<DateTime?>("PaidAt")
.HasColumnType("datetime2");
@@ -641,6 +668,8 @@ namespace CMSMicroservice.Infrastructure.Persistence.Migrations
b.HasKey("Id");
b.HasIndex("PackageId");
b.HasIndex("Status")
.HasDatabaseName("IX_UserCommissionPayout_Status");
@@ -649,9 +678,9 @@ namespace CMSMicroservice.Infrastructure.Persistence.Migrations
b.HasIndex("WeeklyPoolId")
.HasDatabaseName("IX_UserCommissionPayout_WeeklyPoolId");
b.HasIndex("UserId", "WeekDefinitionId")
b.HasIndex("UserId", "WeekDefinitionId", "PackageId")
.IsUnique()
.HasDatabaseName("IX_UserCommissionPayout_UserId_WeekDefinitionId");
.HasDatabaseName("IX_UserCommissionPayout_User_WeekDef_Package");
b.ToTable("UserCommissionPayouts", "CMS");
});
@@ -685,6 +714,9 @@ namespace CMSMicroservice.Infrastructure.Persistence.Migrations
b.Property<string>("LastModifiedBy")
.HasColumnType("nvarchar(max)");
b.Property<long>("PackageId")
.HasColumnType("bigint");
b.Property<int>("TotalBalances")
.HasColumnType("int");
@@ -702,9 +734,11 @@ namespace CMSMicroservice.Infrastructure.Persistence.Migrations
b.HasIndex("IsCalculated")
.HasDatabaseName("IX_WeeklyCommissionPool_IsCalculated");
b.HasIndex("WeekDefinitionId")
b.HasIndex("PackageId");
b.HasIndex("WeekDefinitionId", "PackageId")
.IsUnique()
.HasDatabaseName("IX_WeeklyCommissionPool_WeekDefinitionId");
.HasDatabaseName("IX_WeeklyCommissionPool_WeekDef_Package");
b.ToTable("WeeklyCommissionPools", "CMS");
});
@@ -1901,6 +1935,81 @@ namespace CMSMicroservice.Infrastructure.Persistence.Migrations
b.ToTable("States", "GMS");
});
modelBuilder.Entity("CMSMicroservice.Domain.Entities.History.ClubMembershipCycleHistory", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<long>("Id"));
b.Property<int>("Action")
.HasColumnType("int");
b.Property<long>("ClubMembershipCycleId")
.HasColumnType("bigint");
b.Property<DateTime>("Created")
.HasColumnType("datetime2");
b.Property<string>("CreatedBy")
.HasColumnType("nvarchar(max)");
b.Property<int>("CycleNumber")
.HasColumnType("int");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("LastModified")
.HasColumnType("datetime2");
b.Property<string>("LastModifiedBy")
.HasColumnType("nvarchar(max)");
b.Property<bool>("NewIsCurrentCycle")
.HasColumnType("bit");
b.Property<DateTime?>("NewMagicCompletedAt")
.HasColumnType("datetime2");
b.Property<DateTime?>("NewMagicStartedAt")
.HasColumnType("datetime2");
b.Property<bool>("OldIsCurrentCycle")
.HasColumnType("bit");
b.Property<DateTime?>("OldMagicCompletedAt")
.HasColumnType("datetime2");
b.Property<DateTime?>("OldMagicStartedAt")
.HasColumnType("datetime2");
b.Property<string>("PerformedBy")
.HasMaxLength(100)
.HasColumnType("nvarchar(100)");
b.Property<string>("Reason")
.HasMaxLength(500)
.HasColumnType("nvarchar(500)");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("Action")
.HasDatabaseName("IX_ClubMembershipCycleHistory_Action");
b.HasIndex("ClubMembershipCycleId")
.HasDatabaseName("IX_ClubMembershipCycleHistory_CycleId");
b.HasIndex("UserId", "Created")
.HasDatabaseName("IX_ClubMembershipCycleHistory_UserId_Created");
b.ToTable("ClubMembershipCycleHistories", "CMS");
});
modelBuilder.Entity("CMSMicroservice.Domain.Entities.History.ClubMembershipHistory", b =>
{
b.Property<long>("Id")
@@ -2099,6 +2208,92 @@ namespace CMSMicroservice.Infrastructure.Persistence.Migrations
b.ToTable("NetworkMembershipHistories", "CMS");
});
modelBuilder.Entity("CMSMicroservice.Domain.Entities.History.PackageHistory", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<long>("Id"));
b.Property<int>("Action")
.HasColumnType("int");
b.Property<DateTime>("Created")
.HasColumnType("datetime2");
b.Property<string>("CreatedBy")
.HasColumnType("nvarchar(max)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("LastModified")
.HasColumnType("datetime2");
b.Property<string>("LastModifiedBy")
.HasColumnType("nvarchar(max)");
b.Property<long?>("NewActivationFee")
.HasColumnType("bigint");
b.Property<bool?>("NewIsActive")
.HasColumnType("bit");
b.Property<long?>("NewMagicMaxDeposit")
.HasColumnType("bigint");
b.Property<decimal?>("NewMagicMultiplier")
.HasPrecision(18, 4)
.HasColumnType("decimal(18,4)");
b.Property<int?>("NewMaxBalancesPerLeg")
.HasColumnType("int");
b.Property<long?>("NewPrice")
.HasColumnType("bigint");
b.Property<long?>("OldActivationFee")
.HasColumnType("bigint");
b.Property<bool?>("OldIsActive")
.HasColumnType("bit");
b.Property<long?>("OldMagicMaxDeposit")
.HasColumnType("bigint");
b.Property<decimal?>("OldMagicMultiplier")
.HasPrecision(18, 4)
.HasColumnType("decimal(18,4)");
b.Property<int?>("OldMaxBalancesPerLeg")
.HasColumnType("int");
b.Property<long?>("OldPrice")
.HasColumnType("bigint");
b.Property<long>("PackageId")
.HasColumnType("bigint");
b.Property<string>("PerformedBy")
.HasMaxLength(100)
.HasColumnType("nvarchar(100)");
b.Property<string>("Reason")
.HasMaxLength(500)
.HasColumnType("nvarchar(500)");
b.HasKey("Id");
b.HasIndex("Action")
.HasDatabaseName("IX_PackageHistory_Action");
b.HasIndex("PackageId", "Created")
.HasDatabaseName("IX_PackageHistory_PackageId_Created");
b.ToTable("PackageHistories", "CMS");
});
modelBuilder.Entity("CMSMicroservice.Domain.Entities.InventoryItem", b =>
{
b.Property<long>("Id")
@@ -2242,6 +2437,9 @@ namespace CMSMicroservice.Infrastructure.Persistence.Migrations
b.Property<int>("LeftLegTotal")
.HasColumnType("int");
b.Property<long>("PackageId")
.HasColumnType("bigint");
b.Property<int>("RightLegBalances")
.HasColumnType("int");
@@ -2280,12 +2478,14 @@ namespace CMSMicroservice.Infrastructure.Persistence.Migrations
b.HasIndex("IsExpired")
.HasDatabaseName("IX_NetworkWeeklyBalance_IsExpired");
b.HasIndex("PackageId");
b.HasIndex("WeekDefinitionId")
.HasDatabaseName("IX_NetworkWeeklyBalance_WeekDefinitionId");
b.HasIndex("UserId", "WeekDefinitionId")
b.HasIndex("UserId", "WeekDefinitionId", "PackageId")
.IsUnique()
.HasDatabaseName("IX_NetworkWeeklyBalance_UserId_WeekDefinitionId");
.HasDatabaseName("IX_NetworkWeeklyBalance_User_WeekDef_Package");
b.ToTable("NetworkWeeklyBalances", "CMS");
});
@@ -2412,6 +2612,11 @@ namespace CMSMicroservice.Infrastructure.Persistence.Migrations
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<long>("Id"));
b.Property<long>("ActivationFee")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasDefaultValue(0L);
b.Property<DateTime>("Created")
.HasColumnType("datetime2");
@@ -2422,10 +2627,26 @@ namespace CMSMicroservice.Infrastructure.Persistence.Migrations
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<decimal>("DiscountMultiplier")
.ValueGeneratedOnAdd()
.HasPrecision(18, 4)
.HasColumnType("decimal(18,4)")
.HasDefaultValue(2.0m);
b.Property<string>("ImagePath")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<bool>("IsActive")
.ValueGeneratedOnAdd()
.HasColumnType("bit")
.HasDefaultValue(true);
b.Property<bool>("IsBasePackage")
.ValueGeneratedOnAdd()
.HasColumnType("bit")
.HasDefaultValue(false);
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
@@ -2435,18 +2656,110 @@ namespace CMSMicroservice.Infrastructure.Persistence.Migrations
b.Property<string>("LastModifiedBy")
.HasColumnType("nvarchar(max)");
b.Property<long>("MagicWalletMaxCredit")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasDefaultValue(2500000000L);
b.Property<long>("MagicWalletMaxDeposit")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasDefaultValue(1000000000L);
b.Property<decimal>("MagicWalletMultiplier")
.ValueGeneratedOnAdd()
.HasPrecision(18, 4)
.HasColumnType("decimal(18,4)")
.HasDefaultValue(2.5m);
b.Property<int>("MaxBalancesPerLeg")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasDefaultValue(300);
b.Property<int>("MaxNetworkLevel")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasDefaultValue(15);
b.Property<long>("Price")
.HasColumnType("bigint");
b.Property<int>("SortOrder")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasDefaultValue(0);
b.Property<bool>("SupportsDayaPurchase")
.ValueGeneratedOnAdd()
.HasColumnType("bit")
.HasDefaultValue(false);
b.Property<bool>("SupportsDirectPurchase")
.ValueGeneratedOnAdd()
.HasColumnType("bit")
.HasDefaultValue(true);
b.Property<string>("Title")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("IsActive")
.HasDatabaseName("IX_Package_IsActive");
b.HasIndex("SortOrder")
.HasDatabaseName("IX_Package_SortOrder");
b.ToTable("Packages", "CMS");
});
modelBuilder.Entity("CMSMicroservice.Domain.Entities.PackageFeature", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<long>("Id"));
b.Property<long>("ClubFeatureId")
.HasColumnType("bigint");
b.Property<DateTime>("Created")
.HasColumnType("datetime2");
b.Property<string>("CreatedBy")
.HasColumnType("nvarchar(max)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<bool>("IsIncluded")
.ValueGeneratedOnAdd()
.HasColumnType("bit")
.HasDefaultValue(true);
b.Property<DateTime?>("LastModified")
.HasColumnType("datetime2");
b.Property<string>("LastModifiedBy")
.HasColumnType("nvarchar(max)");
b.Property<long>("PackageId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("ClubFeatureId");
b.HasIndex("PackageId", "ClubFeatureId")
.IsUnique()
.HasDatabaseName("IX_PackageFeature_PackageId_ClubFeatureId");
b.ToTable("PackageFeatures", "CMS");
});
modelBuilder.Entity("CMSMicroservice.Domain.Entities.Payment.ManualPayment", b =>
{
b.Property<long>("Id")
@@ -3674,7 +3987,7 @@ namespace CMSMicroservice.Infrastructure.Persistence.Migrations
b.ToTable("UserWallets", "CMS");
});
modelBuilder.Entity("CMSMicroservice.Domain.Entities.UserWalletChangeLog", b =>
modelBuilder.Entity("CMSMicroservice.Domain.Entities.UserWalletHistory", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
@@ -3718,6 +4031,9 @@ namespace CMSMicroservice.Infrastructure.Persistence.Migrations
b.Property<string>("LastModifiedBy")
.HasColumnType("nvarchar(max)");
b.Property<long?>("PackageId")
.HasColumnType("bigint");
b.Property<long?>("RefrenceId")
.HasColumnType("bigint");
@@ -3726,9 +4042,11 @@ namespace CMSMicroservice.Infrastructure.Persistence.Migrations
b.HasKey("Id");
b.HasIndex("PackageId");
b.HasIndex("WalletId");
b.ToTable("UserWalletChangeLogs", "CMS");
b.ToTable("UserWalletHistories", "CMS");
});
modelBuilder.Entity("CMSMicroservice.Domain.Entities.Warehouse", b =>
@@ -3947,12 +4265,26 @@ namespace CMSMicroservice.Infrastructure.Persistence.Migrations
modelBuilder.Entity("CMSMicroservice.Domain.Entities.Club.ClubMembership", b =>
{
b.HasOne("CMSMicroservice.Domain.Entities.Package", "FirstPackage")
.WithMany()
.HasForeignKey("FirstPackageId")
.OnDelete(DeleteBehavior.Restrict);
b.HasOne("CMSMicroservice.Domain.Entities.Package", "LastPackage")
.WithMany()
.HasForeignKey("LastPackageId")
.OnDelete(DeleteBehavior.Restrict);
b.HasOne("CMSMicroservice.Domain.Entities.User", "User")
.WithOne("ClubMembership")
.HasForeignKey("CMSMicroservice.Domain.Entities.Club.ClubMembership", "UserId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("FirstPackage");
b.Navigation("LastPackage");
b.Navigation("User");
});
@@ -3964,6 +4296,12 @@ namespace CMSMicroservice.Infrastructure.Persistence.Migrations
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("CMSMicroservice.Domain.Entities.Package", "Package")
.WithMany()
.HasForeignKey("PackageId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("CMSMicroservice.Domain.Entities.User", "User")
.WithMany()
.HasForeignKey("UserId")
@@ -3972,6 +4310,8 @@ namespace CMSMicroservice.Infrastructure.Persistence.Migrations
b.Navigation("ClubMembership");
b.Navigation("Package");
b.Navigation("User");
});
@@ -4004,6 +4344,12 @@ namespace CMSMicroservice.Infrastructure.Persistence.Migrations
modelBuilder.Entity("CMSMicroservice.Domain.Entities.Commission.UserCommissionPayout", b =>
{
b.HasOne("CMSMicroservice.Domain.Entities.Package", "Package")
.WithMany()
.HasForeignKey("PackageId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("CMSMicroservice.Domain.Entities.User", "User")
.WithMany("CommissionPayouts")
.HasForeignKey("UserId")
@@ -4022,6 +4368,8 @@ namespace CMSMicroservice.Infrastructure.Persistence.Migrations
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Package");
b.Navigation("User");
b.Navigation("WeekDefinition");
@@ -4031,12 +4379,20 @@ namespace CMSMicroservice.Infrastructure.Persistence.Migrations
modelBuilder.Entity("CMSMicroservice.Domain.Entities.Commission.WeeklyCommissionPool", b =>
{
b.HasOne("CMSMicroservice.Domain.Entities.Package", "Package")
.WithMany()
.HasForeignKey("PackageId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("CMSMicroservice.Domain.Entities.WeekDefinition", "WeekDefinition")
.WithMany("WeeklyCommissionPools")
.HasForeignKey("WeekDefinitionId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Package");
b.Navigation("WeekDefinition");
});
@@ -4235,6 +4591,17 @@ namespace CMSMicroservice.Infrastructure.Persistence.Migrations
b.Navigation("Country");
});
modelBuilder.Entity("CMSMicroservice.Domain.Entities.History.ClubMembershipCycleHistory", b =>
{
b.HasOne("CMSMicroservice.Domain.Entities.Club.ClubMembershipCycle", "ClubMembershipCycle")
.WithMany("CycleHistories")
.HasForeignKey("ClubMembershipCycleId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("ClubMembershipCycle");
});
modelBuilder.Entity("CMSMicroservice.Domain.Entities.History.ClubMembershipHistory", b =>
{
b.HasOne("CMSMicroservice.Domain.Entities.Club.ClubMembership", "ClubMembership")
@@ -4265,6 +4632,17 @@ namespace CMSMicroservice.Infrastructure.Persistence.Migrations
b.Navigation("WeekDefinition");
});
modelBuilder.Entity("CMSMicroservice.Domain.Entities.History.PackageHistory", b =>
{
b.HasOne("CMSMicroservice.Domain.Entities.Package", "Package")
.WithMany("PackageHistories")
.HasForeignKey("PackageId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Package");
});
modelBuilder.Entity("CMSMicroservice.Domain.Entities.InventoryItem", b =>
{
b.HasOne("CMSMicroservice.Domain.Entities.DiscountShop.DiscountProduct", "DiscountProduct")
@@ -4292,6 +4670,12 @@ namespace CMSMicroservice.Infrastructure.Persistence.Migrations
modelBuilder.Entity("CMSMicroservice.Domain.Entities.Network.NetworkWeeklyBalance", b =>
{
b.HasOne("CMSMicroservice.Domain.Entities.Package", "Package")
.WithMany()
.HasForeignKey("PackageId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("CMSMicroservice.Domain.Entities.User", "User")
.WithMany("NetworkWeeklyBalances")
.HasForeignKey("UserId")
@@ -4304,6 +4688,8 @@ namespace CMSMicroservice.Infrastructure.Persistence.Migrations
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Package");
b.Navigation("User");
b.Navigation("WeekDefinition");
@@ -4320,6 +4706,25 @@ namespace CMSMicroservice.Infrastructure.Persistence.Migrations
b.Navigation("Order");
});
modelBuilder.Entity("CMSMicroservice.Domain.Entities.PackageFeature", b =>
{
b.HasOne("CMSMicroservice.Domain.Entities.Club.ClubFeature", "ClubFeature")
.WithMany()
.HasForeignKey("ClubFeatureId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("CMSMicroservice.Domain.Entities.Package", "Package")
.WithMany("PackageFeatures")
.HasForeignKey("PackageId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("ClubFeature");
b.Navigation("Package");
});
modelBuilder.Entity("CMSMicroservice.Domain.Entities.Payment.ManualPayment", b =>
{
b.HasOne("CMSMicroservice.Domain.Entities.Transaction", "Transaction")
@@ -4504,7 +4909,7 @@ namespace CMSMicroservice.Infrastructure.Persistence.Migrations
.OnDelete(DeleteBehavior.Restrict);
b.HasOne("CMSMicroservice.Domain.Entities.Package", "Package")
.WithMany()
.WithMany("Purchases")
.HasForeignKey("PackageId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
@@ -4559,14 +4964,21 @@ namespace CMSMicroservice.Infrastructure.Persistence.Migrations
b.Navigation("User");
});
modelBuilder.Entity("CMSMicroservice.Domain.Entities.UserWalletChangeLog", b =>
modelBuilder.Entity("CMSMicroservice.Domain.Entities.UserWalletHistory", b =>
{
b.HasOne("CMSMicroservice.Domain.Entities.Package", "Package")
.WithMany()
.HasForeignKey("PackageId")
.OnDelete(DeleteBehavior.Restrict);
b.HasOne("CMSMicroservice.Domain.Entities.UserWallet", "Wallet")
.WithMany("UserWalletChangeLogs")
.WithMany("UserWalletHistories")
.HasForeignKey("WalletId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Package");
b.Navigation("Wallet");
});
@@ -4605,6 +5017,11 @@ namespace CMSMicroservice.Infrastructure.Persistence.Migrations
b.Navigation("UserClubFeatures");
});
modelBuilder.Entity("CMSMicroservice.Domain.Entities.Club.ClubMembershipCycle", b =>
{
b.Navigation("CycleHistories");
});
modelBuilder.Entity("CMSMicroservice.Domain.Entities.Commission.UserCommissionPayout", b =>
{
b.Navigation("CommissionPayoutHistories");
@@ -4670,6 +5087,12 @@ namespace CMSMicroservice.Infrastructure.Persistence.Migrations
modelBuilder.Entity("CMSMicroservice.Domain.Entities.Package", b =>
{
b.Navigation("PackageFeatures");
b.Navigation("PackageHistories");
b.Navigation("Purchases");
b.Navigation("UserOrders");
});
@@ -4751,7 +5174,7 @@ namespace CMSMicroservice.Infrastructure.Persistence.Migrations
modelBuilder.Entity("CMSMicroservice.Domain.Entities.UserWallet", b =>
{
b.Navigation("UserWalletChangeLogs");
b.Navigation("UserWalletHistories");
});
modelBuilder.Entity("CMSMicroservice.Domain.Entities.Warehouse", b =>
@@ -8,6 +8,9 @@
CREATE OR ALTER PROCEDURE [CMS].[sp_CalculateWeeklyBalances]
@WeekDefinitionId BIGINT,
@ForceRecalculate BIT = 0,
@PackageId BIGINT = NULL, -- پکیج خاص (اگر NULL از پکیج پایه استفاده می‌کند)
@InputMaxBalancesPerLeg INT = NULL, -- سقف تعادل هر پا (از Package entity)
@InputMaxNetworkLevel INT = NULL, -- حداکثر عمق شبکه (از Package entity)
@RowCount INT OUTPUT
AS
BEGIN
@@ -18,10 +21,33 @@ BEGIN
DECLARE @StartDate DATETIME;
DECLARE @EndDate DATETIME;
DECLARE @PreviousWeekDefinitionId BIGINT;
DECLARE @MaxBalancesPerLeg INT = 300;
DECLARE @MaxNetworkLevel INT = 15;
DECLARE @MaxBalancesPerLeg INT;
DECLARE @MaxNetworkLevel INT;
DECLARE @CalculatedAt DATETIME = GETDATE();
-- تعیین PackageId پیش‌فرض (پکیج پایه)
IF @PackageId IS NULL
BEGIN
SELECT TOP 1 @PackageId = Id
FROM CMS.Packages
WHERE IsBasePackage = 1 AND IsDeleted = 0;
END
-- خواندن تنظیمات از Package entity اگر پارامتر داده نشده
IF @InputMaxBalancesPerLeg IS NOT NULL
SET @MaxBalancesPerLeg = @InputMaxBalancesPerLeg;
ELSE
SELECT @MaxBalancesPerLeg = ISNULL(MaxBalancesPerLeg, 300) FROM CMS.Packages WHERE Id = @PackageId;
IF @InputMaxNetworkLevel IS NOT NULL
SET @MaxNetworkLevel = @InputMaxNetworkLevel;
ELSE
SELECT @MaxNetworkLevel = ISNULL(MaxNetworkLevel, 15) FROM CMS.Packages WHERE Id = @PackageId;
-- fallbackهای امن
SET @MaxBalancesPerLeg = ISNULL(@MaxBalancesPerLeg, 300);
SET @MaxNetworkLevel = ISNULL(@MaxNetworkLevel, 15);
BEGIN TRY
BEGIN TRANSACTION;
@@ -65,11 +91,9 @@ BEGIN
AND IsActive = 1;
-- =============================================
-- 4. مقادیر ثابت (Hardcoded - از SystemConstants)
-- 4. تنظیمات پکیج (از پارامترها خوانده می‌شود)
-- =============================================
-- این مقادیر ثابت هستند و تغییر نمی‌کنند
SET @MaxBalancesPerLeg = 300; -- سقف تعادل هر پا
SET @MaxNetworkLevel = 15; -- حداکثر عمق شبکه
-- @MaxBalancesPerLeg و @MaxNetworkLevel قبلاً مقداردهی شده‌اند
-- =============================================
-- 5. ایجاد جدول موقت برای نتایج
@@ -96,7 +120,8 @@ BEGIN
INSERT INTO #Balances (UserId)
SELECT DISTINCT u.Id
FROM CMS.Users u
INNER JOIN CMS.ClubMemberships cm ON cm.UserId = u.Id AND cm.IsActive = 1;
INNER JOIN CMS.ClubMemberships cm ON cm.UserId = u.Id AND cm.IsActive = 1
WHERE cm.LastPackageId = @PackageId;
-- =============================================
-- 7. دریافت باقیمانده هفته قبل
@@ -107,7 +132,9 @@ BEGIN
SET b.LeftLegCarryover = ISNULL(nb.LeftLegRemainder, 0),
b.RightLegCarryover = ISNULL(nb.RightLegRemainder, 0)
FROM #Balances b
LEFT JOIN CMS.NetworkWeeklyBalances nb ON nb.UserId = b.UserId AND nb.WeekDefinitionId = @PreviousWeekDefinitionId;
LEFT JOIN CMS.NetworkWeeklyBalances nb ON nb.UserId = b.UserId
AND nb.WeekDefinitionId = @PreviousWeekDefinitionId
AND nb.PackageId = @PackageId;
END
-- =============================================
@@ -269,6 +296,7 @@ BEGIN
INSERT INTO CMS.NetworkWeeklyBalances (
UserId,
WeekDefinitionId,
PackageId,
LeftLegNewMembers,
RightLegNewMembers,
LeftLegCarryover,
@@ -295,6 +323,7 @@ BEGIN
SELECT
UserId,
@WeekDefinitionId,
@PackageId,
LeftLegNewMembers,
RightLegNewMembers,
LeftLegCarryover,
@@ -62,10 +62,20 @@ public class OrmCommissionCalculationStrategy : ICommissionCalculationStrategy
.Select(w => w.UserId)
.ToHashSetAsync(cancellationToken);
var activeClubMemberUserIds = await _context.ClubMemberships
// دریافت عضویت‌های فعال به همراه PackageId هر کاربر
var activeClubMemberships = await _context.ClubMemberships
.Where(c => c.IsActive && !magicModeUserIds.Contains(c.UserId))
.Select(c => new { c.UserId, PackageId = c.LastPackageId })
.ToListAsync(cancellationToken);
var activeClubMemberUserIds = activeClubMemberships
.Select(c => c.UserId)
.ToHashSetAsync(cancellationToken);
.ToHashSet();
// نگاشت کاربر → PackageId
var userPackageMap = activeClubMemberships
.Where(c => c.PackageId.HasValue)
.ToDictionary(c => c.UserId, c => c.PackageId!.Value);
// دریافت کاربران فعال در شبکه که عضو باشگاه هستند
var usersInNetwork = await _context.Users
@@ -73,40 +83,52 @@ public class OrmCommissionCalculationStrategy : ICommissionCalculationStrategy
.Select(x => new { x.Id })
.ToListAsync(cancellationToken);
// دریافت باقیمانده‌های هفته قبل
// بارگذاری همه پکیج‌های فعال (bulk load)
var allPackages = await _context.Packages
.Where(p => !p.IsDeleted)
.ToDictionaryAsync(p => p.Id, cancellationToken);
// پکیج پیش‌فرض (fallback برای کاربرانی که PackageId ندارند)
var defaultPackage = allPackages.Values
.FirstOrDefault(p => p.IsBasePackage)
?? throw new InvalidOperationException("پکیج پایه یافت نشد");
// دریافت باقیمانده‌های هفته قبل — شامل PackageId
var previousWeekDefinitionId = GetPreviousWeekDefinitionId(weekDefinitionId);
Dictionary<long, (int LeftLegRemainder, int RightLegRemainder)> previousWeekCarryovers;
Dictionary<(long UserId, long PackageId), (int LeftLegRemainder, int RightLegRemainder)> previousWeekCarryovers;
if (previousWeekDefinitionId.HasValue)
{
previousWeekCarryovers = await _context.NetworkWeeklyBalances
.Where(x => x.WeekDefinitionId == previousWeekDefinitionId.Value)
.ToDictionaryAsync(
x => x.UserId,
x => (x.UserId, x.PackageId),
x => (x.LeftLegRemainder, x.RightLegRemainder),
cancellationToken);
}
else
{
previousWeekCarryovers = new Dictionary<long, (int, int)>();
previousWeekCarryovers = new Dictionary<(long, long), (int, int)>();
}
var balancesList = new List<NetworkWeeklyBalance>();
var calculatedAt = DateTime.Now;
// استفاده از SystemConstants به جای دیتابیس
var maxBalancesPerLeg = SystemConstants.CommissionMaxWeeklyBalancesPerLeg;
var maxNetworkLevel = SystemConstants.CommissionMaxNetworkLevel;
foreach (var user in usersInNetwork.OrderBy(o => o.Id))
{
// دریافت باقیمانده هفته قبل
// تعیین پکیج هر کاربر (per-user)
var userPackageId = userPackageMap.GetValueOrDefault(user.Id, defaultPackage.Id);
var package = allPackages.GetValueOrDefault(userPackageId, defaultPackage);
var maxBalancesPerLeg = package.MaxBalancesPerLeg;
var maxNetworkLevel = package.MaxNetworkLevel;
// دریافت باقیمانده هفته قبل — فیلتر per-package
var leftCarryover = 0;
var rightCarryover = 0;
if (previousWeekCarryovers.ContainsKey(user.Id))
var carryoverKey = (UserId: user.Id, PackageId: userPackageId);
if (previousWeekCarryovers.ContainsKey(carryoverKey))
{
leftCarryover = previousWeekCarryovers[user.Id].LeftLegRemainder;
rightCarryover = previousWeekCarryovers[user.Id].RightLegRemainder;
leftCarryover = previousWeekCarryovers[carryoverKey].LeftLegRemainder;
rightCarryover = previousWeekCarryovers[carryoverKey].RightLegRemainder;
}
// محاسبه تعداد اعضای جدید در این هفته (تا maxNetworkLevel لول پایین‌تر)
@@ -135,6 +157,7 @@ public class OrmCommissionCalculationStrategy : ICommissionCalculationStrategy
{
UserId = user.Id,
WeekDefinitionId = weekDefinitionId,
PackageId = package.Id,
LeftLegNewMembers = leftNewMembers,
RightLegNewMembers = rightNewMembers,
LeftLegCarryover = leftCarryover,
@@ -162,15 +185,16 @@ public class OrmCommissionCalculationStrategy : ICommissionCalculationStrategy
await _context.NetworkWeeklyBalances.AddRangeAsync(balancesList, cancellationToken);
await _context.SaveChangesAsync(cancellationToken);
// محاسبه تعادل زیرمجموعه
// محاسبه تعادل زیرمجموعه — per-user maxNetworkLevel
var balancesDictionary = balancesList.ToDictionary(x => x.UserId);
foreach (var balance in balancesList)
{
var balancePackage = allPackages.GetValueOrDefault(balance.PackageId, defaultPackage);
var subordinateBalances = await CalculateSubordinateBalancesAsync(
balance.UserId,
balancesDictionary,
maxNetworkLevel,
balancePackage.MaxNetworkLevel,
cancellationToken
);
@@ -284,6 +308,7 @@ public class OrmCommissionCalculationStrategy : ICommissionCalculationStrategy
UserId = balance.UserId,
WeekDefinitionId = weekDefinitionId,
WeeklyPoolId = existingPool.Id,
PackageId = balance.PackageId, // per-user PackageId از محاسبه تعادل
BalancesEarned = userBalance,
ValuePerBalance = valuePerBalance,
TotalAmount = totalAmount,
@@ -446,7 +471,7 @@ public class OrmCommissionCalculationStrategy : ICommissionCalculationStrategy
.ToDictionaryAsync(w => w.UserId, cancellationToken);
var newWallets = new List<UserWallet>();
var walletLogs = new List<UserWalletChangeLog>();
var walletLogs = new List<UserWalletHistory>();
foreach (var payout in payouts)
{
@@ -485,7 +510,7 @@ public class OrmCommissionCalculationStrategy : ICommissionCalculationStrategy
var wallet = existingWallets[payout.UserId];
wallet.NetworkBalance += payout.TotalAmount;
var walletLog = new UserWalletChangeLog
var walletLog = new UserWalletHistory
{
WalletId = wallet.Id,
CurrentBalance = wallet.Balance,
@@ -501,7 +526,7 @@ public class OrmCommissionCalculationStrategy : ICommissionCalculationStrategy
walletLogs.Add(walletLog);
}
await _context.UserWalletChangeLogs.AddRangeAsync(walletLogs, cancellationToken);
await _context.UserWalletHistories.AddRangeAsync(walletLogs, cancellationToken);
await _context.SaveChangesAsync(cancellationToken);
}
@@ -509,7 +534,7 @@ public class OrmCommissionCalculationStrategy : ICommissionCalculationStrategy
List<long> oldPayoutIds,
CancellationToken cancellationToken)
{
var oldWalletLogs = await _context.UserWalletChangeLogs
var oldWalletLogs = await _context.UserWalletHistories
.Where(l => l.RefrenceId.HasValue && oldPayoutIds.Contains(l.RefrenceId.Value))
.ToListAsync(cancellationToken);
@@ -532,7 +557,7 @@ public class OrmCommissionCalculationStrategy : ICommissionCalculationStrategy
}
}
_context.UserWalletChangeLogs.RemoveRange(oldWalletLogs);
_context.UserWalletHistories.RemoveRange(oldWalletLogs);
await _context.SaveChangesAsync(cancellationToken);
}
@@ -6,6 +6,7 @@ namespace CMSMicroservice.Infrastructure.Services.Commission;
/// <summary>
/// پیاده‌سازی محاسبه کمیسیون با استفاده از Stored Procedure
/// این روش برای داده‌های زیاد بهینه‌تر است و از CTE استفاده می‌کند
/// حلقه روی پکیج‌های فعال — هر پکیج با تنظیمات خودش
/// </summary>
public class StoredProcedureCommissionCalculationStrategy : ICommissionCalculationStrategy
{
@@ -22,45 +23,81 @@ public class StoredProcedureCommissionCalculationStrategy : ICommissionCalculati
bool forceRecalculate,
CancellationToken cancellationToken = default)
{
// دسترسی به DbContext واقعی برای اجرای SP
var dbContext = _context as DbContext;
if (dbContext == null)
{
throw new InvalidOperationException("DbContext برای اجرای Stored Procedure در دسترس نیست");
}
// بارگذاری پکیج‌های فعال
var activePackages = await _context.Packages
.Where(p => !p.IsDeleted && p.IsActive)
.ToListAsync(cancellationToken);
if (!activePackages.Any())
{
throw new InvalidOperationException("هیچ پکیج فعالی یافت نشد");
}
var totalRowCount = 0;
var connection = dbContext.Database.GetDbConnection();
await connection.OpenAsync(cancellationToken);
try
{
using var command = connection.CreateCommand();
command.CommandText = "CMS.sp_CalculateWeeklyBalances";
command.CommandType = System.Data.CommandType.StoredProcedure;
command.CommandTimeout = 300; // 5 دقیقه timeout
// حلقه روی پکیج‌ها — هر پکیج با تنظیمات خودش
foreach (var package in activePackages)
{
using var command = connection.CreateCommand();
command.CommandText = "CMS.sp_CalculateWeeklyBalances";
command.CommandType = System.Data.CommandType.StoredProcedure;
command.CommandTimeout = 300; // 5 دقیقه timeout
// پارامترها
var paramWeekDefinitionId = command.CreateParameter();
paramWeekDefinitionId.ParameterName = "@WeekDefinitionId";
paramWeekDefinitionId.Value = weekDefinitionId;
command.Parameters.Add(paramWeekDefinitionId);
// پارامتر WeekDefinitionId
var paramWeekDefinitionId = command.CreateParameter();
paramWeekDefinitionId.ParameterName = "@WeekDefinitionId";
paramWeekDefinitionId.Value = weekDefinitionId;
command.Parameters.Add(paramWeekDefinitionId);
var paramForceRecalculate = command.CreateParameter();
paramForceRecalculate.ParameterName = "@ForceRecalculate";
paramForceRecalculate.Value = forceRecalculate;
command.Parameters.Add(paramForceRecalculate);
// پارامتر ForceRecalculate
var paramForceRecalculate = command.CreateParameter();
paramForceRecalculate.ParameterName = "@ForceRecalculate";
paramForceRecalculate.Value = forceRecalculate;
command.Parameters.Add(paramForceRecalculate);
// پارامتر خروجی
var paramRowCount = command.CreateParameter();
paramRowCount.ParameterName = "@RowCount";
paramRowCount.Direction = System.Data.ParameterDirection.Output;
paramRowCount.DbType = System.Data.DbType.Int32;
command.Parameters.Add(paramRowCount);
// پارامتر PackageId — per-package
var paramPackageId = command.CreateParameter();
paramPackageId.ParameterName = "@PackageId";
paramPackageId.Value = package.Id;
command.Parameters.Add(paramPackageId);
await command.ExecuteNonQueryAsync(cancellationToken);
// پارامتر MaxBalancesPerLeg — per-package
var paramMaxBalances = command.CreateParameter();
paramMaxBalances.ParameterName = "@InputMaxBalancesPerLeg";
paramMaxBalances.Value = package.MaxBalancesPerLeg;
command.Parameters.Add(paramMaxBalances);
var rowCount = (int)(paramRowCount.Value ?? 0);
return rowCount;
// پارامتر MaxNetworkLevel — per-package
var paramMaxLevel = command.CreateParameter();
paramMaxLevel.ParameterName = "@InputMaxNetworkLevel";
paramMaxLevel.Value = package.MaxNetworkLevel;
command.Parameters.Add(paramMaxLevel);
// پارامتر خروجی
var paramRowCount = command.CreateParameter();
paramRowCount.ParameterName = "@RowCount";
paramRowCount.Direction = System.Data.ParameterDirection.Output;
paramRowCount.DbType = System.Data.DbType.Int32;
command.Parameters.Add(paramRowCount);
await command.ExecuteNonQueryAsync(cancellationToken);
var rowCount = (int)(paramRowCount.Value ?? 0);
totalRowCount += rowCount;
}
return totalRowCount;
}
finally
{
@@ -72,7 +72,7 @@ public class KavenegarService : IKavenegarService
}
/// <inheritdoc />
public async Task VerifyLookupAsync(string mobile, string token, string template = "Afrino")
public async Task VerifyLookupAsync(string mobile, string token, string template = "OTP")
{
if (!_smsSettings.Enabled)
{
@@ -106,4 +106,41 @@ public class KavenegarService : IKavenegarService
throw;
}
}
/// <inheritdoc />
public async Task VerifyLookupAsync(string mobile, string token, string token2, string template)
{
if (!_smsSettings.Enabled)
{
_logger.LogInformation("SMS is disabled. Skipping VerifyLookup to {Mobile}", mobile);
return;
}
if (_kavenegarApi == null)
{
_logger.LogWarning("⚠️ Kavenegar API not initialized, cannot send VerifyLookup");
return;
}
try
{
await Task.Run(() =>
{
var result = _kavenegarApi.VerifyLookup(
receptor: mobile,
token: token,
token2: token2,
token3: "",
template: template);
_logger.LogInformation("📱 VerifyLookup SMS sent to {Mobile} with template {Template} (token2), MessageId: {MessageId}",
mobile, template, result.Messageid);
});
}
catch (Exception ex)
{
_logger.LogError(ex, "❌ Kavenegar error sending VerifyLookup to {Mobile}: {Message}", mobile, ex.Message);
throw;
}
}
}
@@ -49,6 +49,7 @@ public class UserNotificationService : IUserNotificationService
long userId,
decimal amount,
int weekNumber,
string? packageName = null,
CancellationToken cancellationToken = default)
{
_logger.LogInformation(
@@ -69,14 +70,15 @@ public class UserNotificationService : IUserNotificationService
if (string.IsNullOrEmpty(userFullName)) userFullName = "کاربر عزیز";
var formattedAmount = amount.ToString("N0", new System.Globalization.CultureInfo("fa-IR"));
var packageInfo = !string.IsNullOrEmpty(packageName) ? $" ({packageName})" : "";
// Send Email
if (_emailSettings.Enabled && !string.IsNullOrEmpty(user.Email))
{
var emailSubject = $"واریز کمیسیون هفته {weekNumber}";
var emailSubject = $"واریز کمیسیون هفته {weekNumber}{packageInfo}";
var emailBody = "<div dir='rtl' style='font-family: Tahoma, Arial; text-align: right;'>" +
$"<h2>سلام {userFullName}</h2>" +
$"<p>کمیسیون هفته {weekNumber} شما به مبلغ <strong>{formattedAmount} ریال</strong> به کیف پول شما واریز شد.</p>" +
$"<p>کمیسیون هفته {weekNumber} شما{packageInfo} به مبلغ <strong>{formattedAmount} تومان</strong> به کیف پول شما واریز شد.</p>" +
"<p>از اعتماد شما سپاسگزاریم.</p>" +
"<hr/>" +
"<p style='color: #666; font-size: 12px;'>FourSat - سیستم مدیریت باشگاه مشتریان</p>" +
@@ -95,7 +97,7 @@ public class UserNotificationService : IUserNotificationService
{
await SendSmsAsync(
phoneNumber: user.Mobile,
message: $"سلام {userFullName}\nکمیسیون هفته {weekNumber} شما به مبلغ {formattedAmount} ریال واریز شد.\nFourSat",
message: $"سلام {userFullName}\nکمیسیون هفته {weekNumber} شما{packageInfo} به مبلغ {formattedAmount} تومان واریز شد.\nFourSat",
cancellationToken: cancellationToken);
}
@@ -109,6 +111,7 @@ public class UserNotificationService : IUserNotificationService
public async Task SendClubActivationNotificationAsync(
long userId,
string? packageName = null,
CancellationToken cancellationToken = default)
{
_logger.LogInformation("🎉 Sending club activation notification: User={UserId}", userId);
@@ -120,6 +123,7 @@ public class UserNotificationService : IUserNotificationService
var userFullName = $"{user.FirstName} {user.LastName}".Trim();
if (string.IsNullOrEmpty(userFullName)) userFullName = "کاربر عزیز";
var packageInfo = !string.IsNullOrEmpty(packageName) ? $" با {packageName}" : "";
// Send Email
if (_emailSettings.Enabled && !string.IsNullOrEmpty(user.Email))
@@ -127,7 +131,7 @@ public class UserNotificationService : IUserNotificationService
var emailSubject = "فعال‌سازی باشگاه مشتریان FourSat";
var emailBody = "<div dir='rtl' style='font-family: Tahoma, Arial; text-align: right;'>" +
$"<h2>تبریک {userFullName}!</h2>" +
"<p>عضویت شما در <strong>باشگاه مشتریان FourSat</strong> با موفقیت فعال شد.</p>" +
$"<p>عضویت شما در <strong>باشگاه مشتریان FourSat</strong>{packageInfo} با موفقیت فعال شد.</p>" +
"<p>از این پس می‌توانید از مزایای ویژه باشگاه بهره‌مند شوید.</p>" +
"<hr/>" +
"<p style='color: #666; font-size: 12px;'>FourSat - سیستم مدیریت باشگاه مشتریان</p>" +
@@ -146,7 +150,7 @@ public class UserNotificationService : IUserNotificationService
{
await SendSmsAsync(
phoneNumber: user.Mobile,
message: $"تبریک! عضویت شما در باشگاه مشتریان FourSat فعال شد.",
message: $"تبریک! عضویت شما در باشگاه مشتریان FourSat{packageInfo} فعال شد.",
cancellationToken: cancellationToken);
}
}
@@ -159,6 +163,7 @@ public class UserNotificationService : IUserNotificationService
public async Task SendPayoutErrorNotificationAsync(
long userId,
string errorMessage,
string? packageName = null,
CancellationToken cancellationToken = default)
{
_logger.LogWarning(
@@ -193,6 +193,16 @@ public class DayaPaymentService : IPaymentGatewayService
}
}
public Task<PaymentVerificationResult> VerifyPaymentAsync(
string refId,
string verificationToken,
decimal amountInToman,
CancellationToken cancellationToken = default)
{
// دایا: درگاه دایا مبلغ را در verify نیاز ندارد — از overload بدون مبلغ استفاده می‌شود
return VerifyPaymentAsync(refId, verificationToken, cancellationToken);
}
public async Task<PayoutResult> ProcessPayoutAsync(
PayoutRequest request,
CancellationToken cancellationToken = default)
@@ -74,6 +74,16 @@ public class MockPaymentGatewayService : IPaymentGatewayService
};
}
public Task<PaymentVerificationResult> VerifyPaymentAsync(
string refId,
string verificationToken,
decimal amountInToman,
CancellationToken cancellationToken = default)
{
// Mock: مبلغ تفاوتی نمی‌کند، از همان overload بدون مبلغ استفاده می‌شود
return VerifyPaymentAsync(refId, verificationToken, cancellationToken);
}
public async Task<PayoutResult> ProcessPayoutAsync(
PayoutRequest request,
CancellationToken cancellationToken = default)
@@ -66,8 +66,9 @@ public class ZarinPalPaymentService : IPaymentGatewayService
{
try
{
// مبلغ از caller به ریال می‌رسد — مستقیم ارسال به زرین‌پال
var amountInRials = (long)request.Amount;
// مبلغ از caller به تومان می‌رسد — تبدیل به ریال برای زرین‌پال (×10)
var amountInToman = (long)request.Amount;
var amountInRials = amountInToman * 10;
var zarinPalRequest = new ZarinPalPaymentRequest
{
@@ -85,8 +86,8 @@ public class ZarinPalPaymentService : IPaymentGatewayService
var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
_logger.LogInformation(
"ZarinPal payment request: Amount={AmountRial} Rial ({AmountToman} Toman), User={UserId}, Sandbox={Sandbox}",
amountInRials, amountInRials / 10m, request.UserId, _useSandbox);
"ZarinPal payment request: Amount={AmountToman} Toman ({AmountRial} Rial), User={UserId}, Sandbox={Sandbox}",
amountInToman, amountInRials, request.UserId, _useSandbox);
var response = await _httpClient.PostAsync(RequestEndpoint, content, cancellationToken);
var responseBody = await response.Content.ReadAsStringAsync(cancellationToken);
@@ -167,7 +168,7 @@ public class ZarinPalPaymentService : IPaymentGatewayService
/// <summary>
/// تأیید پرداخت با مبلغ — نسخه اصلی برای زرین‌پال
/// refId = Authority، verificationToken = Status (OK/NOK)، amount = مبلغ به ریال
/// refId = Authority، verificationToken = Status (OK/NOK)، amount = مبلغ به تومان
/// </summary>
public Task<PaymentVerificationResult> VerifyPaymentAsync(
string refId,
@@ -181,7 +182,7 @@ public class ZarinPalPaymentService : IPaymentGatewayService
private async Task<PaymentVerificationResult> VerifyPaymentWithAmountAsync(
string refId,
string verificationToken,
decimal amountInRials,
decimal amountInToman,
CancellationToken cancellationToken)
{
try
@@ -198,18 +199,21 @@ public class ZarinPalPaymentService : IPaymentGatewayService
};
}
// تبدیل تومان به ریال برای زرین‌پال (×10)
var amountInRials = (long)(amountInToman * 10);
var verifyRequest = new ZarinPalVerifyRequest
{
MerchantId = _merchantId,
Authority = refId,
Amount = (long)amountInRials
Amount = amountInRials
};
var jsonContent = JsonSerializer.Serialize(verifyRequest, JsonOptions);
var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
_logger.LogInformation("ZarinPal verify request: Authority={Authority}, Amount={Amount} Rial ({AmountToman} Toman)",
refId, (long)amountInRials, amountInRials / 10m);
_logger.LogInformation("ZarinPal verify request: Authority={Authority}, Amount={AmountToman} Toman ({AmountRial} Rial)",
refId, (long)amountInToman, amountInRials);
var response = await _httpClient.PostAsync(VerifyEndpoint, content, cancellationToken);
var responseBody = await response.Content.ReadAsStringAsync(cancellationToken);
@@ -231,7 +235,7 @@ public class ZarinPalPaymentService : IPaymentGatewayService
IsSuccess = true,
RefId = refId,
TrackingCode = result.Data.RefId?.ToString(),
Amount = result.Data.Amount ?? 0, // ریال — بدون تبدیل
Amount = (result.Data.Amount ?? 0) / 10, // تبدیل ریال → تومان
CardPan = result.Data.CardPan,
CardHash = result.Data.CardHash,
VerificationCode = result.Data.Code,