Files
BimAI/BimAI.API/Controllers/ProductsController.cs
Michał Zieliński 6d2c46d971
Some checks failed
Build Bimix / Build WebAPI and WebUI (push) Failing after 12s
App name refactor
2025-10-11 11:33:46 +02:00

71 lines
2.3 KiB
C#

using BimAI.Application.DTOModels;
using BimAI.Application.DTOModels.Common;
using BimAI.Infrastructure.Data;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace BimAI.API.Controllers;
[ApiController]
[Route("api/[controller]")]
public class ProductsController(BimAIDbContext context) : ControllerBase
{
private readonly BimAIDbContext _context = context;
[HttpGet]
public async Task<ActionResult<IEnumerable<ProductDto>>> GetProducts([FromQuery] ProductFilterRequest request)
{
var query = _context.Products.AsQueryable();
if (!string.IsNullOrWhiteSpace(request.Search))
{
var searchTerm = request.Search.ToLower();
query = query.Where(x =>
x.Name.ToLower().Contains(searchTerm) ||
(x.Code != null && x.Code.ToLower().Contains(searchTerm)) ||
(x.Ean != null && x.Ean.ToLower().Contains(searchTerm))
);
}
if (!string.IsNullOrWhiteSpace(request.Name))
{
query = query.Where(x => x.Name.ToLower().Contains(request.Name.ToLower()));
}
if (!string.IsNullOrWhiteSpace(request.Code))
{
query = query.Where(x => x.Code != null && x.Code.ToLower().Contains(request.Code.ToLower()));
}
if (!string.IsNullOrWhiteSpace(request.Ean))
{
query = query.Where(x => x.Ean != null && x.Ean.ToLower().Contains(request.Ean.ToLower()));
}
var totalCount = await query.CountAsync();
var items = await query
.OrderBy(x => x.Name)
.Skip((request.Page -1) * request.PageSize)
.Take(request.PageSize)
.Select(x => new ProductDto
{
Id = x.Id,
Name = x.Name,
Code = x.Code ?? string.Empty,
Ean = x.Ean ?? string.Empty,
StockAddresses = x.StockAddresses ?? string.Empty,
CreatedAt = x.CreatedAt,
UpdatedAt = x.UpdatedAt
})
.ToListAsync();
return Ok(new PagedResult<ProductDto>
{
Items = items,
TotalCount = totalCount,
Page = request.Page,
PageSize = request.PageSize,
});
}
}