Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using AutoMapper;
- using Microsoft.Extensions.Logging;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using Timerman.Repository;
- using Timerman.Service.DTO.Entities;
- using Timerman.Service.Interfaces;
- using Microsoft.EntityFrameworkCore;
- using Timerman.Service.Infrastructure;
- using Timerman.Data.Entities;
- using Timerman.Service.Infrastructure.Extentions;
- using Microsoft.AspNetCore.Http;
- using AutoMapper.QueryableExtensions;
- using System.Net.Http;
- using System.Net.Http.Headers;
- using Newtonsoft.Json;
- namespace Timerman.Service.Services
- {
- public class ParticipantRR
- {
- public string EventCode { get; set; }
- public string Distance { get; set; }
- public string FirstName {get; set; }
- public string LastName { get; set; }
- public int StartNumber { get; set; }
- public int? AbsoluteTimeResult { get; set; }
- public int? IndividualTimeResult { get; set; }
- public string Category {get; set;}
- public int Position { get; set; }
- public int GenderAgeNominationPosition { get; set; }
- public int GenderNominationPosition { get; set; }
- public int AgeNominationPosition { get; set; }
- }
- public class EventService : IEventService
- {
- private readonly IUnitOfWork _uow;
- private readonly IMapper _mapper;
- private readonly ICoreService _coreService;
- private readonly ILogger _logger;
- private readonly IFileWorkService _fileWorkService;
- public EventService(
- IUnitOfWork uow,
- IMapper mapper,
- ICoreService filter,
- IFileWorkService fileWorkService,
- ILoggerFactory loggerFactory)
- {
- _uow = uow;
- _mapper = mapper;
- _coreService = filter;
- _logger = loggerFactory.CreateLogger<EventService>();
- _fileWorkService = fileWorkService;
- }
- #region EventEntity
- public async Task<EventDTO> AddEventAsync(EventDTO item, string userId, IFormFile file, IFormFile filePreview)
- {
- try
- {
- var eventItem = _mapper.Map<Event>(item);
- eventItem.AddedBy = userId;
- eventItem.AddedDate = DateTime.UtcNow;
- var srcPath = "";
- var srcPathPreview = "";
- if (file != null)
- srcPath = _fileWorkService.PhotoSave(file);
- if (filePreview != null)
- srcPathPreview = _fileWorkService.PhotoSave(filePreview);
- eventItem.Photo = srcPath;
- eventItem.PhotoPreview = srcPathPreview;
- _logger.LogDebug($"Mapped entity: {eventItem.ToString()}");
- var result = await _uow.Events.CreateRAsync(eventItem);
- await _uow.SaveChangesAsync();
- eventItem = await _uow.Events.Query()
- .Where(e => e.Id == result.Id)
- .IncludeEventRelatedData()
- .FirstOrDefaultAsync();
- return _mapper.Map<EventDTO>(eventItem);
- }
- catch (Exception e)
- {
- throw new UnexpectedException(e.Message);
- }
- }
- public async Task DeleteEventAsync(long eventId)
- {
- try
- {
- var eventItem = await _uow.Events.GetByIdAsync(eventId);
- if (eventItem == null)
- throw new NotFoundException("Мероприятие не найдено", "");
- _uow.Events.RemoveById(eventId);
- await _uow.SaveChangesAsync();
- }
- catch (NotFoundException)
- {
- throw;
- }
- catch (Exception e)
- {
- throw new UnexpectedException(e.Message);
- }
- }
- public async Task<EventDTO> EditEventAsync(long eventId, EventDTO item, string userId, IFormFile file, IFormFile filePreview)
- {
- try
- {
- var eventItem = await _uow.Events.GetByIdAsync(eventId);
- if (eventItem == null)
- throw new NotFoundException("Мероприятие не найдено", "");
- var srcPath = eventItem.Photo;
- var srcPathPreview = eventItem.PhotoPreview;
- if (file != null)
- srcPath = _fileWorkService.PhotoSave(file);
- if (filePreview != null)
- srcPathPreview = _fileWorkService.PhotoSave(filePreview);
- _mapper.Map(item, eventItem);
- eventItem.Photo = srcPath;
- eventItem.PhotoPreview = srcPathPreview;
- eventItem.ModifiedBy = userId;
- eventItem.ModifiedDate = DateTime.UtcNow;
- _logger.LogDebug($"Mapped entity: {eventItem.ToString()}");
- _uow.Events.Update(eventItem);
- await _uow.SaveChangesAsync();
- return _mapper.Map<EventDTO>(eventItem);
- }
- catch (NotFoundException)
- {
- throw;
- }
- catch (Exception e)
- {
- throw new UnexpectedException(e.Message);
- }
- }
- /// <summary>
- /// Получение мероприятия по его Id.
- /// </summary>
- /// <param name="eventId"></param>
- /// <returns></returns>
- public async Task<EventDTO> EventByIdAsync(long eventId)
- {
- try
- {
- // TODO: добавить isActive в предикат
- var eventItem = await _uow.Events.Query()
- .Where(e => e.Id == eventId)
- .IncludeEventRelatedData()
- .FirstOrDefaultAsync();
- if (eventItem == null)
- throw new NotFoundException("Мероприятие не найдено", "The event is not found");
- return _mapper.Map<EventDTO>(eventItem);
- }
- catch (NotFoundException)
- {
- throw;
- }
- catch (Exception e)
- {
- throw new UnexpectedException(e.Message);
- }
- }
- public async Task<IList<EventResultDTO>> GetResultForEventAsync(long eventId)
- {
- try
- {
- // Maybe needs optimizations
- var items = await _uow.EventDistances.Query()
- .Include(c => c.Distance.DistanceType)
- .Include(c => c.Distance.ParticipationType)
- .Include(c => c.Distance.EventParticipantDistances)
- .ThenInclude(c => c.EventParticipantResult)
- .Include(c => c.Distance.EventParticipantDistances)
- .ThenInclude(c => c.EventParticipants.Participant.City)
- .Include(c => c.Distance.EventParticipantDistances)
- .ThenInclude(c => c.EventParticipants.Participant.AgeCategory)
- .Include(c => c.Distance.EventParticipantDistances)
- .ThenInclude(c => c.EventParticipants.Participant.ActivityField)
- .Include(c => c.Distance.EventParticipantDistances)
- .ThenInclude(c => c.EventParticipants.Participant.SportClub)
- .Where(e => e.EventId == eventId)
- .GroupBy(c => c.Distance)
- .ToListAsync();
- var result = new List<EventResultDTO>();
- foreach (var var in items)
- {
- result.Add(new EventResultDTO
- {
- Distance = _mapper.Map<DistanceLightDTO>(var.Key),
- Result = _mapper.Map<IList<ParticipantResultDTO>>(var.SelectMany(c => c.Distance.EventParticipantDistances
- .Where(f => f.EventParticipantResult != null).Select(s => s.EventParticipantResult)))
- });
- }
- return result;
- /* ProjectTo
- var items = await _uow.EventDistances.Query()
- .Include(c => c.Distance.DistanceType)
- .Include(c => c.Distance.ParticipationType)
- .Include(c => c.Distance.EventParticipantDistances)
- .ThenInclude(c => c.EventParticipantResult)
- .Include(c => c.Distance.EventParticipantDistances)
- .ThenInclude(c => c.EventParticipants.Participant.City)
- .Include(c => c.Distance.EventParticipantDistances)
- .ThenInclude(c => c.EventParticipants.Participant.SportClub)
- .Where(e => e.EventId == eventId)
- .ProjectTo<EventResultDTO>(_mapper.ConfigurationProvider)
- .ToListAsync();
- var result = items.GroupBy(c => c.Distance).Select(c => new EventResultDTO
- {
- Distance = c.Key,
- Result = c.SelectMany(f => f.Result).ToList()
- }).ToList();
- return result;
- */
- }
- catch (Exception e)
- {
- throw new UnexpectedException(e.Message);
- }
- }
- ///<summary>
- /// Занесение результатов мероприятий из API Russia Running в базу данных
- ///<summary>
- ///<returns></returns>
- public async Task<string> getEventResultRRAsync(long eventId)
- {
- try
- {
- var eventItem = await _uow.Events.GetByIdAsync(eventId);
- if (eventItem == null)
- throw new NotFoundException("Мероприятие не найдено", "");
- if (eventItem.EventIdRR == null)
- throw new NotFoundException("eventIdRR не найден", "");
- var eventIdRR = eventItem.EventIdRR;
- var login = "press@timerman.org";
- var password = "wKrNwpZRDDR8N3J";
- var static_path = "https://russiarunning.com/api/beneficiary/get-event-results/en?eventId=";
- HttpClient client = new HttpClient();
- var path = static_path + eventIdRR;
- client.DefaultRequestHeaders.Accept.Clear();
- byte[] authbytes = Encoding.ASCII.GetBytes(login + ":" + password);
- string base64 = Convert.ToBase64String(authbytes);
- client.DefaultRequestHeaders.Add("Authorization", "Basic " + base64);
- var response = await client.PostAsync(path, null);
- if ((int) response.StatusCode != 200)
- throw new NotFoundException("status code" + (int)response.StatusCode, "");
- var responseString = await response.Content.ReadAsStringAsync();
- //var responseJson = new JsonResult(responseString);
- ParticipantRR [] ParticipantsRR = JsonConvert.DeserializeObject<ParticipantRR []>(responseString);
- return responseString;
- }
- catch(NotFoundException)
- {
- throw;
- }
- catch (Exception e)
- {
- throw new UnexpectedException(e.Message);
- }
- }
- ///<summary>
- /// Занесение результатов мероприятий из API Russia Running в базу данных
- ///<summary>
- ///<returns></returns>
- public async Task<bool> EventResultRRAsync(string eventId)
- {
- try
- {
- var login = "press@timerman.org";
- var password = "wKrNwpZRDDR8N3J";
- var static_path = "https://russiarunning.com/api/beneficiary/get-event-results/en?eventId=";
- HttpClient client = new HttpClient();
- var path = static_path + eventId;
- var requestContent = new FormUrlEncodedContent(new[] {
- new KeyValuePair<string, string> ("StartDate", "2019-01-06T11:08:42.723Z"),
- new KeyValuePair<string, string> ("EndDate", "2019-08-06T11:08:42.723Z"),
- });
- client.DefaultRequestHeaders.Accept.Clear();
- byte[] authbytes = Encoding.ASCII.GetBytes(login + ":" + password);
- string base64 = Convert.ToBase64String(authbytes);
- client.DefaultRequestHeaders.Add("Authorization", "Basic " + base64);
- var response = await client.PostAsync(path, null);
- var responseString = await response.Content.ReadAsStringAsync();
- Console.WriteLine(responseString);
- return true;
- }
- catch(NotFoundException)
- {
- throw;
- }
- catch (Exception e)
- {
- throw new UnexpectedException(e.Message);
- }
- }
- /// <summary>
- /// Получение всех мероприятий.
- /// </summary>
- /// <returns></returns>
- public async Task<IList<EventDTO>> GetAllAsync()
- {
- try
- {
- var eventItems = await _uow.Events.Query()
- .Where(c => c.IsActive == true)
- .IncludeEventRelatedData()
- .OrderByDescending(c => c.Date)
- .ToListAsync();
- return _mapper.Map<List<EventDTO>>(eventItems);
- }
- catch (NotFoundException)
- {
- throw;
- }
- catch (Exception e)
- {
- throw new UnexpectedException(e.Message);
- }
- }
- public async Task<IList<EventAdminDTO>> GetAllAdminAsync()
- {
- try
- {
- var eventItems = await _uow.Events.Query()
- .IncludeEventRelatedData()
- .ToListAsync();
- return _mapper.Map<List<EventAdminDTO>>(eventItems);
- }
- catch (NotFoundException)
- {
- throw;
- }
- catch (Exception e)
- {
- throw new UnexpectedException(e.Message);
- }
- }
- public async Task<EventDTO> GetClosestAsync()
- {
- try
- {
- var eventItems = await _uow.Events.Query()
- .Where(c => c.IsActive == true && c.Date > DateTime.Now)
- .IncludeEventRelatedData()
- .OrderByDescending(c => c.Date)
- .ToListAsync();
- if (eventItems.Count == 0)
- {
- throw new NotFoundException("Ближайшее мероприятие не найдено");
- }
- return _mapper.Map<EventDTO>(eventItems.Last());
- }
- catch (NotFoundException)
- {
- throw;
- }
- catch (Exception e)
- {
- throw new UnexpectedException(e.Message);
- }
- }
- #endregion
- #region Admin panel event configuration
- public async Task UpdateDistancesAsync(long eventId, IList<DistanceDTO> distances)
- {
- try
- {
- var eventItem = await _uow.Events.GetByIdAsync(eventId);
- if (eventItem == null)
- throw new NotFoundException("Мероприятие не найдено", "");
- var oldDistanceIds = _uow.EventDistances.Query()
- .Where(e => e.EventId == eventId)
- .Select(e => e.DistanceId);
- _uow.EventDistances.Remove(e => e.EventId == eventId);
- _uow.Distances.Remove(e => oldDistanceIds.Contains(e.Id));
- var distanceEntities = _mapper.Map<IList<Distance>>(distances);
- await _uow.Distances.CreateRangeAsync(distanceEntities);
- var distanceIds = distanceEntities.Select(e => e.Id);
- List<EventDistance> eventDistances = new List<EventDistance>();
- foreach (var id in distanceIds)
- {
- eventDistances.Add(new EventDistance
- {
- EventId = eventId,
- DistanceId = id
- });
- }
- await _uow.EventDistances.CreateRangeAsync(eventDistances);
- await _uow.SaveChangesAsync();
- }
- catch (NotFoundException)
- {
- throw;
- }
- catch (Exception e)
- {
- throw new UnexpectedException(e.Message);
- }
- }
- public async Task AddDistanceToEventAsync(long eventId, DistanceDTO distance, IFormFile file)
- {
- try
- {
- var eventItem = await _uow.Events.GetByIdAsync(eventId);
- if (eventItem == null)
- throw new NotFoundException("Мероприятие не найдено", "");
- string photoPath = "";
- if (file != null)
- photoPath = _fileWorkService.PhotoSave(file);
- var distanceEntity = _mapper.Map<Distance>(distance);
- _logger.LogInformation($"Mapped entity: {distanceEntity.ToString()}");
- distance.DistanceMap = photoPath;
- await _uow.Distances.CreateAsync(distanceEntity);
- await _uow.EventDistances.CreateAsync(new EventDistance
- {
- EventId = eventId,
- DistanceId = distanceEntity.Id
- });
- var eventParticipationTypes = await _uow.EventParticipantTypes.GetManyAsync(e => e.EventId == eventId);
- var eventParticipationTypeIds = eventParticipationTypes.Select(e => e.ParticipationTypeId);
- if (!eventParticipationTypeIds.Contains(distance.ParticipationTypeId))
- {
- await _uow.EventParticipantTypes.CreateAsync(new EventParticipantType
- {
- EventId = eventId,
- ParticipationTypeId = distance.ParticipationTypeId,
- });
- }
- await _uow.SaveChangesAsync();
- }
- catch (NotFoundException)
- {
- throw;
- }
- catch (Exception e)
- {
- throw new UnexpectedException(e.Message);
- }
- }
- public async Task DeleteEventDistanceAsync(long eventId, long distanceId)
- {
- try
- {
- var eventItem = await _uow.Events.GetByIdAsync(eventId);
- if (eventItem == null)
- throw new NotFoundException("Мероприятие не найдено", "");
- var distanceItem = await _uow.Distances.GetByIdAsync(distanceId);
- if (distanceItem == null)
- throw new NotFoundException("Дистанция не найдена", "");
- var eventDistances = await _uow.EventDistances.GetManyAsync(e =>
- e.EventId == eventId &&
- e.DistanceId != distanceId,
- d => d.Distance);
- var eventParticipationTypes = eventDistances.Select(e => e.Distance.ParticipationTypeId);
- if (!eventParticipationTypes.Contains(distanceItem.ParticipationTypeId))
- {
- var eventParticipantType = await _uow.EventParticipantTypes.GetAsync(e =>
- e.ParticipationTypeId == distanceItem.ParticipationTypeId);
- if (eventParticipantType != null)
- _uow.EventParticipantTypes.Remove(e =>
- e.ParticipationTypeId == distanceItem.ParticipationTypeId);
- }
- _uow.EventDistances.Remove(e => e.DistanceId == distanceId);
- _uow.Distances.RemoveById(distanceId);
- await _uow.SaveChangesAsync();
- }
- catch (NotFoundException)
- {
- throw;
- }
- catch (Exception e)
- {
- throw new UnexpectedException(e.Message);
- }
- }
- public async Task<DistanceViewDTO> GetEventDistanceByIdAsync(long eventId, long distanceId)
- {
- try
- {
- var eventItem = await _uow.Events.GetByIdAsync(eventId);
- if (eventItem == null)
- throw new NotFoundException("Мероприятие не найдено", "");
- var distanceItem = await _uow.Distances.GetByIdAsync(distanceId);
- if (distanceItem == null)
- throw new NotFoundException("Дистанция не найдена", "");
- var eventDistances = await _uow.EventDistances.Query()
- .Include(e => e.Distance)
- .ThenInclude(e => e.DistanceType)
- .Include(e => e.Distance)
- .ThenInclude(e => e.ParticipationType)
- .Where(e => e.EventId == eventId && e.DistanceId == distanceId)
- .FirstOrDefaultAsync();
- var result = _mapper.Map<DistanceViewDTO>(eventDistances);
- return result;
- }
- catch (NotFoundException)
- {
- throw;
- }
- catch (Exception e)
- {
- throw new UnexpectedException(e.Message);
- }
- }
- public async Task<IList<DistanceViewDTO>> GetEventDistancesAsync(long eventId)
- {
- try
- {
- var eventItem = await _uow.Events.GetByIdAsync(eventId);
- if (eventItem == null)
- throw new NotFoundException("Мероприятие не найдено", "");
- var eventDistances = await _uow.EventDistances.Query()
- .Include(e => e.Distance)
- .ThenInclude(e => e.DistanceType)
- .Include(e => e.Distance)
- .ThenInclude(e => e.ParticipationType)
- .Where(e => e.EventId == eventId)
- .ToListAsync();
- var result = _mapper.Map<IList<DistanceViewDTO>>(eventDistances);
- return result;
- }
- catch (NotFoundException)
- {
- throw;
- }
- catch (Exception e)
- {
- throw new UnexpectedException(e.Message);
- }
- }
- public async Task UpdateEventDistanceAsync(long eventId, long distanceId, DistanceDTO distance, IFormFile file)
- {
- try
- {
- var eventItem = await _uow.Events.GetByIdAsync(eventId);
- if (eventItem == null)
- throw new NotFoundException("Мероприятие не найдено", "");
- var distanceItem = await _uow.Distances.GetByIdAsync(distanceId);
- if (distanceItem == null)
- throw new NotFoundException("Дистанция не найдена", "");
- var eventDistance = await _uow.EventDistances.GetAsync(e => e.EventId == eventId && e.DistanceId == distanceId);
- if (eventDistance == null)
- throw new NotFoundException("Данная дистанция не принадлежит данному мероприятию", "");
- string photoPath = distanceItem.DistanceMap;
- if (file != null)
- photoPath = _fileWorkService.PhotoSave(file);
- _mapper.Map(distance, distanceItem);
- distanceItem.Id = distanceId;
- distanceItem.DistanceMap = photoPath;
- _logger.LogInformation($"Mapped entity while updating: {distanceItem.ToString()}");
- _uow.Distances.Update(distanceItem);
- var eventParticipationTypes = await _uow.EventParticipantTypes.GetManyAsync(e => e.EventId == eventId);
- var eventParticipationTypeIds = eventParticipationTypes.Select(e => e.ParticipationTypeId);
- if (!eventParticipationTypeIds.Contains(distance.ParticipationTypeId))
- {
- await _uow.EventParticipantTypes.CreateAsync(new EventParticipantType
- {
- EventId = eventId,
- ParticipationTypeId = distance.ParticipationTypeId,
- });
- }
- await _uow.SaveChangesAsync();
- }
- catch (NotFoundException)
- {
- throw;
- }
- catch (Exception e)
- {
- throw new UnexpectedException(e.Message);
- }
- }
- public async Task UpdateActiveStatusAsync(long eventId, bool isActive)
- {
- try
- {
- var eventItem = await _uow.Events.GetByIdAsync(eventId);
- if (eventItem == null)
- throw new NotFoundException("Мероприятие не найдено", "");
- eventItem.IsActive = isActive;
- _uow.Events.Update(eventItem);
- await _uow.SaveChangesAsync();
- }
- catch (NotFoundException)
- {
- throw;
- }
- catch (Exception e)
- {
- throw new UnexpectedException(e.Message);
- }
- }
- #endregion
- public async Task<IList<DistanceViewDTO>> GetDistancesByParticipationType(long eventId, long participationType)
- {
- try
- {
- var eventItem = await _uow.Events.GetByIdAsync(eventId);
- if (eventItem == null)
- throw new NotFoundException("Мероприятие не найдео", "");
- var eventDistances = await _uow.EventDistances.Query()
- .Include(e => e.Distance)
- .ThenInclude(e => e.DistanceType)
- .Include(e => e.Distance)
- .ThenInclude(e => e.ParticipationType)
- .Where(e => e.EventId == eventId && e.Distance.ParticipationTypeId == participationType)
- .ToListAsync();
- if (eventDistances.Count == 0)
- {
- throw new NotFoundException("Дистанции не найдены", "");
- }
- var result = _mapper.Map<IList<DistanceViewDTO>>(eventDistances);
- return result;
- }
- catch (NotFoundException)
- {
- throw;
- }
- catch (Exception e)
- {
- throw new UnexpectedException(e.Message);
- }
- }
- public async Task<IList<EventDTO>> GetEventsByParticipationType(long participationType)
- {
- try
- {
- var eventIds = await _uow.EventParticipantTypes.Query()
- .Where(e => e.ParticipationTypeId == participationType)
- .Select(e => e.EventId)
- .ToListAsync();
- var events = await _uow.Events.Query()
- .IncludeEventRelatedData()
- .Where(e => e.IsActive && eventIds.Contains(e.Id))
- .ToListAsync();
- var result = _mapper.Map<IList<EventDTO>>(events);
- return result;
- }
- catch (NotFoundException)
- {
- throw;
- }
- catch (Exception e)
- {
- throw new UnexpectedException(e.Message);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement