PIbd-21_CourseWork_Polyclin.../Polyclinic/PolyclinicDatabaseImplement/Implements/ProcedureStorage.cs

104 lines
3.5 KiB
C#

using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using PolyclinicContracts.BindingModels;
using PolyclinicContracts.SearchModels;
using PolyclinicContracts.StoragesContracts;
using PolyclinicContracts.ViewModels;
using PolyclinicDatabaseImplement.Models;
using SecuritySystemDatabaseImplement;
namespace PolyclinicDatabaseImplement.Implements
{
public class ProcedureStorage : IProcedureStorage
{
public List<ProcedureViewModel> GetFullList()
{
using var database = new PolyclinicDatabase();
return database.Procedures
.Include(p => p.User)
.Select(x => x.GetViewModel)
.ToList();
}
public List<ProcedureViewModel> GetFilteredList(ProcedureSearchModel model)
{
var elements = GetFullList();
if (model.Id != null)
{
elements = elements.Where(x => x.Id == model.Id.Value).ToList();
}
if (model.UserId != null)
{
elements = elements.Where(x => x.UserId == model.UserId.Value).ToList();
}
if (!model.Name.IsNullOrEmpty())
{
elements = elements.Where(x => x.Name == model.Name).ToList();
}
if (model.From != null)
{
elements = elements.Where(x => x.DateStartProcedure >= model.From.Value).ToList();
}
if (model.To != null)
{
elements = elements.Where(x => x.DateStartProcedure <= model.To.Value).ToList();
var elemWithDateStop = elements
.Where(x => x.DateStopProcedure != null)
.Where(x => x.DateStopProcedure <= model.To.Value)
.ToList();
var elemWithoutDateStop = elements.Where(x => x.DateStopProcedure == null).ToList();
elemWithDateStop.AddRange(elemWithoutDateStop);
elements = elemWithDateStop;
}
return elements;
}
public ProcedureViewModel? GetElement(ProcedureSearchModel model)
{
return GetFilteredList(model).FirstOrDefault();
}
public ProcedureViewModel? Insert(ProcedureBindingModel model)
{
using var database = new PolyclinicDatabase();
var newProcedure = Procedure.Create(model);
if (newProcedure == null)
{
return null;
}
database.Procedures.Add(newProcedure);
database.SaveChanges();
return newProcedure.GetViewModel;
}
public ProcedureViewModel? Update(ProcedureBindingModel model)
{
using var database = new PolyclinicDatabase();
var procedure = database.Procedures.FirstOrDefault(x => x.Id == model.Id);
if (procedure == null)
{
return null;
}
procedure.Update(model);
database.SaveChanges();
return procedure.GetViewModel;
}
public ProcedureViewModel? Delete(ProcedureBindingModel model)
{
using var database = new PolyclinicDatabase();
var element = database.Procedures
.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
database.Procedures.Remove(element);
database.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}