using CMSMicroservice.Protobuf.Protos.Inventory; using Google.Protobuf.WellKnownTypes; namespace BackOffice.BFF.Application.InventoryCQ.Queries.GetStockMovements; public class GetStockMovementsQueryHandler : IRequestHandler { private readonly IApplicationContractContext _context; public GetStockMovementsQueryHandler(IApplicationContractContext context) { _context = context; } public async Task Handle(GetStockMovementsQuery request, CancellationToken cancellationToken) { var protoRequest = new GetStockMovementsRequest { Page = request.PageIndex, PageSize = request.PageSize }; if (request.InventoryItemId.HasValue) protoRequest.InventoryItemId = request.InventoryItemId.Value; if (request.ProductId.HasValue) protoRequest.ProductId = request.ProductId.Value; if (request.ProductType.HasValue) protoRequest.ProductType = (ProductType)request.ProductType.Value; if (request.MovementType.HasValue) protoRequest.MovementType = (StockMovementType)request.MovementType.Value; if (request.FromDate.HasValue) protoRequest.FromDate = Timestamp.FromDateTime(request.FromDate.Value.ToUniversalTime()); if (request.ToDate.HasValue) protoRequest.ToDate = Timestamp.FromDateTime(request.ToDate.Value.ToUniversalTime()); var response = await _context.Inventory.GetStockMovementsAsync(protoRequest, cancellationToken: cancellationToken); return new GetStockMovementsResponseDto { TotalCount = response.TotalCount, MetaData = new MetaData { TotalCount = response.TotalCount, PageSize = request.PageSize, CurrentPage = request.PageIndex, TotalPage = (int)Math.Ceiling((double)response.TotalCount / request.PageSize) }, Movements = response.Movements.Select(m => new StockMovementDto { Id = m.Id, InventoryItemId = m.InventoryItemId, ProductName = m.ProductTitle, MovementType = (int)m.MovementType, MovementTypeName = GetMovementTypeName(m.MovementType), Quantity = m.Quantity, QuantityBefore = m.QuantityBefore, QuantityAfter = m.QuantityAfter, OrderId = m.OrderId, DiscountOrderId = m.DiscountOrderId, ReferenceNumber = string.IsNullOrEmpty(m.ReferenceNumber) ? null : m.ReferenceNumber, Note = string.IsNullOrEmpty(m.Note) ? null : m.Note, PerformedByUserId = m.PerformedByUserId, PerformedByUserName = null, CreatedAt = m.Created?.ToDateTime() ?? DateTime.MinValue }).ToList() }; } private static string GetMovementTypeName(StockMovementType type) => type switch { StockMovementType.InitialStock => "موجودی اولیه", StockMovementType.Restock => "ورود کالا", StockMovementType.Return => "برگشت از مشتری", StockMovementType.Sale => "فروش", StockMovementType.AdjustmentIncrease => "تعدیل افزایشی", StockMovementType.AdjustmentDecrease => "تعدیل کاهشی", StockMovementType.Reserved => "رزرو", StockMovementType.Released => "آزادسازی رزرو", StockMovementType.Loss => "مفقودی", StockMovementType.Damaged => "ضایعات", StockMovementType.Expired => "منقضی", StockMovementType.TransferOut => "انتقال به انبار", StockMovementType.TransferIn => "انتقال از انبار", _ => "نامشخص" }; }