PIAPS_CW/RestAPI/Controllers/PurchaseController.cs
2024-06-26 08:04:07 +04:00

153 lines
4.6 KiB
C#

using BusinessLogic.BusinessLogic;
using Contracts.BindingModels;
using Contracts.BusinessLogicContracts;
using Contracts.Exceptions;
using Contracts.SearchModels;
using Contracts.ViewModels;
using DatabaseImplement.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace RestAPI.Controllers
{
[Route("[controller]/[action]")]
[ApiController]
public class PurchaseController : Controller
{
private readonly ILogger _logger;
private readonly IPurchaseLogic _purchaseLogic;
public PurchaseController(ILogger<PurchaseController> logger, IPurchaseLogic purchaseLogic)
{
_logger = logger;
_purchaseLogic = purchaseLogic;
}
[HttpGet]
public List<PurchaseViewModel>? GetList(double? costfrom, double? costto, DateTime? datefrom, DateTime? dateto)
{
try
{
if (costfrom == null && costto == null && datefrom == null && dateto == null)
return _purchaseLogic.ReadElements(null);
else
return _purchaseLogic.ReadElements(new PurchaseSearchModel()
{
CostFrom = costfrom,
CostTo = costto,
DateFrom = datefrom,
DateTo = dateto
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения списка продуктов");
throw;
}
}
[HttpGet]
public PurchaseViewModel Get(Guid id)
{
try
{
return _purchaseLogic.ReadElement(new PurchaseSearchModel() { Id = id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения продукта");
throw;
}
}
[HttpPost]
public PurchaseViewModel Create(Guid UserId)
{
try
{
var purchase = _purchaseLogic.Create(new PurchaseBindingModel()
{
Cost = 0,
DatePurchase = DateTime.Now,
UserId = UserId
});
return new PurchaseViewModel()
{
DatePurchase = purchase.DatePurchase,
UserId = purchase.UserId,
Cost = purchase.Cost,
};
}
catch (Exception ex)
{
_logger.LogError(ex, "Error update purchase");
return null;
}
}
[HttpPatch]
public PurchaseViewModel Update([FromBody] PurchaseBindingModel model)
{
try
{
var res = _purchaseLogic.Update(model);
return new PurchaseViewModel()
{
Id = res.Id,
Cost = res.Cost,
DatePurchase = res.DatePurchase,
PurchaseProducts = res.PurchaseProducts,
UserId = res.UserId,
};
}
catch (Exception ex)
{
_logger.LogError(ex, "Error update purchase");
return null;
}
}
[HttpPatch]
public PurchaseViewModel AddProducts(Guid purchaseId, Guid productId, int count)
{
try
{
var purchase = _purchaseLogic.AddProduct(
new PurchaseSearchModel()
{
Id = purchaseId
},
new ProductSearchModel()
{
Id = productId
},
count);
return new PurchaseViewModel()
{
Id = purchase.Id,
Cost = purchase.Cost,
DatePurchase = purchase.DatePurchase,
PurchaseProducts = purchase.PurchaseProducts,
UserId = purchase.UserId,
};
}
catch (Exception ex)
{
_logger.LogError(ex, "Error update purchase");
return null;
}
}
[HttpGet]
public Dictionary<Guid, int> GetProducts(Guid productId)
{
return _purchaseLogic.GetProducts(new PurchaseSearchModel
{
Id = productId,
});
}
}
}