43 Commits

Author SHA1 Message Date
masoodafar-web 9050c00297 Merge branch 'kub-stage' into production
Build and Deploy to Production / build-and-deploy (push) Successful in 8m56s
2026-02-21 20:37:55 +03:30
masoodafar-web bdd2c51726 fix: Update project version to 0.0.181 and adjust NuGet package path
Build and Deploy to Kubernetes / build-and-deploy (push) Has been cancelled
2026-02-21 20:37:14 +03:30
masoodafar-web 2a569a024f feat: Implement Magic Wallet functionality
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 8m36s
- Added ClubMembershipCycle entity and DbSet to IApplicationDbContext.
- Updated VAT rate from 9% to 10% in VatCalculator and related areas.
- Introduced Magic Wallet settings in SystemConstants.
- Enhanced UserWallet entity to support Magic Wallet features.
- Updated TransactionType enum to include Magic Wallet transactions.
- Configured UserWallet to handle Magic Wallet properties in ApplicationDbContext.
- Implemented OrmCommissionCalculationStrategy to exclude Magic Wallet users from commission calculations.
- Added Protobuf definitions for Magic Wallet methods and responses.
- Created PaymentCallbackController endpoint for handling Magic Wallet charge callbacks.
- Updated UserOrderService to manage Magic Wallet state transitions.
- Developed UserWalletService to support Magic Wallet operations.
- Created ChargeMagicWalletCommand and its handler for initiating Magic Wallet charges.
- Implemented VerifyMagicWalletChargeCommand and handler for payment verification.
- Added validation for ChargeMagicWalletCommand.
- Established ClubMembershipCycle configuration for EF Core.
- Introduced WalletMode enum to differentiate between Normal and Magic modes.
2026-02-21 19:50:28 +03:30
masoodafar-web 04e8c49fa7 fix: IPG DiscountBalance should be 2× BasePackageAmount (112M not 56M)
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 7m44s
Both VerifyBasePackagePayment and VerifyPackagePurchase handlers were
charging DiscountBalance with 1× amount instead of 2×.
Now consistent with DayaLoan and ManualPayment handlers.

- VerifyBasePackagePaymentCommandHandler: DiscountBalance += BasePackageAmount * 2
- VerifyPackagePurchaseCommandHandler: DiscountBalance += order.Amount * 2
- Change logs updated to reflect correct 2× discount value
2026-02-18 23:12:03 +03:30
masoodafar-web f968a6c005 docs: move README to totalDoc, replace with placeholder
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 7m50s
2026-02-18 21:44:46 +03:30
masoodafar-web 6048824b33 docs: move README to totalDoc, replace with placeholder 2026-02-18 21:44:39 +03:30
masoodafar-web 62a247f097 merge: kub-stage → production (inventory auto-init + initializer worker)
Build and Deploy to Production / build-and-deploy (push) Successful in 9m2s
2026-02-18 01:01:15 +03:30
masoodafar-web bc710fdb7b feat: auto-create inventory records for new products + migration worker
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 8m52s
- CreateNewProductsCommandHandler: inject IInventoryService, auto-init
  inventory record with qty=0 when a new regular product is created
  (DiscountProduct handler already had this)
- InventoryInitializerService: one-time BackgroundService that runs on
  startup, finds existing products without InventoryItem records, and
  creates them (migration for legacy products)
- Register InventoryInitializerService in DI
2026-02-18 00:42:41 +03:30
masoodafar-web fd24dcebcd feat: Add SitePageSettings - simplified page management system
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 8m2s
- New entities: SitePageSettings + SitePageImage (4 fixed pages)
- EF Migration: AddSitePageSettings (SitePageSettings + SitePageImages tables)
- Proto: sitepagesettings.proto with 5 RPCs
- CQRS: GetPageSettings, GetAllPageSettings, SavePageSettings, SavePageImage, DeletePageImage
- gRPC Service: SitePageSettingsService (auto-registered)
- Proto NuGet bumped to 0.0.180
2026-02-17 22:34:29 +03:30
masoodafar-web 89e146bf32 fix: set Kestrel protocol to Http1AndHttp2 in appsettings — prevents 502
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 8m38s
2026-02-17 02:55:50 +03:30
masoodafar-web af12f996f1 merge: kub-stage into production — fix prod workflow + add CmsBaseUrl/FrontOfficeBaseUrl
Build and Deploy to Production / build-and-deploy (push) Successful in 8m9s
2026-02-17 01:59:28 +03:30
masoodafar-web 27d995faf4 fix: production deployment — appsettings.Production.json + fix K8S_SERVER + set image
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 7m48s
- appsettings.Production.json: CmsBaseUrl=cms.kbs1.ir, FrontOfficeBaseUrl=kbs1.ir, DB=KBS
- prod-deploy.yml: K8S_SERVER 194.5.195.53 → 45.149.79.127
- prod-deploy.yml: kubectl set image instead of rollout restart
2026-02-17 01:58:07 +03:30
masoodafar-web 3b0d9eadd3 Fix production workflow: use SERVER_PASSWORD, add docker login, use set image for deploy
Build and Deploy to Production / build-and-deploy (push) Successful in 8m17s
2026-02-17 01:23:53 +03:30
masoodafar-web db07838ecb Remove staging workflow files from production branch to prevent cross-deployment 2026-02-17 01:15:50 +03:30
masoodafar-web 167991890c Merge branch 'kub-stage' into production
Build and Deploy to Production / build-and-deploy (push) Successful in 2m43s
Features merged:
- ZarinPal payment gateway (sandbox mode)
- Discount store improvements (100% discount auto-apply)
- VAT breakdown on checkout
- PaymentStatus in order responses (proto v0.0.179)
- ExpirePendingOrdersService (background job for stale orders)
- DeliveryStatus proper mapping + cancel on failed payment
- Inventory management system
- Various bug fixes

Production config preserved:
- DB: 45.149.79.127 / KBS
- CmsBaseUrl: https://cms.kbs1.ir
- FrontOfficeBaseUrl: https://foursat.kbs1.ir
- Payment gateway: sandbox (will show 'درگاه فعال نمیباشد')
- Production workflow unchanged
2026-02-17 00:53:28 +03:30
masoodafar-web ef1716e243 fix: proper DeliveryStatus mapping + cancel delivery on failed payment
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 8m22s
- Added MapDeliveryStatus() to correctly map Domain→Proto enum values
- Domain Pending(1) was incorrectly cast to Proto PROCESSING(1) instead of PROCESSING
- Set DeliveryStatus=Cancelled when payment fails (CompleteOrderPaymentCommandHandler)
- Set DeliveryStatus=Cancelled when order expires (ExpirePendingOrdersService)
2026-02-17 00:41:48 +03:30
masoodafar-web c2ccd32f39 fix: use DateTime.Now instead of UtcNow in ExpirePendingOrdersService
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 8m33s
Database stores Created timestamps using DateTime.Now (local time).
Background service was comparing with DateTime.UtcNow causing 3.5 hour offset (Iran timezone).
Orders would only expire after ~4 hours instead of 30 minutes.
2026-02-16 22:52:33 +03:30
masoodafar-web c435319025 feat: add PaymentStatus to discount order proto + expire pending orders background service
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 7m53s
- Added payment_status field to GetOrderByIdResponse and OrderSummaryDto in proto
- Proto version bumped to 0.0.179
- Added PaymentStatus mapping in DiscountOrderService gRPC responses
- Created ExpirePendingOrdersService: expires pending orders after 30 min, releases inventory
- Registered background service in ConfigureServices
2026-02-16 22:37:58 +03:30
masoodafar-web 18a65de8c7 fix: force 100% discount in PlaceOrder — ignore client DiscountBalanceToUse, always use max
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 7m51s
2026-02-16 21:52:02 +03:30
masoodafar-web e2e09ac4e8 fix: add CmsBaseUrl/FrontOfficeBaseUrl to appsettings.json for staging callback URLs
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 7m43s
- Added CmsBaseUrl=https://cms.se.kbs1.ir to appsettings.json
- Added FrontOfficeBaseUrl=https://foursat.se.kbs1.ir to appsettings.json
- Fixed PurchasePackageCommandHandler hardcoded yourdomain.com
- Development keeps localhost values via appsettings.Development.json
2026-02-16 02:31:27 +03:30
masoodafar-web 61a0d68b7c feat: add staging configuration file for environment-specific settings
Build and Deploy to Kubernetes / build-and-deploy (push) Has been cancelled
2026-02-16 02:24:22 +03:30
masoodafar-web 1c4beb5f05 chore: bump Protobuf NuGet package version to 0.0.178
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 7m45s
2026-02-16 01:39:49 +03:30
masoodafar-web 163a0a2f1a fix: discount store DeliveryStatus stays Pending after payment (matches regular store)
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 8m34s
- CompleteOrderPaymentCommandHandler: DeliveryStatus.InTransit → DeliveryStatus.Pending
- PlaceOrderCommandHandler (full discount-balance path): same fix
- Now both stores behave the same: admin must manually update delivery status
- Consistent with regular store flow where order stays Pending after payment
2026-02-16 00:45:55 +03:30
masoodafar-web e77611012b fix: PaymentStatus→PaymentCompleted mapping in DiscountOrderService
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 8m25s
- GetOrderById and GetUserOrders were using Mapster auto-mapping which
  could not map 'PaymentStatus' (enum: Success=0) to 'payment_completed' (bool)
- Replaced with manual mapping: PaymentStatus == Success → true
- Also maps DeliveryStatus and all other fields correctly
- Fixed FrontOfficeBaseUrl and CmsBaseUrl to use HTTP for local dev
2026-02-16 00:36:29 +03:30
masoodafar-web a39a36e66d feat: add PaymentTransaction table for gateway-level tracking
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 9m6s
- New PaymentTransaction entity (Domain/Entities/Payment/) with all gateway fields:
  GatewayProvider, MerchantId, Authority, CardPan, CardHash, RefId, VerificationStatusCode, etc.
- New PaymentTransactionConfiguration with indexes on Authority, GatewayProvider, UserId, TransactionId, RefId
- Added DbSet<PaymentTransaction> to IApplicationDbContext and ApplicationDbContext
- Extended PaymentVerificationResult DTO with CardPan, CardHash, VerificationCode
- Updated ZarinPalPaymentService.VerifyPayment to return CardPan/CardHash/VerificationCode
- Updated all 5 payment consumers to create/update PaymentTransaction:
  * PlaceOrderCommandHandler — creates PaymentTransaction after InitiatePayment
  * PaymentCallbackController — updates PaymentTransaction after VerifyPayment
  * ChargeDiscountWalletCommandHandler — creates PaymentTransaction + fixed callback URL
  * VerifyDiscountWalletChargeCommandHandler — updates PaymentTransaction after verify
  * TransactionsService.CustomerPaymentRequest/Verification — create/update PaymentTransaction
  * PackageService.CustomerPurchasePackage/Verify — create/update PaymentTransaction
- Transaction table untouched — PaymentTransaction is a separate table
- Pattern inspired by PYMS: create row before gateway → update after verify
- EF migration: AddPaymentTransactionTable
2026-02-15 23:53:28 +03:30
masoodafar-web 207f53ef80 refactor: remove PYMS microservice, use ZarinPal directly in CMS
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 8m26s
- Remove PYMSPaymentService.cs and PYMS proto files
- Remove 'pyms' case from DI ConfigureServices
- Remove PYMS config from appsettings
- Switch PaymentProvider to 'zarinpal' (direct integration)
- ZarinPalPaymentService handles sandbox/production, verify, errors
- PYMS deployment/service/ingress removed from K8s
2026-02-15 23:25:20 +03:30
masoodafar-web 2502cbbda2 feat: integrate PYMS payment gateway, add blog/sitepage/image services, local file manager
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 8m44s
Payment Gateway:
- Add PYMSPaymentService: IPaymentGatewayService via gRPC to PYMS microservice
- Add ZarinPalPaymentService: direct ZarinPal integration (backup)
- Register 'pyms' payment provider in DI ConfigureServices
- Add PYMS proto files (pyms_transaction.proto, pyms_public_messages.proto)
- Fix VerifyDiscountWalletCharge: pass 'OK' as status instead of Authority
- Update appsettings: PaymentProvider=pyms, sandbox mode, merchant ID

Blog System:
- Add BlogCategory, BlogPost, BlogPostImage entities and CQRS
- Add proto files and gRPC services for blog management
- Add Mapster profiles for blog responses

Content Management:
- Add SitePage entity and CQRS for static pages
- Add proto and gRPC service for site pages

Image/File Management:
- Add LocalFileManager with disk storage + base64 serving + FMS fallback
- Add ImagePathResolverInterceptor for gRPC responses
- Add ImageResolverService for explicit image resolution
- Add UploadsController for public file serving with FMS fallback
- Add PaymentCallbackController for discount order payment callbacks

Database:
- Add blog and content entity migrations
- Remove ImagePath MaxLength constraints
- Remove old FileManagementService (replaced by LocalFileManager)
2026-02-15 23:01:16 +03:30
masoodafar-web 5a4e4a960d fix: Update production deployment workflow for improved Docker handling and Kubernetes integration
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 7m19s
2026-02-11 00:40:29 +03:30
masoodafar-web dc1e00f514 fix: Disable BuildKit for Docker image build in CI workflow
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 9m15s
2026-02-11 00:19:27 +03:30
masoodafar-web 9d929dc7fb fix: Add network option to Docker run and build commands in CI workflow
Build and Deploy to Kubernetes / build-and-deploy (push) Failing after 3m23s
2026-02-11 00:08:02 +03:30
masoodafar-web 9b7d61593b fix: Remove unnecessary security options from Docker container in CI workflow
Build and Deploy to Kubernetes / build-and-deploy (push) Failing after 23s
2026-02-10 23:41:56 +03:30
masoodafar-web e3e3e8cec4 fix: Enhance Docker container security options in CI workflow
Build and Deploy to Kubernetes / build-and-deploy (push) Failing after 13s
2026-02-10 23:13:07 +03:30
masoodafar-web 2885ff20c0 fix: Streamline Docker registry login process in CI workflow
Build and Deploy to Kubernetes / build-and-deploy (push) Failing after 15s
2026-02-10 23:08:51 +03:30
masoodafar-web f2a0b4d211 fix: Update dotnet restore command to use custom NuGet configuration
Build and Deploy to Kubernetes / build-and-deploy (push) Failing after 5s
2026-02-10 23:05:45 +03:30
masoodafar-web 6c9f3dd671 fix: Add storage driver option to Docker daemon startup in Kubernetes deployment
Build and Deploy to Kubernetes / build-and-deploy (push) Failing after 5s
2026-02-10 23:03:03 +03:30
masoodafar-web d1ca72300d refactor: Remove ICurrentUserService dependency from query handlers and update user ID handling logic
Build and Deploy to Kubernetes / build-and-deploy (push) Failing after 8s
2026-02-10 23:01:49 +03:30
masoodafar-web 1a425f0d93 chore: Update production workflow to use Nexus registry (no proxy needed)
Build and Deploy to Production / build-and-deploy (push) Failing after 0s
- Changed Dockerfile base images to use 194.5.195.53:32082 (Nexus)
- Updated workflow to use docker-sshpass image from Nexus
- Removed HTTP_PROXY/HTTPS_PROXY dependencies
- Changed deploy method to SSH instead of kubeconfig
- Registry: 194.5.195.53:30080 (Gitea internal)
- K8S Server: 45.149.79.127 (Production)
2026-01-29 22:04:31 +03:30
masoodafar-web 6f8aefc2ce Merge branch 'kub-stage' into production
Build and Deploy to Production / build-and-deploy (push) Successful in 1m40s
2025-12-29 00:36:51 +03:30
masoodafar-web 2bd5c7db78 Merge branch 'kub-stage' into production
Build and Deploy to Production / build-and-deploy (push) Successful in 1m50s
2025-12-27 07:37:30 +03:30
masoodafar-web 0728ec2b76 feat: add background job configuration for weekly commission calculation
Build and Deploy to Production / build-and-deploy (push) Successful in 3m18s
2025-12-27 01:51:32 +03:30
masoodafar-web 1425fb187b Merge branch 'kub-stage' into production
# Conflicts:
#	src/CMSMicroservice.WebApi/Program.cs
2025-12-27 01:49:11 +03:30
masoodafar-web 81d2b39ee1 fix: update Seq ServerUrl and change Hangfire job timezone to local - Adjusted Seq server URL for production and modified recurring job options to use local timezone 2025-12-27 01:14:31 +03:30
masoodafar-web fce194a195 feat: update connection strings and add production configuration - Modified database connection details and created appsettings.Production.json for production environment
Build and Deploy to Production / build-and-deploy (push) Successful in 4m2s
2025-12-27 00:16:36 +03:30
235 changed files with 28454 additions and 1271 deletions
-46
View File
@@ -1,46 +0,0 @@
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
-89
View File
@@ -1,89 +0,0 @@
name: Build and Deploy to Kubernetes
on:
push:
branches:
- kub-stage
env:
REGISTRY: 194.5.195.53:30080
IMAGE_NAME: admin/cms
K8S_SERVER: 194.5.195.53
jobs:
build-and-deploy:
runs-on: ubuntu-latest
container:
image: 194.5.195.53:32082/docker-sshpass:latest
options: --privileged
steps:
- name: Start Docker daemon
run: |
mkdir -p /etc/docker
cat > /etc/docker/daemon.json << 'DAEMON'
{
"insecure-registries": ["194.5.195.53:30080", "194.5.195.53:32500", "194.5.195.53:32082"]
}
DAEMON
echo "🚀 Starting Docker daemon..."
dockerd &
# Wait up to 3 minutes for Docker to be ready
for i in $(seq 1 90); do
if docker info >/dev/null 2>&1; then
echo "✅ Docker daemon is ready (attempt $i)"
docker version
break
else
echo "⏳ Waiting for Docker daemon... (attempt $i/90)"
sleep 2
fi
done
# Final check
if ! docker info >/dev/null 2>&1; then
echo "❌ Docker daemon failed to start after 3 minutes"
exit 1
fi
- name: Checkout code
run: |
git clone --depth 1 --branch kub-stage http://gitea-svc:3000/admin/CMS.git .
- name: Publish Protobuf packages
run: |
echo "📦 Publishing Protobuf packages..."
docker run --rm -v $(pwd):/src -w /src \
194.5.195.53:32082/dotnet/sdk:9.0 sh -c '
for proj in $(find . -name "*Protobuf*.csproj" -type f); do
echo "📦 $proj"
dotnet restore "$proj"
dotnet build "$proj" -c Release --no-restore
dotnet pack "$proj" -c Release --no-build -o "$(dirname $proj)/nupkg"
for nupkg in $(dirname $proj)/nupkg/*.nupkg; do
[ -f "$nupkg" ] && dotnet nuget push "$nupkg" \
--source "http://194.5.195.53:32081/repository/foursat-nuget-hosted/index.json" \
--api-key "admin:87zH26nbqT" \
--skip-duplicate --allow-insecure-connections || true
done
done
'
echo "✅ Protobuf packages done!"
- name: Build Docker Image
run: |
docker build -t ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest .
- name: Push to Registry
run: |
echo "${{ secrets.REGISTRY_PASSWORD }}" | docker login ${{ env.REGISTRY }} -u admin --password-stdin
docker push ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest
- name: Deploy to Kubernetes
run: |
export SSHPASS="${{ secrets.SERVER_PASSWORD }}"
sshpass -e ssh -o StrictHostKeyChecking=no root@${{ env.K8S_SERVER }} "
kubectl rollout restart deployment/cms
kubectl rollout status deployment/cms --timeout=180s
"
echo "✅ Deployed!"
+56 -49
View File
@@ -8,81 +8,88 @@ on:
env: env:
REGISTRY: 194.5.195.53:30080 REGISTRY: 194.5.195.53:30080
IMAGE_NAME: admin/cms IMAGE_NAME: admin/cms
K8S_SERVER: 45.149.79.127
jobs: jobs:
build-and-deploy: build-and-deploy:
runs-on: ubuntu-latest runs-on: ubuntu-latest
container: container:
image: docker:latest image: 194.5.195.53:32082/docker-sshpass:latest
options: --privileged options: --privileged
env:
HTTP_PROXY: http://proxyuser:87zH26nbqT2@46.249.98.211:3128
HTTPS_PROXY: http://proxyuser:87zH26nbqT2@46.249.98.211:3128
NO_PROXY: localhost,127.0.0.1,gitea-svc,45.149.79.127,10.0.0.0/8
steps: steps:
- name: Install dependencies - name: Start Docker daemon
run: |
apk add --no-cache git curl
# Install kubectl with fixed version
KUBECTL_VERSION="v1.31.0"
curl -LO "https://dl.k8s.io/release/${KUBECTL_VERSION}/bin/linux/amd64/kubectl"
chmod +x kubectl
mv kubectl /usr/local/bin/
- name: Start Docker daemon with insecure registry
run: | run: |
mkdir -p /etc/docker mkdir -p /etc/docker
cat > /etc/docker/daemon.json << 'DAEMON' cat > /etc/docker/daemon.json << 'DAEMON'
{ {
"insecure-registries": ["194.5.195.53:30080", "194.5.195.53:32082", "gitea-svc:3000"] "insecure-registries": ["194.5.195.53:30080", "194.5.195.53:32500", "194.5.195.53:32082"]
} }
DAEMON DAEMON
mkdir -p ~/.docker echo "🚀 Starting Docker daemon..."
cat > ~/.docker/config.json << 'CONF' dockerd --iptables=false --ip6tables=false --bridge=none --storage-driver=vfs &
{
"proxies": { for i in $(seq 1 90); do
"default": { if docker info >/dev/null 2>&1; then
"httpProxy": "http://proxyuser:87zH26nbqT2@46.249.98.211:3128", echo "✅ Docker daemon is ready (attempt $i)"
"httpsProxy": "http://proxyuser:87zH26nbqT2@46.249.98.211:3128", docker version
"noProxy": "localhost,127.0.0.1,gitea-svc,45.149.79.127,10.0.0.0/8" break
} else
} echo "⏳ Waiting for Docker daemon... (attempt $i/90)"
} sleep 2
CONF fi
dockerd &
for i in $(seq 1 30); do
docker info >/dev/null 2>&1 && break || sleep 2
done done
docker info
if ! docker info >/dev/null 2>&1; then
echo "❌ Docker daemon failed to start"
exit 1
fi
- name: Checkout code - name: Checkout code
run: | run: |
git clone --depth 1 --branch production http://gitea-svc:3000/admin/CMS.git . git clone --depth 1 --branch production http://gitea-svc:3000/admin/CMS.git .
git log -1 --format="%H %s"
- name: Login to Docker registries
run: |
echo "${{ secrets.REGISTRY_PASSWORD }}" | docker login 194.5.195.53:32082 -u admin --password-stdin
echo "${{ secrets.REGISTRY_PASSWORD }}" | docker login ${{ env.REGISTRY }} -u admin --password-stdin
- name: Publish Protobuf packages
run: |
echo "📦 Publishing Protobuf packages..."
docker run --rm --network host -v $(pwd):/src -w /src \
194.5.195.53:32082/dotnet/sdk:9.0 sh -c '
for proj in $(find . -name "*Protobuf*.csproj" -type f); do
echo "📦 $proj"
dotnet restore "$proj" --configfile src/NuGet.config
dotnet build "$proj" -c Release --no-restore
dotnet pack "$proj" -c Release --no-build -o "$(dirname $proj)/nupkg"
for nupkg in $(dirname $proj)/nupkg/*.nupkg; do
[ -f "$nupkg" ] && dotnet nuget push "$nupkg" \
--source "http://194.5.195.53:32081/repository/foursat-nuget-hosted/index.json" \
--api-key "admin:87zH26nbqT" \
--skip-duplicate --allow-insecure-connections || true
done
done
'
echo "✅ Protobuf packages done!"
- name: Build Docker Image - name: Build Docker Image
run: | run: |
docker build -t ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.sha }} \ DOCKER_BUILDKIT=0 docker build --network host \
-t ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:prod \ -t ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.sha }} \
--build-arg HTTP_PROXY=http://proxyuser:87zH26nbqT2@46.249.98.211:3128 \ -t ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:prod \
--build-arg HTTPS_PROXY=http://proxyuser:87zH26nbqT2@46.249.98.211:3128 \ .
.
- name: Push to Registry - name: Push to Registry
run: | run: |
echo "${{ secrets.REGISTRY_PASSWORD }}" | docker login ${{ env.REGISTRY }} -u admin --password-stdin
docker push ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.sha }} docker push ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.sha }}
docker push ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:prod docker push ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:prod
- name: Deploy to Production - name: Deploy to Production
run: | run: |
# Setup kubeconfig for PRODUCTION export SSHPASS="${{ secrets.SERVER_PASSWORD }}"
mkdir -p ~/.kube sshpass -e ssh -o StrictHostKeyChecking=no root@${{ env.K8S_SERVER }} "
echo "${{ secrets.KUBECONFIG_PROD }}" | base64 -d > ~/.kube/config kubectl set image deployment/cms cms=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.sha }}
kubectl rollout status deployment/cms --timeout=300s
# Restart deployment to pull new image "
kubectl rollout restart deployment/cms || echo "Deployment doesn't exist yet" echo "✅ Deployed to Production!"
# Wait for rollout to complete
kubectl rollout status deployment/cms --timeout=5m || echo "Deployment rollout pending"
+2 -444
View File
@@ -1,445 +1,3 @@
# CMS Microservice - Network & Club Commission + Inventory Management System # CMS Microservice
[![Status](https://img.shields.io/badge/Status-Active%20Development-success)]() Documentation moved to [totalDoc/INDEX.md](../totalDoc/INDEX.md).
[![Progress](https://img.shields.io/badge/Inventory%20System-Phase%202%20Complete-blue)]()
[![Phase](https://img.shields.io/badge/Next-Business%20Services-orange)]()
## 📊 Project Status (January 2026)
### 🏪 Inventory Management System - NEW!
**Progress**: Phase 2 Complete (50%)
**Architecture**: Clean Architecture + CQRS + Repository Pattern
#### ✅ Completed Phases
1.**Phase 1: Infrastructure & Domain Layer**
- Domain Entities: `InventoryItem`, `StockMovement`, `Warehouse`
- Domain Enums: `StockMovementType`
- EF Core Configurations with proper indexing
- Database migration applied
2.**Phase 2: Repository Pattern & CQRS**
- Repository Interfaces & Implementations
- CQRS Commands (17 commands)
- CQRS Queries (35 queries)
- MediatR Handlers (52 handlers)
#### 🔄 In Progress
3. 🔄 **Phase 3: Business Services Layer**
4.**Phase 4: DTOs & AutoMapper**
5.**Phase 5: API Controllers**
---
### 💼 Commission System - Production Ready
**Progress**: 85% Complete
**MVP Status**: ✅ 100% Complete
#### ✅ Completed Features
- ✅ Binary network tree with automatic placement
- ✅ Club membership (Member/Trial) with commission rates
- ✅ Weekly commission calculation (Lesser Leg algorithm)
- ✅ Background worker with Hangfire
- ✅ Email + SMS notifications (MailKit + Kavenegar)
- ✅ Health check endpoints (Kubernetes-ready)
### 🟡 Partially Complete
- Phase 10: Withdrawal & Settlement (40%)
- ✅ Commands & Database
- ❌ Payment Gateway Integration
### ❌ Not Started
- Phase 9: Club Shop & Product Integration (0%)
---
## 🚀 Recent Updates (January 2026)
### 🏪 Inventory Management System - NEW! ✅
**Complete CQRS-based inventory management with:**
#### Domain Layer:
-`InventoryItem` - Multi-warehouse product tracking with min/max thresholds
-`StockMovement` - Complete audit trail with 8 movement types
-`Warehouse` - Multi-location support with default warehouse
#### Repository Pattern:
-`IInventoryItemRepository` - 25+ methods for inventory operations
-`IStockMovementRepository` - Movement tracking & analytics
-`IWarehouseRepository` - Warehouse management & statistics
#### CQRS Commands (17 total):
- **Inventory:** Create, Update, Delete, Reserve, Release, Reduce, Increase
- **Movement:** Create, BulkCreate, Delete
- **Warehouse:** Create, Update, Delete, SetDefault, Activate, BulkCreate
#### CQRS Queries (35 total):
- **Inventory:** GetById, Search, LowStock, OutOfStock, CheckAvailability
- **Movement:** GetHistory, GetByOrder, Search, Analytics, DailyVolume, TopMoving
- **Warehouse:** GetById, Search, GetStats, GetLowStock, GetAllStats
#### Business Features:
- ✅ Multi-warehouse inventory management
- ✅ Stock reservation system for orders
- ✅ Automatic movement tracking
- ✅ Low stock & out-of-stock alerts
- ✅ Advanced analytics & reporting
- ✅ Bulk operations support
- ✅ Transaction-safe operations
---
### Email & SMS Notifications - COMPLETED ✅
-**MailKit 4.14.1** for Email (SMTP with HTML templates)
-**Kavenegar 1.2.5** for SMS (Iranian SMS gateway)
- ✅ User.Email field added with migration
- ✅ 3 notification types: Commission, Club activation, Errors
- ✅ Persian RTL templates with rich formatting
- ✅ Production configuration guide created
### Hangfire Job Scheduling - COMPLETED ✅
- ✅ Dashboard UI at `/hangfire`
- ✅ Cron schedule: Sunday 00:05 UTC
- ✅ SQL Server persistence
- ✅ Manual trigger API endpoints
- ✅ Distributed execution support
### Infrastructure Enhancements - COMPLETED ✅
- ✅ Health Check endpoints (`/health`, `/health/ready`, `/health/live`)
- ✅ AlertService (structured logging for Sentry/Slack)
- ✅ Retry logic (Polly 8.5.0 with exponential backoff)
- ✅ WorkerExecutionLog (database audit trail)
- ✅ CurrentUserService (JWT authentication context)
---
## 🏗️ Architecture
**Clean Architecture** with 4 layers:
```
CMSMicroservice.Domain/ # Entities, Enums, Interfaces
├── Entities/
│ ├── InventoryItem.cs # NEW: Inventory tracking
│ ├── StockMovement.cs # NEW: Movement audit
│ └── Warehouse.cs # NEW: Multi-warehouse
├── Enums/
│ └── StockMovementType.cs # NEW: Movement types
CMSMicroservice.Application/ # CQRS (Commands, Queries, MediatR)
├── Features/
│ ├── InventoryItems/ # NEW: Inventory CQRS
│ │ ├── Commands/
│ │ ├── Queries/
│ │ └── Handlers/
│ ├── StockMovements/ # NEW: Movement CQRS
│ │ ├── Commands/
│ │ ├── Queries/
│ │ └── Handlers/
│ └── Warehouses/ # NEW: Warehouse CQRS
│ ├── Commands/
│ ├── Queries/
│ └── Handlers/
└── Common/Interfaces/
└── Repositories/ # NEW: Repository interfaces
CMSMicroservice.Infrastructure/ # DbContext, Services, Background Jobs
├── Persistence/
│ ├── Context/
│ ├── Configurations/ # NEW: EF Core configs
│ ├── Repositories/ # NEW: Repository implementations
│ └── Migrations/
└── DependencyInjection.cs # NEW: DI setup
CMSMicroservice.WebApi/ # gRPC Services, Controllers
CMSMicroservice.Protobuf/ # Protocol Buffers definitions
```
**Technology Stack**:
- .NET 9.0
- Entity Framework Core 9.0.11
- gRPC + JSON Transcoding
- Hangfire 1.8.22 (Job Scheduling)
- MediatR 13.0.0 (CQRS)
- Polly 8.5.0 (Resilience)
- MailKit 4.14.1 (Email)
- Kavenegar 1.2.5 (SMS)
- SQL Server
---
## 📖 Documentation
- **[Development Plan](docs/development-plan.md)** - NEW: Inventory system roadmap
- **[Implementation Progress](docs/implementation-progress.md)** - Detailed phase-by-phase progress
- **[Email/SMS Configuration Guide](docs/email-sms-configuration-guide.md)** - Production setup instructions
- **[Balance Calculation Logic](docs/balance-calculation-carryover-logic.md)** - Commission algorithm details
- **[Binary Tree Registration](docs/binary-tree-registration-guide.md)** - Network tree guide
- **[Network Club Commission System](docs/network-club-commission-system-v1.1.md)** - Full system specification
---
## 🏪 Inventory System Usage
### Create Warehouse
```csharp
await mediator.Send(new CreateWarehouseCommand
{
Name = "Main Warehouse",
Code = "WH-001",
IsDefault = true,
IsActive = true
});
```
### Create Inventory Item
```csharp
await mediator.Send(new CreateInventoryItemCommand
{
ProductId = 1,
WarehouseId = 1,
Quantity = 100,
MinQuantity = 10,
MaxQuantity = 1000
});
```
### Reserve Stock for Order
```csharp
await mediator.Send(new ReserveInventoryCommand
{
Id = inventoryId,
Quantity = 5,
OrderId = 12345
});
```
### Check Availability
```csharp
bool available = await mediator.Send(
new CheckInventoryAvailabilityQuery(inventoryId, 10));
```
### Get Low Stock Alerts
```csharp
var lowStock = await mediator.Send(new GetLowStockItemsQuery
{
WarehouseId = 1,
Count = 50
});
```
### Get Movement Analytics
```csharp
var summary = await mediator.Send(new GetMovementSummaryQuery
{
FromDate = DateTime.Now.AddDays(-7),
ToDate = DateTime.Now
});
var topProducts = await mediator.Send(new GetTopMovingProductsQuery
{
FromDate = DateTime.Now.AddDays(-30),
ToDate = DateTime.Now,
Count = 10
});
```
---
## 🚀 Quick Start
### Prerequisites
- .NET 9.0 SDK
- SQL Server (local or remote)
- (Optional) Gmail account for Email
- (Optional) Kavenegar account for SMS
### 1. Clone & Build
```bash
cd /home/masoud/Apps/project/FourSat/CMS/src
dotnet build
```
### 2. Configure Database
Update `appsettings.json` with your SQL Server connection:
```json
"ConnectionStrings": {
"DefaultConnection": "Server=YOUR_SERVER;Database=Foursat_CMS;..."
}
```
### 3. Apply Migrations
```bash
cd CMSMicroservice.WebApi
dotnet ef database update
```
### 4. Configure Notifications (Optional)
See [Email/SMS Configuration Guide](docs/email-sms-configuration-guide.md)
### 5. Run
```bash
dotnet run --urls="http://localhost:5133"
```
### 6. Access Endpoints
- **Health**: http://localhost:5133/health
- **Hangfire Dashboard**: http://localhost:5133/hangfire
- **gRPC**: localhost:5133 (HTTP/2)
---
## 🔧 Configuration
### Email (SMTP)
```json
"Email": {
"Enabled": true,
"SmtpHost": "smtp.gmail.com",
"SmtpPort": 587,
"SmtpUsername": "your-email@gmail.com",
"SmtpPassword": "your-gmail-app-password",
"FromEmail": "noreply@foursat.com",
"FromName": "FourSat CMS",
"EnableSsl": true
}
```
### SMS (Kavenegar)
```json
"Sms": {
"Enabled": true,
"Provider": "Kavenegar",
"KavenegarApiKey": "YOUR_API_KEY",
"Sender": "10008663"
}
```
### Background Worker
```csharp
// Cron: "5 0 * * 0" = Every Sunday at 00:05 UTC
RecurringJob.AddOrUpdate<WeeklyCommissionJob>(
"weekly-commission-calculation",
job => job.ExecuteAsync(CancellationToken.None),
"5 0 * * 0");
```
---
## 🧪 Testing
### Manual Trigger (via API)
```bash
# Trigger weekly calculation immediately
curl -X POST http://localhost:5133/api/admin/trigger-weekly-calculation
# Trigger recurring job now
curl -X POST http://localhost:5133/api/admin/trigger-recurring-job-now
# Get recurring jobs status
curl http://localhost:5133/api/admin/recurring-jobs-status
```
### Health Checks
```bash
curl http://localhost:5133/health # Overall health
curl http://localhost:5133/health/ready # Readiness probe (K8s)
curl http://localhost:5133/health/live # Liveness probe (K8s)
```
---
## 📊 What's Remaining?
### 🏪 Inventory System (Current Focus)
1. **Phase 3: Business Services** (In Progress)
- `IInventoryManagementService` - High-level operations
- `IStockMovementService` - Movement orchestration
- `IWarehouseService` - Warehouse business logic
- `IInventoryReportingService` - Advanced reporting
2. **Phase 4: DTOs & AutoMapper** (Next)
- Request/Response DTOs
- AutoMapper profiles
- Validation rules
3. **Phase 5: API Controllers** (Planned)
- `InventoryController` - REST API
- `WarehouseController` - Warehouse management
- `StockMovementController` - Movement tracking
- Swagger documentation
### 💼 Commission System
1. **Payment Gateway Integration** (Phase 10 - 1 week)
- Daya or Bank Mellat API integration
- IBAN transfer automation
- Admin approval UI in BackOffice
2. **Production Configuration** (30 minutes)
- Gmail App Password setup
- Kavenegar API key registration
- Update `appsettings.Production.json`
### Medium Priority
3. **Club Shop Integration** (Phase 9 - 2 weeks)
- Product catalog for club memberships
- Shopping cart integration
- Auto-activation on purchase
### Low Priority
4. **Testing** (Phase 7 - Postponed)
- Unit tests for business logic
- Integration tests for API
- Load testing for background worker
### Optional Enhancements
- Redis distributed locks (multi-server deployment)
- Sentry error tracking (API key needed)
- Slack notifications (webhook needed)
- FCM push notifications
---
## 🎯 MVP Features (100% Complete)
### 💼 Commission System:
✅ Binary network tree with automatic placement
✅ Club membership (Member/Trial) with different commission rates
✅ Weekly commission calculation (Lesser Leg algorithm)
✅ Background worker with Hangfire (cron scheduling)
✅ Balance carryover logic (rollover unused volumes)
✅ MaxWeeklyBalances cap enforcement
✅ Health check endpoints (Kubernetes-ready)
✅ Manual trigger API (admin control)
✅ Email + SMS notifications (MailKit + Kavenegar)
✅ Retry logic with exponential backoff (Polly)
✅ Audit trail (WorkerExecutionLog, History tables)
✅ Structured logging (AlertService for Sentry/Slack)
✅ JWT authentication context (CurrentUserService)
### 🏪 Inventory System (Phase 2 Complete):
✅ Domain entities (InventoryItem, StockMovement, Warehouse)
✅ Multi-warehouse inventory management
✅ Stock reservation system for orders
✅ 8 movement types with complete audit trail
✅ Repository pattern with 25+ methods per repository
✅ CQRS with 17 commands and 35 queries
✅ 52 MediatR handlers with business logic
✅ Low stock and out-of-stock alerts
✅ Advanced analytics (top products, daily volume)
✅ Bulk operations support
✅ Transaction-safe operations with rollback
✅ DI container configuration
---
## 👥 Team
**Development**: FourSat Team
**Last Updated**: January 2026
---
## 📝 License
Proprietary - FourSat Company
# Multi-remote push enabled
@@ -0,0 +1,13 @@
using MediatR;
namespace CMSMicroservice.Application.BlogCategoryCQ.Commands.CreateBlogCategory;
public class CreateBlogCategoryCommand : IRequest<long>
{
public string Title { get; set; } = default!;
public string Slug { get; set; } = default!;
public string? Description { get; set; }
public string? IconName { get; set; }
public int SortOrder { get; set; }
public bool IsActive { get; set; } = true;
}
@@ -0,0 +1,33 @@
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities.Blog;
using MediatR;
namespace CMSMicroservice.Application.BlogCategoryCQ.Commands.CreateBlogCategory;
public class CreateBlogCategoryCommandHandler : IRequestHandler<CreateBlogCategoryCommand, long>
{
private readonly IApplicationDbContext _context;
public CreateBlogCategoryCommandHandler(IApplicationDbContext context)
{
_context = context;
}
public async Task<long> Handle(CreateBlogCategoryCommand request, CancellationToken cancellationToken)
{
var entity = new BlogCategory
{
Title = request.Title,
Slug = request.Slug.ToLower(),
Description = request.Description,
IconName = request.IconName,
SortOrder = request.SortOrder,
IsActive = request.IsActive
};
_context.BlogCategories.Add(entity);
await _context.SaveChangesAsync(cancellationToken);
return entity.Id;
}
}
@@ -0,0 +1,24 @@
using FluentValidation;
namespace CMSMicroservice.Application.BlogCategoryCQ.Commands.CreateBlogCategory;
public class CreateBlogCategoryCommandValidator : AbstractValidator<CreateBlogCategoryCommand>
{
public CreateBlogCategoryCommandValidator()
{
RuleFor(x => x.Title)
.NotEmpty().WithMessage("عنوان دسته‌بندی الزامی است")
.MaximumLength(200).WithMessage("عنوان دسته‌بندی حداکثر ۲۰۰ کاراکتر");
RuleFor(x => x.Slug)
.NotEmpty().WithMessage("اسلاگ الزامی است")
.MaximumLength(200).WithMessage("اسلاگ حداکثر ۲۰۰ کاراکتر")
.Matches(@"^[a-z0-9\-]+$").WithMessage("اسلاگ فقط شامل حروف کوچک، اعداد و خط تیره");
RuleFor(x => x.Description)
.MaximumLength(1000).WithMessage("توضیحات حداکثر ۱۰۰۰ کاراکتر");
RuleFor(x => x.IconName)
.MaximumLength(100).WithMessage("نام آیکون حداکثر ۱۰۰ کاراکتر");
}
}
@@ -0,0 +1,8 @@
using MediatR;
namespace CMSMicroservice.Application.BlogCategoryCQ.Commands.DeleteBlogCategory;
public class DeleteBlogCategoryCommand : IRequest<Unit>
{
public long Id { get; set; }
}
@@ -0,0 +1,29 @@
using CMSMicroservice.Application.Common.Exceptions;
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities.Blog;
using MediatR;
namespace CMSMicroservice.Application.BlogCategoryCQ.Commands.DeleteBlogCategory;
public class DeleteBlogCategoryCommandHandler : IRequestHandler<DeleteBlogCategoryCommand, Unit>
{
private readonly IApplicationDbContext _context;
public DeleteBlogCategoryCommandHandler(IApplicationDbContext context)
{
_context = context;
}
public async Task<Unit> Handle(DeleteBlogCategoryCommand request, CancellationToken cancellationToken)
{
var entity = await _context.BlogCategories.FindAsync(new object[] { request.Id }, cancellationToken);
if (entity == null || entity.IsDeleted)
throw new NotFoundException(nameof(BlogCategory), request.Id);
entity.IsDeleted = true;
await _context.SaveChangesAsync(cancellationToken);
return Unit.Value;
}
}
@@ -0,0 +1,14 @@
using MediatR;
namespace CMSMicroservice.Application.BlogCategoryCQ.Commands.UpdateBlogCategory;
public class UpdateBlogCategoryCommand : IRequest<Unit>
{
public long Id { get; set; }
public string Title { get; set; } = default!;
public string Slug { get; set; } = default!;
public string? Description { get; set; }
public string? IconName { get; set; }
public int SortOrder { get; set; }
public bool IsActive { get; set; }
}
@@ -0,0 +1,34 @@
using CMSMicroservice.Application.Common.Exceptions;
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities.Blog;
using MediatR;
namespace CMSMicroservice.Application.BlogCategoryCQ.Commands.UpdateBlogCategory;
public class UpdateBlogCategoryCommandHandler : IRequestHandler<UpdateBlogCategoryCommand, Unit>
{
private readonly IApplicationDbContext _context;
public UpdateBlogCategoryCommandHandler(IApplicationDbContext context)
{
_context = context;
}
public async Task<Unit> Handle(UpdateBlogCategoryCommand request, CancellationToken cancellationToken)
{
var entity = await _context.BlogCategories.FindAsync(new object[] { request.Id }, cancellationToken);
if (entity == null || entity.IsDeleted)
throw new NotFoundException(nameof(BlogCategory), request.Id);
entity.Title = request.Title;
entity.Slug = request.Slug.ToLower();
entity.Description = request.Description;
entity.IconName = request.IconName;
entity.SortOrder = request.SortOrder;
entity.IsActive = request.IsActive;
await _context.SaveChangesAsync(cancellationToken);
return Unit.Value;
}
}
@@ -0,0 +1,27 @@
using FluentValidation;
namespace CMSMicroservice.Application.BlogCategoryCQ.Commands.UpdateBlogCategory;
public class UpdateBlogCategoryCommandValidator : AbstractValidator<UpdateBlogCategoryCommand>
{
public UpdateBlogCategoryCommandValidator()
{
RuleFor(x => x.Id)
.GreaterThan(0).WithMessage("شناسه دسته‌بندی نامعتبر است");
RuleFor(x => x.Title)
.NotEmpty().WithMessage("عنوان دسته‌بندی الزامی است")
.MaximumLength(200).WithMessage("عنوان دسته‌بندی حداکثر ۲۰۰ کاراکتر");
RuleFor(x => x.Slug)
.NotEmpty().WithMessage("اسلاگ الزامی است")
.MaximumLength(200).WithMessage("اسلاگ حداکثر ۲۰۰ کاراکتر")
.Matches(@"^[a-z0-9\-]+$").WithMessage("اسلاگ فقط شامل حروف کوچک، اعداد و خط تیره");
RuleFor(x => x.Description)
.MaximumLength(1000).WithMessage("توضیحات حداکثر ۱۰۰۰ کاراکتر");
RuleFor(x => x.IconName)
.MaximumLength(100).WithMessage("نام آیکون حداکثر ۱۰۰ کاراکتر");
}
}
@@ -0,0 +1,45 @@
using CMSMicroservice.Application.BlogCategoryCQ.Queries.GetBlogCategory;
using CMSMicroservice.Application.Common.Interfaces;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace CMSMicroservice.Application.BlogCategoryCQ.Queries.GetActiveBlogCategories;
public class GetActiveBlogCategoriesQuery : IRequest<List<BlogCategoryDto>>
{
}
public class GetActiveBlogCategoriesQueryHandler : IRequestHandler<GetActiveBlogCategoriesQuery, List<BlogCategoryDto>>
{
private readonly IApplicationDbContext _context;
public GetActiveBlogCategoriesQueryHandler(IApplicationDbContext context)
{
_context = context;
}
public async Task<List<BlogCategoryDto>> Handle(GetActiveBlogCategoriesQuery request, CancellationToken cancellationToken)
{
var categories = await _context.BlogCategories
.Include(x => x.BlogPostCategories)
.Where(x => !x.IsDeleted && x.IsActive)
.OrderBy(x => x.SortOrder)
.ThenBy(x => x.Title)
.Select(x => new BlogCategoryDto
{
Id = x.Id,
Title = x.Title,
Slug = x.Slug,
Description = x.Description,
IconName = x.IconName,
SortOrder = x.SortOrder,
IsActive = x.IsActive,
PostCount = x.BlogPostCategories.Count,
Created = x.Created,
LastModified = x.LastModified
})
.ToListAsync(cancellationToken);
return categories;
}
}
@@ -0,0 +1,11 @@
using CMSMicroservice.Application.Common.Models;
using MediatR;
namespace CMSMicroservice.Application.BlogCategoryCQ.Queries.GetAllBlogCategories;
public class GetAllBlogCategoriesQuery : IRequest<GetAllBlogCategoriesResponseDto>
{
public int PageNumber { get; set; } = 1;
public int PageSize { get; set; } = 20;
public string? SearchTerm { get; set; }
}
@@ -0,0 +1,64 @@
using CMSMicroservice.Application.BlogCategoryCQ.Queries.GetBlogCategory;
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Application.Common.Models;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace CMSMicroservice.Application.BlogCategoryCQ.Queries.GetAllBlogCategories;
public class GetAllBlogCategoriesQueryHandler : IRequestHandler<GetAllBlogCategoriesQuery, GetAllBlogCategoriesResponseDto>
{
private readonly IApplicationDbContext _context;
public GetAllBlogCategoriesQueryHandler(IApplicationDbContext context)
{
_context = context;
}
public async Task<GetAllBlogCategoriesResponseDto> Handle(GetAllBlogCategoriesQuery request, CancellationToken cancellationToken)
{
var query = _context.BlogCategories
.Include(x => x.BlogPostCategories)
.Where(x => !x.IsDeleted);
if (!string.IsNullOrEmpty(request.SearchTerm))
{
var term = request.SearchTerm.ToLower();
query = query.Where(x => x.Title.ToLower().Contains(term) || x.Slug.ToLower().Contains(term));
}
var totalCount = await query.CountAsync(cancellationToken);
var categories = await query
.OrderBy(x => x.SortOrder)
.ThenBy(x => x.Title)
.Skip((request.PageNumber - 1) * request.PageSize)
.Take(request.PageSize)
.Select(x => new BlogCategoryDto
{
Id = x.Id,
Title = x.Title,
Slug = x.Slug,
Description = x.Description,
IconName = x.IconName,
SortOrder = x.SortOrder,
IsActive = x.IsActive,
PostCount = x.BlogPostCategories.Count,
Created = x.Created,
LastModified = x.LastModified
})
.ToListAsync(cancellationToken);
var metaData = new MetaData
{
TotalCount = totalCount,
PageSize = request.PageSize,
CurrentPage = request.PageNumber,
TotalPage = (int)Math.Ceiling(totalCount / (double)request.PageSize),
HasNext = request.PageNumber < (int)Math.Ceiling(totalCount / (double)request.PageSize),
HasPrevious = request.PageNumber > 1
};
return new GetAllBlogCategoriesResponseDto { MetaData = metaData, Models = categories };
}
}
@@ -0,0 +1,10 @@
using CMSMicroservice.Application.BlogCategoryCQ.Queries.GetBlogCategory;
using CMSMicroservice.Application.Common.Models;
namespace CMSMicroservice.Application.BlogCategoryCQ.Queries.GetAllBlogCategories;
public class GetAllBlogCategoriesResponseDto
{
public MetaData MetaData { get; set; } = default!;
public List<BlogCategoryDto> Models { get; set; } = new();
}
@@ -0,0 +1,15 @@
namespace CMSMicroservice.Application.BlogCategoryCQ.Queries.GetBlogCategory;
public class BlogCategoryDto
{
public long Id { get; set; }
public string Title { get; set; } = default!;
public string Slug { get; set; } = default!;
public string? Description { get; set; }
public string? IconName { get; set; }
public int SortOrder { get; set; }
public bool IsActive { get; set; }
public int PostCount { get; set; }
public DateTime Created { get; set; }
public DateTime? LastModified { get; set; }
}
@@ -0,0 +1,8 @@
using MediatR;
namespace CMSMicroservice.Application.BlogCategoryCQ.Queries.GetBlogCategory;
public class GetBlogCategoryQuery : IRequest<BlogCategoryDto>
{
public long Id { get; set; }
}
@@ -0,0 +1,41 @@
using CMSMicroservice.Application.Common.Exceptions;
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities.Blog;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace CMSMicroservice.Application.BlogCategoryCQ.Queries.GetBlogCategory;
public class GetBlogCategoryQueryHandler : IRequestHandler<GetBlogCategoryQuery, BlogCategoryDto>
{
private readonly IApplicationDbContext _context;
public GetBlogCategoryQueryHandler(IApplicationDbContext context)
{
_context = context;
}
public async Task<BlogCategoryDto> Handle(GetBlogCategoryQuery request, CancellationToken cancellationToken)
{
var entity = await _context.BlogCategories
.Include(x => x.BlogPostCategories)
.FirstOrDefaultAsync(x => x.Id == request.Id && !x.IsDeleted, cancellationToken);
if (entity == null)
throw new NotFoundException(nameof(BlogCategory), request.Id);
return new BlogCategoryDto
{
Id = entity.Id,
Title = entity.Title,
Slug = entity.Slug,
Description = entity.Description,
IconName = entity.IconName,
SortOrder = entity.SortOrder,
IsActive = entity.IsActive,
PostCount = entity.BlogPostCategories.Count,
Created = entity.Created,
LastModified = entity.LastModified
};
}
}
@@ -0,0 +1,14 @@
using MediatR;
namespace CMSMicroservice.Application.BlogPostCQ.Commands.ArchiveBlogPost;
public class ArchiveBlogPostCommand : IRequest<ArchiveBlogPostResult>
{
public long Id { get; set; }
}
public class ArchiveBlogPostResult
{
public bool Success { get; set; }
public string Message { get; set; } = string.Empty;
}
@@ -0,0 +1,32 @@
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Enums;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace CMSMicroservice.Application.BlogPostCQ.Commands.ArchiveBlogPost;
public class ArchiveBlogPostCommandHandler : IRequestHandler<ArchiveBlogPostCommand, ArchiveBlogPostResult>
{
private readonly IApplicationDbContext _context;
private readonly ILogger<ArchiveBlogPostCommandHandler> _logger;
public ArchiveBlogPostCommandHandler(IApplicationDbContext context, ILogger<ArchiveBlogPostCommandHandler> logger)
{
_context = context;
_logger = logger;
}
public async Task<ArchiveBlogPostResult> Handle(ArchiveBlogPostCommand request, CancellationToken cancellationToken)
{
var post = await _context.BlogPosts.FirstOrDefaultAsync(x => x.Id == request.Id && !x.IsDeleted, cancellationToken)
?? throw new KeyNotFoundException($"مقاله با شناسه {request.Id} یافت نشد");
post.Status = BlogPostStatus.Archived;
await _context.SaveChangesAsync(cancellationToken);
_logger.LogInformation("Blog post archived. Id: {Id}, Title: {Title}", post.Id, post.Title);
return new ArchiveBlogPostResult { Success = true, Message = "مقاله آرشیو شد" };
}
}
@@ -0,0 +1,25 @@
using MediatR;
namespace CMSMicroservice.Application.BlogPostCQ.Commands.CreateBlogPost;
/// <summary>
/// دستور ایجاد مقاله جدید
/// </summary>
public class CreateBlogPostCommand : IRequest<long>
{
public string Title { get; set; } = string.Empty;
public string Slug { get; set; } = string.Empty;
public string? Summary { get; set; }
public string HtmlContent { get; set; } = string.Empty;
public string? FeaturedImagePath { get; set; }
public string? FeaturedImageThumbnailPath { get; set; }
public List<long> CategoryIds { get; set; } = new();
public List<long> TagIds { get; set; } = new();
public bool IsFeatured { get; set; }
public int SortOrder { get; set; }
// Image upload properties
public byte[]? ImageFileBytes { get; set; }
public string? ImageFileMime { get; set; }
public string? ImageFileName { get; set; }
}
@@ -0,0 +1,98 @@
using CMSMicroservice.Application.Common.FileManager;
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities.Blog;
using CMSMicroservice.Domain.Enums;
using MediatR;
using Microsoft.Extensions.Logging;
namespace CMSMicroservice.Application.BlogPostCQ.Commands.CreateBlogPost;
public class CreateBlogPostCommandHandler : IRequestHandler<CreateBlogPostCommand, long>
{
private readonly IApplicationDbContext _context;
private readonly ICurrentUserService _currentUser;
private readonly IFileManager _fileManager;
private readonly ILogger<CreateBlogPostCommandHandler> _logger;
public CreateBlogPostCommandHandler(
IApplicationDbContext context,
ICurrentUserService currentUser,
IFileManager fileManager,
ILogger<CreateBlogPostCommandHandler> logger)
{
_context = context;
_currentUser = currentUser;
_fileManager = fileManager;
_logger = logger;
}
public async Task<long> Handle(CreateBlogPostCommand request, CancellationToken cancellationToken)
{
var currentUserId = _currentUser.UserId;
if (string.IsNullOrEmpty(currentUserId) || !long.TryParse(currentUserId, out var authorUserId))
throw new UnauthorizedAccessException("کاربر احراز هویت نشده است");
var post = new BlogPost
{
Title = request.Title.Trim(),
Slug = string.IsNullOrWhiteSpace(request.Slug)
? $"post-{Guid.NewGuid():N}".Substring(0, 20)
: request.Slug.Trim().ToLower(),
Summary = request.Summary?.Trim(),
HtmlContent = request.HtmlContent,
FeaturedImagePath = request.FeaturedImagePath,
FeaturedImageThumbnailPath = request.FeaturedImageThumbnailPath,
Status = BlogPostStatus.Draft,
AuthorUserId = authorUserId,
IsFeatured = request.IsFeatured,
SortOrder = request.SortOrder,
ViewCount = 0
};
// آپلود تصویر شاخص (اگر فایل ارسال شده باشد)
if (request.ImageFileBytes is { Length: > 0 })
{
var result = await _fileManager.UploadImageAsync(
"Images/BlogPosts",
request.ImageFileBytes,
request.ImageFileMime ?? "image/jpeg",
request.ImageFileName,
cancellationToken);
post.FeaturedImagePath = result.Main.Path;
post.FeaturedImageThumbnailPath = result.Thumbnail.Path;
}
_context.BlogPosts.Add(post);
await _context.SaveChangesAsync(cancellationToken);
// افزودن دسته‌بندی‌ها
foreach (var categoryId in request.CategoryIds)
{
_context.BlogPostCategories.Add(new BlogPostCategory
{
BlogPostId = post.Id,
BlogCategoryId = categoryId
});
}
// افزودن تگ‌ها
foreach (var tagId in request.TagIds)
{
_context.BlogPostTags.Add(new BlogPostTag
{
BlogPostId = post.Id,
TagId = tagId
});
}
if (request.CategoryIds.Any() || request.TagIds.Any())
await _context.SaveChangesAsync(cancellationToken);
_logger.LogInformation(
"Blog post created. Id: {Id}, Title: {Title}, Author: {Author}",
post.Id, post.Title, authorUserId);
return post.Id;
}
}
@@ -0,0 +1,25 @@
using FluentValidation;
namespace CMSMicroservice.Application.BlogPostCQ.Commands.CreateBlogPost;
public class CreateBlogPostCommandValidator : AbstractValidator<CreateBlogPostCommand>
{
public CreateBlogPostCommandValidator()
{
RuleFor(x => x.Title)
.NotEmpty().WithMessage("عنوان مقاله الزامی است")
.MaximumLength(200).WithMessage("عنوان نمی‌تواند بیشتر از 200 کاراکتر باشد");
RuleFor(x => x.Slug)
.NotEmpty().WithMessage("نشانی یکتا (slug) الزامی است")
.MaximumLength(200).WithMessage("نشانی نمی‌تواند بیشتر از 200 کاراکتر باشد")
.Matches(@"^[a-z0-9\-]+$").WithMessage("نشانی فقط می‌تواند شامل حروف کوچک انگلیسی، اعداد و خط تیره باشد");
RuleFor(x => x.Summary)
.MaximumLength(500).WithMessage("خلاصه نمی‌تواند بیشتر از 500 کاراکتر باشد")
.When(x => !string.IsNullOrEmpty(x.Summary));
RuleFor(x => x.HtmlContent)
.NotEmpty().WithMessage("محتوای مقاله الزامی است");
}
}
@@ -0,0 +1,8 @@
using MediatR;
namespace CMSMicroservice.Application.BlogPostCQ.Commands.DeleteBlogPost;
public class DeleteBlogPostCommand : IRequest<Unit>
{
public long Id { get; set; }
}
@@ -0,0 +1,31 @@
using CMSMicroservice.Application.Common.Interfaces;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace CMSMicroservice.Application.BlogPostCQ.Commands.DeleteBlogPost;
public class DeleteBlogPostCommandHandler : IRequestHandler<DeleteBlogPostCommand, Unit>
{
private readonly IApplicationDbContext _context;
private readonly ILogger<DeleteBlogPostCommandHandler> _logger;
public DeleteBlogPostCommandHandler(IApplicationDbContext context, ILogger<DeleteBlogPostCommandHandler> logger)
{
_context = context;
_logger = logger;
}
public async Task<Unit> Handle(DeleteBlogPostCommand request, CancellationToken cancellationToken)
{
var post = await _context.BlogPosts.FirstOrDefaultAsync(x => x.Id == request.Id && !x.IsDeleted, cancellationToken)
?? throw new KeyNotFoundException($"مقاله با شناسه {request.Id} یافت نشد");
post.IsDeleted = true;
await _context.SaveChangesAsync(cancellationToken);
_logger.LogInformation("Blog post soft-deleted. Id: {Id}", post.Id);
return Unit.Value;
}
}
@@ -0,0 +1,8 @@
using MediatR;
namespace CMSMicroservice.Application.BlogPostCQ.Commands.IncrementViewCount;
public class IncrementViewCountCommand : IRequest<Unit>
{
public long Id { get; set; }
}
@@ -0,0 +1,27 @@
using CMSMicroservice.Application.Common.Interfaces;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace CMSMicroservice.Application.BlogPostCQ.Commands.IncrementViewCount;
public class IncrementViewCountCommandHandler : IRequestHandler<IncrementViewCountCommand, Unit>
{
private readonly IApplicationDbContext _context;
public IncrementViewCountCommandHandler(IApplicationDbContext context)
{
_context = context;
}
public async Task<Unit> Handle(IncrementViewCountCommand request, CancellationToken cancellationToken)
{
var post = await _context.BlogPosts.FirstOrDefaultAsync(x => x.Id == request.Id && !x.IsDeleted, cancellationToken);
if (post != null)
{
post.ViewCount++;
await _context.SaveChangesAsync(cancellationToken);
}
return Unit.Value;
}
}
@@ -0,0 +1,15 @@
using MediatR;
namespace CMSMicroservice.Application.BlogPostCQ.Commands.PublishBlogPost;
public class PublishBlogPostCommand : IRequest<PublishBlogPostResult>
{
public long Id { get; set; }
}
public class PublishBlogPostResult
{
public bool Success { get; set; }
public string Message { get; set; } = string.Empty;
public DateTime? PublishedAt { get; set; }
}
@@ -0,0 +1,41 @@
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Enums;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace CMSMicroservice.Application.BlogPostCQ.Commands.PublishBlogPost;
public class PublishBlogPostCommandHandler : IRequestHandler<PublishBlogPostCommand, PublishBlogPostResult>
{
private readonly IApplicationDbContext _context;
private readonly ILogger<PublishBlogPostCommandHandler> _logger;
public PublishBlogPostCommandHandler(IApplicationDbContext context, ILogger<PublishBlogPostCommandHandler> logger)
{
_context = context;
_logger = logger;
}
public async Task<PublishBlogPostResult> Handle(PublishBlogPostCommand request, CancellationToken cancellationToken)
{
var post = await _context.BlogPosts.FirstOrDefaultAsync(x => x.Id == request.Id && !x.IsDeleted, cancellationToken)
?? throw new KeyNotFoundException($"مقاله با شناسه {request.Id} یافت نشد");
if (post.Status == BlogPostStatus.Published)
return new PublishBlogPostResult { Success = false, Message = "مقاله قبلاً منتشر شده است" };
post.Status = BlogPostStatus.Published;
post.PublishedAt = DateTime.UtcNow;
await _context.SaveChangesAsync(cancellationToken);
_logger.LogInformation("Blog post published. Id: {Id}, Title: {Title}", post.Id, post.Title);
return new PublishBlogPostResult
{
Success = true,
Message = "مقاله با موفقیت منتشر شد",
PublishedAt = post.PublishedAt
};
}
}
@@ -0,0 +1,23 @@
using MediatR;
namespace CMSMicroservice.Application.BlogPostCQ.Commands.UpdateBlogPost;
public class UpdateBlogPostCommand : IRequest<Unit>
{
public long Id { get; set; }
public string Title { get; set; } = string.Empty;
public string Slug { get; set; } = string.Empty;
public string? Summary { get; set; }
public string HtmlContent { get; set; } = string.Empty;
public string? FeaturedImagePath { get; set; }
public string? FeaturedImageThumbnailPath { get; set; }
public List<long> CategoryIds { get; set; } = new();
public List<long> TagIds { get; set; } = new();
public bool IsFeatured { get; set; }
public int SortOrder { get; set; }
// Image upload properties
public byte[]? ImageFileBytes { get; set; }
public string? ImageFileMime { get; set; }
public string? ImageFileName { get; set; }
}
@@ -0,0 +1,88 @@
using CMSMicroservice.Application.Common.FileManager;
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities.Blog;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace CMSMicroservice.Application.BlogPostCQ.Commands.UpdateBlogPost;
public class UpdateBlogPostCommandHandler : IRequestHandler<UpdateBlogPostCommand, Unit>
{
private readonly IApplicationDbContext _context;
private readonly IFileManager _fileManager;
private readonly ILogger<UpdateBlogPostCommandHandler> _logger;
public UpdateBlogPostCommandHandler(
IApplicationDbContext context,
IFileManager fileManager,
ILogger<UpdateBlogPostCommandHandler> logger)
{
_context = context;
_fileManager = fileManager;
_logger = logger;
}
public async Task<Unit> Handle(UpdateBlogPostCommand request, CancellationToken cancellationToken)
{
var post = await _context.BlogPosts.FirstOrDefaultAsync(x => x.Id == request.Id && !x.IsDeleted, cancellationToken)
?? throw new KeyNotFoundException($"مقاله با شناسه {request.Id} یافت نشد");
post.Title = request.Title.Trim();
// حفظ slug قبلی اگر مقدار جدید خالی باشد
if (!string.IsNullOrWhiteSpace(request.Slug))
post.Slug = request.Slug.Trim().ToLower();
post.Summary = request.Summary?.Trim();
post.HtmlContent = request.HtmlContent;
post.FeaturedImagePath = request.FeaturedImagePath;
post.FeaturedImageThumbnailPath = request.FeaturedImageThumbnailPath;
post.IsFeatured = request.IsFeatured;
post.SortOrder = request.SortOrder;
// آپلود تصویر شاخص (اگر فایل جدید ارسال شده باشد)
if (request.ImageFileBytes is { Length: > 0 })
{
var result = await _fileManager.UploadImageAsync(
"Images/BlogPosts",
request.ImageFileBytes,
request.ImageFileMime ?? "image/jpeg",
request.ImageFileName,
cancellationToken);
post.FeaturedImagePath = result.Main.Path;
post.FeaturedImageThumbnailPath = result.Thumbnail.Path;
}
// بروزرسانی دسته‌بندی‌ها
var existingCategories = await _context.BlogPostCategories
.Where(x => x.BlogPostId == post.Id).ToListAsync(cancellationToken);
_context.BlogPostCategories.RemoveRange(existingCategories);
foreach (var categoryId in request.CategoryIds)
{
_context.BlogPostCategories.Add(new BlogPostCategory
{
BlogPostId = post.Id,
BlogCategoryId = categoryId
});
}
// بروزرسانی تگ‌ها
var existingTags = await _context.BlogPostTags
.Where(x => x.BlogPostId == post.Id).ToListAsync(cancellationToken);
_context.BlogPostTags.RemoveRange(existingTags);
foreach (var tagId in request.TagIds)
{
_context.BlogPostTags.Add(new BlogPostTag
{
BlogPostId = post.Id,
TagId = tagId
});
}
await _context.SaveChangesAsync(cancellationToken);
_logger.LogInformation("Blog post updated. Id: {Id}, Title: {Title}", post.Id, post.Title);
return Unit.Value;
}
}
@@ -0,0 +1,23 @@
using FluentValidation;
namespace CMSMicroservice.Application.BlogPostCQ.Commands.UpdateBlogPost;
public class UpdateBlogPostCommandValidator : AbstractValidator<UpdateBlogPostCommand>
{
public UpdateBlogPostCommandValidator()
{
RuleFor(x => x.Id).GreaterThan(0).WithMessage("شناسه مقاله نامعتبر است");
RuleFor(x => x.Title)
.NotEmpty().WithMessage("عنوان مقاله الزامی است")
.MaximumLength(200).WithMessage("عنوان نمی‌تواند بیشتر از 200 کاراکتر باشد");
RuleFor(x => x.Slug)
.NotEmpty().WithMessage("نشانی یکتا (slug) الزامی است")
.MaximumLength(200).WithMessage("نشانی نمی‌تواند بیشتر از 200 کاراکتر باشد")
.Matches(@"^[a-z0-9\-]+$").WithMessage("نشانی فقط می‌تواند شامل حروف کوچک انگلیسی، اعداد و خط تیره باشد");
RuleFor(x => x.HtmlContent)
.NotEmpty().WithMessage("محتوای مقاله الزامی است");
}
}
@@ -0,0 +1,16 @@
using CMSMicroservice.Application.Common.Models;
using CMSMicroservice.Domain.Enums;
using MediatR;
namespace CMSMicroservice.Application.BlogPostCQ.Queries.GetAllBlogPosts;
public class GetAllBlogPostsQuery : IRequest<GetAllBlogPostsResponseDto>
{
public int PageNumber { get; set; } = 1;
public int PageSize { get; set; } = 10;
public string? SortBy { get; set; }
public string? SearchTerm { get; set; }
public BlogPostStatus? Status { get; set; }
public long? CategoryId { get; set; }
public bool? IsFeatured { get; set; }
}
@@ -0,0 +1,85 @@
using CMSMicroservice.Application.BlogPostCQ.Queries.GetBlogPost;
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Application.Common.Models;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace CMSMicroservice.Application.BlogPostCQ.Queries.GetAllBlogPosts;
public class GetAllBlogPostsQueryHandler : IRequestHandler<GetAllBlogPostsQuery, GetAllBlogPostsResponseDto>
{
private readonly IApplicationDbContext _context;
public GetAllBlogPostsQueryHandler(IApplicationDbContext context)
{
_context = context;
}
public async Task<GetAllBlogPostsResponseDto> Handle(GetAllBlogPostsQuery request, CancellationToken cancellationToken)
{
var query = _context.BlogPosts
.Include(x => x.BlogPostCategories).ThenInclude(x => x.BlogCategory)
.Where(x => !x.IsDeleted);
// فیلترها
if (request.Status.HasValue)
query = query.Where(x => x.Status == request.Status.Value);
if (request.CategoryId.HasValue)
query = query.Where(x => x.BlogPostCategories.Any(c => c.BlogCategoryId == request.CategoryId.Value));
if (request.IsFeatured.HasValue)
query = query.Where(x => x.IsFeatured == request.IsFeatured.Value);
if (!string.IsNullOrEmpty(request.SearchTerm))
{
var term = request.SearchTerm.ToLower();
query = query.Where(x => x.Title.ToLower().Contains(term) || (x.Summary != null && x.Summary.ToLower().Contains(term)));
}
var totalCount = await query.CountAsync(cancellationToken);
// مرتب‌سازی
query = request.SortBy?.ToLower() switch
{
"title" => query.OrderBy(x => x.Title),
"viewcount" => query.OrderByDescending(x => x.ViewCount),
"publishedat" => query.OrderByDescending(x => x.PublishedAt),
_ => query.OrderByDescending(x => x.Created)
};
var posts = await query
.Skip((request.PageNumber - 1) * request.PageSize)
.Take(request.PageSize)
.Select(x => new BlogPostListItemDto
{
Id = x.Id,
Title = x.Title,
Slug = x.Slug,
Summary = x.Summary,
FeaturedImageThumbnailPath = x.FeaturedImageThumbnailPath,
Status = (int)x.Status,
StatusName = GetBlogPostQueryHandler.GetStatusName(x.Status),
PublishedAt = x.PublishedAt,
ViewCount = x.ViewCount,
IsFeatured = x.IsFeatured,
Created = x.Created,
Categories = x.BlogPostCategories.Select(c => new BlogPostCategoryDto
{
Id = c.BlogCategory.Id,
Title = c.BlogCategory.Title,
Slug = c.BlogCategory.Slug
}).ToList()
})
.ToListAsync(cancellationToken);
var metaData = new MetaData
{
TotalCount = totalCount,
PageSize = request.PageSize,
CurrentPage = request.PageNumber,
TotalPage = (int)Math.Ceiling(totalCount / (double)request.PageSize),
HasNext = request.PageNumber < (int)Math.Ceiling(totalCount / (double)request.PageSize),
HasPrevious = request.PageNumber > 1
};
return new GetAllBlogPostsResponseDto { MetaData = metaData, Models = posts };
}
}
@@ -0,0 +1,26 @@
using CMSMicroservice.Application.Common.Models;
using CMSMicroservice.Application.BlogPostCQ.Queries.GetBlogPost;
namespace CMSMicroservice.Application.BlogPostCQ.Queries.GetAllBlogPosts;
public class GetAllBlogPostsResponseDto
{
public MetaData MetaData { get; set; } = new();
public List<BlogPostListItemDto> Models { get; set; } = new();
}
public class BlogPostListItemDto
{
public long Id { get; set; }
public string Title { get; set; } = string.Empty;
public string Slug { get; set; } = string.Empty;
public string? Summary { get; set; }
public string? FeaturedImageThumbnailPath { get; set; }
public int Status { get; set; }
public string StatusName { get; set; } = string.Empty;
public DateTime? PublishedAt { get; set; }
public int ViewCount { get; set; }
public bool IsFeatured { get; set; }
public DateTime Created { get; set; }
public List<BlogPostCategoryDto> Categories { get; set; } = new();
}
@@ -0,0 +1,39 @@
using CMSMicroservice.Domain.Enums;
namespace CMSMicroservice.Application.BlogPostCQ.Queries.GetBlogPost;
public class BlogPostDto
{
public long Id { get; set; }
public string Title { get; set; } = string.Empty;
public string Slug { get; set; } = string.Empty;
public string? Summary { get; set; }
public string HtmlContent { get; set; } = string.Empty;
public string? FeaturedImagePath { get; set; }
public string? FeaturedImageThumbnailPath { get; set; }
public BlogPostStatus Status { get; set; }
public string StatusName { get; set; } = string.Empty;
public DateTime? PublishedAt { get; set; }
public int ViewCount { get; set; }
public long AuthorUserId { get; set; }
public bool IsFeatured { get; set; }
public int SortOrder { get; set; }
public DateTime Created { get; set; }
public DateTime? LastModified { get; set; }
public List<BlogPostCategoryDto> Categories { get; set; } = new();
public List<BlogPostTagDto> Tags { get; set; } = new();
}
public class BlogPostCategoryDto
{
public long Id { get; set; }
public string Title { get; set; } = string.Empty;
public string Slug { get; set; } = string.Empty;
}
public class BlogPostTagDto
{
public long Id { get; set; }
public string Title { get; set; } = string.Empty;
public string Name { get; set; } = string.Empty;
}
@@ -0,0 +1,8 @@
using MediatR;
namespace CMSMicroservice.Application.BlogPostCQ.Queries.GetBlogPost;
public class GetBlogPostQuery : IRequest<BlogPostDto>
{
public long Id { get; set; }
}
@@ -0,0 +1,66 @@
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Enums;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace CMSMicroservice.Application.BlogPostCQ.Queries.GetBlogPost;
public class GetBlogPostQueryHandler : IRequestHandler<GetBlogPostQuery, BlogPostDto>
{
private readonly IApplicationDbContext _context;
public GetBlogPostQueryHandler(IApplicationDbContext context)
{
_context = context;
}
public async Task<BlogPostDto> Handle(GetBlogPostQuery request, CancellationToken cancellationToken)
{
var post = await _context.BlogPosts
.Include(x => x.BlogPostCategories).ThenInclude(x => x.BlogCategory)
.Include(x => x.BlogPostTags).ThenInclude(x => x.Tag)
.FirstOrDefaultAsync(x => x.Id == request.Id && !x.IsDeleted, cancellationToken)
?? throw new KeyNotFoundException($"مقاله با شناسه {request.Id} یافت نشد");
return new BlogPostDto
{
Id = post.Id,
Title = post.Title,
Slug = post.Slug,
Summary = post.Summary,
HtmlContent = post.HtmlContent,
FeaturedImagePath = post.FeaturedImagePath,
FeaturedImageThumbnailPath = post.FeaturedImageThumbnailPath,
Status = post.Status,
StatusName = GetStatusName(post.Status),
PublishedAt = post.PublishedAt,
ViewCount = post.ViewCount,
AuthorUserId = post.AuthorUserId,
IsFeatured = post.IsFeatured,
SortOrder = post.SortOrder,
Created = post.Created,
LastModified = post.LastModified,
Categories = post.BlogPostCategories.Select(c => new BlogPostCategoryDto
{
Id = c.BlogCategory.Id,
Title = c.BlogCategory.Title,
Slug = c.BlogCategory.Slug
}).ToList(),
Tags = post.BlogPostTags.Select(t => new BlogPostTagDto
{
Id = t.Tag.Id,
Title = t.Tag.Title,
Name = t.Tag.Name
}).ToList()
};
}
public static string GetStatusName(BlogPostStatus status) => status switch
{
BlogPostStatus.Draft => "پیش‌نویس",
BlogPostStatus.Published => "منتشرشده",
BlogPostStatus.Scheduled => "زمانبندی‌شده",
BlogPostStatus.Archived => "آرشیو",
_ => "نامشخص"
};
}
@@ -0,0 +1,8 @@
using MediatR;
namespace CMSMicroservice.Application.BlogPostCQ.Queries.GetBlogPostBySlug;
public class GetBlogPostBySlugQuery : IRequest<GetBlogPost.BlogPostDto>
{
public string Slug { get; set; } = string.Empty;
}
@@ -0,0 +1,58 @@
using CMSMicroservice.Application.BlogPostCQ.Queries.GetBlogPost;
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Enums;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace CMSMicroservice.Application.BlogPostCQ.Queries.GetBlogPostBySlug;
public class GetBlogPostBySlugQueryHandler : IRequestHandler<GetBlogPostBySlugQuery, BlogPostDto>
{
private readonly IApplicationDbContext _context;
public GetBlogPostBySlugQueryHandler(IApplicationDbContext context)
{
_context = context;
}
public async Task<BlogPostDto> Handle(GetBlogPostBySlugQuery request, CancellationToken cancellationToken)
{
var post = await _context.BlogPosts
.Include(x => x.BlogPostCategories).ThenInclude(x => x.BlogCategory)
.Include(x => x.BlogPostTags).ThenInclude(x => x.Tag)
.FirstOrDefaultAsync(x => x.Slug == request.Slug && !x.IsDeleted, cancellationToken)
?? throw new KeyNotFoundException($"مقاله با نشانی '{request.Slug}' یافت نشد");
return new BlogPostDto
{
Id = post.Id,
Title = post.Title,
Slug = post.Slug,
Summary = post.Summary,
HtmlContent = post.HtmlContent,
FeaturedImagePath = post.FeaturedImagePath,
FeaturedImageThumbnailPath = post.FeaturedImageThumbnailPath,
Status = post.Status,
StatusName = GetBlogPostQueryHandler.GetStatusName(post.Status),
PublishedAt = post.PublishedAt,
ViewCount = post.ViewCount,
AuthorUserId = post.AuthorUserId,
IsFeatured = post.IsFeatured,
SortOrder = post.SortOrder,
Created = post.Created,
LastModified = post.LastModified,
Categories = post.BlogPostCategories.Select(c => new BlogPostCategoryDto
{
Id = c.BlogCategory.Id,
Title = c.BlogCategory.Title,
Slug = c.BlogCategory.Slug
}).ToList(),
Tags = post.BlogPostTags.Select(t => new BlogPostTagDto
{
Id = t.Tag.Id,
Title = t.Tag.Title,
Name = t.Tag.Name
}).ToList()
};
}
}
@@ -0,0 +1,55 @@
using CMSMicroservice.Application.BlogPostCQ.Queries.GetBlogPost;
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Enums;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace CMSMicroservice.Application.BlogPostCQ.Queries.GetFeaturedBlogPosts;
public class GetFeaturedBlogPostsQuery : IRequest<List<GetAllBlogPosts.BlogPostListItemDto>>
{
public int Count { get; set; } = 5;
}
public class GetFeaturedBlogPostsQueryHandler : IRequestHandler<GetFeaturedBlogPostsQuery, List<GetAllBlogPosts.BlogPostListItemDto>>
{
private readonly IApplicationDbContext _context;
public GetFeaturedBlogPostsQueryHandler(IApplicationDbContext context)
{
_context = context;
}
public async Task<List<GetAllBlogPosts.BlogPostListItemDto>> Handle(GetFeaturedBlogPostsQuery request, CancellationToken cancellationToken)
{
var posts = await _context.BlogPosts
.Include(x => x.BlogPostCategories).ThenInclude(x => x.BlogCategory)
.Where(x => !x.IsDeleted && x.Status == BlogPostStatus.Published && x.IsFeatured)
.OrderBy(x => x.SortOrder)
.ThenByDescending(x => x.PublishedAt)
.Take(request.Count)
.Select(x => new GetAllBlogPosts.BlogPostListItemDto
{
Id = x.Id,
Title = x.Title,
Slug = x.Slug,
Summary = x.Summary,
FeaturedImageThumbnailPath = x.FeaturedImageThumbnailPath,
Status = (int)x.Status,
StatusName = GetBlogPostQueryHandler.GetStatusName(x.Status),
PublishedAt = x.PublishedAt,
ViewCount = x.ViewCount,
IsFeatured = x.IsFeatured,
Created = x.Created,
Categories = x.BlogPostCategories.Select(c => new BlogPostCategoryDto
{
Id = c.BlogCategory.Id,
Title = c.BlogCategory.Title,
Slug = c.BlogCategory.Slug
}).ToList()
})
.ToListAsync(cancellationToken);
return posts;
}
}
@@ -0,0 +1,81 @@
using CMSMicroservice.Application.BlogPostCQ.Queries.GetBlogPost;
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Application.Common.Models;
using CMSMicroservice.Domain.Enums;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace CMSMicroservice.Application.BlogPostCQ.Queries.GetPublishedBlogPosts;
public class GetPublishedBlogPostsQuery : IRequest<GetAllBlogPosts.GetAllBlogPostsResponseDto>
{
public int PageNumber { get; set; } = 1;
public int PageSize { get; set; } = 10;
public string? SearchTerm { get; set; }
public long? CategoryId { get; set; }
}
public class GetPublishedBlogPostsQueryHandler : IRequestHandler<GetPublishedBlogPostsQuery, GetAllBlogPosts.GetAllBlogPostsResponseDto>
{
private readonly IApplicationDbContext _context;
public GetPublishedBlogPostsQueryHandler(IApplicationDbContext context)
{
_context = context;
}
public async Task<GetAllBlogPosts.GetAllBlogPostsResponseDto> Handle(GetPublishedBlogPostsQuery request, CancellationToken cancellationToken)
{
var query = _context.BlogPosts
.Include(x => x.BlogPostCategories).ThenInclude(x => x.BlogCategory)
.Where(x => !x.IsDeleted && x.Status == BlogPostStatus.Published);
if (request.CategoryId.HasValue)
query = query.Where(x => x.BlogPostCategories.Any(c => c.BlogCategoryId == request.CategoryId.Value));
if (!string.IsNullOrEmpty(request.SearchTerm))
{
var term = request.SearchTerm.ToLower();
query = query.Where(x => x.Title.ToLower().Contains(term) || (x.Summary != null && x.Summary.ToLower().Contains(term)));
}
var totalCount = await query.CountAsync(cancellationToken);
var posts = await query
.OrderByDescending(x => x.PublishedAt)
.Skip((request.PageNumber - 1) * request.PageSize)
.Take(request.PageSize)
.Select(x => new GetAllBlogPosts.BlogPostListItemDto
{
Id = x.Id,
Title = x.Title,
Slug = x.Slug,
Summary = x.Summary,
FeaturedImageThumbnailPath = x.FeaturedImageThumbnailPath,
Status = (int)x.Status,
StatusName = GetBlogPostQueryHandler.GetStatusName(x.Status),
PublishedAt = x.PublishedAt,
ViewCount = x.ViewCount,
IsFeatured = x.IsFeatured,
Created = x.Created,
Categories = x.BlogPostCategories.Select(c => new BlogPostCategoryDto
{
Id = c.BlogCategory.Id,
Title = c.BlogCategory.Title,
Slug = c.BlogCategory.Slug
}).ToList()
})
.ToListAsync(cancellationToken);
var metaData = new MetaData
{
TotalCount = totalCount,
PageSize = request.PageSize,
CurrentPage = request.PageNumber,
TotalPage = (int)Math.Ceiling(totalCount / (double)request.PageSize),
HasNext = request.PageNumber < (int)Math.Ceiling(totalCount / (double)request.PageSize),
HasPrevious = request.PageNumber > 1
};
return new GetAllBlogPosts.GetAllBlogPostsResponseDto { MetaData = metaData, Models = posts };
}
}
@@ -0,0 +1,13 @@
using MediatR;
namespace CMSMicroservice.Application.BlogPostImageCQ.Commands.AddBlogPostImage;
public class AddBlogPostImageCommand : IRequest<long>
{
public long BlogPostId { get; set; }
public string ImagePath { get; set; } = default!;
public string ThumbnailPath { get; set; } = default!;
public string? AltText { get; set; }
public string? Caption { get; set; }
public int SortOrder { get; set; }
}
@@ -0,0 +1,39 @@
using CMSMicroservice.Application.Common.Exceptions;
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities.Blog;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace CMSMicroservice.Application.BlogPostImageCQ.Commands.AddBlogPostImage;
public class AddBlogPostImageCommandHandler : IRequestHandler<AddBlogPostImageCommand, long>
{
private readonly IApplicationDbContext _context;
public AddBlogPostImageCommandHandler(IApplicationDbContext context)
{
_context = context;
}
public async Task<long> Handle(AddBlogPostImageCommand request, CancellationToken cancellationToken)
{
var blogPost = await _context.BlogPosts.FirstOrDefaultAsync(x => x.Id == request.BlogPostId && !x.IsDeleted, cancellationToken);
if (blogPost == null)
throw new NotFoundException(nameof(BlogPost), request.BlogPostId);
var entity = new BlogPostImage
{
BlogPostId = request.BlogPostId,
ImagePath = request.ImagePath,
ThumbnailPath = request.ThumbnailPath,
AltText = request.AltText,
Caption = request.Caption,
SortOrder = request.SortOrder
};
_context.BlogPostImages.Add(entity);
await _context.SaveChangesAsync(cancellationToken);
return entity.Id;
}
}
@@ -0,0 +1,21 @@
using FluentValidation;
namespace CMSMicroservice.Application.BlogPostImageCQ.Commands.AddBlogPostImage;
public class AddBlogPostImageCommandValidator : AbstractValidator<AddBlogPostImageCommand>
{
public AddBlogPostImageCommandValidator()
{
RuleFor(x => x.BlogPostId)
.GreaterThan(0).WithMessage("شناسه پست نامعتبر است");
RuleFor(x => x.ImagePath)
.NotEmpty().WithMessage("مسیر تصویر الزامی است");
RuleFor(x => x.AltText)
.MaximumLength(500).WithMessage("متن جایگزین حداکثر ۵۰۰ کاراکتر");
RuleFor(x => x.Caption)
.MaximumLength(1000).WithMessage("عنوان تصویر حداکثر ۱۰۰۰ کاراکتر");
}
}
@@ -0,0 +1,8 @@
using MediatR;
namespace CMSMicroservice.Application.BlogPostImageCQ.Commands.DeleteBlogPostImage;
public class DeleteBlogPostImageCommand : IRequest<Unit>
{
public long Id { get; set; }
}
@@ -0,0 +1,29 @@
using CMSMicroservice.Application.Common.Exceptions;
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities.Blog;
using MediatR;
namespace CMSMicroservice.Application.BlogPostImageCQ.Commands.DeleteBlogPostImage;
public class DeleteBlogPostImageCommandHandler : IRequestHandler<DeleteBlogPostImageCommand, Unit>
{
private readonly IApplicationDbContext _context;
public DeleteBlogPostImageCommandHandler(IApplicationDbContext context)
{
_context = context;
}
public async Task<Unit> Handle(DeleteBlogPostImageCommand request, CancellationToken cancellationToken)
{
var entity = await _context.BlogPostImages.FindAsync(new object[] { request.Id }, cancellationToken);
if (entity == null || entity.IsDeleted)
throw new NotFoundException(nameof(BlogPostImage), request.Id);
entity.IsDeleted = true;
await _context.SaveChangesAsync(cancellationToken);
return Unit.Value;
}
}
@@ -0,0 +1,14 @@
using MediatR;
namespace CMSMicroservice.Application.BlogPostImageCQ.Commands.ReorderBlogPostImages;
public class ReorderBlogPostImagesCommand : IRequest<Unit>
{
public List<ImageSortItem> Items { get; set; } = new();
}
public class ImageSortItem
{
public long Id { get; set; }
public int SortOrder { get; set; }
}
@@ -0,0 +1,34 @@
using CMSMicroservice.Application.Common.Interfaces;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace CMSMicroservice.Application.BlogPostImageCQ.Commands.ReorderBlogPostImages;
public class ReorderBlogPostImagesCommandHandler : IRequestHandler<ReorderBlogPostImagesCommand, Unit>
{
private readonly IApplicationDbContext _context;
public ReorderBlogPostImagesCommandHandler(IApplicationDbContext context)
{
_context = context;
}
public async Task<Unit> Handle(ReorderBlogPostImagesCommand request, CancellationToken cancellationToken)
{
var ids = request.Items.Select(x => x.Id).ToList();
var images = await _context.BlogPostImages
.Where(x => ids.Contains(x.Id) && !x.IsDeleted)
.ToListAsync(cancellationToken);
foreach (var item in request.Items)
{
var image = images.FirstOrDefault(x => x.Id == item.Id);
if (image != null)
image.SortOrder = item.SortOrder;
}
await _context.SaveChangesAsync(cancellationToken);
return Unit.Value;
}
}
@@ -0,0 +1,19 @@
using MediatR;
namespace CMSMicroservice.Application.BlogPostImageCQ.Queries.GetBlogPostImages;
public class GetBlogPostImagesQuery : IRequest<List<BlogPostImageDto>>
{
public long BlogPostId { get; set; }
}
public class BlogPostImageDto
{
public long Id { get; set; }
public long BlogPostId { get; set; }
public string ImagePath { get; set; } = default!;
public string? ThumbnailPath { get; set; }
public string? AltText { get; set; }
public string? Caption { get; set; }
public int SortOrder { get; set; }
}
@@ -0,0 +1,35 @@
using CMSMicroservice.Application.Common.Interfaces;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace CMSMicroservice.Application.BlogPostImageCQ.Queries.GetBlogPostImages;
public class GetBlogPostImagesQueryHandler : IRequestHandler<GetBlogPostImagesQuery, List<BlogPostImageDto>>
{
private readonly IApplicationDbContext _context;
public GetBlogPostImagesQueryHandler(IApplicationDbContext context)
{
_context = context;
}
public async Task<List<BlogPostImageDto>> Handle(GetBlogPostImagesQuery request, CancellationToken cancellationToken)
{
var images = await _context.BlogPostImages
.Where(x => x.BlogPostId == request.BlogPostId && !x.IsDeleted)
.OrderBy(x => x.SortOrder)
.Select(x => new BlogPostImageDto
{
Id = x.Id,
BlogPostId = x.BlogPostId,
ImagePath = x.ImagePath,
ThumbnailPath = x.ThumbnailPath,
AltText = x.AltText,
Caption = x.Caption,
SortOrder = x.SortOrder
})
.ToListAsync(cancellationToken);
return images;
}
}
@@ -31,7 +31,18 @@ public class GetAllCategoryByFilterQueryHandler : IRequestHandler<GetAllCategory
{ {
MetaData = await query.GetMetaData(request.PaginationState, cancellationToken), MetaData = await query.GetMetaData(request.PaginationState, cancellationToken),
Models = await query.PaginatedListAsync(paginationState: request.PaginationState) Models = await query.PaginatedListAsync(paginationState: request.PaginationState)
.ProjectToType<GetAllCategoryByFilterResponseModel>().ToListAsync(cancellationToken) .Select(x => new GetAllCategoryByFilterResponseModel
{
Id = x.Id,
Name = x.Name,
Title = x.Title,
Description = x.Description,
ImagePath = x.ImagePath,
ParentId = x.ParentId,
IsActive = x.IsActive,
SortOrder = x.SortOrder,
ProductCount = x.ProductCategories.Count
}).ToListAsync(cancellationToken)
}; };
} }
} }
@@ -24,4 +24,6 @@ public class GetAllCategoryByFilterResponseDto
public bool IsActive { get; set; } public bool IsActive { get; set; }
//ترتیب نمایش //ترتیب نمایش
public int SortOrder { get; set; } public int SortOrder { get; set; }
//تعداد محصولات
public int ProductCount { get; set; }
} }
@@ -53,20 +53,28 @@ public class AcceptClubMembershipContractCommandHandler
AcceptClubMembershipContractCommand request, AcceptClubMembershipContractCommand request,
CancellationToken cancellationToken) CancellationToken cancellationToken)
{ {
// خواندن UserId از JWT (امن‌تر از دریافت از کلاینت)
if (!long.TryParse(_currentUser.UserId, out var userId))
return new AcceptClubMembershipContractResponseDto
{
Success = false,
Message = "کاربر احراز هویت نشده است"
};
_logger.LogInformation( _logger.LogInformation(
"Processing club membership contract for UserId: {UserId}", "Processing club membership contract for UserId: {UserId}",
request.UserId userId
); );
// 1. دریافت کاربر // 1. دریافت کاربر
var user = await _context.Users var user = await _context.Users
.Include(u => u.ClubMembership) .Include(u => u.ClubMembership)
.FirstOrDefaultAsync(u => u.Id == request.UserId, cancellationToken); .FirstOrDefaultAsync(u => u.Id == userId, cancellationToken);
if (user == null) if (user == null)
{ {
_logger.LogWarning("User not found: {UserId}", request.UserId); _logger.LogWarning("User not found: {UserId}", userId);
throw new NotFoundException(nameof(User), request.UserId); throw new NotFoundException(nameof(User), userId);
} }
// 2. بررسی خرید پکیج // 2. بررسی خرید پکیج
@@ -4,10 +4,6 @@ public class AcceptClubMembershipContractCommandValidator : AbstractValidator<Ac
{ {
public AcceptClubMembershipContractCommandValidator() public AcceptClubMembershipContractCommandValidator()
{ {
RuleFor(x => x.UserId)
.GreaterThan(0)
.WithMessage("شناسه کاربر الزامی است");
RuleFor(x => x.OtpCode) RuleFor(x => x.OtpCode)
.NotEmpty() .NotEmpty()
.WithMessage("کد تایید الزامی است") .WithMessage("کد تایید الزامی است")
@@ -183,10 +183,9 @@ public class ActivateClubMembershipCommandHandler : IRequestHandler<ActivateClub
return true; return true;
} }
// فعال‌سازی مجدد // فعال‌سازی مجدد — ActivatedAt حفظ میشه (overwrite نمیشه)
entity = existingMembership; entity = existingMembership;
entity.IsActive = true; entity.IsActive = true;
entity.ActivatedAt = activationDate;
entity.PurchaseMethod = user.PackagePurchaseMethod; entity.PurchaseMethod = user.PackagePurchaseMethod;
_context.ClubMemberships.Update(entity); _context.ClubMemberships.Update(entity);
@@ -199,6 +198,41 @@ public class ActivateClubMembershipCommandHandler : IRequestHandler<ActivateClub
await _context.SaveChangesAsync(cancellationToken); await _context.SaveChangesAsync(cancellationToken);
// 6.5. ایجاد ClubMembershipCycle — هر خرید پکیج یک دور جدید
var previousCycles = await _context.ClubMembershipCycles
.Where(c => c.UserId == user.Id && c.IsCurrentCycle)
.ToListAsync(cancellationToken);
foreach (var prevCycle in previousCycles)
{
prevCycle.IsCurrentCycle = false;
}
var maxCycleNumber = await _context.ClubMembershipCycles
.Where(c => c.ClubMembershipId == entity.Id)
.MaxAsync(c => (int?)c.CycleNumber, cancellationToken) ?? 0;
var newCycle = new ClubMembershipCycle
{
UserId = user.Id,
ClubMembershipId = entity.Id,
CycleNumber = maxCycleNumber + 1,
PackagePurchasedAt = activationDate,
PurchaseMethod = user.PackagePurchaseMethod,
PackageAmount = SystemConstants.BasePackageAmount,
IsCurrentCycle = true
};
_context.ClubMembershipCycles.Add(newCycle);
await _context.SaveChangesAsync(cancellationToken);
_logger.LogInformation(
"Created ClubMembershipCycle #{CycleNumber} for UserId {UserId}, MembershipId {MembershipId}",
newCycle.CycleNumber,
user.Id,
entity.Id
);
// 7. ثبت تاریخچه // 7. ثبت تاریخچه
var history = new ClubMembershipHistory var history = new ClubMembershipHistory
{ {
@@ -43,8 +43,14 @@ public class CalculateWeeklyBalancesCommandHandler : IRequestHandler<CalculateWe
// ⭐ دریافت همه کاربرانی که عضو فعال باشگاه هستند // ⭐ دریافت همه کاربرانی که عضو فعال باشگاه هستند
// بدون محدودیت زمانی - همه اعضای فعال کلاب باید کمیسیون بگیرند // بدون محدودیت زمانی - همه اعضای فعال کلاب باید کمیسیون بگیرند
// ⚠️ Magic Wallet: کاربرهایی که در حالت جادویی هستند از کمیسیون خارج میشن
var magicModeUserIds = await _context.UserWallets
.Where(w => w.WalletMode == WalletMode.Magic)
.Select(w => w.UserId)
.ToHashSetAsync(cancellationToken);
var activeClubMemberUserIds = await _context.ClubMemberships var activeClubMemberUserIds = await _context.ClubMemberships
.Where(c => c.IsActive) .Where(c => c.IsActive && !magicModeUserIds.Contains(c.UserId))
.Select(c => c.UserId) .Select(c => c.UserId)
.ToHashSetAsync(cancellationToken); .ToHashSetAsync(cancellationToken);
@@ -256,11 +262,12 @@ public class CalculateWeeklyBalancesCommandHandler : IRequestHandler<CalculateWe
var count = 0; var count = 0;
// اگر فرزند در این هفته فعال شده، 1 امتیاز // اگر فرزند در این هفته پکیج خریده (Cycle جدید ساخته شده)، 1 امتیاز
var membership = await _context.ClubMemberships // ⚠️ از ClubMembershipCycle.PackagePurchasedAt استفاده میکنیم (نه ActivatedAt که overwrite میشد)
.FirstOrDefaultAsync(x => x.UserId == child.Id && x.IsActive, cancellationToken); var currentCycle = await _context.ClubMembershipCycles
.FirstOrDefaultAsync(x => x.UserId == child.Id && x.IsCurrentCycle, cancellationToken);
if (membership?.ActivatedAt >= startDate && membership?.ActivatedAt <= endDate) if (currentCycle?.PackagePurchasedAt >= startDate && currentCycle?.PackagePurchasedAt <= endDate)
{ {
count = 1; count = 1;
} }
@@ -6,14 +6,14 @@ namespace CMSMicroservice.Application.CommissionCQ.Queries.GetAllWeeklyPools;
public record GetAllWeeklyPoolsQuery : IRequest<GetAllWeeklyPoolsResponseDto> public record GetAllWeeklyPoolsQuery : IRequest<GetAllWeeklyPoolsResponseDto>
{ {
/// <summary> /// <summary>
/// از هفته (فیلتر اختیاری) /// از هفته — WeekDefinitionId (فیلتر اختیاری)
/// </summary> /// </summary>
public int? FromWeekOrder { get; init; } public long? FromWeekDefinitionId { get; init; }
/// <summary> /// <summary>
/// تا هفته (فیلتر اختیاری) /// تا هفته — WeekDefinitionId (فیلتر اختیاری)
/// </summary> /// </summary>
public int? ToWeekOrder { get; init; } public long? ToWeekDefinitionId { get; init; }
/// <summary> /// <summary>
/// فقط Pool های محاسبه شده /// فقط Pool های محاسبه شده
@@ -20,14 +20,14 @@ public class GetAllWeeklyPoolsQueryHandler : IRequestHandler<GetAllWeeklyPoolsQu
.AsNoTracking(); .AsNoTracking();
// Apply filters // Apply filters
if (request.FromWeekOrder!=null) if (request.FromWeekDefinitionId != null)
{ {
query = query.Where(x => x.WeekDefinition.WeekOrder>=request.FromWeekOrder ); query = query.Where(x => x.WeekDefinitionId >= request.FromWeekDefinitionId);
} }
if (request.ToWeekOrder!=null) if (request.ToWeekDefinitionId != null)
{ {
query = query.Where(x =>x.WeekDefinition.WeekOrder<= request.ToWeekOrder); query = query.Where(x => x.WeekDefinitionId <= request.ToWeekDefinitionId);
} }
if (request.OnlyCalculated.HasValue && request.OnlyCalculated.Value) if (request.OnlyCalculated.HasValue && request.OnlyCalculated.Value)
@@ -4,16 +4,13 @@ public class GetUserCommissionPayoutsQueryHandler : IRequestHandler<GetUserCommi
{ {
private readonly IApplicationDbContext _context; private readonly IApplicationDbContext _context;
private readonly IWeekDefinitionRepository _weekDefinitionRepository; private readonly IWeekDefinitionRepository _weekDefinitionRepository;
private readonly ICurrentUserService _currentUser;
public GetUserCommissionPayoutsQueryHandler( public GetUserCommissionPayoutsQueryHandler(
IApplicationDbContext context, IApplicationDbContext context,
IWeekDefinitionRepository weekDefinitionRepository, IWeekDefinitionRepository weekDefinitionRepository)
ICurrentUserService currentUser)
{ {
_context = context; _context = context;
_weekDefinitionRepository = weekDefinitionRepository; _weekDefinitionRepository = weekDefinitionRepository;
_currentUser = currentUser;
} }
public async Task<GetUserCommissionPayoutsResponseDto> Handle(GetUserCommissionPayoutsQuery request, CancellationToken cancellationToken) public async Task<GetUserCommissionPayoutsResponseDto> Handle(GetUserCommissionPayoutsQuery request, CancellationToken cancellationToken)
@@ -24,17 +21,11 @@ public class GetUserCommissionPayoutsQueryHandler : IRequestHandler<GetUserCommi
.AsNoTracking() .AsNoTracking()
.AsQueryable(); .AsQueryable();
// اگر UserId داده نشده، از CurrentUser بگیر (برای Customer API) // UserId > 0 → filter by that user
// UserId == 0 or null → show ALL users (admin mode)
// Customer endpoints resolve UserId from JWT before calling this handler
long? userId = request.UserId; long? userId = request.UserId;
if (!userId.HasValue || userId.Value == 0)
{
if (long.TryParse(_currentUser.UserId, out var currentUserId))
{
userId = currentUserId;
}
}
// فیلترها
if (userId.HasValue && userId.Value > 0) if (userId.HasValue && userId.Value > 0)
{ {
query = query.Where(x => x.UserId == userId.Value); query = query.Where(x => x.UserId == userId.Value);
@@ -4,16 +4,13 @@ public class GetUserWeeklyBalancesQueryHandler : IRequestHandler<GetUserWeeklyBa
{ {
private readonly IApplicationDbContext _context; private readonly IApplicationDbContext _context;
private readonly IWeekDefinitionRepository _weekDefinitionRepository; private readonly IWeekDefinitionRepository _weekDefinitionRepository;
private readonly ICurrentUserService _currentUser;
public GetUserWeeklyBalancesQueryHandler( public GetUserWeeklyBalancesQueryHandler(
IApplicationDbContext context, IApplicationDbContext context,
IWeekDefinitionRepository weekDefinitionRepository, IWeekDefinitionRepository weekDefinitionRepository)
ICurrentUserService currentUser)
{ {
_context = context; _context = context;
_weekDefinitionRepository = weekDefinitionRepository; _weekDefinitionRepository = weekDefinitionRepository;
_currentUser = currentUser;
} }
public async Task<GetUserWeeklyBalancesResponseDto> Handle(GetUserWeeklyBalancesQuery request, CancellationToken cancellationToken) public async Task<GetUserWeeklyBalancesResponseDto> Handle(GetUserWeeklyBalancesQuery request, CancellationToken cancellationToken)
@@ -24,17 +21,11 @@ public class GetUserWeeklyBalancesQueryHandler : IRequestHandler<GetUserWeeklyBa
.AsNoTracking() .AsNoTracking()
.AsQueryable(); .AsQueryable();
// اگر UserId داده نشده، از CurrentUser بگیر (برای Customer API) // UserId > 0 → filter by that user
// UserId == 0 or null → show ALL users (admin mode)
// Customer endpoints resolve UserId from JWT before calling this handler
long? userId = request.UserId; long? userId = request.UserId;
if (!userId.HasValue || userId.Value == 0)
{
if (long.TryParse(_currentUser.UserId, out var currentUserId))
{
userId = currentUserId;
}
}
// فیلترها
if (userId.HasValue && userId.Value > 0) if (userId.HasValue && userId.Value > 0)
{ {
query = query.Where(x => x.UserId == userId.Value); query = query.Where(x => x.UserId == userId.Value);
@@ -18,7 +18,10 @@ public class LoggingBehaviour<TRequest> : IRequestPreProcessor<TRequest> where T
{ {
var requestName = typeof(TRequest).Name; var requestName = typeof(TRequest).Name;
var userId = _currentUserService.UserId ?? string.Empty; var userId = _currentUserService.UserId ?? string.Empty;
_logger.LogInformation("Request: {Name} {@UserId} {@Request}", var safeLog = request?.ToString() ?? "";
requestName, userId, request); if (safeLog.Length > 2000)
safeLog = safeLog[..2000] + "... [TRUNCATED]";
_logger.LogInformation("Request: {Name} {UserId} {Request}",
requestName, userId, safeLog);
} }
} }
@@ -1,16 +1,20 @@
using System.Diagnostics; using System.Diagnostics;
using System.Text.RegularExpressions;
using MediatR; using MediatR;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
namespace CMSMicroservice.Application.Common.Behaviours; namespace CMSMicroservice.Application.Common.Behaviours;
public class PerformanceBehaviour<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse> public partial class PerformanceBehaviour<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
where TRequest : IRequest<TResponse> where TRequest : IRequest<TResponse>
{ {
private readonly Stopwatch _timer; private readonly Stopwatch _timer;
private readonly ILogger<TRequest> _logger; private readonly ILogger<TRequest> _logger;
private readonly ICurrentUserService _currentUserService; private readonly ICurrentUserService _currentUserService;
[GeneratedRegex(@"ImageFile(?:Bytes|Mime|FileName)|ImageFile|File", RegexOptions.None)]
private static partial Regex BinaryPropertyPattern();
public PerformanceBehaviour(ILogger<TRequest> logger, ICurrentUserService currentUserService) public PerformanceBehaviour(ILogger<TRequest> logger, ICurrentUserService currentUserService)
{ {
_timer = new Stopwatch(); _timer = new Stopwatch();
@@ -33,11 +37,20 @@ public class PerformanceBehaviour<TRequest, TResponse> : IPipelineBehavior<TRequ
{ {
var requestName = typeof(TRequest).Name; var requestName = typeof(TRequest).Name;
var userId = _currentUserService.UserId ?? string.Empty; var userId = _currentUserService.UserId ?? string.Empty;
var safeLog = SanitizeForLog(request);
_logger.LogWarning("Long Running Request: {Name} ({ElapsedMilliseconds} milliseconds) {@UserId} {@Request}", _logger.LogWarning("Long Running Request: {Name} ({ElapsedMilliseconds} milliseconds) {UserId} {Request}",
requestName, elapsedMilliseconds, userId, request); requestName, elapsedMilliseconds, userId, safeLog);
} }
return response; return response;
} }
private static string SanitizeForLog(TRequest request)
{
var text = request?.ToString() ?? "";
if (text.Length > 2000)
return text[..2000] + "... [TRUNCATED]";
return text;
}
} }
@@ -22,8 +22,11 @@ public class UnhandledExceptionBehaviour<TRequest, TResponse> : IPipelineBehavio
catch (Exception ex) catch (Exception ex)
{ {
var requestName = typeof(TRequest).Name; var requestName = typeof(TRequest).Name;
var safeLog = request?.ToString() ?? "";
if (safeLog.Length > 2000)
safeLog = safeLog[..2000] + "... [TRUNCATED]";
_logger.LogError(ex, "Request: Unhandled Exception for Request {Name} {@Request}", requestName, request); _logger.LogError(ex, "Request: Unhandled Exception for Request {Name} {Request}", requestName, safeLog);
throw; throw;
} }
@@ -0,0 +1,67 @@
namespace CMSMicroservice.Application.Common.FileManager;
/// <summary>
/// سرویس مدیریت فایل — ذخیره روی دیسک، مسیر نسبی در دیتابیس
/// موقع واکشی: خواندن از دیسک و تبدیل به base64 data-URI
/// </summary>
public interface IFileManager
{
/// <summary>
/// آپلود یک فایل خام به دیسک
/// </summary>
/// <returns>نتیجه آپلود شامل مسیر نسبی فایل</returns>
/// <exception cref="FileUploadException">در صورت خطای آپلود</exception>
Task<UploadedFile> UploadAsync(
string directory,
byte[] fileBytes,
string mime,
string? fileName = null,
CancellationToken ct = default);
/// <summary>
/// آپلود تصویر با بهینه‌سازی خودکار + ساخت بندانگشتی
/// </summary>
/// <returns>نتیجه آپلود شامل تصویر اصلی و بندانگشتی (مسیرهای نسبی)</returns>
/// <exception cref="FileUploadException">در صورت خطای آپلود</exception>
Task<UploadedImage> UploadImageAsync(
string directory,
byte[] fileBytes,
string mime,
string? fileName = null,
CancellationToken ct = default);
/// <summary>
/// حذف فایل از دیسک
/// </summary>
Task DeleteAsync(long fileId, CancellationToken ct = default);
/// <summary>
/// خواندن فایل از دیسک و تبدیل به base64 data-URI
/// اگر مسیر از قبل data: باشد، همان را برمی‌گرداند
/// اگر فایل وجود نداشته باشد، رشته خالی برمی‌گرداند
/// </summary>
string ResolveImageUrl(string? path);
}
/// <summary>
/// نتیجه آپلود فایل
/// </summary>
/// <param name="Id">شناسه فایل در FMS</param>
/// <param name="Path">مسیر فایل ذخیره‌شده (مثلاً /Images/Products/abc.jpg)</param>
public sealed record UploadedFile(long Id, string Path);
/// <summary>
/// نتیجه آپلود تصویر — شامل تصویر اصلی و بندانگشتی
/// </summary>
/// <param name="Main">تصویر اصلی بهینه‌شده</param>
/// <param name="Thumbnail">تصویر بندانگشتی</param>
public sealed record UploadedImage(UploadedFile Main, UploadedFile Thumbnail);
/// <summary>
/// خطای آپلود فایل
/// </summary>
public class FileUploadException : Exception
{
public FileUploadException(string message) : base(message) { }
public FileUploadException(string message, Exception inner) : base(message, inner) { }
}
@@ -1,3 +1,5 @@
using CMSMicroservice.Domain.Entities.Blog;
using CMSMicroservice.Domain.Entities.Content;
using CMSMicroservice.Domain.Entities.Payment; using CMSMicroservice.Domain.Entities.Payment;
using CMSMicroservice.Domain.Entities.Order; using CMSMicroservice.Domain.Entities.Order;
using CMSMicroservice.Domain.Entities.DiscountShop; using CMSMicroservice.Domain.Entities.DiscountShop;
@@ -32,9 +34,11 @@ public interface IApplicationDbContext
DbSet<UserWallet> UserWallets { get; } DbSet<UserWallet> UserWallets { get; }
DbSet<UserWalletChangeLog> UserWalletChangeLogs { get; } DbSet<UserWalletChangeLog> UserWalletChangeLogs { get; }
DbSet<ManualPayment> ManualPayments { get; } DbSet<ManualPayment> ManualPayments { get; }
DbSet<PaymentTransaction> PaymentTransactions { get; }
DbSet<PublicMessage> PublicMessages { get; } DbSet<PublicMessage> PublicMessages { get; }
DbSet<ClubMembership> ClubMemberships { get; } DbSet<ClubMembership> ClubMemberships { get; }
DbSet<ClubMembershipHistory> ClubMembershipHistories { get; } DbSet<ClubMembershipHistory> ClubMembershipHistories { get; }
DbSet<ClubMembershipCycle> ClubMembershipCycles { get; }
DbSet<ClubFeature> ClubFeatures { get; } DbSet<ClubFeature> ClubFeatures { get; }
DbSet<UserClubFeature> UserClubFeatures { get; } DbSet<UserClubFeature> UserClubFeatures { get; }
DbSet<NetworkWeeklyBalance> NetworkWeeklyBalances { get; } DbSet<NetworkWeeklyBalance> NetworkWeeklyBalances { get; }
@@ -66,6 +70,21 @@ public interface IApplicationDbContext
DbSet<InventoryItem> InventoryItems { get; } DbSet<InventoryItem> InventoryItems { get; }
DbSet<StockMovement> StockMovements { get; } DbSet<StockMovement> StockMovements { get; }
// ============= Blog =============
DbSet<BlogPost> BlogPosts { get; }
DbSet<BlogCategory> BlogCategories { get; }
DbSet<BlogPostCategory> BlogPostCategories { get; }
DbSet<BlogPostTag> BlogPostTags { get; }
DbSet<BlogPostImage> BlogPostImages { get; }
// ============= Content Management =============
DbSet<SitePage> SitePages { get; }
DbSet<SitePageSection> SitePageSections { get; }
// ============= Site Page Settings (Simplified) =============
DbSet<SitePageSettings> SitePageSettingsEntities { get; }
DbSet<SitePageImage> SitePageImages { get; }
/// <summary> /// <summary>
/// دسترسی به DatabaseFacade برای اجرای raw SQL و Stored Procedures /// دسترسی به DatabaseFacade برای اجرای raw SQL و Stored Procedures
/// </summary> /// </summary>
@@ -1,37 +0,0 @@
namespace CMSMicroservice.Application.Common.Interfaces;
/// <summary>
/// Service for uploading files to FMS (File Management Service)
/// </summary>
public interface IFileManagementService
{
/// <summary>
/// Uploads a file to FMS and returns the stored file path
/// </summary>
/// <param name="directory">Target directory path (e.g. "Images/Products")</param>
/// <param name="fileBytes">Raw file bytes</param>
/// <param name="mime">MIME type (e.g. "image/jpeg")</param>
/// <param name="fileName">Original file name</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>The stored file path returned by FMS, or null if upload failed</returns>
Task<string?> UploadFileAsync(string directory, byte[] fileBytes, string mime, string? fileName, CancellationToken cancellationToken = default);
/// <summary>
/// Uploads an image to FMS with optimization (resize + compress)
/// Returns both main image path and thumbnail path
/// </summary>
/// <param name="directory">Target directory path (e.g. "Images/Products")</param>
/// <param name="fileBytes">Raw image bytes</param>
/// <param name="mime">MIME type (e.g. "image/jpeg")</param>
/// <param name="fileName">Original file name</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>Tuple of (mainImagePath, thumbnailPath), either can be null if upload failed</returns>
Task<(string? MainImagePath, string? ThumbnailPath)> UploadImageWithThumbnailAsync(
string directory, byte[] fileBytes, string mime, string? fileName,
CancellationToken cancellationToken = default);
/// <summary>
/// Deletes a file from FMS by its ID
/// </summary>
Task<bool> DeleteFileAsync(long fileId, CancellationToken cancellationToken = default);
}
@@ -27,6 +27,24 @@ public interface IPaymentGatewayService
string verificationToken, string verificationToken,
CancellationToken cancellationToken = default); CancellationToken cancellationToken = default);
/// <summary>
/// تأیید پرداخت با مبلغ — برای درگاه‌هایی مثل زرین‌پال که مبلغ را در Verify نیاز دارند
/// </summary>
/// <param name="refId">شماره مرجع تراکنش (Authority در زرین‌پال)</param>
/// <param name="verificationToken">توکن تأیید از درگاه (Status در زرین‌پال)</param>
/// <param name="amountInToman">مبلغ تراکنش به تومان</param>
/// <param name="cancellationToken"></param>
/// <returns>وضعیت نهایی تراکنش</returns>
Task<PaymentVerificationResult> VerifyPaymentAsync(
string refId,
string verificationToken,
decimal amountInToman,
CancellationToken cancellationToken = default)
{
// پیش‌فرض: درگاه‌هایی که Amount نمی‌خواهند، از overload بدون amount استفاده کنند
return VerifyPaymentAsync(refId, verificationToken, cancellationToken);
}
/// <summary> /// <summary>
/// واریز مبلغ به حساب کاربر (برداشت از کیف پول) /// واریز مبلغ به حساب کاربر (برداشت از کیف پول)
/// </summary> /// </summary>
@@ -124,6 +142,21 @@ public class PaymentVerificationResult
/// پیام /// پیام
/// </summary> /// </summary>
public string? Message { get; set; } public string? Message { get; set; }
/// <summary>
/// شماره کارت ماسک‌شده (مثلاً 6037-****-****-1234)
/// </summary>
public string? CardPan { get; set; }
/// <summary>
/// هش کارت بانکی
/// </summary>
public string? CardHash { get; set; }
/// <summary>
/// کد وضعیت verify از درگاه (100=موفق، 101=تکراری)
/// </summary>
public int? VerificationCode { get; set; }
} }
/// <summary> /// <summary>
@@ -6,14 +6,14 @@ namespace CMSMicroservice.Application.Common.Services;
public static class VatCalculator public static class VatCalculator
{ {
/// <summary> /// <summary>
/// نرخ VAT ایران - 9 درصد /// نرخ VAT ایران - 10 درصد
/// </summary> /// </summary>
public const decimal VAT_RATE = 0.09m; public const decimal VAT_RATE = 0.10m;
/// <summary> /// <summary>
/// نرخ VAT به صورت درصد (9) /// نرخ VAT به صورت درصد (10)
/// </summary> /// </summary>
public const int VAT_PERCENT = 9; public const int VAT_PERCENT = 10;
/// <summary> /// <summary>
/// محاسبه VAT از مبلغ خالص /// محاسبه VAT از مبلغ خالص
@@ -9,4 +9,9 @@ public class AddDiscountProductImageCommand : IRequest<long>
public string ThumbnailPath { get; set; } = string.Empty; public string ThumbnailPath { get; set; } = string.Empty;
public string? Title { get; set; } public string? Title { get; set; }
public string? AltText { get; set; } public string? AltText { get; set; }
// Image file upload
public byte[]? ImageFileBytes { get; set; }
public string? ImageFileMime { get; set; }
public string? ImageFileName { get; set; }
} }
@@ -1,3 +1,4 @@
using CMSMicroservice.Application.Common.FileManager;
using CMSMicroservice.Application.Common.Interfaces; using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities.DiscountShop; using CMSMicroservice.Domain.Entities.DiscountShop;
using MediatR; using MediatR;
@@ -8,10 +9,12 @@ namespace CMSMicroservice.Application.DiscountShopCQ.Commands.AddDiscountProduct
public class AddDiscountProductImageCommandHandler : IRequestHandler<AddDiscountProductImageCommand, long> public class AddDiscountProductImageCommandHandler : IRequestHandler<AddDiscountProductImageCommand, long>
{ {
private readonly IApplicationDbContext _context; private readonly IApplicationDbContext _context;
private readonly IFileManager _fileManager;
public AddDiscountProductImageCommandHandler(IApplicationDbContext context) public AddDiscountProductImageCommandHandler(IApplicationDbContext context, IFileManager fileManager)
{ {
_context = context; _context = context;
_fileManager = fileManager;
} }
public async Task<long> Handle(AddDiscountProductImageCommand request, CancellationToken cancellationToken) public async Task<long> Handle(AddDiscountProductImageCommand request, CancellationToken cancellationToken)
@@ -23,6 +26,23 @@ public class AddDiscountProductImageCommandHandler : IRequestHandler<AddDiscount
if (!productExists) if (!productExists)
throw new InvalidOperationException($"DiscountProduct with Id {request.DiscountProductId} not found."); throw new InvalidOperationException($"DiscountProduct with Id {request.DiscountProductId} not found.");
var imagePath = request.ImagePath;
var thumbnailPath = request.ThumbnailPath;
// آپلود تصویر (اگر فایل ارسال شده باشد)
if (request.ImageFileBytes is { Length: > 0 })
{
var result = await _fileManager.UploadImageAsync(
"Images/DiscountProducts/Gallery",
request.ImageFileBytes,
request.ImageFileMime ?? "image/jpeg",
request.ImageFileName,
cancellationToken);
imagePath = result.Main.Path;
thumbnailPath = result.Thumbnail.Path;
}
// Get the max sort order for this product // Get the max sort order for this product
var maxSortOrder = await _context.DiscountProductImages var maxSortOrder = await _context.DiscountProductImages
.Where(i => i.DiscountProductId == request.DiscountProductId) .Where(i => i.DiscountProductId == request.DiscountProductId)
@@ -31,8 +51,8 @@ public class AddDiscountProductImageCommandHandler : IRequestHandler<AddDiscount
var image = new DiscountProductImage var image = new DiscountProductImage
{ {
DiscountProductId = request.DiscountProductId, DiscountProductId = request.DiscountProductId,
ImagePath = request.ImagePath, ImagePath = imagePath,
ThumbnailPath = request.ThumbnailPath, ThumbnailPath = thumbnailPath,
Title = request.Title, Title = request.Title,
AltText = request.AltText, AltText = request.AltText,
SortOrder = maxSortOrder + 1, SortOrder = maxSortOrder + 1,
@@ -56,7 +56,7 @@ public class CompleteOrderPaymentCommandHandler : IRequestHandler<CompleteOrderP
// Update order // Update order
order.PaymentStatus = PaymentStatus.Success; order.PaymentStatus = PaymentStatus.Success;
order.PaymentDate = DateTime.Now; order.PaymentDate = DateTime.Now;
order.DeliveryStatus = DeliveryStatus.InTransit; order.DeliveryStatus = DeliveryStatus.Pending;
// Deduct discount balance from user wallet // Deduct discount balance from user wallet
var userWallet = await _context.UserWallets var userWallet = await _context.UserWallets
@@ -105,6 +105,7 @@ public class CompleteOrderPaymentCommandHandler : IRequestHandler<CompleteOrderP
transaction.PaymentStatus = PaymentStatus.Reject; transaction.PaymentStatus = PaymentStatus.Reject;
order.PaymentStatus = PaymentStatus.Reject; order.PaymentStatus = PaymentStatus.Reject;
order.DeliveryStatus = DeliveryStatus.Cancelled;
await _context.SaveChangesAsync(cancellationToken); await _context.SaveChangesAsync(cancellationToken);
@@ -11,5 +11,15 @@ public class CreateDiscountProductCommand : IRequest<long>
public int MaxDiscountPercent { get; set; } public int MaxDiscountPercent { get; set; }
public string ImagePath { get; set; } public string ImagePath { get; set; }
public string ThumbnailPath { get; set; } public string ThumbnailPath { get; set; }
public int SortOrder { get; set; }
public bool IsActive { get; set; } = true;
public List<long> CategoryIds { get; set; } = new(); public List<long> CategoryIds { get; set; } = new();
// Image file upload
public byte[]? ImageFileBytes { get; set; }
public string? ImageFileMime { get; set; }
public string? ImageFileName { get; set; }
public byte[]? ThumbnailFileBytes { get; set; }
public string? ThumbnailFileMime { get; set; }
public string? ThumbnailFileName { get; set; }
} }
@@ -1,3 +1,4 @@
using CMSMicroservice.Application.Common.FileManager;
using CMSMicroservice.Application.Common.Interfaces; using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities.DiscountShop; using CMSMicroservice.Domain.Entities.DiscountShop;
using CMSMicroservice.Domain.Enums; using CMSMicroservice.Domain.Enums;
@@ -10,13 +11,16 @@ public class CreateDiscountProductCommandHandler : IRequestHandler<CreateDiscoun
{ {
private readonly IApplicationDbContext _context; private readonly IApplicationDbContext _context;
private readonly IInventoryService _inventoryService; private readonly IInventoryService _inventoryService;
private readonly IFileManager _fileManager;
public CreateDiscountProductCommandHandler( public CreateDiscountProductCommandHandler(
IApplicationDbContext context, IApplicationDbContext context,
IInventoryService inventoryService) IInventoryService inventoryService,
IFileManager fileManager)
{ {
_context = context; _context = context;
_inventoryService = inventoryService; _inventoryService = inventoryService;
_fileManager = fileManager;
} }
public async Task<long> Handle(CreateDiscountProductCommand request, CancellationToken cancellationToken) public async Task<long> Handle(CreateDiscountProductCommand request, CancellationToken cancellationToken)
@@ -28,15 +32,42 @@ public class CreateDiscountProductCommandHandler : IRequestHandler<CreateDiscoun
FullInformation = request.FullInformation, FullInformation = request.FullInformation,
Price = request.Price, Price = request.Price,
MaxDiscountPercent = request.MaxDiscountPercent, MaxDiscountPercent = request.MaxDiscountPercent,
ImagePath = request.ImagePath, ImagePath = request.ImagePath ?? string.Empty,
ThumbnailPath = request.ThumbnailPath, ThumbnailPath = request.ThumbnailPath ?? string.Empty,
RemainingCount = 0, // موجودی اولیه صفر - باید از طریق Inventory اضافه شود RemainingCount = 0,
Rate = 0, Rate = 0,
SaleCount = 0, SaleCount = 0,
ViewCount = 0, ViewCount = 0,
IsActive = true IsActive = request.IsActive
}; };
// آپلود تصویر اصلی (اگر فایل ارسال شده باشد)
if (request.ImageFileBytes is { Length: > 0 })
{
var result = await _fileManager.UploadImageAsync(
"Images/DiscountProducts",
request.ImageFileBytes,
request.ImageFileMime ?? "image/jpeg",
request.ImageFileName,
cancellationToken);
product.ImagePath = result.Main.Path;
product.ThumbnailPath = result.Thumbnail.Path;
}
// آپلود بندانگشتی جداگانه (اختیاری)
if (request.ThumbnailFileBytes is { Length: > 0 })
{
var thumbResult = await _fileManager.UploadAsync(
"Images/DiscountProducts/Thumbnails",
request.ThumbnailFileBytes,
request.ThumbnailFileMime ?? "image/jpeg",
request.ThumbnailFileName,
cancellationToken);
product.ThumbnailPath = thumbResult.Path;
}
_context.DiscountProducts.Add(product); _context.DiscountProducts.Add(product);
await _context.SaveChangesAsync(cancellationToken); await _context.SaveChangesAsync(cancellationToken);
@@ -18,4 +18,9 @@ public class PlaceOrderResponseDto
public long TotalAmount { get; set; } public long TotalAmount { get; set; }
public long DiscountBalanceUsed { get; set; } public long DiscountBalanceUsed { get; set; }
public long GatewayAmountRequired { get; set; } public long GatewayAmountRequired { get; set; }
/// <summary>
/// URL درگاه پرداخت — اگر null باشد یعنی نیاز به پرداخت آنلاین نیست
/// </summary>
public string? PaymentUrl { get; set; }
} }
@@ -5,6 +5,8 @@ using CMSMicroservice.Domain.Entities.Payment;
using CMSMicroservice.Domain.Enums; using CMSMicroservice.Domain.Enums;
using MediatR; using MediatR;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace CMSMicroservice.Application.DiscountShopCQ.Commands.PlaceOrder; namespace CMSMicroservice.Application.DiscountShopCQ.Commands.PlaceOrder;
@@ -12,13 +14,22 @@ public class PlaceOrderCommandHandler : IRequestHandler<PlaceOrderCommand, Place
{ {
private readonly IApplicationDbContext _context; private readonly IApplicationDbContext _context;
private readonly IInventoryService _inventoryService; private readonly IInventoryService _inventoryService;
private readonly IPaymentGatewayService _paymentGateway;
private readonly IConfiguration _configuration;
private readonly ILogger<PlaceOrderCommandHandler> _logger;
public PlaceOrderCommandHandler( public PlaceOrderCommandHandler(
IApplicationDbContext context, IApplicationDbContext context,
IInventoryService inventoryService) IInventoryService inventoryService,
IPaymentGatewayService paymentGateway,
IConfiguration configuration,
ILogger<PlaceOrderCommandHandler> logger)
{ {
_context = context; _context = context;
_inventoryService = inventoryService; _inventoryService = inventoryService;
_paymentGateway = paymentGateway;
_configuration = configuration;
_logger = logger;
} }
public async Task<PlaceOrderResponseDto> Handle(PlaceOrderCommand request, CancellationToken cancellationToken) public async Task<PlaceOrderResponseDto> Handle(PlaceOrderCommand request, CancellationToken cancellationToken)
@@ -98,19 +109,13 @@ public class PlaceOrderCommandHandler : IRequestHandler<PlaceOrderCommand, Place
}); });
} }
// Validate discount balance usage // Always apply maximum possible discount (100%) — user cannot choose less
var maxDiscountBalanceUsable = totalDiscountAmount; var maxDiscountBalanceUsable = totalDiscountAmount;
var actualDiscountBalanceUsed = Math.Min(request.DiscountBalanceToUse, maxDiscountBalanceUsable); var actualDiscountBalanceUsed = Math.Min(maxDiscountBalanceUsable, userWallet.DiscountBalance);
actualDiscountBalanceUsed = Math.Min(actualDiscountBalanceUsed, userWallet.DiscountBalance);
if (actualDiscountBalanceUsed < request.DiscountBalanceToUse) _logger.LogInformation(
{ "Discount auto-applied: max allowed={MaxAllowed}, wallet balance={WalletBalance}, used={Used}",
return new PlaceOrderResponseDto maxDiscountBalanceUsable, userWallet.DiscountBalance, actualDiscountBalanceUsed);
{
Success = false,
Message = $"موجودی تخفیف کافی نیست. حداکثر قابل استفاده: {maxDiscountBalanceUsable:N0} تومان، موجودی شما: {userWallet.DiscountBalance:N0} تومان"
};
}
var gatewayAmountRequired = totalAmount - actualDiscountBalanceUsed; var gatewayAmountRequired = totalAmount - actualDiscountBalanceUsed;
@@ -172,15 +177,121 @@ public class PlaceOrderCommandHandler : IRequestHandler<PlaceOrderCommand, Place
await _context.SaveChangesAsync(cancellationToken); await _context.SaveChangesAsync(cancellationToken);
// اگر مبلغ درگاه > ۰ باشد، باید به درگاه پرداخت متصل شویم
string? paymentUrl = null;
if (finalGatewayAmount > 0)
{
try
{
// آدرس callback — زرین‌پال بعد از پرداخت کاربر را به اینجا هدایت می‌کند
var cmsBaseUrl = _configuration["CmsBaseUrl"] ?? "https://localhost:32846";
var callbackUrl = $"{cmsBaseUrl}/api/payment/discount-order/callback?orderId={order.Id}";
// درخواست به درگاه
var paymentResult = await _paymentGateway.InitiatePaymentAsync(new PaymentRequest
{
Amount = finalGatewayAmount,
UserId = request.UserId,
Description = $"فروشگاه تخفیفی - سفارش #{order.Id}",
CallbackUrl = callbackUrl
}, cancellationToken);
if (paymentResult.IsSuccess && !string.IsNullOrEmpty(paymentResult.GatewayUrl))
{
// ذخیره Authority/RefId در تراکنش برای verify بعدی
transaction.RefId = paymentResult.RefId;
// ثبت PaymentTransaction — جدول جدید با اطلاعات درگاه
var paymentTx = new PaymentTransaction
{
GatewayProvider = _configuration["PaymentProvider"] ?? "zarinpal",
MerchantId = _configuration["ZarinPal:MerchantId"] ?? "",
Amount = finalGatewayAmount,
CallbackUrl = callbackUrl,
Description = $"فروشگاه تخفیفی - سفارش #{order.Id}",
Mobile = null,
UserId = request.UserId,
RequestStatusCode = 100,
RequestStatusMessage = "Success",
Authority = paymentResult.RefId,
PaymentStatus = false, // هنوز verify نشده
TransactionId = transaction.Id,
OrderId = order.Id.ToString()
};
_context.PaymentTransactions.Add(paymentTx);
await _context.SaveChangesAsync(cancellationToken);
paymentUrl = paymentResult.GatewayUrl;
_logger.LogInformation(
"Payment gateway initiated for DiscountOrder #{OrderId}: RefId={RefId}, Url={Url}",
order.Id, paymentResult.RefId, paymentResult.GatewayUrl);
}
else
{
_logger.LogError(
"Payment gateway initiation failed for DiscountOrder #{OrderId}: {Error}",
order.Id, paymentResult.ErrorMessage);
return new PlaceOrderResponseDto
{
Success = false,
Message = $"خطا در اتصال به درگاه پرداخت: {paymentResult.ErrorMessage}",
OrderId = order.Id
};
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Payment gateway exception for DiscountOrder #{OrderId}", order.Id);
return new PlaceOrderResponseDto
{
Success = false,
Message = $"خطا در اتصال به درگاه پرداخت: {ex.Message}",
OrderId = order.Id
};
}
}
else
{
// اگر کل مبلغ از کیف تخفیفی پرداخت شد — مستقیماً تکمیل شود
transaction.PaymentStatus = PaymentStatus.Success;
transaction.PaymentDate = DateTime.Now;
order.PaymentStatus = PaymentStatus.Success;
order.PaymentDate = DateTime.Now;
order.DeliveryStatus = DeliveryStatus.Pending;
var walletForDeduct = await _context.UserWallets
.FirstOrDefaultAsync(w => w.UserId == request.UserId, cancellationToken);
if (walletForDeduct != null)
walletForDeduct.DiscountBalance -= actualDiscountBalanceUsed;
foreach (var cartItem in cartItems)
{
await _inventoryService.ConfirmSaleAsync(
cartItem.ProductId, ProductType.DiscountProduct,
cartItem.Count, order.Id, cancellationToken);
cartItem.Product.SaleCount += cartItem.Count;
}
await _context.SaveChangesAsync(cancellationToken);
_logger.LogInformation(
"DiscountOrder #{OrderId} fully paid via discount balance ({Amount} T)",
order.Id, actualDiscountBalanceUsed);
}
return new PlaceOrderResponseDto return new PlaceOrderResponseDto
{ {
Success = true, Success = true,
Message = "سفارش ایجاد شد. لطفا پرداخت را تکمیل کنید", Message = finalGatewayAmount > 0
? "سفارش ایجاد شد. در حال انتقال به درگاه پرداخت..."
: "سفارش با موفقیت ثبت و پرداخت شد",
OrderId = order.Id, OrderId = order.Id,
TransactionId = transaction.Id, TransactionId = transaction.Id,
TotalAmount = totalAmount, TotalAmount = totalAmount,
DiscountBalanceUsed = actualDiscountBalanceUsed, DiscountBalanceUsed = actualDiscountBalanceUsed,
GatewayAmountRequired = finalGatewayAmount GatewayAmountRequired = finalGatewayAmount,
PaymentUrl = paymentUrl
}; };
} }
} }
@@ -12,7 +12,16 @@ public class UpdateDiscountProductCommand : IRequest<Unit>
public int MaxDiscountPercent { get; set; } public int MaxDiscountPercent { get; set; }
public string ImagePath { get; set; } public string ImagePath { get; set; }
public string ThumbnailPath { get; set; } public string ThumbnailPath { get; set; }
public int SortOrder { get; set; }
public int RemainingCount { get; set; } public int RemainingCount { get; set; }
public bool IsActive { get; set; } public bool IsActive { get; set; }
public List<long> CategoryIds { get; set; } = new(); public List<long> CategoryIds { get; set; } = new();
// Image file upload
public byte[]? ImageFileBytes { get; set; }
public string? ImageFileMime { get; set; }
public string? ImageFileName { get; set; }
public byte[]? ThumbnailFileBytes { get; set; }
public string? ThumbnailFileMime { get; set; }
public string? ThumbnailFileName { get; set; }
} }
@@ -1,3 +1,4 @@
using CMSMicroservice.Application.Common.FileManager;
using CMSMicroservice.Application.Common.Interfaces; using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities.DiscountShop; using CMSMicroservice.Domain.Entities.DiscountShop;
using MediatR; using MediatR;
@@ -8,10 +9,12 @@ namespace CMSMicroservice.Application.DiscountShopCQ.Commands.UpdateDiscountProd
public class UpdateDiscountProductCommandHandler : IRequestHandler<UpdateDiscountProductCommand, Unit> public class UpdateDiscountProductCommandHandler : IRequestHandler<UpdateDiscountProductCommand, Unit>
{ {
private readonly IApplicationDbContext _context; private readonly IApplicationDbContext _context;
private readonly IFileManager _fileManager;
public UpdateDiscountProductCommandHandler(IApplicationDbContext context) public UpdateDiscountProductCommandHandler(IApplicationDbContext context, IFileManager fileManager)
{ {
_context = context; _context = context;
_fileManager = fileManager;
} }
public async Task<Unit> Handle(UpdateDiscountProductCommand request, CancellationToken cancellationToken) public async Task<Unit> Handle(UpdateDiscountProductCommand request, CancellationToken cancellationToken)
@@ -27,11 +30,44 @@ public class UpdateDiscountProductCommandHandler : IRequestHandler<UpdateDiscoun
product.FullInformation = request.FullInformation; product.FullInformation = request.FullInformation;
product.Price = request.Price; product.Price = request.Price;
product.MaxDiscountPercent = request.MaxDiscountPercent; product.MaxDiscountPercent = request.MaxDiscountPercent;
product.ImagePath = request.ImagePath;
product.ThumbnailPath = request.ThumbnailPath;
product.RemainingCount = request.RemainingCount; product.RemainingCount = request.RemainingCount;
product.IsActive = request.IsActive; product.IsActive = request.IsActive;
// آپلود تصویر اصلی (اگر فایل جدید ارسال شده باشد)
if (request.ImageFileBytes is { Length: > 0 })
{
var result = await _fileManager.UploadImageAsync(
"Images/DiscountProducts",
request.ImageFileBytes,
request.ImageFileMime ?? "image/jpeg",
request.ImageFileName,
cancellationToken);
product.ImagePath = result.Main.Path;
product.ThumbnailPath = result.Thumbnail.Path;
}
else if (!string.IsNullOrEmpty(request.ImagePath))
{
product.ImagePath = request.ImagePath;
}
// آپلود بندانگشتی جداگانه (اختیاری)
if (request.ThumbnailFileBytes is { Length: > 0 })
{
var thumbResult = await _fileManager.UploadAsync(
"Images/DiscountProducts/Thumbnails",
request.ThumbnailFileBytes,
request.ThumbnailFileMime ?? "image/jpeg",
request.ThumbnailFileName,
cancellationToken);
product.ThumbnailPath = thumbResult.Path;
}
else if (!string.IsNullOrEmpty(request.ThumbnailPath))
{
product.ThumbnailPath = request.ThumbnailPath;
}
// Update categories // Update categories
var existingCategories = await _context.DiscountProductCategories var existingCategories = await _context.DiscountProductCategories
.Where(pc => pc.ProductId == request.ProductId) .Where(pc => pc.ProductId == request.ProductId)
@@ -43,4 +43,6 @@ public class OrderItemDto
public int DiscountPercentUsed { get; set; } public int DiscountPercentUsed { get; set; }
public long DiscountAmount { get; set; } public long DiscountAmount { get; set; }
public long FinalPrice { get; set; } public long FinalPrice { get; set; }
public string ImagePath { get; set; }
public string ThumbnailPath { get; set; }
} }
@@ -53,7 +53,9 @@ public class GetOrderByIdQueryHandler : IRequestHandler<GetOrderByIdQuery, Order
UnitPrice = od.UnitPrice, UnitPrice = od.UnitPrice,
DiscountPercentUsed = od.DiscountPercentUsed, DiscountPercentUsed = od.DiscountPercentUsed,
DiscountAmount = od.DiscountAmount, DiscountAmount = od.DiscountAmount,
FinalPrice = od.FinalPrice FinalPrice = od.FinalPrice,
ImagePath = od.Product.ImagePath ?? "",
ThumbnailPath = od.Product.ThumbnailPath ?? ""
}).ToList() }).ToList()
}; };
} }
@@ -0,0 +1,36 @@
using CMSMicroservice.Application.Common.Interfaces;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace CMSMicroservice.Application.SitePageSettingsCQ.Commands.DeletePageImage;
// ── Command ──
public class DeletePageImageCommand : IRequest<Unit>
{
public long Id { get; set; }
}
// ── Handler ──
public class DeletePageImageCommandHandler : IRequestHandler<DeletePageImageCommand, Unit>
{
private readonly IApplicationDbContext _context;
public DeletePageImageCommandHandler(IApplicationDbContext context)
{
_context = context;
}
public async Task<Unit> Handle(DeletePageImageCommand request, CancellationToken cancellationToken)
{
var entity = await _context.SitePageImages
.FirstOrDefaultAsync(x => x.Id == request.Id && !x.IsDeleted, cancellationToken);
if (entity != null)
{
entity.IsDeleted = true; // Soft delete
await _context.SaveChangesAsync(cancellationToken);
}
return Unit.Value;
}
}
@@ -0,0 +1,96 @@
using CMSMicroservice.Application.Common.FileManager;
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities.Content;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace CMSMicroservice.Application.SitePageSettingsCQ.Commands.SavePageImage;
// ── Command ──
public class SavePageImageCommand : IRequest<SavePageImageResult>
{
public long Id { get; set; } // 0 = ایجاد جدید
public long SitePageSettingsId { get; set; }
public string ImageGroup { get; set; } = default!;
public string? Title { get; set; }
public string? Subtitle { get; set; }
public string? Description { get; set; }
public string? LinkUrl { get; set; }
public string? IconName { get; set; }
public int SortOrder { get; set; }
public bool IsActive { get; set; } = true;
// Image upload
public byte[]? ImageFileBytes { get; set; }
public string? ImageFileMime { get; set; }
public string? ImageFileName { get; set; }
}
public class SavePageImageResult
{
public long Id { get; set; }
public bool Success { get; set; }
}
// ── Handler ──
public class SavePageImageCommandHandler : IRequestHandler<SavePageImageCommand, SavePageImageResult>
{
private readonly IApplicationDbContext _context;
private readonly IFileManager _fileManager;
public SavePageImageCommandHandler(IApplicationDbContext context, IFileManager fileManager)
{
_context = context;
_fileManager = fileManager;
}
public async Task<SavePageImageResult> Handle(SavePageImageCommand request, CancellationToken cancellationToken)
{
SitePageImage entity;
if (request.Id > 0)
{
// ویرایش
entity = await _context.SitePageImages
.FirstOrDefaultAsync(x => x.Id == request.Id && !x.IsDeleted, cancellationToken)
?? throw new Exception($"تصویر با شناسه {request.Id} یافت نشد");
}
else
{
// ایجاد جدید
entity = new SitePageImage
{
SitePageSettingsId = request.SitePageSettingsId,
ImageGroup = request.ImageGroup,
ImagePath = string.Empty // placeholder — will be set below
};
_context.SitePageImages.Add(entity);
}
entity.Title = request.Title;
entity.Subtitle = request.Subtitle;
entity.Description = request.Description;
entity.LinkUrl = request.LinkUrl;
entity.IconName = request.IconName;
entity.SortOrder = request.SortOrder;
entity.IsActive = request.IsActive;
// آپلود تصویر
if (request.ImageFileBytes is { Length: > 0 })
{
var result = await _fileManager.UploadImageAsync(
$"Images/SitePageSettings/{request.ImageGroup}",
request.ImageFileBytes,
request.ImageFileMime ?? "image/jpeg",
request.ImageFileName,
cancellationToken);
entity.ImagePath = result.Main.Path;
entity.ThumbnailPath = result.Thumbnail.Path;
}
await _context.SaveChangesAsync(cancellationToken);
return new SavePageImageResult { Id = entity.Id, Success = true };
}
}
@@ -0,0 +1,83 @@
using CMSMicroservice.Application.Common.FileManager;
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities.Content;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace CMSMicroservice.Application.SitePageSettingsCQ.Commands.SavePageSettings;
// ── Command ──
public class SavePageSettingsCommand : IRequest<SavePageSettingsResult>
{
public string PageKey { get; set; } = default!;
public string Title { get; set; } = default!;
public string? MetaDescription { get; set; }
public string? HeroTitle { get; set; }
public string? HeroSubtitle { get; set; }
public bool IsActive { get; set; }
public string? SettingsJson { get; set; }
// Hero image upload
public byte[]? ImageFileBytes { get; set; }
public string? ImageFileMime { get; set; }
public string? ImageFileName { get; set; }
}
public class SavePageSettingsResult
{
public long Id { get; set; }
public bool Success { get; set; }
}
// ── Handler ──
public class SavePageSettingsCommandHandler : IRequestHandler<SavePageSettingsCommand, SavePageSettingsResult>
{
private readonly IApplicationDbContext _context;
private readonly IFileManager _fileManager;
public SavePageSettingsCommandHandler(IApplicationDbContext context, IFileManager fileManager)
{
_context = context;
_fileManager = fileManager;
}
public async Task<SavePageSettingsResult> Handle(SavePageSettingsCommand request, CancellationToken cancellationToken)
{
var entity = await _context.SitePageSettingsEntities
.FirstOrDefaultAsync(x => x.PageKey == request.PageKey && !x.IsDeleted, cancellationToken);
if (entity == null)
{
// ایجاد صفحه جدید (فقط برای seed اولیه — صفحات ثابت هستند)
entity = new SitePageSettings
{
PageKey = request.PageKey,
};
_context.SitePageSettingsEntities.Add(entity);
}
entity.Title = request.Title;
entity.MetaDescription = request.MetaDescription;
entity.HeroTitle = request.HeroTitle;
entity.HeroSubtitle = request.HeroSubtitle;
entity.IsActive = request.IsActive;
entity.SettingsJson = request.SettingsJson;
// آپلود تصویر هیرو
if (request.ImageFileBytes is { Length: > 0 })
{
var result = await _fileManager.UploadImageAsync(
"Images/SitePageSettings",
request.ImageFileBytes,
request.ImageFileMime ?? "image/jpeg",
request.ImageFileName,
cancellationToken);
entity.HeroImagePath = result.Main.Path;
}
await _context.SaveChangesAsync(cancellationToken);
return new SavePageSettingsResult { Id = entity.Id, Success = true };
}
}
@@ -0,0 +1,30 @@
using FluentValidation;
namespace CMSMicroservice.Application.SitePageSettingsCQ.Commands.SavePageSettings;
public class SavePageSettingsCommandValidator : AbstractValidator<SavePageSettingsCommand>
{
private static readonly string[] ValidPageKeys = { "landing", "about", "contact", "licenses" };
public SavePageSettingsCommandValidator()
{
RuleFor(x => x.PageKey)
.NotEmpty().WithMessage("کلید صفحه الزامی است")
.MaximumLength(50)
.Must(key => ValidPageKeys.Contains(key))
.WithMessage("کلید صفحه باید یکی از مقادیر landing, about, contact, licenses باشد");
RuleFor(x => x.Title)
.NotEmpty().WithMessage("عنوان صفحه الزامی است")
.MaximumLength(200).WithMessage("عنوان صفحه حداکثر ۲۰۰ کاراکتر");
RuleFor(x => x.MetaDescription)
.MaximumLength(300).WithMessage("توضیحات متا حداکثر ۳۰۰ کاراکتر");
RuleFor(x => x.HeroTitle)
.MaximumLength(200).WithMessage("عنوان هیرو حداکثر ۲۰۰ کاراکتر");
RuleFor(x => x.HeroSubtitle)
.MaximumLength(500).WithMessage("زیرعنوان هیرو حداکثر ۵۰۰ کاراکتر");
}
}
@@ -0,0 +1,49 @@
using CMSMicroservice.Application.Common.Interfaces;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace CMSMicroservice.Application.SitePageSettingsCQ.Queries.GetAllPageSettings;
// ── Query ──
public class GetAllPageSettingsQuery : IRequest<List<PageSettingsSummaryDto>>
{
}
// ── Handler ──
public class GetAllPageSettingsQueryHandler : IRequestHandler<GetAllPageSettingsQuery, List<PageSettingsSummaryDto>>
{
private readonly IApplicationDbContext _context;
public GetAllPageSettingsQueryHandler(IApplicationDbContext context)
{
_context = context;
}
public async Task<List<PageSettingsSummaryDto>> Handle(GetAllPageSettingsQuery request, CancellationToken cancellationToken)
{
return await _context.SitePageSettingsEntities
.Where(x => !x.IsDeleted)
.OrderBy(x => x.Id)
.Select(x => new PageSettingsSummaryDto
{
Id = x.Id,
PageKey = x.PageKey,
Title = x.Title,
IsActive = x.IsActive,
ImageCount = x.Images.Count(i => !i.IsDeleted),
LastModified = x.LastModified ?? x.Created
})
.ToListAsync(cancellationToken);
}
}
// ── DTO ──
public class PageSettingsSummaryDto
{
public long Id { get; set; }
public string PageKey { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public bool IsActive { get; set; }
public int ImageCount { get; set; }
public DateTime LastModified { get; set; }
}
@@ -0,0 +1,92 @@
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities.Content;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace CMSMicroservice.Application.SitePageSettingsCQ.Queries.GetPageSettings;
// ── Query ──
public class GetPageSettingsQuery : IRequest<PageSettingsDto?>
{
public string PageKey { get; set; } = default!;
}
// ── Handler ──
public class GetPageSettingsQueryHandler : IRequestHandler<GetPageSettingsQuery, PageSettingsDto?>
{
private readonly IApplicationDbContext _context;
public GetPageSettingsQueryHandler(IApplicationDbContext context)
{
_context = context;
}
public async Task<PageSettingsDto?> Handle(GetPageSettingsQuery request, CancellationToken cancellationToken)
{
var entity = await _context.SitePageSettingsEntities
.Include(x => x.Images.Where(i => !i.IsDeleted && i.IsActive).OrderBy(i => i.SortOrder))
.FirstOrDefaultAsync(x => x.PageKey == request.PageKey && !x.IsDeleted, cancellationToken);
if (entity == null)
return null;
return MapToDto(entity);
}
public static PageSettingsDto MapToDto(SitePageSettings entity) => new()
{
Id = entity.Id,
PageKey = entity.PageKey,
Title = entity.Title,
MetaDescription = entity.MetaDescription,
HeroTitle = entity.HeroTitle,
HeroSubtitle = entity.HeroSubtitle,
HeroImagePath = entity.HeroImagePath,
IsActive = entity.IsActive,
SettingsJson = entity.SettingsJson,
Images = entity.Images.Select(i => new PageImageDto
{
Id = i.Id,
ImageGroup = i.ImageGroup,
Title = i.Title,
Subtitle = i.Subtitle,
Description = i.Description,
ImagePath = i.ImagePath,
ThumbnailPath = i.ThumbnailPath,
LinkUrl = i.LinkUrl,
IconName = i.IconName,
SortOrder = i.SortOrder,
IsActive = i.IsActive
}).ToList()
};
}
// ── DTOs ──
public class PageSettingsDto
{
public long Id { get; set; }
public string PageKey { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public string? MetaDescription { get; set; }
public string? HeroTitle { get; set; }
public string? HeroSubtitle { get; set; }
public string? HeroImagePath { get; set; }
public bool IsActive { get; set; }
public string? SettingsJson { get; set; }
public List<PageImageDto> Images { get; set; } = new();
}
public class PageImageDto
{
public long Id { get; set; }
public string ImageGroup { get; set; } = string.Empty;
public string? Title { get; set; }
public string? Subtitle { get; set; }
public string? Description { get; set; }
public string ImagePath { get; set; } = string.Empty;
public string? ThumbnailPath { get; set; }
public string? LinkUrl { get; set; }
public string? IconName { get; set; }
public int SortOrder { get; set; }
public bool IsActive { get; set; }
}
@@ -3,7 +3,7 @@ namespace CMSMicroservice.Application.NetworkMembershipCQ.Queries.GetNetworkStat
public class GetNetworkStatisticsQuery : IRequest<GetNetworkStatisticsResponseDto> public class GetNetworkStatisticsQuery : IRequest<GetNetworkStatisticsResponseDto>
{ {
/// <summary> /// <summary>
/// شناسه کاربر برای محاسبه آمار شبکه او - 0 یا null یعنی کاربر جاری /// شناسه کاربر برای محاسبه آمار شبکه او - 0 یعنی آمار کل شبکه (root user)
/// </summary> /// </summary>
public long UserId { get; set; } public long UserId { get; set; }
} }
@@ -5,30 +5,33 @@ namespace CMSMicroservice.Application.NetworkMembershipCQ.Queries.GetNetworkStat
public class GetNetworkStatisticsQueryHandler : IRequestHandler<GetNetworkStatisticsQuery, GetNetworkStatisticsResponseDto> public class GetNetworkStatisticsQueryHandler : IRequestHandler<GetNetworkStatisticsQuery, GetNetworkStatisticsResponseDto>
{ {
private readonly IApplicationDbContext _context; private readonly IApplicationDbContext _context;
private readonly ICurrentUserService _currentUser;
public GetNetworkStatisticsQueryHandler( public GetNetworkStatisticsQueryHandler(
IApplicationDbContext context, IApplicationDbContext context)
ICurrentUserService currentUser)
{ {
_context = context; _context = context;
_currentUser = currentUser;
} }
public async Task<GetNetworkStatisticsResponseDto> Handle(GetNetworkStatisticsQuery request, CancellationToken cancellationToken) public async Task<GetNetworkStatisticsResponseDto> Handle(GetNetworkStatisticsQuery request, CancellationToken cancellationToken)
{ {
// Get userId - use current user if not specified or is 0 // UserId > 0 → stats for that user's network
var userId = request.UserId == 0 // UserId == 0 → global stats (find root user of the network)
? (long.TryParse(_currentUser.UserId, out var currentUserId) ? currentUserId : 0) var userId = request.UserId;
: request.UserId;
// Get all users (needed for descendant calculation anyway)
var allUsers = await _context.Users.ToListAsync(cancellationToken);
if (userId == 0) if (userId == 0)
{ {
throw new UnauthorizedAccessException("User ID not found"); // Find root user (user with no NetworkParentId)
var rootUser = allUsers.FirstOrDefault(x => x.NetworkParentId == null || x.NetworkParentId == 0);
if (rootUser != null)
userId = rootUser.Id;
else if (allUsers.Count > 0)
userId = allUsers.First().Id;
else
throw new InvalidOperationException("No users found in the system");
} }
// Get all descendants recursively
var allUsers = await _context.Users.ToListAsync(cancellationToken);
var allDescendants = GetAllDescendants(userId, allUsers); var allDescendants = GetAllDescendants(userId, allUsers);
// Statistics for the user's network (all descendants) // Statistics for the user's network (all descendants)
@@ -8,28 +8,23 @@ public class GetNetworkTreeQueryHandler : IRequestHandler<GetNetworkTreeQuery, N
{ {
private readonly IApplicationDbContext _context; private readonly IApplicationDbContext _context;
private readonly ILogger<GetNetworkTreeQueryHandler> _logger; private readonly ILogger<GetNetworkTreeQueryHandler> _logger;
private readonly ICurrentUserService _currentUser;
public GetNetworkTreeQueryHandler( public GetNetworkTreeQueryHandler(
IApplicationDbContext context, IApplicationDbContext context,
ILogger<GetNetworkTreeQueryHandler> logger, ILogger<GetNetworkTreeQueryHandler> logger)
ICurrentUserService currentUser)
{ {
_context = context; _context = context;
_logger = logger; _logger = logger;
_currentUser = currentUser;
} }
public async Task<NetworkTreeDto?> Handle(GetNetworkTreeQuery request, CancellationToken cancellationToken) public async Task<NetworkTreeDto?> Handle(GetNetworkTreeQuery request, CancellationToken cancellationToken)
{ {
// Get userId - use current user if UserId is 0 // UserId must be provided - customer endpoints resolve from JWT before calling
var userId = request.UserId == 0 var userId = request.UserId;
? (long.TryParse(_currentUser.UserId, out var currentUserId) ? currentUserId : 0)
: request.UserId;
if (userId == 0) if (userId == 0)
{ {
throw new UnauthorizedAccessException("User ID not found"); throw new ArgumentException("UserId is required for network tree query");
} }
// Create a new request with the resolved userId // Create a new request with the resolved userId
@@ -5,5 +5,8 @@ public record CreateNewOtpTokenCommand : IRequest<CreateNewOtpTokenResponseDto>
public string Mobile { get; init; } public string Mobile { get; init; }
//مقصود //مقصود
public string Purpose { get; init; } public string Purpose { get; init; }
/// <summary>
/// شناسه GUID قرارداد (فقط برای purpose=signcontract/signclubcontract)
/// </summary>
public string? SignGuid { get; init; }
} }
@@ -57,7 +57,7 @@ public class CreateNewOtpTokenCommandHandler : IRequestHandler<CreateNewOtpToken
}; };
await _context.OtpTokens.AddAsync(entity, cancellationToken); await _context.OtpTokens.AddAsync(entity, cancellationToken);
entity.AddDomainEvent(new CreateNewOtpTokenEvent(entity, code)); entity.AddDomainEvent(new CreateNewOtpTokenEvent(entity, code, request.SignGuid));
await _context.SaveChangesAsync(cancellationToken); await _context.SaveChangesAsync(cancellationToken);
return new CreateNewOtpTokenResponseDto() return new CreateNewOtpTokenResponseDto()
{ {
@@ -24,7 +24,20 @@ public class CreateNewOtpTokenEventHandler : INotificationHandler<CreateNewOtpTo
try try
{ {
await _kavenegarService.VerifyLookupAsync(notification.Item.Mobile, notification.PlainCode); var purpose = notification.Item.Purpose?.ToLowerInvariant();
// برای امضای قرارداد، پیامک ساده با GUID ارسال شود
if ((purpose == "signcontract" || purpose == "signclubcontract")
&& !string.IsNullOrEmpty(notification.SignGuid))
{
var message = $"کد تایید امضای قرارداد: {notification.PlainCode}\nشناسه قرارداد: {notification.SignGuid}";
await _kavenegarService.SendAsync(notification.Item.Mobile, message);
}
else
{
await _kavenegarService.VerifyLookupAsync(notification.Item.Mobile, notification.PlainCode);
}
_logger.LogInformation("OTP SMS sent successfully to {Mobile}", notification.Item.Mobile); _logger.LogInformation("OTP SMS sent successfully to {Mobile}", notification.Item.Mobile);
} }
catch (Exception ex) catch (Exception ex)
@@ -5,6 +5,7 @@ using CMSMicroservice.Domain.Entities;
using CMSMicroservice.Domain.Enums; using CMSMicroservice.Domain.Enums;
using MediatR; using MediatR;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using ValidationException = FluentValidation.ValidationException; using ValidationException = FluentValidation.ValidationException;
@@ -15,15 +16,18 @@ public class PurchasePackageCommandHandler
{ {
private readonly IApplicationDbContext _context; private readonly IApplicationDbContext _context;
private readonly IPaymentGatewayService _paymentGateway; private readonly IPaymentGatewayService _paymentGateway;
private readonly IConfiguration _configuration;
private readonly ILogger<PurchasePackageCommandHandler> _logger; private readonly ILogger<PurchasePackageCommandHandler> _logger;
public PurchasePackageCommandHandler( public PurchasePackageCommandHandler(
IApplicationDbContext context, IApplicationDbContext context,
IPaymentGatewayService paymentGateway, IPaymentGatewayService paymentGateway,
IConfiguration configuration,
ILogger<PurchasePackageCommandHandler> logger) ILogger<PurchasePackageCommandHandler> logger)
{ {
_context = context; _context = context;
_paymentGateway = paymentGateway; _paymentGateway = paymentGateway;
_configuration = configuration;
_logger = logger; _logger = logger;
} }
@@ -116,7 +120,7 @@ public class PurchasePackageCommandHandler
Amount = order.Amount, Amount = order.Amount,
UserId = user.Id, UserId = user.Id,
Mobile = user.Mobile ?? "", Mobile = user.Mobile ?? "",
CallbackUrl = $"https://yourdomain.com/api/package/verify-package", CallbackUrl = $"{_configuration["CmsBaseUrl"] ?? "https://localhost:32846"}/api/package/verify-package",
Description = $"خرید پکیج - سفارش #{order.Id}" Description = $"خرید پکیج - سفارش #{order.Id}"
}; };
@@ -133,7 +133,7 @@ public class VerifyBasePackagePaymentCommandHandler : IRequestHandler<VerifyBase
var oldDiscountBalance = userWallet.DiscountBalance; var oldDiscountBalance = userWallet.DiscountBalance;
userWallet.Balance += SystemConstants.BasePackageAmount; userWallet.Balance += SystemConstants.BasePackageAmount;
userWallet.DiscountBalance += SystemConstants.BasePackageAmount; userWallet.DiscountBalance += SystemConstants.BasePackageAmount * 2;
_logger.LogInformation( _logger.LogInformation(
"Charging wallet for user {UserId}. Balance: {OldBalance} -> {NewBalance}, DiscountBalance: {OldDiscount} -> {NewDiscount}", "Charging wallet for user {UserId}. Balance: {OldBalance} -> {NewBalance}, DiscountBalance: {OldDiscount} -> {NewDiscount}",
@@ -157,7 +157,7 @@ public class VerifyBasePackagePaymentCommandHandler : IRequestHandler<VerifyBase
CurrentNetworkBalance = userWallet.NetworkBalance, CurrentNetworkBalance = userWallet.NetworkBalance,
ChangeNerworkValue = 0, ChangeNerworkValue = 0,
CurrentDiscountBalance = userWallet.DiscountBalance, CurrentDiscountBalance = userWallet.DiscountBalance,
ChangeDiscountValue = SystemConstants.BasePackageAmount, ChangeDiscountValue = SystemConstants.BasePackageAmount * 2,
IsIncrease = true, IsIncrease = true,
RefrenceId = transaction.Id RefrenceId = transaction.Id
}; };
@@ -99,9 +99,9 @@ public class VerifyPackagePurchaseCommandHandler
wallet.Balance wallet.Balance
); );
// شارژ DiscountBalance (موجودی تخفیف) // شارژ DiscountBalance (موجودی تخفیف) — دو برابر مبلغ سفارش
var oldDiscountBalance = wallet.DiscountBalance; var oldDiscountBalance = wallet.DiscountBalance;
wallet.DiscountBalance += order.Amount; wallet.DiscountBalance += order.Amount * 2;
_logger.LogInformation( _logger.LogInformation(
"Charging DiscountBalance for UserId {UserId}: {OldBalance} -> {NewBalance}", "Charging DiscountBalance for UserId {UserId}: {OldBalance} -> {NewBalance}",
@@ -132,7 +132,7 @@ public class VerifyPackagePurchaseCommandHandler
ChangeValue = order.Amount, ChangeValue = order.Amount,
CurrentNetworkBalance = wallet.NetworkBalance, CurrentNetworkBalance = wallet.NetworkBalance,
ChangeNerworkValue = 0, ChangeNerworkValue = 0,
CurrentDiscountBalance = wallet.DiscountBalance - order.Amount, // قبل از شارژ DiscountBalance CurrentDiscountBalance = wallet.DiscountBalance - (order.Amount * 2), // قبل از شارژ DiscountBalance
ChangeDiscountValue = 0, ChangeDiscountValue = 0,
IsIncrease = true, IsIncrease = true,
RefrenceId = transaction.Id RefrenceId = transaction.Id
@@ -148,7 +148,7 @@ public class VerifyPackagePurchaseCommandHandler
CurrentNetworkBalance = wallet.NetworkBalance, CurrentNetworkBalance = wallet.NetworkBalance,
ChangeNerworkValue = 0, ChangeNerworkValue = 0,
CurrentDiscountBalance = wallet.DiscountBalance, CurrentDiscountBalance = wallet.DiscountBalance,
ChangeDiscountValue = order.Amount, ChangeDiscountValue = order.Amount * 2,
IsIncrease = true, IsIncrease = true,
RefrenceId = transaction.Id RefrenceId = transaction.Id
}; };
@@ -1,3 +1,4 @@
using CMSMicroservice.Application.Common.FileManager;
using CMSMicroservice.Application.Common.Interfaces; using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities; using CMSMicroservice.Domain.Entities;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
@@ -7,64 +8,52 @@ namespace CMSMicroservice.Application.ProductsCQ.Commands.AddProductImage;
public class AddProductImageCommandHandler : IRequestHandler<AddProductImageCommand, AddProductImageResponseDto> public class AddProductImageCommandHandler : IRequestHandler<AddProductImageCommand, AddProductImageResponseDto>
{ {
private readonly IApplicationDbContext _context; private readonly IApplicationDbContext _context;
private readonly IFileManagementService _fileManagementService; private readonly IFileManager _fileManager;
private readonly ILogger<AddProductImageCommandHandler> _logger; private readonly ILogger<AddProductImageCommandHandler> _logger;
public AddProductImageCommandHandler( public AddProductImageCommandHandler(
IApplicationDbContext context, IApplicationDbContext context,
IFileManagementService fileManagementService, IFileManager fileManager,
ILogger<AddProductImageCommandHandler> logger) ILogger<AddProductImageCommandHandler> logger)
{ {
_context = context; _context = context;
_fileManagementService = fileManagementService; _fileManager = fileManager;
_logger = logger; _logger = logger;
} }
public async Task<AddProductImageResponseDto> Handle(AddProductImageCommand request, public async Task<AddProductImageResponseDto> Handle(AddProductImageCommand request,
CancellationToken cancellationToken) CancellationToken cancellationToken)
{ {
// Verify product exists // بررسی وجود محصول
var productExists = await _context.Products var productExists = await _context.Products
.AnyAsync(p => p.Id == request.ProductId, cancellationToken); .AnyAsync(p => p.Id == request.ProductId, cancellationToken);
if (!productExists) if (!productExists)
throw new NotFoundException(nameof(Product), request.ProductId); throw new NotFoundException(nameof(Product), request.ProductId);
string imagePath = string.Empty; // بدون فایل تصویر، کاری انجام نمی‌شود
string thumbnailPath = string.Empty; if (request.ImageFileBytes is not { Length: > 0 })
throw new FileUploadException("فایل تصویر ارسال نشده است");
// Upload image to FMS // آپلود تصویر به FMS (اگر خطا بخوره، exception پرتاب می‌شه و entity ذخیره نمیشه)
if (request.ImageFileBytes is { Length: > 0 }) var uploaded = await _fileManager.UploadImageAsync(
{ "Images/Products/Gallery",
try request.ImageFileBytes,
{ request.ImageFileMime ?? "image/jpeg",
var (mainPath, thumbPath) = await _fileManagementService.UploadImageWithThumbnailAsync( request.ImageFileName,
"Images/Products/Gallery", cancellationToken);
request.ImageFileBytes,
request.ImageFileMime ?? "image/jpeg",
request.ImageFileName,
cancellationToken);
imagePath = mainPath ?? string.Empty; // ساخت رکورد تصویر
thumbnailPath = thumbPath ?? string.Empty;
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to upload gallery image to FMS for product {ProductId}", request.ProductId);
}
}
// Create ProductImage entity
var productImage = new ProductImage var productImage = new ProductImage
{ {
Title = request.Title, Title = request.Title,
ImagePath = imagePath, ImagePath = uploaded.Main.Path,
ImageThumbnailPath = thumbnailPath ImageThumbnailPath = uploaded.Thumbnail.Path
}; };
await _context.ProductImages.AddAsync(productImage, cancellationToken); await _context.ProductImages.AddAsync(productImage, cancellationToken);
await _context.SaveChangesAsync(cancellationToken); await _context.SaveChangesAsync(cancellationToken);
// Create ProductGallery join entity // اتصال تصویر به محصول
var productGallery = new ProductGallery var productGallery = new ProductGallery
{ {
ProductId = request.ProductId, ProductId = request.ProductId,
@@ -1,5 +1,7 @@
using CMSMicroservice.Application.Common.FileManager;
using CMSMicroservice.Application.Common.Interfaces; using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities; using CMSMicroservice.Domain.Entities;
using CMSMicroservice.Domain.Enums;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
namespace CMSMicroservice.Application.ProductsCQ.Commands.CreateNewProducts; namespace CMSMicroservice.Application.ProductsCQ.Commands.CreateNewProducts;
@@ -7,16 +9,19 @@ namespace CMSMicroservice.Application.ProductsCQ.Commands.CreateNewProducts;
public class CreateNewProductsCommandHandler : IRequestHandler<CreateNewProductsCommand, CreateNewProductsResponseDto> public class CreateNewProductsCommandHandler : IRequestHandler<CreateNewProductsCommand, CreateNewProductsResponseDto>
{ {
private readonly IApplicationDbContext _context; private readonly IApplicationDbContext _context;
private readonly IFileManagementService _fileManagementService; private readonly IFileManager _fileManager;
private readonly IInventoryService _inventoryService;
private readonly ILogger<CreateNewProductsCommandHandler> _logger; private readonly ILogger<CreateNewProductsCommandHandler> _logger;
public CreateNewProductsCommandHandler( public CreateNewProductsCommandHandler(
IApplicationDbContext context, IApplicationDbContext context,
IFileManagementService fileManagementService, IFileManager fileManager,
IInventoryService inventoryService,
ILogger<CreateNewProductsCommandHandler> logger) ILogger<CreateNewProductsCommandHandler> logger)
{ {
_context = context; _context = context;
_fileManagementService = fileManagementService; _fileManager = fileManager;
_inventoryService = inventoryService;
_logger = logger; _logger = logger;
} }
@@ -32,61 +37,57 @@ public class CreateNewProductsCommandHandler : IRequestHandler<CreateNewProducts
Price = request.Price, Price = request.Price,
Discount = request.Discount, Discount = request.Discount,
Rate = request.Rate, Rate = request.Rate,
ImagePath = request.ImagePath ?? string.Empty, ImagePath = string.Empty,
ThumbnailPath = request.ThumbnailPath ?? string.Empty, ThumbnailPath = string.Empty,
SaleCount = request.SaleCount, SaleCount = request.SaleCount,
ViewCount = request.ViewCount, ViewCount = request.ViewCount,
RemainingCount = request.RemainingCount RemainingCount = request.RemainingCount
}; };
// Handle image upload to FMS if file bytes provided // آپلود تصویر اصلی (اگر ارسال شده باشد)
if (request.ImageFileBytes is { Length: > 0 }) if (request.ImageFileBytes is { Length: > 0 })
{ {
try var result = await _fileManager.UploadImageAsync(
{ "Images/Products",
var (mainPath, thumbPath) = await _fileManagementService.UploadImageWithThumbnailAsync( request.ImageFileBytes,
"Images/Products", request.ImageFileMime ?? "image/jpeg",
request.ImageFileBytes, request.ImageFileName,
request.ImageFileMime ?? "image/jpeg", cancellationToken);
request.ImageFileName,
cancellationToken);
if (!string.IsNullOrWhiteSpace(mainPath)) entity.ImagePath = result.Main.Path;
entity.ImagePath = mainPath; entity.ThumbnailPath = result.Thumbnail.Path;
if (!string.IsNullOrWhiteSpace(thumbPath))
entity.ThumbnailPath = thumbPath;
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to upload product image to FMS");
}
} }
// Handle separate thumbnail upload if provided (and not already set from main image) // آپلود بندانگشتی جداگانه (اختیاری — جایگزین بندانگشتی خودکار)
if (request.ThumbnailFileBytes is { Length: > 0 } && string.IsNullOrWhiteSpace(entity.ThumbnailPath)) if (request.ThumbnailFileBytes is { Length: > 0 })
{ {
try var thumbResult = await _fileManager.UploadAsync(
{ "Images/Products/Thumbnails",
var thumbPath = await _fileManagementService.UploadFileAsync( request.ThumbnailFileBytes,
"Images/Products/Thumbnails", request.ThumbnailFileMime ?? "image/jpeg",
request.ThumbnailFileBytes, request.ThumbnailFileName,
request.ThumbnailFileMime ?? "image/jpeg", cancellationToken);
request.ThumbnailFileName,
cancellationToken);
if (!string.IsNullOrWhiteSpace(thumbPath)) entity.ThumbnailPath = thumbResult.Path;
entity.ThumbnailPath = thumbPath;
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to upload product thumbnail to FMS");
}
} }
await _context.Products.AddAsync(entity, cancellationToken); await _context.Products.AddAsync(entity, cancellationToken);
await _context.SaveChangesAsync(cancellationToken); await _context.SaveChangesAsync(cancellationToken);
// ایجاد رکورد موجودی در سیستم انبارداری
try
{
await _inventoryService.InitializeInventoryAsync(
entity.Id,
ProductType.RegularProduct,
0, // موجودی اولیه صفر — باید از طریق Inventory اضافه شود
ct: cancellationToken);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Failed to initialize inventory for Product Id={ProductId}", entity.Id);
}
// Handle category assignments // Handle category assignments
if (request.CategoryIds is { Count: > 0 }) if (request.CategoryIds is { Count: > 0 })
{ {
@@ -1,3 +1,4 @@
using CMSMicroservice.Application.Common.FileManager;
using CMSMicroservice.Application.Common.Interfaces; using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities; using CMSMicroservice.Domain.Entities;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
@@ -7,16 +8,16 @@ namespace CMSMicroservice.Application.ProductsCQ.Commands.UpdateProducts;
public class UpdateProductsCommandHandler : IRequestHandler<UpdateProductsCommand, Unit> public class UpdateProductsCommandHandler : IRequestHandler<UpdateProductsCommand, Unit>
{ {
private readonly IApplicationDbContext _context; private readonly IApplicationDbContext _context;
private readonly IFileManagementService _fileManagementService; private readonly IFileManager _fileManager;
private readonly ILogger<UpdateProductsCommandHandler> _logger; private readonly ILogger<UpdateProductsCommandHandler> _logger;
public UpdateProductsCommandHandler( public UpdateProductsCommandHandler(
IApplicationDbContext context, IApplicationDbContext context,
IFileManagementService fileManagementService, IFileManager fileManager,
ILogger<UpdateProductsCommandHandler> logger) ILogger<UpdateProductsCommandHandler> logger)
{ {
_context = context; _context = context;
_fileManagementService = fileManagementService; _fileManager = fileManager;
_logger = logger; _logger = logger;
} }
@@ -38,57 +39,31 @@ public class UpdateProductsCommandHandler : IRequestHandler<UpdateProductsComman
entity.ViewCount = request.ViewCount; entity.ViewCount = request.ViewCount;
entity.RemainingCount = request.RemainingCount; entity.RemainingCount = request.RemainingCount;
// Handle image upload to FMS if new file bytes provided // آپلود تصویر اصلی جدید (اگر ارسال شده باشد)
if (request.ImageFileBytes is { Length: > 0 }) if (request.ImageFileBytes is { Length: > 0 })
{ {
try var result = await _fileManager.UploadImageAsync(
{ "Images/Products",
var (mainPath, thumbPath) = await _fileManagementService.UploadImageWithThumbnailAsync( request.ImageFileBytes,
"Images/Products", request.ImageFileMime ?? "image/jpeg",
request.ImageFileBytes, request.ImageFileName,
request.ImageFileMime ?? "image/jpeg", cancellationToken);
request.ImageFileName,
cancellationToken);
if (!string.IsNullOrWhiteSpace(mainPath)) entity.ImagePath = result.Main.Path;
entity.ImagePath = mainPath; entity.ThumbnailPath = result.Thumbnail.Path;
if (!string.IsNullOrWhiteSpace(thumbPath))
entity.ThumbnailPath = thumbPath;
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to upload updated product image to FMS for product {ProductId}", request.Id);
}
}
else
{
// If no new file uploaded, keep existing paths or update from request
if (!string.IsNullOrWhiteSpace(request.ImagePath))
entity.ImagePath = request.ImagePath;
if (!string.IsNullOrWhiteSpace(request.ThumbnailPath))
entity.ThumbnailPath = request.ThumbnailPath;
} }
// Handle separate thumbnail upload if provided // آپلود بندانگشتی جداگانه (اختیاری — جایگزین بندانگشتی خودکار)
if (request.ThumbnailFileBytes is { Length: > 0 }) if (request.ThumbnailFileBytes is { Length: > 0 })
{ {
try var thumbResult = await _fileManager.UploadAsync(
{ "Images/Products/Thumbnails",
var thumbPath = await _fileManagementService.UploadFileAsync( request.ThumbnailFileBytes,
"Images/Products/Thumbnails", request.ThumbnailFileMime ?? "image/jpeg",
request.ThumbnailFileBytes, request.ThumbnailFileName,
request.ThumbnailFileMime ?? "image/jpeg", cancellationToken);
request.ThumbnailFileName,
cancellationToken);
if (!string.IsNullOrWhiteSpace(thumbPath)) entity.ThumbnailPath = thumbResult.Path;
entity.ThumbnailPath = thumbPath;
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to upload updated product thumbnail to FMS for product {ProductId}", request.Id);
}
} }
_context.Products.Update(entity); _context.Products.Update(entity);
@@ -21,5 +21,6 @@ public class GetCustomerProductsByFilterQuery : IRequest<GetCustomerProductsByFi
public int? SaleCount { get; set; } public int? SaleCount { get; set; }
public int? ViewCount { get; set; } public int? ViewCount { get; set; }
public int? RemainingCount { get; set; } public int? RemainingCount { get; set; }
public bool? IsActive { get; set; }
public List<long>? CategoryIds { get; set; } public List<long>? CategoryIds { get; set; }
} }

Some files were not shown because too many files have changed in this diff Show More