using EventVisitorClientApp.Models; using EventVisitorLogic.BindingModels; using EventVisitorLogic.Logic; using EventVisitorLogic.ViewModels; using Microsoft.AspNetCore.Mvc; using System; using System.Diagnostics; namespace EventVisitorClientApp.Controllers { public class HomeController : Controller { Random rnd = new Random(); private static readonly Random _random = new Random(); private void DisplayErrorMessage(string message) { ViewBag.ErrorMessage = message; } public IActionResult Index() { return View(); } [HttpGet] public IActionResult Enter() { return View(); } [HttpPost] public IActionResult Enter(string login, string password) { string returnUrl = HttpContext.Request.Headers["Referer"].ToString(); if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password)) { return RedirectToAction("Error", new { errorMessage = "Введите логин и пароль.", returnUrl }); } APIClient.Client = APIClient.GetRequest($"api/Organizer/login?login={login}&password={password}"); if (APIClient.Client == null) { return RedirectToAction("Error", new { errorMessage = "Неверный логин/пароль.", returnUrl }); } return RedirectToAction("Index"); } [HttpGet] public IActionResult Privacy() { if (APIClient.Client == null) { return Redirect("~Home/Enter"); } return View(APIClient.Client); } [HttpPost] public void Privacy(string login, string password, string surname, string name, string lastname, string role, string organizationName, string phone) { if (APIClient.Client == null) { throw new Exception("Вы как сюда попали? Сюда вход только авторизованным"); } if (string.IsNullOrEmpty(login)) { throw new Exception("Введите e-mail"); } if (string.IsNullOrEmpty(password)) { throw new Exception("Введите пароль"); } if (string.IsNullOrEmpty(name)) { throw new Exception("Введите имя"); } if (string.IsNullOrEmpty(surname)) { throw new Exception("Введите фамилию"); } if (string.IsNullOrEmpty(organizationName)) { throw new Exception("Введите название организации"); } if (string.IsNullOrEmpty(role)) { throw new Exception("Введите роль"); } APIClient.PostRequest("api/client/updatedata", new OrganizerBindingModel { Id = APIClient.Client.Id, Name = name, Surname = surname, LastName = lastname, OrganizationName = organizationName, Phone = phone, Email = login, Password = password }); APIClient.Client.Name = name; APIClient.Client.Surname = surname; APIClient.Client.LastName = lastname; APIClient.Client.OrganizationName = organizationName; APIClient.Client.Phone = phone; APIClient.Client.Email = login; APIClient.Client.Password = password; Response.Redirect("Index"); } /// /// Методы для организатора /// /// public IActionResult Logout() { APIClient.Client = null; return Redirect("~/Home/Enter"); } [HttpGet] public IActionResult Register() { return View(); } [HttpPost] public IActionResult Register(string login, string password, string surname, string name, string lastname, string organizationName, string phone, string code) { // Получаем URL страницы, с которой пришли string returnUrl = HttpContext.Request.Headers["Referer"].ToString(); // Проверяем, существует ли пользователь с таким логином var existingUser = APIClient.GetRequest($"api/Organizer/GetOrganizer?login={login}"); // Если пользователь существует, перенаправляем на страницу ошибки if (existingUser != null) { return RedirectToAction("Error", new { errorMessage = "Пользователь с таким email уже существует.", returnUrl }); } // Если пользователя нет, продолжаем с регистрацией APIClient.PostRequest("api/Organizer/Register", new OrganizerBindingModel { Name = name, Surname = surname, LastName = lastname, OrganizationName = organizationName, Phone = phone, Email = login, Password = password }); return RedirectToAction("Enter"); // Перенаправление на страницу входа } /// /// Управление мероприятиями /// /// public IActionResult MyEvents(string statusFilter, string typeFilter) { if (APIClient.Client == null) { return Redirect("~/Home/Enter"); } var events = APIClient.GetRequest>($"api/main/GetEventList?OrganizerId={APIClient.Client.Id}"); var currentDateTime = DateTime.Now; // Фильтрация по статусу if (!string.IsNullOrEmpty(statusFilter)) { if (statusFilter == "past") { events = events.Where(e => e.TimeStart < currentDateTime).ToList(); } else if (statusFilter == "future") { events = events.Where(e => e.TimeStart > currentDateTime).ToList(); } } // Фильтрация по типу if (!string.IsNullOrEmpty(typeFilter)) { events = events.Where(e => e.Type.Equals(typeFilter, StringComparison.OrdinalIgnoreCase)).ToList(); } return View(events); } public IActionResult CreateEvent() { if (APIClient.Client == null) { return Redirect("~/Home/Enter"); } return View(); } public IActionResult ViewEvent(int id) { if (APIClient.Client == null) { return Redirect("~/Home/Enter"); } var eventDetails = APIClient.GetRequest($"api/main/GetEvent?EventId={id}"); return View(eventDetails); } [HttpPost] public IActionResult CreateEvent(string name, string description, string type, string phone, string email, string address, string city, string status, int count, DateTime timestart, DateTime timeend) { string returnUrl = HttpContext.Request.Headers["Referer"].ToString(); if (timestart < DateTime.UtcNow) { return RedirectToAction("Error", new { errorMessage = "Дата начала не может быть в прошлом.", returnUrl }); } if (timestart >= timeend) { return RedirectToAction("Error", new { errorMessage = "Дата начала не может быть позже или равна дате окончания.", returnUrl }); } string eventId = Guid.NewGuid().ToString(); string registrationLink = $"https://localhost:7186/registrationonevent?EventId={eventId}"; APIClient.PostRequest("api/main/createevent", new EventBindingModel { Name = name, Description = description, Type = type, ContactPhone = phone, Address = address, City = city, Status = status, ContactEmail = email, TimeEnd = timeend.ToUniversalTime(), TimeStart = timestart.ToUniversalTime(), Date = DateTime.UtcNow, // Используйте UtcNow для текущей даты CountVisitors = count, FreePlaces = count, OrganizerId = APIClient.Client.Id, Link = registrationLink }); return RedirectToAction("MyEvents"); } public IActionResult DeleteEvent(int id) { if (APIClient.Client == null) { return Redirect("~/Home/Enter"); } APIClient.PostRequest($"api/main/DeleteEvent", new EventBindingModel { Id = id }); return RedirectToAction("MyEvents"); } public IActionResult UpdateEvent(int id) { if (APIClient.Client == null) { return Redirect("~/Home/Enter"); } var eventDetails = APIClient.GetRequest($"api/main/GetEvent?EventId={id}"); return View(eventDetails); } [HttpPost] public IActionResult UpdateEvent(int id, string name, string description, string type, string phone, string email, string address, string city, string status, int count, DateTime? timestart, DateTime? timeend) { if (APIClient.Client == null) { throw new Exception("Необходима авторизация"); } var existingEvent = APIClient.GetRequest($"api/main/GetEvent?EventId={id}"); DateTime start = (timestart.HasValue) ? DateTime.SpecifyKind(timestart.Value, DateTimeKind.Utc) : existingEvent.TimeStart.ToUniversalTime(); DateTime end = (timeend.HasValue) ? DateTime.SpecifyKind(timeend.Value, DateTimeKind.Utc) : existingEvent.TimeEnd.ToUniversalTime(); int countRegisterPlace = existingEvent.CountVisitors - existingEvent.FreePlaces; var visitorList = APIClient.GetRequest>($"api/main/GetVisitorList?EventId={id}"); string msg = ""; string returnUrl = HttpContext.Request.Headers["Referer"].ToString(); if (timestart < DateTime.UtcNow) { return RedirectToAction("Error", new { errorMessage = "Дата начала не может быть в прошлом.", returnUrl }); } if (timestart >= timeend) { return RedirectToAction("Error", new { errorMessage = "Дата начала не может быть позже или равна дате окончания.", returnUrl }); } if (existingEvent.TimeStart != timestart && existingEvent.Address != address) { msg = $"Внимание! Изменилась дата начала и адресс мероприятия {existingEvent.Name}. Мероприятие начнется: {timestart} и пройдет по адрессу {address}"; } else if(existingEvent.TimeStart == timestart && existingEvent.Address != address) { msg = $"Внимание! Изменился адресс мероприятия {existingEvent.Name}. Мероприятие пройдет по адрессу {address}"; } else if(existingEvent.TimeStart != timestart && existingEvent.Address == address) { msg = $"Внимание! Изменилось время начала мероприятия мероприятия {existingEvent.Name}. Мероприятие начнется: {timestart}"; } if (msg != "") { if (visitorList.Count != 0) { foreach (var visitor in visitorList) { APIClient.PostRequest("api/main/SendToMail", new MailSendInfoBindingModel { MailAddress = visitor.Email, Subject = "Изменения в мероприятии", Text = msg }); } } } APIClient.PostRequest("api/main/UpdateEvent", new EventBindingModel { Id = id, Name = existingEvent.Name, Description = description, Type = type, ContactPhone = phone, Address = address, City = city, Status = status, ContactEmail = email, TimeEnd = end, TimeStart = start, Date = DateTime.Now.ToUniversalTime(), CountVisitors = count, FreePlaces = count - countRegisterPlace, OrganizerId = APIClient.Client.Id }); return RedirectToAction("MyEvents"); } /// /// Управление посетителями /// /// /// /// public IActionResult Visitors(int id) { if (APIClient.Client == null) { return Redirect("~/Home/Enter"); } // Получите всех посетителей var visitors = APIClient.GetRequest>($"api/main/GetVisitorList?EventId={id}"); return View(visitors); } [HttpPost] public IActionResult Visitors(int id, string action, string searchTerm, [FromForm] List presentIds) { // Получите всех посетителей var visitors = APIClient.GetRequest>($"api/main/GetVisitorList?EventId={id}"); var visitorsFiltered = new List(); // Обработка поиска if (action == "search" && !string.IsNullOrEmpty(searchTerm)) { visitorsFiltered = visitors.Where(v => v.Name.Contains(searchTerm, StringComparison.OrdinalIgnoreCase) || v.Email.Contains(searchTerm, StringComparison.OrdinalIgnoreCase)).ToList(); } // Обработка сохранения статусов if (action == "save") { foreach (var visitor in visitors) { var status = presentIds.Contains(visitor.Id) ? "Пришел" : "Зарегистрирован"; APIClient.PostRequest("api/main/updatevisitor", new VisitorBindingModel { Id = visitor.Id, Status = status }); } // Высвечивание статуса сохранения TempData["SuccessMessage"] = "Статусы посетителей успешно обновлены."; // После сохранения перенаправляем обратно на этот же метод с id return RedirectToAction("Visitors", new { id }); } // Если ничего не найдено, вернем всё if (visitorsFiltered.Any()) { return View(visitorsFiltered); } return View(visitors); } public IActionResult DeleteVisitor(int id) { if (APIClient.Client == null) { return Redirect("~/Home/Enter"); } var existingVisitor = APIClient.GetRequest($"api/main/GetVisitor?VisitorId={id}"); var existingEvent = APIClient.GetRequest($"api/main/GetEvent?EventId={existingVisitor.EventId}"); int eventId = existingEvent.Id; APIClient.PostRequest($"api/main/DeleteVisitor", new VisitorBindingModel { Id = id }); APIClient.PostRequest("api/main/UpdateEvent", new EventBindingModel { Id = existingVisitor.EventId, Name = existingEvent.Name, Description = existingEvent.Description, Type = existingEvent.Type, ContactPhone = existingEvent.ContactPhone, Address = existingEvent.Address, City = existingEvent.City, Status = existingEvent.Status, ContactEmail = existingEvent.ContactEmail, TimeEnd = existingEvent.TimeEnd, TimeStart = existingEvent.TimeStart, Date = existingEvent.Date.ToUniversalTime(), CountVisitors = existingEvent.CountVisitors, FreePlaces = existingEvent.FreePlaces + 1, OrganizerId = APIClient.Client.Id }); return Redirect($"~/Home/Visitors/{eventId}"); } public IActionResult ResultRegistration() { return View(); } public IActionResult RegistrationOnEvent(int id) { var eventDetails = APIClient.GetRequest($"api/main/GetEvent?EventId={id}"); return View(eventDetails); } [HttpPost] public async Task RegistrationOnEventAsync(int id, string name, string phone, string email, DateTime dayBirth) { var eventDetails = APIClient.GetRequest($"api/main/GetEvent?EventId={id}"); string returnUrl = HttpContext.Request.Headers["Referer"].ToString(); if (dayBirth >= DateTime.Now) { return RedirectToAction("Error", new { errorMessage = "Неверная дата рождения.", returnUrl }); } 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 = "Зарегистирован" }); // 4. Обновите количество свободных мест APIClient.PostRequest("api/main/updateevent", new EventBindingModel { Id = 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.ToUniversalTime(), TimeStart = eventDetails.TimeStart.ToUniversalTime(), Date = eventDetails.Date.ToUniversalTime(), CountVisitors = eventDetails.CountVisitors, OrganizerId = eventDetails.OrganizerId, 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" + "Чтобы отменить регистрацию, нажмите на следующую ссылку:" + cancelLink + ".\n" + "По всем вопросам можно обращаться по телефону: " + eventDetails.ContactPhone + " или по почте: " + eventDetails.ContactEmail + ".\n" + "Будем ждать Вас на наших мероприятиях!" }); return Redirect("/Home/ResultRegistration"); } else { return Redirect("MyEvents"); } } public IActionResult CancelRegistration(int id) { var registration = APIClient.GetRequest($"api/main/GetVisitor?VisitorId={id}"); if (registration != null) { // Здесь вы не выполняете удаление, пока пользователь не подтвердит. return View(registration); } return NotFound(); } public IActionResult DeleteRegistration(int id) { var registration = APIClient.GetRequest($"api/main/GetVisitor?VisitorId={id}"); if (registration != null) { APIClient.PostRequest("api/main/deleteVisitor", new VisitorBindingModel { Id = id }); var eventDetails = APIClient.GetRequest($"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 IActionResult ViewEvent(int id, string subject, string message) { if (APIClient.Client == null) { throw new Exception("Необходима авторизация"); } var visitorList = APIClient.GetRequest>($"api/main/GetVisitorList?EventId={id}"); string returnUrl = HttpContext.Request.Headers["Referer"].ToString(); if (visitorList.Count != 0) { foreach (var visitor in visitorList) { APIClient.PostRequest("api/main/SendToMail", new MailSendInfoBindingModel { MailAddress = visitor.Email, Subject = subject, Text = message }); } } else { return RedirectToAction("Error", new { errorMessage = "Еще нет зарегистрированных пользователей", returnUrl }); } APIClient.PostRequest("api/main/CreateMessage", new SentMessageBindingModel { Subject = subject, Body = message, EventId = id, OrganizerId = APIClient.Client.Id, SentDate = DateTime.Now.ToUniversalTime() }); return Redirect($"/Home/ViewEvent/{id}"); } public IActionResult MessageHistory(int id) { if (APIClient.Client == null) { return Redirect("~/Home/Enter"); } var allMessages = APIClient.GetRequest>($"api/main/GetSentMessageList?EventId={id}"); return View(allMessages); } /// /// Отчеты /// /// /// [HttpPost] public IActionResult ReportExcel(int id) { if (APIClient.Client == null) { throw new Exception("Вы как суда попали? Суда вход только авторизованным"); } var reportFilePath = $"F:\\EventVisitor\\Report_{id}_{DateTime.Now.ToString("yyyyMMdd_HHmmss")}.xlsx"; APIClient.PostRequest("api/main/createreporttoexcelfile", new ReportVisitorsBindingModel { EventId = id, FileName = reportFilePath }); return PhysicalFile(reportFilePath, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", $"Report_{id}.xlsx"); } [HttpPost] public IActionResult ReportWord(int id) { if (APIClient.Client == null) { throw new Exception("Вы как суда попали? Суда вход только авторизованным"); } // Создайте отчет var reportFilePath = $"F:\\EventVisitor\\Report_{id}_{DateTime.Now.ToString("yyyyMMdd_HHmmss")}.docx"; APIClient.PostRequest("api/main/createreporttowordfile", new ReportVisitorsBindingModel { EventId = id, FileName = reportFilePath }); // Возвращаем файл и устанавливаем имя файла для сохранения return PhysicalFile(reportFilePath, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", $"Report_{id}.docx"); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error(string errorMessage, string returnUrl) { ViewBag.ErrorMessage = errorMessage ?? "Произошла неизвестная ошибка."; // Дефолтное сообщение ViewBag.ReturnUrl = returnUrl; // Сохраняем returnUrl return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } } }