using EventVisitorClientApp.Models; using EventVisitorLogic.BindingModels; using EventVisitorLogic.Logic; using EventVisitorLogic.ViewModels; using Microsoft.AspNetCore.Mvc; using System; using System.Diagnostics; using System.Net.NetworkInformation; using System.Net; using System.Numerics; using System.Security.Cryptography.Xml; using System.Xml.Linq; using Microsoft.Extensions.Logging; using static System.Runtime.InteropServices.JavaScript.JSType; using DocumentFormat.OpenXml.Office2010.Excel; using System.Text; using System.Security.Cryptography; using DocumentFormat.OpenXml.Spreadsheet; using DocumentFormat.OpenXml.Bibliography; using DocumentFormat.OpenXml.Drawing.Diagrams; using DocumentFormat.OpenXml.Office2016.Drawing.ChartDrawing; using DocumentFormat.OpenXml.Wordprocessing; 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 void Enter(string login, string password) { if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password)) { throw new Exception("Введите логин и пароль"); } APIClient.Client = APIClient.GetRequest($"api/Organizer/login?login={login}&password={password}"); if (APIClient.Client == null) { throw new Exception("Неверный логин/пароль"); } Response.Redirect("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"); } /// /// Методы для организатора /// /// [HttpGet] public IActionResult Register() { return View(); } public IActionResult Logout() { APIClient.Client = null; return Redirect("~/Home/Enter"); } public static string GenerateRandomString() { const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; return new string(Enumerable.Repeat(chars, 6) .Select(s => s[_random.Next(s.Length)]).ToArray()); } [HttpPost] public void Register(string login, string password, string surname, string name, string lastname, string organizationName, string phone, string code) { //var confirmationCode = GenerateRandomString(); //APIClient.PostRequest("api/main/SendToMail", new MailSendInfoBindingModel //{ // MailAddress = login, // Subject = "Код для подтверждения регистрации", // Text = $"Ваш код для подтверждения регистрации: {confirmationCode}" //}); APIClient.PostRequest("api/Organizer/Register", new OrganizerBindingModel { Name = name, Surname = surname, LastName = lastname, OrganizationName = organizationName, Phone = phone, Email = login, Password = password }); Response.Redirect("Enter"); return; } [HttpPost] public void CheckCode(string confirmationCode, string login, string password, string surname, string name, string lastname, string organizationName, string phone) { // Получаем сохранённый код из сессии var storedCode = HttpContext.Session.GetString("ConfirmationCode"); if (storedCode == confirmationCode) { } else { // Обработка неправильного кода, например, ошибка 400 Response.StatusCode = 400; return; } } /// /// Управление мероприятиями /// /// public IActionResult MyEvents() { if (APIClient.Client == null) { return Redirect("~/Home/Enter"); } return View(APIClient.GetRequest>($"api/main/GetEventList?OrganizerId={APIClient.Client.Id}")); } 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 void CreateEvent(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("Вы как сюда попали? Сюда вход только авторизованным"); } 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.Now.ToUniversalTime(), CountVisitors = count, FreePlaces = count, OrganizerId = APIClient.Client.Id, Link = registrationLink }); Response.Redirect("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 void 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; APIClient.PostRequest("api/main/UpdateEvent", new EventBindingModel { Id = id, Name = 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 }); Response.Redirect("/Home/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}"); if (action == "search" && !string.IsNullOrEmpty(searchTerm)) { visitors = 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 }); } // После сохранения перенаправляем обратно на этот же метод с id return RedirectToAction("Visitors", new { id }); } 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 void RegistrationOnEvent(int id, string name, string phone, string email, DateTime dayBirth) { var eventDetails = APIClient.GetRequest($"api/main/GetEvent?EventId={id}"); if (eventDetails != null && eventDetails.FreePlaces > 0) { int updatedFreePlaces = eventDetails.FreePlaces - 1; 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 { 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 }); 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" + "Будем ждать Вас на наших мероприятиях!" }); Response.Redirect("/Home/ResultRegistration"); } else { Response.Redirect("MyEvents"); } } [HttpPost] public void ViewEvent(int id, string subject, string message) { if (APIClient.Client == null) { throw new Exception("Необходима авторизация"); } var visitorList = APIClient.GetRequest>($"api/main/GetVisitorList?EventId={id}"); if (visitorList != null) { foreach (var visitor in visitorList) { APIClient.PostRequest("api/main/SendToMail", new MailSendInfoBindingModel { MailAddress = visitor.Email, Subject = subject, Text = message }); } } APIClient.PostRequest("api/main/CreateMessage", new SentMessageBindingModel { Subject = subject, Body = message, EventId = id, OrganizerId = APIClient.Client.Id, SentDate = DateTime.Now.ToUniversalTime() }); Response.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); } /// /// Отчеты /// /// public IActionResult GetWordFile() { return new PhysicalFileResult("F:\\EventVisitor\\wordfile.docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"); } public IActionResult GetExcelFile() { return new PhysicalFileResult("F:\\EventVisitor\\excelfile.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); } //[HttpPost] //public void ReportWord(int[] Ids, int id) //{ // if (APIClient.Client == null) // { // throw new Exception("Вы как суда попали? Суда вход только авторизованным"); // } // List registeredVisitorsIds = APIClient.GetRequest>($"api/main/GetVisitorList?EventId={id}"); // foreach (var item in Ids) // { // res.Add(item); // } // APIClient.PostRequest("api/main/createreporttowordfile", new ReportVisitorsBindingModel // { // Ids = res, // FileName = "F:\\EventVisitor\\wordfile.docx" // }); // Response.Redirect("GetWordFile"); //} } }