Работает отмена регистрации

This commit is contained in:
EkaterinaR 2024-11-23 11:53:53 +04:00
parent 01ea8b36ca
commit 9d302c88ae
12 changed files with 258 additions and 43 deletions

View File

@ -1,4 +1,5 @@
using EventVisitorLogic.ViewModels;
using EventVisitorLogic.BindingModels;
using EventVisitorLogic.ViewModels;
using Newtonsoft.Json;
using System.Net.Http.Headers;
using System.Text;
@ -40,5 +41,55 @@ namespace EventVisitorClientApp
throw new Exception(result);
}
}
public static int PostRequestAndGetId<T>(string requestUrl, T model)
{
var json = JsonConvert.SerializeObject(model);
var data = new StringContent(json, Encoding.UTF8, "application/json");
var response = _client.PostAsync(requestUrl, data).Result;
var result = response.Content.ReadAsStringAsync().Result;
if (response.IsSuccessStatusCode)
{
// Попробуем десериализовать результат
var createdObject = JsonConvert.DeserializeObject<VisitorBindingModel>(result);
// Добавьте проверку на null
if (createdObject == null)
{
throw new Exception("Не удалось получить созданный объект из ответа сервера: " + result);
}
// Теперь безопасно обращаемся к Id
return createdObject.Id;
}
else
{
throw new Exception(result);
}
}
public static async Task<int> PostRequestAsync<T>(string requestUrl, T model)
{
var json = JsonConvert.SerializeObject(model);
var data = new StringContent(json, Encoding.UTF8, "application/json");
// Выполняем асинхронный запрос
var response = await _client.PostAsync(requestUrl, data);
// Читаем результат как строку
var result = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
throw new Exception(result);
}
// Попытка десериализовать результат, чтобы получить ID (например, ожидаем, что API возвращает объект с ID)
var createdVisitor = JsonConvert.DeserializeObject<VisitorBindingModel>(result);
return createdVisitor.Id; // Предполагается, что у вас есть свойство Id в VisitorBindingModel
}
}
}

View File

@ -459,26 +459,25 @@ namespace EventVisitorClientApp.Controllers
}
[HttpPost]
public void RegistrationOnEvent(int id, string name, string phone, string email, DateTime dayBirth)
public async Task RegistrationOnEventAsync(int id, string name, string phone, string email, DateTime dayBirth)
{
var eventDetails = APIClient.GetRequest<EventViewModel>($"api/main/GetEvent?EventId={id}");
if (eventDetails != null && eventDetails.FreePlaces > 0)
{
int updatedFreePlaces = eventDetails.FreePlaces - 1;
var visitorId = await APIClient.PostRequestAsync("api/main/registrationonevent", new VisitorBindingModel
{
Name = name,
Phone = phone,
Email = email,
DayBirth = dayBirth.ToUniversalTime(),
EventId = id,
Status = "Çàðåãèñòèðîâàí"
});
APIClient.PostRequest("api/main/registrationonevent", new VisitorBindingModel
{
Name = name,
Phone = phone,
Email = email,
DayBirth = dayBirth.ToUniversalTime(),
EventId = id,
Status = "Çàðåãèñòèðîâàí"
});
// 4. Îáíîâèòå êîëè÷åñòâî ñâîáîäíûõ ìåñò
APIClient.PostRequest("api/main/updateevent", new EventBindingModel
// 4. Îáíîâèòå êîëè÷åñòâî ñâîáîäíûõ ìåñò
APIClient.PostRequest("api/main/updateevent", new EventBindingModel
{
Id = id,
Name = eventDetails.Name,
@ -497,11 +496,14 @@ namespace EventVisitorClientApp.Controllers
Link = eventDetails.Link,
FreePlaces = updatedFreePlaces
});
string cancelLink = Url.Action("CancelRegistration", "Home", new { id = visitorId }, Request.Scheme);
APIClient.PostRequest("api/main/SendToMail", new MailSendInfoBindingModel
{
MailAddress = email,
Subject = "Ðåãèñòðàöèÿ íà ìåðîïðèÿòèå",
Text = "Âû çàðåãåñòðèðîâàíû íà ìåðîïðèÿòèå " + eventDetails.Name + ", êîòîðîå ïðîéäåò " + eventDetails.TimeStart + ". Ïî àäðåñó: " + eventDetails.Address + " ã. " + eventDetails.City + ".\n" + "Ïî âñåì âîïðîñàì ìîæíî îáðàùàòüñÿ ïî òåëåôîíó: " + eventDetails.ContactPhone + " èëè ïî ïî÷òå: " + eventDetails.ContactEmail + ".\n" + "Áóäåì æäàòü Âàñ íà íàøèõ ìåðîïðèÿòèÿõ!"
Text = "Âû çàðåãåñòðèðîâàíû íà ìåðîïðèÿòèå " + eventDetails.Name + ", êîòîðîå ïðîéäåò " + eventDetails.TimeStart + ". Ïî àäðåñó: " + eventDetails.Address + " ã. " + eventDetails.City + ".\n" + "×òîáû îòìåíèòü ðåãèñòðàöèþ, íàæìèòå íà ñëåäóþùóþ ññûëêó:" + cancelLink + ".\n" + "Ïî âñåì âîïðîñàì ìîæíî îáðàùàòüñÿ ïî òåëåôîíó: " + eventDetails.ContactPhone + " èëè ïî ïî÷òå: " + eventDetails.ContactEmail + ".\n" + "Áóäåì æäàòü Âàñ íà íàøèõ ìåðîïðèÿòèÿõ!"
});
Response.Redirect("/Home/ResultRegistration");
}
@ -511,6 +513,61 @@ namespace EventVisitorClientApp.Controllers
}
}
public IActionResult CancelRegistration(int id)
{
var registration = APIClient.GetRequest<VisitorBindingModel>($"api/main/GetVisitor?VisitorId={id}");
if (registration != null)
{
// Çäåñü âû íå âûïîëíÿåòå óäàëåíèå, ïîêà ïîëüçîâàòåëü íå ïîäòâåðäèò.
return View(registration);
}
return NotFound();
}
public IActionResult DeleteRegistration(int id)
{
var registration = APIClient.GetRequest<VisitorBindingModel>($"api/main/GetVisitor?VisitorId={id}");
if (registration != null)
{
APIClient.PostRequest("api/main/deleteVisitor", new VisitorBindingModel { Id = id });
var eventDetails = APIClient.GetRequest<EventViewModel>($"api/main/GetEvent?EventId={registration.EventId}");
APIClient.PostRequest("api/main/UpdateEvent", new EventBindingModel
{
Id = eventDetails.Id,
Name = eventDetails.Name,
Description = eventDetails.Description,
Type = eventDetails.Type,
ContactPhone = eventDetails.ContactPhone,
Address = eventDetails.Address,
City = eventDetails.City,
Status = eventDetails.Status,
ContactEmail = eventDetails.ContactEmail,
TimeEnd = eventDetails.TimeEnd,
TimeStart = eventDetails.TimeStart,
Date = eventDetails.Date.ToUniversalTime(),
CountVisitors = eventDetails.CountVisitors,
FreePlaces = eventDetails.FreePlaces + 1,
OrganizerId = eventDetails.OrganizerId
});
APIClient.PostRequest("api/main/SendToMail", new MailSendInfoBindingModel
{
MailAddress = registration.Email,
Subject = "Îòìåíà ðåãèñòðàöèè",
Text = "Âû óñïåøíî îòìåíèëè ðåãèñòðàöèþ íà ìåðîïðèÿòèå " + eventDetails.Name + "."
});
return RedirectToAction("CancellationSuccess"); // Ïåðåõîä íà ñòðàíèöó óñïåõà
}
return NotFound();
}
public IActionResult CancellationSuccess()
{
return View();
}
[HttpPost]
public void ViewEvent(int id, string subject, string message)
{

View File

@ -0,0 +1,55 @@
@using EventVisitorLogic.BindingModels
@model VisitorBindingModel
@{
Layout = null;
ViewData["Title"] = "Отмена регистрации";
}
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - EventVisitorClientApp</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
<link rel="stylesheet" href="~/EventVisitorClientApp.styles.css" asp-append-version="true" />
<style>
body {
background-color: #f8f9fa; /* Светлый фон */
margin: 0;
padding: 20px;
}
.container {
max-width: 600px; /* Ширина контейнера */
margin: auto;
padding: 20px;
background-color: #ffffff; /* Белый фон для контента */
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); /* Тень */
}
h2 {
text-align: center;
margin-bottom: 20px;
}
.btn-custom {
width: 100%;
margin-top: 10px;
}
</style>
</head>
<body>
<div class="container">
<h2>Отмена регистрации</h2>
<p class="text-center">Вы уверены, что хотите отменить регистрацию на мероприятие?</p>
<form method="post" asp-action="DeleteRegistration" asp-controller="Home">
<input type="hidden" name="id" value="@Model.Id" />
<button type="submit" class="btn btn-danger btn-custom">Да, отменить</button>
</form>
<button type="button" class="btn btn-secondary btn-custom" onclick="window.close();">Нет, оставить регистрацию</button>
</div>
</body>

View File

@ -0,0 +1,12 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace EventVisitorClientApp.Views.Home
{
public class CancelRegistrationModel : PageModel
{
public void OnGet()
{
}
}
}

View File

@ -0,0 +1,39 @@
@{
Layout = null;
ViewData["Title"] = "Успешная регистрация";
}
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - EventVisitorClientApp</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
<link rel="stylesheet" href="~/EventVisitorClientApp.styles.css" asp-append-version="true" />
</head>
<body>
<div class="container mt-5">
<div class="row align-items-center justify-content-center">
<div class="col-md-6 text-center">
<h1 class="display-4">Вы успещно отменили регистрацию на мероприятие!</h1>
</div>
</div>
</div>
<style>
body {
margin-top: 100px;
background-color: #f8f9fa;
}
h1 {
margin-bottom: 20px; /* Отступ ниже заголовка */
font-weight: bold;
}
p {
margin: 0; /* Убираем отступы для абзацев */
}
</style>
</body>

View File

@ -0,0 +1,12 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace EventVisitorClientApp.Views.Home
{
public class CancellationSuccessModel : PageModel
{
public void OnGet()
{
}
}
}

View File

@ -17,9 +17,6 @@
<div class="mb-4">
<button type="submit" class="btn btn-dark btn-lg w-100">Войти</button>
</div>
<div>
<a href="/forgot-password" class="text-decoration-none">Забыли пароль?</a>
</div>
</form>
</div>

View File

@ -62,21 +62,20 @@ namespace EventVisitorDatabase.Implements
.ToList();
}
public VisitorViewModel? Insert(VisitorBindingModel model)
public int? Insert(VisitorBindingModel model)
{
using var context = new EventVisitorDbContext();
var newRecipe = VisitorEntity.Create(model);
if (newRecipe == null)
var newVisitor = VisitorEntity.Create(model); // Предполагается, что здесь создается сущность
if (newVisitor == null)
{
return null;
}
context.Visitors.Add(newRecipe);
context.Visitors.Add(newVisitor);
context.SaveChanges();
return context.Visitors
.Include(x => x.Event)
.FirstOrDefault(x => x.Id == newRecipe.Id)?.GetViewModel;
return newVisitor.Id; // Возвращаете ID нового посетителя
}
public VisitorViewModel? Update(VisitorBindingModel model)
{
using var context = new EventVisitorDbContext();

View File

@ -12,7 +12,7 @@ namespace EventVisitorLogic.Logic
{
List<VisitorViewModel>? ReadList(VisitorBindingModel? model);
VisitorViewModel? ReadElement(VisitorBindingModel model);
bool Create(VisitorBindingModel model);
int? Create(VisitorBindingModel model);
bool Update(VisitorBindingModel model);
bool Delete(VisitorBindingModel model);
}

View File

@ -16,16 +16,12 @@ namespace EventVisitorLogic.Logic
{
_visitorStorage = visitorStorage;
}
public bool Create(VisitorBindingModel model)
public int? Create(VisitorBindingModel model)
{
CheckModel(model);
var result = _visitorStorage.Insert(model);
var visitorId = _visitorStorage.Insert(model);
if (result == null)
{
return false;
}
return true;
return visitorId; // Теперь возвращаем ID или null
}
public bool Delete(VisitorBindingModel model)

View File

@ -14,7 +14,7 @@ namespace EventVisitorLogic.StoragesContracts
List<VisitorViewModel> GetFullList();
List<VisitorViewModel> GetFilteredList(VisitorBindingModel model);
VisitorViewModel? GetElement(VisitorBindingModel model);
VisitorViewModel? Insert(VisitorBindingModel model);
int? Insert(VisitorBindingModel model);
VisitorViewModel? Update(VisitorBindingModel model);
VisitorViewModel? Delete(VisitorBindingModel model);
}

View File

@ -113,18 +113,15 @@ namespace EventVisitorRestApi.Controllers
}
[HttpPost]
public void RegistrationOnEvent(VisitorBindingModel model)
public IActionResult RegistrationOnEvent([FromBody] VisitorBindingModel model)
{
try
{
_visitor.Create(model);
}
catch (Exception ex)
{
throw;
}
// логика создания нового посетителя в БД
int? visitorId = _visitor.Create(model); // Получаем ID созданного посетителя
return Ok(new VisitorBindingModel { Id = (int)visitorId });
}
[HttpGet]
public EventViewModel? GetEvent(int eventId)
{