Add validators and services for Product Galleries and Product Tags

- Implemented Create, Delete, Get, and Update validators for Product Galleries.
- Added Create, Delete, Get, and Update validators for Product Tags.
- Created service classes for handling Discount Categories, Discount Orders, Discount Products, Discount Shopping Cart, Product Categories, Product Galleries, and Product Tags.
- Each service class integrates with CQRS for command and query handling.
- Established mapping profiles for Product Galleries.
This commit is contained in:
masoodafar-web
2025-12-04 02:40:49 +03:30
parent 40d54d08fc
commit f0f48118e7
436 changed files with 33159 additions and 2005 deletions
@@ -0,0 +1,19 @@
using MediatR;
namespace CMSMicroservice.Application.ManualPaymentCQ.Commands.ApproveManualPayment;
/// <summary>
/// دستور تایید پرداخت دستی توسط SuperAdmin
/// </summary>
public class ApproveManualPaymentCommand : IRequest<bool>
{
/// <summary>
/// شناسه ManualPayment
/// </summary>
public long ManualPaymentId { get; set; }
/// <summary>
/// یادداشت تایید (اختیاری)
/// </summary>
public string? ApprovalNote { get; set; }
}
@@ -0,0 +1,261 @@
using CMSMicroservice.Application.Common.Exceptions;
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities;
using CMSMicroservice.Domain.Entities.Payment;
using CMSMicroservice.Domain.Enums;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace CMSMicroservice.Application.ManualPaymentCQ.Commands.ApproveManualPayment;
public class ApproveManualPaymentCommandHandler : IRequestHandler<ApproveManualPaymentCommand, bool>
{
private readonly IApplicationDbContext _context;
private readonly ICurrentUserService _currentUser;
private readonly ILogger<ApproveManualPaymentCommandHandler> _logger;
public ApproveManualPaymentCommandHandler(
IApplicationDbContext context,
ICurrentUserService currentUser,
ILogger<ApproveManualPaymentCommandHandler> logger)
{
_context = context;
_currentUser = currentUser;
_logger = logger;
}
public async Task<bool> Handle(
ApproveManualPaymentCommand request,
CancellationToken cancellationToken)
{
try
{
_logger.LogInformation(
"Approving manual payment: {ManualPaymentId}",
request.ManualPaymentId
);
// 1. پیدا کردن ManualPayment
var manualPayment = await _context.ManualPayments
.Include(m => m.User)
.FirstOrDefaultAsync(m => m.Id == request.ManualPaymentId, cancellationToken);
if (manualPayment == null)
{
_logger.LogWarning("ManualPayment not found: {Id}", request.ManualPaymentId);
throw new NotFoundException(nameof(ManualPayment), request.ManualPaymentId);
}
// 2. بررسی وضعیت
if (manualPayment.Status != ManualPaymentStatus.Pending)
{
_logger.LogWarning(
"ManualPayment {Id} is not in Pending status: {Status}",
request.ManualPaymentId,
manualPayment.Status
);
throw new BadRequestException($"فقط درخواست‌های در وضعیت Pending قابل تایید هستند. وضعیت فعلی: {manualPayment.Status}");
}
// 3. بررسی SuperAdmin
var currentUserId = _currentUser.UserId;
if (string.IsNullOrEmpty(currentUserId))
{
throw new UnauthorizedAccessException("کاربر احراز هویت نشده است");
}
if (!long.TryParse(currentUserId, out var approvedById))
{
throw new UnauthorizedAccessException("شناسه کاربر نامعتبر است");
}
// 4. پیدا کردن Wallet کاربر
var wallet = await _context.UserWallets
.FirstOrDefaultAsync(w => w.UserId == manualPayment.UserId, cancellationToken);
if (wallet == null)
{
_logger.LogError("Wallet not found for UserId: {UserId}", manualPayment.UserId);
throw new NotFoundException($"کیف پول کاربر {manualPayment.UserId} یافت نشد");
}
// 5. ایجاد Transaction
var transaction = new Transaction
{
Amount = manualPayment.Amount,
Description = $"پرداخت دستی - {manualPayment.Type} - {manualPayment.Description}",
PaymentStatus = PaymentStatus.Success,
PaymentDate = DateTime.UtcNow,
RefId = manualPayment.ReferenceNumber,
Type = MapToTransactionType(manualPayment.Type)
};
_context.Transactions.Add(transaction);
await _context.SaveChangesAsync(cancellationToken);
// 6. اعمال تغییرات بر کیف پول
var oldBalance = wallet.Balance;
var oldDiscountBalance = wallet.DiscountBalance;
var oldNetworkBalance = wallet.NetworkBalance;
switch (manualPayment.Type)
{
case ManualPaymentType.CashDeposit:
case ManualPaymentType.Settlement:
case ManualPaymentType.ErrorCorrection:
wallet.Balance += manualPayment.Amount;
wallet.DiscountBalance += manualPayment.Amount;
// لاگ Balance
await _context.UserWalletChangeLogs.AddAsync(new UserWalletChangeLog
{
WalletId = wallet.Id,
CurrentBalance = wallet.Balance,
ChangeValue = manualPayment.Amount,
CurrentNetworkBalance = wallet.NetworkBalance,
ChangeNerworkValue = 0,
CurrentDiscountBalance = oldDiscountBalance,
ChangeDiscountValue = 0,
IsIncrease = true,
RefrenceId = transaction.Id
}, cancellationToken);
// لاگ DiscountBalance
await _context.UserWalletChangeLogs.AddAsync(new UserWalletChangeLog
{
WalletId = wallet.Id,
CurrentBalance = wallet.Balance,
ChangeValue = 0,
CurrentNetworkBalance = wallet.NetworkBalance,
ChangeNerworkValue = 0,
CurrentDiscountBalance = wallet.DiscountBalance,
ChangeDiscountValue = manualPayment.Amount,
IsIncrease = true,
RefrenceId = transaction.Id
}, cancellationToken);
break;
case ManualPaymentType.DiscountWalletCharge:
wallet.DiscountBalance += manualPayment.Amount;
await _context.UserWalletChangeLogs.AddAsync(new UserWalletChangeLog
{
WalletId = wallet.Id,
CurrentBalance = wallet.Balance,
ChangeValue = 0,
CurrentNetworkBalance = wallet.NetworkBalance,
ChangeNerworkValue = 0,
CurrentDiscountBalance = wallet.DiscountBalance,
ChangeDiscountValue = manualPayment.Amount,
IsIncrease = true,
RefrenceId = transaction.Id
}, cancellationToken);
break;
case ManualPaymentType.NetworkWalletCharge:
wallet.NetworkBalance += manualPayment.Amount;
await _context.UserWalletChangeLogs.AddAsync(new UserWalletChangeLog
{
WalletId = wallet.Id,
CurrentBalance = wallet.Balance,
ChangeValue = 0,
CurrentNetworkBalance = wallet.NetworkBalance,
ChangeNerworkValue = manualPayment.Amount,
CurrentDiscountBalance = wallet.DiscountBalance,
ChangeDiscountValue = 0,
IsIncrease = true,
RefrenceId = transaction.Id
}, cancellationToken);
break;
case ManualPaymentType.Refund:
// بازگشت وجه - کم کردن از Balance و DiscountBalance
if (wallet.Balance < manualPayment.Amount)
{
throw new BadRequestException("موجودی کیف پول برای بازگشت وجه کافی نیست");
}
wallet.Balance -= manualPayment.Amount;
if (wallet.DiscountBalance >= manualPayment.Amount)
{
wallet.DiscountBalance -= manualPayment.Amount;
}
await _context.UserWalletChangeLogs.AddAsync(new UserWalletChangeLog
{
WalletId = wallet.Id,
CurrentBalance = wallet.Balance,
ChangeValue = manualPayment.Amount,
CurrentNetworkBalance = wallet.NetworkBalance,
ChangeNerworkValue = 0,
CurrentDiscountBalance = wallet.DiscountBalance,
ChangeDiscountValue = wallet.DiscountBalance < oldDiscountBalance ? manualPayment.Amount : 0,
IsIncrease = false,
RefrenceId = transaction.Id
}, cancellationToken);
break;
default:
// Other یا سایر موارد - فقط Balance
wallet.Balance += manualPayment.Amount;
await _context.UserWalletChangeLogs.AddAsync(new UserWalletChangeLog
{
WalletId = wallet.Id,
CurrentBalance = wallet.Balance,
ChangeValue = manualPayment.Amount,
CurrentNetworkBalance = wallet.NetworkBalance,
ChangeNerworkValue = 0,
CurrentDiscountBalance = wallet.DiscountBalance,
ChangeDiscountValue = 0,
IsIncrease = true,
RefrenceId = transaction.Id
}, cancellationToken);
break;
}
// 7. به‌روزرسانی ManualPayment
manualPayment.Status = ManualPaymentStatus.Approved;
manualPayment.ApprovedBy = approvedById;
manualPayment.ApprovedAt = DateTime.UtcNow;
manualPayment.TransactionId = transaction.Id;
await _context.SaveChangesAsync(cancellationToken);
_logger.LogInformation(
"Manual payment approved successfully. Id: {Id}, UserId: {UserId}, Amount: {Amount}, ApprovedBy: {ApprovedBy}",
manualPayment.Id,
manualPayment.UserId,
manualPayment.Amount,
approvedById
);
return true;
}
catch (Exception ex)
{
_logger.LogError(
ex,
"Error approving manual payment: {ManualPaymentId}",
request.ManualPaymentId
);
throw;
}
}
private TransactionType MapToTransactionType(ManualPaymentType type)
{
return type switch
{
ManualPaymentType.CashDeposit => TransactionType.DepositExternal1,
ManualPaymentType.DiscountWalletCharge => TransactionType.DiscountWalletCharge,
ManualPaymentType.NetworkWalletCharge => TransactionType.NetworkCommission,
ManualPaymentType.Settlement => TransactionType.DepositExternal1,
ManualPaymentType.ErrorCorrection => TransactionType.DepositExternal1,
ManualPaymentType.Refund => TransactionType.Withdraw,
_ => TransactionType.DepositExternal1
};
}
}
@@ -0,0 +1,35 @@
using CMSMicroservice.Domain.Enums;
using MediatR;
namespace CMSMicroservice.Application.ManualPaymentCQ.Commands.CreateManualPayment;
/// <summary>
/// دستور ثبت پرداخت دستی توسط Admin
/// </summary>
public class CreateManualPaymentCommand : IRequest<long>
{
/// <summary>
/// شناسه کاربری که پرداخت برای او ثبت می‌شود
/// </summary>
public long UserId { get; set; }
/// <summary>
/// مبلغ تراکنش (ریال)
/// </summary>
public long Amount { get; set; }
/// <summary>
/// نوع تراکنش دستی
/// </summary>
public ManualPaymentType Type { get; set; }
/// <summary>
/// توضیحات (اجباری)
/// </summary>
public string Description { get; set; } = string.Empty;
/// <summary>
/// شماره مرجع یا شماره فیش (اختیاری)
/// </summary>
public string? ReferenceNumber { get; set; }
}
@@ -0,0 +1,97 @@
using CMSMicroservice.Application.Common.Exceptions;
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities;
using CMSMicroservice.Domain.Entities.Payment;
using CMSMicroservice.Domain.Enums;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace CMSMicroservice.Application.ManualPaymentCQ.Commands.CreateManualPayment;
public class CreateManualPaymentCommandHandler : IRequestHandler<CreateManualPaymentCommand, long>
{
private readonly IApplicationDbContext _context;
private readonly ICurrentUserService _currentUser;
private readonly ILogger<CreateManualPaymentCommandHandler> _logger;
public CreateManualPaymentCommandHandler(
IApplicationDbContext context,
ICurrentUserService currentUser,
ILogger<CreateManualPaymentCommandHandler> logger)
{
_context = context;
_currentUser = currentUser;
_logger = logger;
}
public async Task<long> Handle(
CreateManualPaymentCommand request,
CancellationToken cancellationToken)
{
try
{
_logger.LogInformation(
"Creating manual payment for UserId: {UserId}, Amount: {Amount}, Type: {Type}",
request.UserId,
request.Amount,
request.Type
);
// 1. بررسی وجود کاربر
var user = await _context.Users
.FirstOrDefaultAsync(u => u.Id == request.UserId, cancellationToken);
if (user == null)
{
_logger.LogWarning("User not found: {UserId}", request.UserId);
throw new NotFoundException(nameof(User), request.UserId);
}
// 2. بررسی Admin فعلی
var currentUserId = _currentUser.UserId;
if (string.IsNullOrEmpty(currentUserId))
{
throw new UnauthorizedAccessException("کاربر احراز هویت نشده است");
}
if (!long.TryParse(currentUserId, out var requestedById))
{
throw new UnauthorizedAccessException("شناسه کاربر نامعتبر است");
}
// 3. ایجاد ManualPayment
var manualPayment = new ManualPayment
{
UserId = request.UserId,
Amount = request.Amount,
Type = request.Type,
Description = request.Description,
ReferenceNumber = request.ReferenceNumber,
Status = ManualPaymentStatus.Pending,
RequestedBy = requestedById
};
_context.ManualPayments.Add(manualPayment);
await _context.SaveChangesAsync(cancellationToken);
_logger.LogInformation(
"Manual payment created successfully. Id: {Id}, UserId: {UserId}, RequestedBy: {RequestedBy}",
manualPayment.Id,
request.UserId,
requestedById
);
return manualPayment.Id;
}
catch (Exception ex)
{
_logger.LogError(
ex,
"Error creating manual payment for UserId: {UserId}",
request.UserId
);
throw;
}
}
}
@@ -0,0 +1,34 @@
using FluentValidation;
namespace CMSMicroservice.Application.ManualPaymentCQ.Commands.CreateManualPayment;
public class CreateManualPaymentCommandValidator : AbstractValidator<CreateManualPaymentCommand>
{
public CreateManualPaymentCommandValidator()
{
RuleFor(x => x.UserId)
.GreaterThan(0)
.WithMessage("شناسه کاربر باید بزرگتر از صفر باشد");
RuleFor(x => x.Amount)
.GreaterThan(0)
.WithMessage("مبلغ باید بزرگتر از صفر باشد")
.LessThanOrEqualTo(1_000_000_000)
.WithMessage("مبلغ نمی‌تواند بیشتر از 1 میلیارد ریال باشد");
RuleFor(x => x.Type)
.IsInEnum()
.WithMessage("نوع تراکنش نامعتبر است");
RuleFor(x => x.Description)
.NotEmpty()
.WithMessage("توضیحات الزامی است")
.MaximumLength(1000)
.WithMessage("توضیحات نمی‌تواند بیشتر از 1000 کاراکتر باشد");
RuleFor(x => x.ReferenceNumber)
.MaximumLength(100)
.WithMessage("شماره مرجع نمی‌تواند بیشتر از 100 کاراکتر باشد")
.When(x => !string.IsNullOrEmpty(x.ReferenceNumber));
}
}
@@ -0,0 +1,19 @@
using MediatR;
namespace CMSMicroservice.Application.ManualPaymentCQ.Commands.RejectManualPayment;
/// <summary>
/// دستور رد پرداخت دستی توسط SuperAdmin
/// </summary>
public class RejectManualPaymentCommand : IRequest<bool>
{
/// <summary>
/// شناسه ManualPayment
/// </summary>
public long ManualPaymentId { get; set; }
/// <summary>
/// دلیل رد (الزامی)
/// </summary>
public string RejectionReason { get; set; } = string.Empty;
}
@@ -0,0 +1,98 @@
using CMSMicroservice.Application.Common.Exceptions;
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities.Payment;
using CMSMicroservice.Domain.Enums;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace CMSMicroservice.Application.ManualPaymentCQ.Commands.RejectManualPayment;
public class RejectManualPaymentCommandHandler : IRequestHandler<RejectManualPaymentCommand, bool>
{
private readonly IApplicationDbContext _context;
private readonly ICurrentUserService _currentUser;
private readonly ILogger<RejectManualPaymentCommandHandler> _logger;
public RejectManualPaymentCommandHandler(
IApplicationDbContext context,
ICurrentUserService currentUser,
ILogger<RejectManualPaymentCommandHandler> logger)
{
_context = context;
_currentUser = currentUser;
_logger = logger;
}
public async Task<bool> Handle(
RejectManualPaymentCommand request,
CancellationToken cancellationToken)
{
try
{
_logger.LogInformation(
"Rejecting manual payment: {ManualPaymentId}",
request.ManualPaymentId
);
// 1. پیدا کردن ManualPayment
var manualPayment = await _context.ManualPayments
.FirstOrDefaultAsync(m => m.Id == request.ManualPaymentId, cancellationToken);
if (manualPayment == null)
{
_logger.LogWarning("ManualPayment not found: {Id}", request.ManualPaymentId);
throw new NotFoundException(nameof(ManualPayment), request.ManualPaymentId);
}
// 2. بررسی وضعیت
if (manualPayment.Status != ManualPaymentStatus.Pending)
{
_logger.LogWarning(
"ManualPayment {Id} is not in Pending status: {Status}",
request.ManualPaymentId,
manualPayment.Status
);
throw new BadRequestException($"فقط درخواست‌های در وضعیت Pending قابل رد هستند. وضعیت فعلی: {manualPayment.Status}");
}
// 3. بررسی SuperAdmin
var currentUserId = _currentUser.UserId;
if (string.IsNullOrEmpty(currentUserId))
{
throw new UnauthorizedAccessException("کاربر احراز هویت نشده است");
}
if (!long.TryParse(currentUserId, out var rejectedById))
{
throw new UnauthorizedAccessException("شناسه کاربر نامعتبر است");
}
// 4. رد درخواست
manualPayment.Status = ManualPaymentStatus.Rejected;
manualPayment.ApprovedBy = rejectedById;
manualPayment.ApprovedAt = DateTime.UtcNow;
manualPayment.RejectionReason = request.RejectionReason;
await _context.SaveChangesAsync(cancellationToken);
_logger.LogInformation(
"Manual payment rejected successfully. Id: {Id}, RejectedBy: {RejectedBy}, Reason: {Reason}",
manualPayment.Id,
rejectedById,
request.RejectionReason
);
return true;
}
catch (Exception ex)
{
_logger.LogError(
ex,
"Error rejecting manual payment: {ManualPaymentId}",
request.ManualPaymentId
);
throw;
}
}
}