1 Commits

Author SHA1 Message Date
masoodafar-web ea1d2d4400 feat(network): enrich network tree with package leg scores and update Protobuf definitions
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 12m47s
- Added logic to enrich the network tree with the latest left/right leg totals for gold and silver packages in GetNetworkTreeQueryHandler.
- Introduced new properties in NetworkTreeDto for GoldLeftLegTotal, GoldRightLegTotal, SilverLeftLegTotal, and SilverRightLegTotal.
- Updated Protobuf definitions to include new fields for leg scores in NetworkTreeNodeModel.
- Enhanced mapping in NetworkMembershipProfile and NetworkMembershipService to accommodate new leg score properties.
- Bumped Protobuf project version to reflect the addition of new features.
2026-08-25 22:39:19 +03:30
13 changed files with 200 additions and 179 deletions
+46
View File
@@ -0,0 +1,46 @@
name: Push nuget and docker image Actions Workflow
on:
push:
branches:
- stage_new
jobs:
Deploy:
runs-on: windows
steps:
- name: Checkout
uses: https://git.afrino.co/actions/checkout@v3
- name: Setup dotnet
uses: https://git.afrino.co/actions/setup-dotnet@v3
with:
dotnet-version: 7.0.x
- name: Remove Package Source
run: dotnet nuget remove source FourSat
continue-on-error: true
- name: Add Package Source
run: dotnet nuget add source --name FourSat --username systemuser --password sZSA7PTiv3pUSQZ https://git.afrino.co/api/packages/FourSat/nuget/index.json --store-password-in-clear-text
- name: Install dependencies
run: dotnet restore ".\src\CMSMicroservice.WebApi\CMSMicroservice.WebApi.csproj"
- name: Build
run: dotnet build ".\src\CMSMicroservice.WebApi\CMSMicroservice.WebApi.csproj" --configuration Release --no-restore
- name: Test
run: dotnet test ".\src\CMSMicroservice.WebApi\CMSMicroservice.WebApi.csproj" --no-restore --verbosity normal
- name: Recycle Apppool
run: |
& "C:\Windows\System32\inetsrv\appcmd.exe" recycle apppool /apppool.name:cms.kbs1.ir
shell: powershell
- name: Stop Website
run: |
& "C:\Windows\System32\inetsrv\appcmd.exe" stop site /site.name:cms.kbs1.ir
shell: powershell
- name: Publish
run: dotnet publish ".\src\CMSMicroservice.WebApi\CMSMicroservice.WebApi.csproj" -c Release -o publish
- name: Copy Publish To IIS Directory
run: Get-ChildItem -Path "publish\*" | Copy-Item -Destination "E:\kbs1.ir\cms.kbs1.ir\" -Recurse -Force
- name: Start Website
run: |
& "C:\Windows\System32\inetsrv\appcmd.exe" start site /site.name:cms.kbs1.ir
shell: powershell
+3 -5
View File
@@ -40,7 +40,7 @@ jobs:
done
if ! docker info >/dev/null 2>&1; then
echo "❌ Docker daemon failed to start"
echo "❌ Docker daemon failed to start after 3 minutes"
exit 1
fi
@@ -75,10 +75,8 @@ jobs:
- name: Build Docker Image
run: |
DOCKER_BUILDKIT=0 docker build --network host \
-t ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.sha }} \
-t ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:prod \
.
DOCKER_BUILDKIT=0 docker build --network host -t ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.sha }} \
-t ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:prod .
- name: Push to Registry
run: |
@@ -1,5 +1,4 @@
using System.Data;
using System.Data.Common;
using Microsoft.EntityFrameworkCore;
namespace CMSMicroservice.Application.NetworkMembershipCQ.Queries.GetNetworkTree;
@@ -42,6 +41,11 @@ public class GetNetworkTreeQueryHandler : IRequestHandler<GetNetworkTreeQuery, N
// تبدیل نتایج flat به ساختار درختی
var tree = BuildTreeFromFlatNodes(flatNodes);
if (tree != null)
{
await EnrichWithPackageLegScoresAsync(tree, flatNodes, cancellationToken);
}
return tree;
}
catch (Exception ex)
@@ -194,4 +198,93 @@ public class GetNetworkTreeQueryHandler : IRequestHandler<GetNetworkTreeQuery, N
var rootNode = flatNodes.FirstOrDefault(n => n.NetworkLevel == 0);
return rootNode != null ? nodeDict[rootNode.UserId] : null;
}
/// <summary>
/// آخرین Left/RightLegTotal طلایی و نقره‌ای برای هر نود درخت (برنامه‌ریزی پای چپ/راست).
/// </summary>
private async Task EnrichWithPackageLegScoresAsync(
NetworkTreeDto root,
List<NetworkTreeNodeDto> flatNodes,
CancellationToken cancellationToken)
{
var userIds = flatNodes.Select(n => n.UserId).Distinct().ToList();
if (userIds.Count == 0) return;
var packages = await _context.Packages
.AsNoTracking()
.Where(p => !p.IsDeleted && p.IsActive)
.Select(p => new { p.Id, p.Title, p.IsBasePackage, p.MaxBalancesPerLeg })
.ToListAsync(cancellationToken);
var goldPackageId = packages.FirstOrDefault(p => p.IsBasePackage)?.Id
?? packages.FirstOrDefault(p => p.Title.Contains("طلایی") || p.Title.Contains("طلايی"))?.Id;
var silverPackageId = packages.FirstOrDefault(p =>
!p.IsBasePackage && (p.Title.Contains("نقره") || p.MaxBalancesPerLeg <= 30))?.Id
?? packages.FirstOrDefault(p => !p.IsBasePackage)?.Id;
if (!goldPackageId.HasValue && !silverPackageId.HasValue)
{
_logger.LogWarning("GetNetworkTree: no gold/silver packages found for leg score enrichment");
return;
}
var packageIds = new List<long>();
if (goldPackageId.HasValue) packageIds.Add(goldPackageId.Value);
if (silverPackageId.HasValue && silverPackageId != goldPackageId)
packageIds.Add(silverPackageId.Value);
var rawBalances = await _context.NetworkWeeklyBalances
.AsNoTracking()
.Where(b => userIds.Contains(b.UserId) && packageIds.Contains(b.PackageId))
.Select(b => new LegScoreRow(
b.UserId,
b.PackageId,
b.WeekDefinitionId,
b.LeftLegTotal,
b.RightLegTotal))
.ToListAsync(cancellationToken);
var latestByUserPackage = rawBalances
.GroupBy(b => (b.UserId, b.PackageId))
.ToDictionary(
g => g.Key,
g => g.OrderByDescending(x => x.WeekDefinitionId).First());
ApplyLegScores(root, goldPackageId, silverPackageId, latestByUserPackage);
}
private static void ApplyLegScores(
NetworkTreeDto node,
long? goldPackageId,
long? silverPackageId,
Dictionary<(long UserId, long PackageId), LegScoreRow> latestByUserPackage)
{
if (goldPackageId.HasValue &&
latestByUserPackage.TryGetValue((node.UserId, goldPackageId.Value), out var gold))
{
node.GoldLeftLegTotal = gold.LeftLegTotal;
node.GoldRightLegTotal = gold.RightLegTotal;
}
if (silverPackageId.HasValue &&
latestByUserPackage.TryGetValue((node.UserId, silverPackageId.Value), out var silver))
{
node.SilverLeftLegTotal = silver.LeftLegTotal;
node.SilverRightLegTotal = silver.RightLegTotal;
}
if (node.LeftChild != null)
ApplyLegScores(node.LeftChild, goldPackageId, silverPackageId, latestByUserPackage);
if (node.RightChild != null)
ApplyLegScores(node.RightChild, goldPackageId, silverPackageId, latestByUserPackage);
}
private sealed record LegScoreRow(
long UserId,
long PackageId,
long WeekDefinitionId,
int LeftLegTotal,
int RightLegTotal);
}
@@ -60,6 +60,18 @@ public class NetworkTreeDto
public long? PackageId { get; set; }
/// <summary>آخرین LeftLegTotal پکیج طلایی (پایه)</summary>
public int GoldLeftLegTotal { get; set; }
/// <summary>آخرین RightLegTotal پکیج طلایی (پایه)</summary>
public int GoldRightLegTotal { get; set; }
/// <summary>آخرین LeftLegTotal پکیج نقره‌ای</summary>
public int SilverLeftLegTotal { get; set; }
/// <summary>آخرین RightLegTotal پکیج نقره‌ای</summary>
public int SilverRightLegTotal { get; set; }
public NetworkTreeDto? LeftChild { get; set; }
public NetworkTreeDto? RightChild { get; set; }
}
@@ -12,7 +12,7 @@ using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace CMSMicroservice.Infrastructure.Persistence.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20260222155925_u21")]
[Migration("20260222160755_u21")]
partial class u21
{
/// <inheritdoc />
@@ -1,136 +0,0 @@
-- =============================================
-- Stored Procedure: GetNetworkTree
-- Description: دریافت درخت شبکه باینری با CTE recursive
-- Author: FourSat Team
-- Updated: 2026-04-30 — اضافه کردن IsNewActivation، PackageName، PackageId
-- منطق هفته‌بندی از ActivatedAt به PackagePurchasedAt تغییر کرد
-- =============================================
CREATE OR ALTER PROCEDURE [CMS].[GetNetworkTree]
@RootUserId BIGINT,
@MaxDepth INT = 100,
@IsClubActive BIT = NULL,
@ActivationWeekDefinitionId BIGINT = NULL
AS
BEGIN
SET NOCOUNT ON;
-- تاریخ شروع و پایان هفته فیلتر
DECLARE @WeekStartDate DATETIME = NULL;
DECLARE @WeekEndDate DATETIME = NULL;
IF @ActivationWeekDefinitionId IS NOT NULL
BEGIN
SELECT @WeekStartDate = StartDate, @WeekEndDate = EndDate
FROM [CMS].[WeekDefinitions]
WHERE Id = @ActivationWeekDefinitionId;
END
-- CTE برای پیمایش درخت باینری به صورت recursive
;WITH NetworkTreeCTE AS (
-- Base case: ریشه درخت
SELECT
u.Id AS UserId,
u.Mobile,
u.FirstName,
u.LastName,
u.ReferralCode,
u.LegPosition,
u.NetworkParentId AS ParentId,
0 AS NetworkLevel,
u.Created AS UserCreated
FROM [CMS].[Users] u
WHERE u.Id = @RootUserId
AND u.IsDeleted = 0
UNION ALL
-- Recursive case: فرزندان
SELECT
u.Id AS UserId,
u.Mobile,
u.FirstName,
u.LastName,
u.ReferralCode,
u.LegPosition,
u.NetworkParentId AS ParentId,
parent.NetworkLevel + 1 AS NetworkLevel,
u.Created AS UserCreated
FROM [CMS].[Users] u
INNER JOIN NetworkTreeCTE parent ON u.NetworkParentId = parent.UserId
WHERE u.IsDeleted = 0
AND parent.NetworkLevel < @MaxDepth
)
SELECT
t.UserId,
t.Mobile,
t.FirstName,
t.LastName,
t.ReferralCode,
t.LegPosition,
t.ParentId,
t.NetworkLevel,
cm.ActivatedAt AS ClubActivatedAt,
ISNULL(cm.IsActive, 0) AS IsClubActive,
-- هفته فعال‌سازی بر اساس Cycle جاری (PackagePurchasedAt)
wd.Id AS ActivationWeekDefinitionId,
wd.DisplayName AS ActivationWeekDisplayName,
-- آیا کاربر در هفته هدف Cycle داشته؟
CASE WHEN cc_target.UserId IS NOT NULL THEN 1 ELSE 0 END AS IsActivatedInTargetWeek,
-- نوع فعال‌سازی: 1=جدید، 0=تمدید/خرید مجدد، NULL=بدون Cycle
CASE
WHEN cc_eff.CycleNumber IS NULL THEN NULL
WHEN cc_eff.CycleNumber = 1 THEN 1
ELSE 0
END AS IsNewActivation,
-- نام پکیج موثر (هفته هدف اگر فیلتر باشد، وگرنه پکیج فعلی)
ISNULL(p_eff.Title, '') AS PackageName,
cc_eff.PackageId AS PackageId,
t.UserCreated
FROM NetworkTreeCTE t
LEFT JOIN [CMS].[ClubMemberships] cm ON cm.UserId = t.UserId AND cm.IsDeleted = 0
-- Cycle جاری — برای نمایش هفته و پکیج وقتی فیلتر هفته نیست
OUTER APPLY (
SELECT TOP 1 CycleNumber, PackageId, PackagePurchasedAt
FROM [CMS].[ClubMembershipCycles]
WHERE UserId = t.UserId AND IsCurrentCycle = 1
) cc_current
-- Cycle هفته هدف — برای IsActivatedInTargetWeek و نوع فعال‌سازی
OUTER APPLY (
SELECT TOP 1 UserId, CycleNumber, PackageId
FROM [CMS].[ClubMembershipCycles]
WHERE UserId = t.UserId
AND @WeekStartDate IS NOT NULL
AND PackagePurchasedAt >= @WeekStartDate
AND PackagePurchasedAt < @WeekEndDate
ORDER BY CycleNumber ASC
) cc_target
-- Cycle موثر: اگر هفته فیلتر داریم → cc_target، وگرنه → cc_current
CROSS APPLY (
SELECT
CASE WHEN @WeekStartDate IS NOT NULL AND cc_target.UserId IS NOT NULL
THEN cc_target.CycleNumber ELSE cc_current.CycleNumber END AS CycleNumber,
CASE WHEN @WeekStartDate IS NOT NULL AND cc_target.UserId IS NOT NULL
THEN cc_target.PackageId ELSE cc_current.PackageId END AS PackageId
) cc_eff
-- پکیج موثر
LEFT JOIN [CMS].[Packages] p_eff ON p_eff.Id = cc_eff.PackageId AND p_eff.IsDeleted = 0
-- هفته بر اساس PackagePurchasedAt سایکل جاری
LEFT JOIN [CMS].[WeekDefinitions] wd
ON cc_current.PackagePurchasedAt >= wd.StartDate
AND cc_current.PackagePurchasedAt < wd.EndDate
WHERE (@IsClubActive IS NULL OR ISNULL(cm.IsActive, 0) = @IsClubActive OR t.NetworkLevel = 0)
ORDER BY t.NetworkLevel, t.ParentId, t.LegPosition
OPTION (MAXRECURSION 0);
END
@@ -3,7 +3,7 @@
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<Version>0.0.209</Version>
<Version>0.0.210</Version>
<DebugType>None</DebugType>
<DebugSymbols>False</DebugSymbols>
<GeneratePackageOnBuild>False</GeneratePackageOnBuild>
@@ -209,6 +209,11 @@ message NetworkTreeNodeModel
google.protobuf.BoolValue is_new_activation = 22; // true=اولین فعال‌سازی، false=خرید مجدد، null=بدون Cycle
string package_name = 23; // نام پکیج موثر
google.protobuf.Int64Value package_id = 24; // شناسه پکیج
// آخرین NetworkWeeklyBalance: امتیاز پای چپ/راست برای پکیج طلایی و نقره‌ای (D3)
int32 gold_left_leg_total = 25;
int32 gold_right_leg_total = 26;
int32 silver_left_leg_total = 27;
int32 silver_right_leg_total = 28;
}
// GetHistory Query
@@ -95,7 +95,11 @@ public class NetworkMembershipProfile : IRegister
IsActivatedInTargetWeek = node.IsActivatedInTargetWeek,
PackageName = node.PackageName ?? string.Empty,
PackageId = node.PackageId.HasValue ? node.PackageId.Value : null,
IsNewActivation = node.IsNewActivation.HasValue ? node.IsNewActivation.Value : null
IsNewActivation = node.IsNewActivation.HasValue ? node.IsNewActivation.Value : null,
GoldLeftLegTotal = node.GoldLeftLegTotal,
GoldRightLegTotal = node.GoldRightLegTotal,
SilverLeftLegTotal = node.SilverLeftLegTotal,
SilverRightLegTotal = node.SilverRightLegTotal
};
if (parentId.HasValue)
@@ -185,6 +185,11 @@ public class NetworkMembershipService : NetworkMembershipContract.NetworkMembers
node.PackageId = dto.PackageId.Value;
}
node.GoldLeftLegTotal = dto.GoldLeftLegTotal;
node.GoldRightLegTotal = dto.GoldRightLegTotal;
node.SilverLeftLegTotal = dto.SilverLeftLegTotal;
node.SilverRightLegTotal = dto.SilverRightLegTotal;
if (dto.IsNewActivation.HasValue)
{
node.IsNewActivation = dto.IsNewActivation.Value;
@@ -2,16 +2,19 @@
"PaymentProvider": "zarinpal",
"ZarinPal": {
"MerchantId": "4225d555-5fa9-4df0-9b61-1ce152cbbba8",
"UseSandbox": false
"UseSandbox": true
},
"CmsBaseUrl": "https://cms.se.kbs1.ir",
"FrontOfficeBaseUrl": "https://frontoffice.se.kbs1.ir",
"FMS": {
"Address": "https://dl.afrino.co"
},
"CmsBaseUrl": "https://cms.kbs2.ir",
"FrontOfficeBaseUrl": "https://kbs2.ir",
"JwtSecurityKey": "TvlZVx5TJaHs8e9HgUdGzhGP2CIidoI444nAj+8+g7c=",
"JwtIssuer": "https://localhost",
"JwtAudience": "https://localhost",
"JwtExpiryInDays": 5,
"ConnectionStrings": {
"DefaultConnection": "Server=mssql-svc;Database=KBS;User Id=sa;Password=YourStrong@Passw0rd;TrustServerCertificate=True;",
"DefaultConnection": "Data Source=194.5.195.53,31433; Initial Catalog=Foursat;User ID=sa;Password=87zH26nbqT;Connection Timeout=300000;MultipleActiveResultSets=True;Encrypt=False",
"providerName": "System.Data.SqlClient"
},
"Otp": {
@@ -20,12 +23,12 @@
},
"Monitoring": {
"SentryEnabled": false,
"SentryDsn": "",
"SentryDsn": "",
"SlackEnabled": false,
"SlackWebhookUrl": "",
"EmailAlertsEnabled": false,
"AdminEmails": [
"admin@example.com"
"admin@example.com"
],
"SmsNotificationsEnabled": false,
"SmsApiKey": "",
@@ -64,7 +67,7 @@
},
"BackgroundJobs": {
"WeeklyCommissionCalculation": {
"Enabled": false,
"Enabled": true,
"CronExpression": "5 0 * * 0"
}
},
@@ -84,13 +87,7 @@
"Audience": "domain_api"
},
"Seq": {
"ServerUrl": "http://seq-svc:5341",
"ServerUrl": "https://seq.afrino.co",
"ApiKey": "oxpvpUzU1pZxMS4s3Fqq"
},
"Logging": {
"LogLevel": {
"Default": "Warning",
"Microsoft.AspNetCore": "Warning"
}
}
}
+17 -20
View File
@@ -2,16 +2,24 @@
"PaymentProvider": "zarinpal",
"ZarinPal": {
"MerchantId": "4225d555-5fa9-4df0-9b61-1ce152cbbba8",
"UseSandbox": false
"UseSandbox": true
},
"CmsBaseUrl": "https://localhost:32846",
"FrontOfficeBaseUrl": "http://localhost:5268",
"FMS": {
"Address": "https://dl.afrino.co"
},
"CmsBaseUrl": "https://cms.kbs2.ir",
"FrontOfficeBaseUrl": "https://kbs2.ir",
"JwtSecurityKey": "TvlZVx5TJaHs8e9HgUdGzhGP2CIidoI444nAj+8+g7c=",
"JwtIssuer": "https://localhost",
"JwtAudience": "https://localhost",
"JwtExpiryInDays": 5,
"Kestrel": {
"EndpointDefaults": {
"Protocols": "Http1AndHttp2"
}
},
"ConnectionStrings": {
"DefaultConnection": "Server=45.149.79.127,31433;Database=KBS;User Id=sa;Password=YourStrong@Passw0rd;TrustServerCertificate=True;",
"DefaultConnection": "Data Source=194.5.195.53,31433; Initial Catalog=Foursat;User ID=sa;Password=87zH26nbqT;Connection Timeout=300000;MultipleActiveResultSets=True;Encrypt=False",
"providerName": "System.Data.SqlClient"
},
"Otp": {
@@ -19,12 +27,12 @@
},
"Monitoring": {
"SentryEnabled": false,
"SentryDsn": "",
"SentryDsn": "",
"SlackEnabled": false,
"SlackWebhookUrl": "",
"EmailAlertsEnabled": false,
"AdminEmails": [
"admin@example.com"
"admin@example.com"
],
"SmsNotificationsEnabled": false,
"SmsApiKey": "",
@@ -43,7 +51,7 @@
"Sms": {
"Enabled": true,
"Provider": "Kavenegar",
"KavenegarApiKey": "497263626F32626A48685A6137524C4F78575A766E4C74694A556B79317648424964655030682B554545413D",
"KavenegarApiKey": "43676A4E786A6C50452F2F6252507939346A5145764B33566B456454374E657A614468706658656D6534593D",
"Sender": "1000001110100"
},
"DayaPayment": {
@@ -63,7 +71,7 @@
},
"BackgroundJobs": {
"WeeklyCommissionCalculation": {
"Enabled": false,
"Enabled": true,
"CronExpression": "5 0 * * 0"
}
},
@@ -76,23 +84,12 @@
}
},
"AllowedHosts": "*",
"Kestrel": {
"EndpointDefaults": {
"Protocols": "Http2"
}
},
"Authentication": {
"Authority": "https://ids.domain.com/",
"Audience": "domain_api"
},
"Seq": {
"ServerUrl": "http://seq-svc:5341",
"ServerUrl": "https://seq.afrino.co",
"ApiKey": "oxpvpUzU1pZxMS4s3Fqq"
},
"Logging": {
"LogLevel": {
"Default": "Warning",
"Microsoft.AspNetCore": "Warning"
}
}
}