CRUD для комментариев готов

This commit is contained in:
Николай 2023-05-16 14:38:49 +04:00 committed by dasha
parent 7ee3f34450
commit a3bd2346ca
7 changed files with 302 additions and 35 deletions

View File

@ -56,7 +56,6 @@ namespace HardwareShopDatabaseImplement.Implements.Worker
return context.Builds
.Include(x => x.Purchases)
.ThenInclude(x => x.Purchase)
.Where(x => x.Id == model.Id)
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.BuildName) && x.BuildName == model.BuildName) ||
(model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
@ -75,7 +74,6 @@ namespace HardwareShopDatabaseImplement.Implements.Worker
return context.Builds
.Include(x => x.Purchases)
.ThenInclude(x => x.Purchase)
.Where(x => x.UserId == model.Id)
.FirstOrDefault(x => x.Id == newBuild.Id)
?.GetViewModel;
}
@ -89,7 +87,6 @@ namespace HardwareShopDatabaseImplement.Implements.Worker
var build = context.Builds
.Include(x => x.Purchases)
.ThenInclude(x => x.Purchase)
.Where(x => x.UserId == model.UserId)
.FirstOrDefault(x => x.Id == model.Id);
if (build == null)
{
@ -114,7 +111,6 @@ namespace HardwareShopDatabaseImplement.Implements.Worker
var element = context.Builds
.Include(x => x.Purchases)
.ThenInclude(x => x.Purchase)
.Where(x => x.UserId == model.Id)
.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{

View File

@ -63,7 +63,10 @@ namespace HardwareShopDatabaseImplement.Implements.Worker
}
context.Comments.Add(newComment);
context.SaveChanges();
return newComment.GetViewModel;
return context.Comments
.Include(x => x.Build)
.FirstOrDefault(x => x.Id == newComment.Id)
?.GetViewModel;
}
public CommentViewModel? Update(CommentBindingModel model)

View File

@ -23,7 +23,7 @@ namespace HardwareShopRestApi.Controllers
_buildLogic = buildLogic;
}
[HttpGet]
[HttpGet]
public List<BuildViewModel>? GetBuilds(int userId)
{
try
@ -35,11 +35,12 @@ namespace HardwareShopRestApi.Controllers
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения списка сборок");
_logger.LogError(ex, "Ошибка получения списка сборок пользоватля");
throw;
}
}
[HttpGet]
public BuildViewModel? GetBuild(int buildId)
{

View File

@ -19,5 +19,78 @@ namespace HardwareShopRestApi.Controllers
_logger = logger;
_commentLogic = commentLogic;
}
}
[HttpGet]
public List<CommentViewModel>? GetComments(int userId)
{
try
{
return _commentLogic.ReadList(new CommentSearchModel
{
UserId = userId
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения списка комментариев пользоватля");
throw;
}
}
[HttpGet]
public CommentViewModel? GetComment(int commentId)
{
try
{
return _commentLogic.ReadElement(new() { Id = commentId });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка чтения комментария");
throw;
}
}
[HttpPost]
public void Create(CommentBindingModel model)
{
try
{
_commentLogic.Create(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка создания комментария");
throw;
}
}
[HttpPost]
public void Update(CommentBindingModel model)
{
try
{
_commentLogic.Update(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка обновления комментария");
throw;
}
}
[HttpPost]
public void Delete(CommentBindingModel model)
{
try
{
_commentLogic.Delete(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка удаления комментария");
throw;
}
}
}
}

View File

@ -6,6 +6,7 @@ using HardwareShopDataModels.Enums;
using HardwareShopWorkerApp.Models;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using static System.Net.Mime.MediaTypeNames;
namespace HardwareShopWorkerApp.Controllers
{
@ -137,8 +138,7 @@ namespace HardwareShopWorkerApp.Controllers
APIClient.PostRequest("api/build/update", new BuildBindingModel
{
Id = buildId,
BuildName = name,
UserId = APIClient.User.Id
BuildName = name
});
Response.Redirect("Builds");
}
@ -157,22 +157,112 @@ namespace HardwareShopWorkerApp.Controllers
}
APIClient.PostRequest("api/build/DeleteBuild", new BuildBindingModel
{
Id = deleteBuildId,
UserId = APIClient.User.Id
Id = deleteBuildId
});
Response.Redirect("Builds");
}
public IActionResult MainWorker()
{
return View();
}
public IActionResult Comments()
{
return View();
{
if (APIClient.User == null)
{
return Redirect("~/Home/Enter");
}
ViewBag.Builds = APIClient.GetRequest<List<BuildViewModel>>($"api/build/getbuilds?userId={APIClient.User.Id}");
return View(APIClient.GetRequest<List<CommentViewModel>>($"api/comment/getcomments?userId={APIClient.User.Id}"));
}
public IActionResult listComponents()
[HttpPost]
public void CreateComment(int buildId, string text)
{
if (APIClient.User == null)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
if (string.IsNullOrEmpty(text))
{
throw new Exception($"Текст не должен быть пустым");
}
if (buildId <= 0)
{
throw new Exception($"Идентификатор сборки должен быть больше 0");
}
APIClient.PostRequest("api/comment/create", new CommentBindingModel
{
BuildId = buildId,
UserId = APIClient.User.Id,
Text = text
});
Response.Redirect("Comments");
}
[HttpGet]
public CommentViewModel GetComment(int commentId)
{
if (APIClient.User == null)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
if (commentId <= 0)
{
throw new Exception($"Идентификтаор комментария не может быть ниже или равен 0");
}
var result = APIClient.GetRequest<CommentViewModel>($"api/comment/getcomment?commentId={commentId}");
if (result == null)
{
return null;
}
return result;
}
[HttpPost]
public void UpdateComment(string text, int commentId)
{
if (APIClient.User == null)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
if (string.IsNullOrEmpty(text))
{
throw new Exception($"Текст комментария не должно быть пустым");
}
if (commentId <= 0)
{
throw new Exception($"Идентификтаор комментария не может быть ниже или равен 0");
}
APIClient.PostRequest("api/comment/update", new CommentBindingModel
{
Id = commentId,
Text = text
});
Response.Redirect("Comments");
}
[HttpPost]
public void DeleteComment(int deleteCommentId)
{
if (APIClient.User == null)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
if (deleteCommentId <= 0)
{
throw new Exception($"Идентификтаор комментария не может быть ниже или равен 0");
}
APIClient.PostRequest("api/comment/delete", new CommentBindingModel
{
Id = deleteCommentId,
});
Response.Redirect("Comments");
}
public IActionResult listComponents()
{
return View();
}
@ -208,8 +298,7 @@ namespace HardwareShopWorkerApp.Controllers
{
return Redirect("~/Home/Enter");
}
var list = APIClient.GetRequest<List<BuildViewModel>>($"api/build/getbuilds?userId={APIClient.User.Id}");
return View(list);
return View(APIClient.GetRequest<List<BuildViewModel>>($"api/build/getbuilds?userId={APIClient.User.Id}"));
}
[HttpPost]

View File

@ -29,6 +29,9 @@
<th>
Название
</th>
<th>
Действия
</th>
</tr>
</thead>
<tbody>
@ -45,10 +48,10 @@
@Html.DisplayFor(modelItem => item.BuildName)
</td>
<td>
<button onclick="getBuild(@item.Id)" type="button" class="btn btn-primary btn-lg mb-5" data-bs-toggle="modal" data-bs-target="#updateModal">Изменить</button>
</td>
<td>
<button onclick="getBuild(@item.Id)" type="button" class="btn btn-primary btn-lg mb-5" data-bs-toggle="modal" data-bs-target="#deleteModal">Удалить</button>
<div>
<button onclick="getBuild(@item.Id)" type="button" class="btn btn-primary btn-lg mb-5" data-bs-toggle="modal" data-bs-target="#updateModal">Изменить</button>
<button onclick="getBuild(@item.Id)" type="button" class="btn btn-primary btn-lg mb-5" data-bs-toggle="modal" data-bs-target="#deleteModal">Удалить</button>
</div>
</td>
</tr>
}
@ -112,7 +115,7 @@
<div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<form method="post" asp-controller="home" asp-action="DeleteBuild">
<form method="post" asp-controller="home" asp-action="DeleteBuild">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Удаление сборки</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Закрыть"></button>

View File

@ -1,11 +1,19 @@
@{
@using HardwareShopContracts.ViewModels
@model List<CommentViewModel>
@{
ViewData["Title"] = "Comments";
Layout = "~/Views/Shared/_LayoutWorker.cshtml";
}
<form method="post" class="d-flex justify-content-evenly">
<div class="d-flex justify-content-evenly">
@{
if (Model == null)
{
<h3 class="display-4">Введите пароль</h3>
return;
}
<div class=" col-sm-8">
<div class="text-center">
<h2 class="display-4">Комментарии</h2>
@ -23,23 +31,45 @@
<th>
Название сборки к которой относиться комментарий
</th>
<th>
Действия
</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Id)
</td>
<td>
@Html.DisplayFor(modelItem => item.Text)
</td>
<td>
@Html.DisplayFor(modelItem => item.BuildName)
</td>
<td>
<div>
<button onclick="getComment(@item.Id)" type="button" class="btn btn-primary btn-lg mb-5" data-bs-toggle="modal" data-bs-target="#updateModal">Изменить</button>
<button onclick="getComment(@item.Id)" type="button" class="btn btn-primary btn-lg mb-5" data-bs-toggle="modal" data-bs-target="#deleteModal">Удалить</button>
</div>
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
<div class="text-center d-flex flex-column mt-5">
<button type="button" class="btn btn-primary btn-lg mb-5" data-bs-toggle="modal" data-bs-target="#exampleModal">Добавить</button>
<button type="button" class="btn btn-primary btn-lg mb-5" data-bs-toggle="modal" data-bs-target="#exampleModal">Изменить</button>
<button type="button" class="btn btn-primary btn-lg mb-5">Удалить</button>
<button type="button" class="btn btn-primary btn-lg mb-5" data-bs-toggle="modal" data-bs-target="#createModal">Добавить</button>
<button type="button" class="btn btn-primary btn-lg mb-5">Обновить</button>
</div>
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal fade" id="createModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<form method="post" asp-controller="home" asp-action="CreateComment">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Комментарий</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Закрыть"></button>
@ -47,21 +77,93 @@
<div class="modal-body">
<div>
<label class="form-label">Сборка</label>
<select class="form-select">
<option value="1">Сборка 1</option>
<option value="2">Сборка 2</option>
</select>
<select id="buildId" name="buildId" class="form-control" asp-items="@(new SelectList(@ViewBag.Builds,"Id", "BuildName"))"></select>
</div>
<div>
<label class="form-label">Текст</label>
<input type="text" class="form-control">
<input type="text" class="form-control" required="required" name="text" />
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Закрыть</button>
<button type="button" class="btn btn-primary">Сохранить</button>
<input type="submit" class="btn btn-primary" value="Сохранить">
</div>
</form>
</div>
</div>
</div>
</form>
<div class="modal fade" id="updateModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<form method="post" asp-controller="home" asp-action="UpdateComment">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Комментарий</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Закрыть"></button>
</div>
<div class="modal-body">
<div>
<label class="form-label">Сборка</label>
<select id="buildId" name="buildId" class="form-control" asp-items="@(new SelectList(@ViewBag.Builds,"Id", "BuildName"))"></select>
</div>
<div>
<label class="form-label">Текст</label>
<input type="text" class="form-control" required="required" id="text" name="text" />
</div>
<input type="hidden" id="commentId" name="commentId" />
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Закрыть</button>
<input type="submit" class="btn btn-primary" value="Сохранить">
</div>
</form>
</div>
</div>
</div>
<div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<form method="post" asp-controller="home" asp-action="DeleteComment">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Удаление сборки</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Закрыть"></button>
</div>
<div class="modal-body">
<div class="form-group">
<h1>Вы уверенны что хотите удалить сборку?</h1>
</div>
</div>
<input type="hidden" id="deleteCommentId" name="deleteCommentId" />
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Закрыть</button>
<input type="submit" class="btn btn-primary" value="Удалить">
</div>
</form>
</div>
</div>
</div>
}
</div>
@section Scripts
{
<script>
function getComment(CommentId) {
$.ajax({
method: "GET",
url: "/Home/GetComment",
data: { CommentId: CommentId },
success: function (result) {
if (result != null) {
$('#text').val(result.text);
$('#commentId').val(result.id);
$('#deleteCommentId').val(result.id);
console.log(result);
}
console.log(result);
}
});
}
</script>
}