круд - осталось удаление

This commit is contained in:
Владимир Данилов 2024-05-29 14:44:16 +04:00
parent 2d4eb46712
commit 9fab1534a5
9 changed files with 303 additions and 41 deletions

View File

@ -23,7 +23,6 @@ namespace VeterinaryClinicDatabaseImplement.Implements
.ThenInclude(x => x.Animal) .ThenInclude(x => x.Animal)
.Include(x => x.Services) .Include(x => x.Services)
.ThenInclude(x => x.Service) .ThenInclude(x => x.Service)
.ToList()
.Select(x => x.GetViewModel) .Select(x => x.GetViewModel)
.ToList(); .ToList();
} }
@ -31,20 +30,23 @@ namespace VeterinaryClinicDatabaseImplement.Implements
{ {
using var context = new VeterinaryClinicDatabase(); using var context = new VeterinaryClinicDatabase();
if (model.DateFrom.HasValue && model.DateTo.HasValue) var filtered = context.Visits
{
return context.Visits
.Include(x => x.User) .Include(x => x.User)
.Include(x => x.Animals) .Include(x => x.Animals)
.ThenInclude(x => x.Animal) .ThenInclude(x => x.Animal)
.Include(x => x.Services) .Include(x => x.Services)
.ThenInclude(x => x.Service) .ThenInclude (x => x.Service)
.Where(x => x.Date >= model.DateFrom && x.Date <= model.DateTo)
.Select(x => x.GetViewModel) .Select(x => x.GetViewModel)
.ToList(); .ToList();
if (model.UserId.HasValue)
{
filtered = filtered
.Where(x => x.UserId.Equals(model.UserId))
.ToList();
} }
return new(); return filtered ?? new();
} }
public VisitViewModel? GetElement(VisitSearchModel model) public VisitViewModel? GetElement(VisitSearchModel model)
@ -96,7 +98,7 @@ namespace VeterinaryClinicDatabaseImplement.Implements
visit.Update(model); visit.Update(model);
context.SaveChanges(); context.SaveChanges();
visit.UpdateAnimals(context, model); visit.UpdateAnimals(context, model);
visit.UpdateMedication(context, model); visit.UpdateServices(context, model);
transaction.Commit(); transaction.Commit();
return visit.GetViewModel; return visit.GetViewModel;
} }

View File

@ -94,11 +94,8 @@ namespace VeterinaryClinicDatabaseImplement.Models
public void UpdateMedications(VeterinaryClinicDatabase context, AnimalBindingModel model) public void UpdateMedications(VeterinaryClinicDatabase context, AnimalBindingModel model)
{ {
var animalMedications = context.AnimalMedications.Where(rec => rec.AnimalId == model.Id).ToList(); var animalMedications = context.AnimalMedications.Where(rec => rec.AnimalId == model.Id).ToList();
if (animalMedications != null && animalMedications.Count > 0) context.AnimalMedications.RemoveRange(animalMedications);
{ context.SaveChanges();
context.AnimalMedications.RemoveRange(animalMedications.Where(rec => !model.AnimalMedications.ContainsKey(rec.MedicationId)));
context.SaveChanges();
}
var animal = context.Animals.First(x => x.Id == Id); var animal = context.Animals.First(x => x.Id == Id);
foreach (var pr in model.AnimalMedications) foreach (var pr in model.AnimalMedications)

View File

@ -105,11 +105,8 @@ namespace VeterinaryClinicDatabaseImplement.Models
public void UpdateAnimals(VeterinaryClinicDatabase context, VisitBindingModel model) public void UpdateAnimals(VeterinaryClinicDatabase context, VisitBindingModel model)
{ {
var visitAnimals = context.VisitAnimals.Where(rec => rec.VisitId == model.Id).ToList(); var visitAnimals = context.VisitAnimals.Where(rec => rec.VisitId == model.Id).ToList();
if (visitAnimals != null && visitAnimals.Count > 0) context.VisitAnimals.RemoveRange(visitAnimals);
{ context.SaveChanges();
context.VisitAnimals.RemoveRange(visitAnimals.Where(rec => !model.VisitAnimals.ContainsKey(rec.AnimalId)));
context.SaveChanges();
}
var visit = context.Visits.First(x => x.Id == Id); var visit = context.Visits.First(x => x.Id == Id);
foreach (var rm in model.VisitAnimals) foreach (var rm in model.VisitAnimals)
@ -124,14 +121,11 @@ namespace VeterinaryClinicDatabaseImplement.Models
_visitAnimals = null; _visitAnimals = null;
} }
public void UpdateMedication(VeterinaryClinicDatabase context, VisitBindingModel model) public void UpdateServices(VeterinaryClinicDatabase context, VisitBindingModel model)
{ {
var visitServices = context.VisitServices.Where(rec => rec.VisitId == model.Id).ToList(); var visitServices = context.VisitServices.Where(rec => rec.VisitId == model.Id).ToList();
if (visitServices != null && visitServices.Count > 0) context.VisitServices.RemoveRange(visitServices);
{ context.SaveChanges();
context.VisitServices.RemoveRange(visitServices.Where(rec => !model.VisitServices.ContainsKey(rec.ServiceId)));
context.SaveChanges();
}
var visit = context.Visits.First(x => x.Id == Id); var visit = context.Visits.First(x => x.Id == Id);
foreach (var rm in model.VisitServices) foreach (var rm in model.VisitServices)

View File

@ -1,6 +1,11 @@
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using System.Diagnostics; using System.Diagnostics;
using VeterinaryClinicBusinessLogics.BusinessLogics;
using VeterinaryClinicContracts.BindingModels;
using VeterinaryClinicContracts.BusinessLogicsContracts;
using VeterinaryClinicContracts.SearchModels;
using VeterinaryClinicDataModels.Models;
using VeterinaryClinicWebApp.Models; using VeterinaryClinicWebApp.Models;
namespace VeterinaryClinicWebApp.Controllers namespace VeterinaryClinicWebApp.Controllers
@ -8,20 +13,156 @@ namespace VeterinaryClinicWebApp.Controllers
public class VisitController : Controller public class VisitController : Controller
{ {
private readonly ILogger<VisitController> _logger; private readonly ILogger<VisitController> _logger;
public VisitController(ILogger<VisitController> logger)
private readonly IVisitLogic _visitLogic;
private readonly IAnimalLogic _animalLogic;
private readonly IServiceLogic _serviceLogic;
public VisitController(ILogger<VisitController> logger, IVisitLogic visitLogic, IAnimalLogic animalLogic, IServiceLogic serviceLogic)
{ {
_logger = logger; _logger = logger;
_visitLogic = visitLogic;
_animalLogic = animalLogic;
_serviceLogic = serviceLogic;
} }
public IActionResult Visits() /// <summary>
/// Вывести список животных
/// </summary>
public IActionResult Visits()
{ {
return View(); if (APIClient.User == null)
} {
return Redirect("~/Home/Enter");
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] return View(_visitLogic.ReadList(new VisitSearchModel
public IActionResult Error() {
{ UserId = APIClient.User.Id,
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); }));
} }
}
/// <summary>
/// Создать животного
/// </summary>
[HttpGet]
public IActionResult CreateVisit()
{
if (APIClient.User == null)
{
return Redirect("~/Home/Enter");
}
ViewBag.Animals = _animalLogic.ReadList(new AnimalSearchModel
{
UserId = APIClient.User.Id,
});
ViewBag.Services = _serviceLogic.ReadList(null);
return View();
}
[HttpPost]
public void CreateVisit(DateTime dateVisit, List<int> animal, List<int> service)
{
if (APIClient.User == null)
{
throw new Exception("Необходимо авторизоваться!");
}
if (dateVisit == DateTime.MinValue || animal == null || service == null)
{
throw new Exception("Введены не все данные!");
}
Dictionary<int, IAnimalModel> visitAnimals = new Dictionary<int, IAnimalModel>();
foreach (var animalId in animal)
{
visitAnimals.Add(animalId, _animalLogic.ReadElement(new AnimalSearchModel { Id = animalId })!);
}
Dictionary<int, IServiceModel> visitServices = new Dictionary<int, IServiceModel>();
foreach (var serviceId in service)
{
visitServices.Add(serviceId, _serviceLogic.ReadElement(new ServiceSearchModel { Id = serviceId })!);
}
_visitLogic.Create(new VisitBindingModel
{
Date = dateVisit,
VisitAnimals = visitAnimals,
VisitServices = visitServices,
UserId = APIClient.User.Id
});
Response.Redirect("/Visit/Visits");
}
/// <summary>
/// Редактировать животного
/// </summary>
[HttpGet]
public IActionResult UpdateVisit(int id)
{
if (APIClient.User == null)
{
return Redirect("~/Home/Enter");
}
ViewBag.Animals = _animalLogic.ReadList(new AnimalSearchModel
{
UserId = APIClient.User.Id,
});
ViewBag.Services = _serviceLogic.ReadList(null);
return View(_visitLogic.ReadElement(new VisitSearchModel
{
Id = id
}));
}
[HttpPost]
public void UpdateVisit(int id, DateTime dateVisit, List<int> animal, List<int> service)
{
if (APIClient.User == null)
{
throw new Exception("Необходимо авторизоваться!");
}
if (dateVisit == DateTime.MinValue || animal == null || service == null)
{
throw new Exception("Введены не все данные!");
}
Dictionary<int, IAnimalModel> visitAnimals = new Dictionary<int, IAnimalModel>();
foreach (var animalId in animal)
{
visitAnimals.Add(animalId, _animalLogic.ReadElement(new AnimalSearchModel { Id = animalId })!);
}
Dictionary<int, IServiceModel> visitServices = new Dictionary<int, IServiceModel>();
foreach (var serviceId in service)
{
visitServices.Add(serviceId, _serviceLogic.ReadElement(new ServiceSearchModel { Id = serviceId })!);
}
_visitLogic.Update(new VisitBindingModel
{
Id = id,
Date = dateVisit,
VisitAnimals = visitAnimals,
VisitServices = visitServices,
UserId = APIClient.User.Id
});
Response.Redirect("/Visit/Visits");
}
/// <summary>
/// Удалить животного
/// </summary>
}
} }

View File

@ -28,7 +28,7 @@
<div class="row"> <div class="row">
<div class="col-4">Медикаменты:</div> <div class="col-4">Медикаменты:</div>
<div class="col-8"> <div class="col-8">
<select name="medications" id="medications" class="form-control" size="4" multiple> <select name="medication" id="medication" class="form-control" size="4" multiple>
@foreach (var medication in ViewBag.Medications) @foreach (var medication in ViewBag.Medications)
{ {
<option value="@medication.Id">@medication.Name</option> <option value="@medication.Id">@medication.Name</option>

View File

@ -34,7 +34,7 @@
<div class="row"> <div class="row">
<div class="col-4">Медикаменты:</div> <div class="col-4">Медикаменты:</div>
<div class="col-8"> <div class="col-8">
<select name="medications" id="medications" class="form-control" multiple> <select name="medication" id="medication" class="form-control" multiple>
@foreach (var medication in ViewBag.Medications) @foreach (var medication in ViewBag.Medications)
{ {
var isSelected = Model.AnimalMedications.Any(x => x.Key.Equals(medication.Id)); var isSelected = Model.AnimalMedications.Any(x => x.Key.Equals(medication.Id));

View File

@ -0,0 +1,47 @@
@{
ViewData["Title"] = "Создание визита";
}
<div class="text-center">
<h2 class="display-4">Создание визита</h2>
</div>
<form method="post" style="margin-top: 50px">
<!-- Дата визита -->
<div class="row">
<div class="col-4">Дата визита:</div>
<div class="col-8"><input type="datetime-local" class="form-control" name="dateVisit" id="dateVisit" /></div>
</div>
<!-- Животные -->
<div class="row">
<div class="col-4">Животные:</div>
<div class="col-8">
<select name="animal" id="animal" class="form-control" size="4" multiple>
@foreach (var animal in ViewBag.Animals)
{
<option value="@animal.Id">@animal.Breed</option>
}
</select>
</div>
</div>
<!-- Услуги -->
<div class="row">
<div class="col-4">Услуги:</div>
<div class="col-8">
<select name="service" id="service" class="form-control" size="4" multiple>
@foreach (var service in ViewBag.Services)
{
<option value="@service.Id">@service.Name - @service.Cost</option>
}
</select>
</div>
</div>
<!-- Кнопка "Создать" -->
<div class="row">
<div class="col-8"></div>
<div class="col-4"><input type="submit" value="Создать" class="btn btn-primary" /></div>
</div>
</form>

View File

@ -0,0 +1,54 @@

@using VeterinaryClinicContracts.ViewModels
@model VisitViewModel
@{
ViewData["Title"] = "Редактирование визита";
}
<div class="text-center">
<h2 class="display-4">Редактирование визита</h2>
</div>
<form method="post" style="margin-top: 50px">
<!-- Дата визита -->
<div class="row">
<div class="col-4">Дата визита:</div>
<div class="col-8"><input type="datetime-local" class="form-control" name="dateVisit" value="@Model.Date.ToString("yyyy-MM-ddTHH:mm")" /></div>
</div>
<!-- Животные -->
<div class="row">
<div class="col-4">Животные:</div>
<div class="col-8">
<select name="animal" id="animal" class="form-control" size="4" multiple>
@foreach (var animal in ViewBag.Animals)
{
var isSelected = Model.VisitAnimals.Any(x => x.Key.Equals(animal.Id));
<option value="@animal.Id" selected="@isSelected">@animal.Breed</option>
}
</select>
</div>
</div>
<!-- Услуги -->
<div class="row">
<div class="col-4">Услуги:</div>
<div class="col-8">
<select name="service" id="service" class="form-control" size="4" multiple>
@foreach (var service in ViewBag.Services)
{
var isSelected = Model.VisitServices.Any(x => x.Key.Equals(service.Id));
<option value="@service.Id" selected="@isSelected">@service.Name - @service.Cost</option>
}
</select>
</div>
</div>
<!-- Кнопка "Сохранить" -->
<div class="row">
<div class="col-8"></div>
<div class="col-4"><input type="submit" value="Сохранить" class="btn btn-primary" /></div>
</div>
</form>

View File

@ -30,6 +30,7 @@
<th>Пользователь</th> <th>Пользователь</th>
<th>Животные</th> <th>Животные</th>
<th>Услуги</th> <th>Услуги</th>
<th>Действия</th>
</tr> </tr>
</thead> </thead>
@ -38,14 +39,40 @@
{ {
<tr> <tr>
<td>@Html.DisplayFor(modelItem => visit.Id)</td> <td>@Html.DisplayFor(modelItem => visit.Id)</td>
<td>@Html.DisplayFor(modelItem => visit.Date.ToShortDateString())</td> <td>@Html.DisplayFor(modelItem => visit.Date)</td>
<td>@Html.DisplayFor(modelItem => visit.UserFullName)</td> <td>@Html.DisplayFor(modelItem => visit.UserFullName)</td>
<td>@Html.DisplayFor(modelItem => visit.VisitAnimals)</td> <td>
<td>@Html.DisplayFor(modelItem => visit.VisitServices)</td> @if (visit.VisitAnimals.Any())
{
<ul>
@foreach (var animal in visit.VisitAnimals)
{
<li>@animal.Value.Breed</li>
}
</ul>
}
else
{
<p>Нет назначенных лекарств</p>
}
</td>
<td>
@if (visit.VisitServices.Any())
{
<ul>
@foreach (var service in visit.VisitServices)
{
<li>@service.Value.Name - @service.Value.Cost</li>
}
</ul>
}
else
{
<p>Нет назначенных лекарств</p>
}
</td>
<td> <td>
<p><button type="button" class="btn btn-primary" onclick="location.href='@Url.Action("UpdateVisit", "/Visit", new { id = visit.Id })'">Изменить</button></p> <p><button type="button" class="btn btn-primary" onclick="location.href='@Url.Action("UpdateVisit", "/Visit", new { id = visit.Id })'">Изменить</button></p>
</td>
<td>
<p><button type="button" class="btn btn-primary" onclick="deleteVisit(@visit.Id)">Удалить</button></p> <p><button type="button" class="btn btn-primary" onclick="deleteVisit(@visit.Id)">Удалить</button></p>
</td> </td>
</tr> </tr>