-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathEventService.cs
More file actions
639 lines (538 loc) · 22.3 KB
/
EventService.cs
File metadata and controls
639 lines (538 loc) · 22.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using AutoMapper;
using EventsExpress.Core.DTOs;
using EventsExpress.Core.Exceptions;
using EventsExpress.Core.Extensions;
using EventsExpress.Core.IServices;
using EventsExpress.Core.Notifications;
using EventsExpress.Db.Bridge;
using EventsExpress.Db.EF;
using EventsExpress.Db.Entities;
using EventsExpress.Db.Enums;
using FluentValidation;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using NetTopologySuite.Geometries;
namespace EventsExpress.Core.Services
{
public class EventService : BaseService<Event>, IEventService
{
private readonly IPhotoService _photoService;
private readonly ILocationService _locationService;
private readonly IMediator _mediator;
private readonly IEventScheduleService _eventScheduleService;
private readonly IValidator<Event> _validator;
private readonly ISecurityContext _securityContextService;
public EventService(
AppDbContext context,
IMapper mapper,
IMediator mediator,
IPhotoService photoService,
ILocationService locationService,
IEventScheduleService eventScheduleService,
IValidator<Event> validator,
ISecurityContext securityContextService)
: base(context, mapper)
{
_photoService = photoService;
_locationService = locationService;
_mediator = mediator;
_eventScheduleService = eventScheduleService;
_validator = validator;
_securityContextService = securityContextService;
}
public async Task AddUserToEvent(Guid userId, Guid eventId)
{
if (!Context.Events.Any(e => e.Id == eventId))
{
throw new EventsExpressException("Event not found!");
}
var ev = Context.Events
.Include(e => e.Visitors)
.First(e => e.Id == eventId);
if (ev.MaxParticipants <= ev.Visitors.Count)
{
throw new EventsExpressException("Too much participants!");
}
var us = Context.Users.Find(userId);
if (us == null)
{
throw new EventsExpressException("User not found!");
}
Context.UserEvent.Add(new UserEvent
{
EventId = eventId,
UserId = userId,
UserStatusEvent = ev.IsPublic.Value ? UserStatusEvent.Approved : UserStatusEvent.Pending,
});
await Context.SaveChangesAsync();
}
public async Task ChangeVisitorStatus(Guid userId, Guid eventId, UserStatusEvent status)
{
var userEvent = Context.UserEvent
.Where(x => x.EventId == eventId && x.UserId == userId)
.FirstOrDefault();
userEvent.UserStatusEvent = status;
Context.UserEvent.Update(userEvent);
await Context.SaveChangesAsync();
await _mediator.Publish(new ParticipationMessage(userEvent.UserId, userEvent.EventId, status));
}
public async Task DeleteUserFromEvent(Guid userId, Guid eventId)
{
var ev = Context.Events
.Include(e => e.Visitors)
.FirstOrDefault(e => e.Id == eventId);
if (ev == null)
{
throw new EventsExpressException("Event not found!");
}
var uei = Context.UserEventInventories.Where(ue => ue.UserId == userId).ToArray();
if (uei != null)
{
Context.UserEventInventories.RemoveRange(uei);
}
var v = ev.Visitors?.FirstOrDefault(x => x.UserId == userId);
if (v != null)
{
ev.Visitors.Remove(v);
await Context.SaveChangesAsync();
}
else
{
throw new EventsExpressException("Visitor not found!");
}
}
public Guid CreateDraft()
{
var ev = new Event();
ev.StatusHistory = new List<EventStatusHistory>
{
new EventStatusHistory
{
EventStatus = EventStatus.Draft,
CreatedOn = DateTime.UtcNow,
UserId = CurrentUserId(),
},
};
ev.Owners = new List<EventOwner>
{
new EventOwner
{
UserId = CurrentUserId(),
EventId = ev.Id,
},
};
var result = Insert(ev);
Context.SaveChanges();
return result.Id;
}
public async Task<Guid> Create(EventDto eventDTO)
{
eventDTO.DateFrom = (eventDTO.DateFrom == DateTime.MinValue) ? DateTime.Today : eventDTO.DateFrom;
eventDTO.DateTo = (eventDTO.DateTo < eventDTO.DateFrom) ? eventDTO.DateFrom : eventDTO.DateTo;
var locationDTO = Mapper.Map<EventDto, LocationDto>(eventDTO);
var locationId = await _locationService.AddLocationToEvent(locationDTO);
var ev = Mapper.Map<EventDto, Event>(eventDTO);
ev.EventLocationId = locationId;
ev.StatusHistory = new List<EventStatusHistory>
{
new EventStatusHistory
{
EventStatus = EventStatus.Active,
CreatedOn = DateTime.UtcNow,
UserId = CurrentUserId(),
},
};
ev.Owners = new List<EventOwner>
{
new EventOwner
{
UserId = CurrentUserId(),
EventId = eventDTO.Id,
},
};
var eventCategories = eventDTO.Categories?
.Select(x => new EventCategory { Event = ev, CategoryId = x.Id })
.ToList();
ev.Categories = eventCategories;
var result = Insert(ev);
eventDTO.Id = result.Id;
await Context.SaveChangesAsync();
await _mediator.Publish(new EventCreatedMessage(eventDTO));
await _photoService.ChangeTempToImagePhoto(eventDTO.Id);
return result.Id;
}
public async Task<Guid> CreateNextEvent(Guid eventId)
{
var eventDTO = EventById(eventId);
var eventScheduleDTO = _eventScheduleService.EventScheduleByEventId(eventId);
var ticksDiff = eventDTO.DateTo.Value.Ticks - eventDTO.DateFrom.Value.Ticks;
eventDTO.Id = Guid.Empty;
eventDTO.Owners = null;
eventDTO.Inventories = null;
eventDTO.IsReccurent = false;
eventDTO.DateFrom = eventScheduleDTO.NextRun;
eventDTO.DateTo = eventDTO.DateFrom.Value.AddTicks(ticksDiff);
eventScheduleDTO.LastRun = eventDTO.DateTo.Value;
eventScheduleDTO.NextRun = DateTimeExtensions
.AddDateUnit(eventScheduleDTO.Periodicity, eventScheduleDTO.Frequency, eventDTO.DateTo.Value);
await _eventScheduleService.Edit(eventScheduleDTO);
var createResult = await Create(eventDTO);
return createResult;
}
private async Task<Guid> InternalEdit(EventDto e)
{
var ev = Context.Events
.Include(e => e.EventLocation)
.Include(e => e.Categories)
.ThenInclude(c => c.Category)
.Include(e => e.EventSchedule)
.FirstOrDefault(x => x.Id == e.Id);
if (e.OnlineMeeting != null || e.Point != null)
{
var locationDTO = Mapper.Map<EventDto, LocationDto>(e);
var locationId = await _locationService.AddLocationToEvent(locationDTO);
ev.EventLocationId = locationId;
}
if (e.IsReccurent)
{
if (e.EventStatus == EventStatus.Draft)
{
if (ev.EventSchedule == null)
{
await _eventScheduleService.Create(Mapper.Map<EventScheduleDto>(e));
}
else
{
var eventScheduleDTO = Mapper.Map<EventScheduleDto>(e);
eventScheduleDTO.Id = ev.EventSchedule.Id;
await _eventScheduleService.Edit(eventScheduleDTO);
}
}
}
else
{
if (ev.EventSchedule != null)
{
await _eventScheduleService.Delete(ev.EventSchedule.Id);
}
}
ev.Title = e.Title;
ev.MaxParticipants = e.MaxParticipants;
ev.Description = e.Description;
ev.DateFrom = e.DateFrom;
ev.DateTo = e.DateTo;
ev.IsPublic = e.IsPublic;
ev.IsMultiEvent = e.IsMultiEvent;
var eventCategories = e.Categories?.Select(x => new EventCategory { Event = ev, CategoryId = x.Id })
.ToList();
ev.Categories = eventCategories;
await Context.SaveChangesAsync();
await _photoService.ChangeTempToImagePhoto(e.Id);
return ev.Id;
}
public async Task<Guid> Edit(EventDto eventInstance)
{
if (eventInstance.Events.CollectionIsNullOrEmpty())
{
await InternalEdit(eventInstance);
}
else
{
eventInstance.IsMultiEvent = true;
await InternalEdit(eventInstance);
ChildEventDto[] childEventDtos = eventInstance.Events.ToArray();
EventDto[] childs = new EventDto[childEventDtos.Length];
for (int i = 0; i < childEventDtos.Length; i++)
{
childs[i] = Mapper.Map<ChildEventDto, EventDto>(childEventDtos[i]);
childs[i].Id = CreateDraft();
childs[i].IsMultiEvent = true;
childs[i].Inventories = eventInstance.Inventories;
childs[i].IsPublic = eventInstance.IsPublic;
childs[i].IsReccurent = eventInstance.IsReccurent;
childs[i].MaxParticipants = eventInstance.MaxParticipants;
childs[i].Categories = eventInstance.Categories;
Context.MultiEventStatus.Add(
new MultiEventStatus
{
ParentId = eventInstance.Id,
ChildId = childs[i].Id,
});
await InternalEdit(childs[i]);
}
}
return eventInstance.Id;
}
private void InternalPublish(Guid eventId)
{
var ev = Context.Events
.Include(e => e.EventLocation)
.Include(e => e.StatusHistory)
.Include(e => e.Categories)
.ThenInclude(c => c.Category)
.FirstOrDefault(x => x.Id == eventId);
if (ev == null)
{
throw new EventsExpressException("Not found");
}
ev.StatusHistory.Add(
new EventStatusHistory
{
EventStatus = EventStatus.Active,
CreatedOn = DateTime.UtcNow,
UserId = CurrentUserId(),
});
}
public async Task<Guid> Publish(Guid eventId)
{
var ev = Context.Events.FirstOrDefault(x => x.Id == eventId);
InternalPublish(eventId);
if (ev.IsMultiEvent == true)
{
var childsId = Context.MultiEventStatus
.Where(x => x.ParentId == eventId)
.Select(x => x.ChildId)
.ToArray();
foreach (var item in childsId)
{
InternalPublish(item);
}
}
await Context.SaveChangesAsync();
EventDto dtos = Mapper.Map<Event, EventDto>(ev);
await _mediator.Publish(new EventCreatedMessage(dtos));
return eventId;
}
public async Task<Guid> EditNextEvent(EventDto eventDTO)
{
var eventScheduleDTO = _eventScheduleService.EventScheduleByEventId(eventDTO.Id);
eventScheduleDTO.LastRun = eventDTO.DateTo.Value;
eventScheduleDTO.NextRun = DateTimeExtensions
.AddDateUnit(eventScheduleDTO.Periodicity, eventScheduleDTO.Frequency, eventDTO.DateTo.Value);
await _eventScheduleService.Edit(eventScheduleDTO);
eventDTO.IsReccurent = false;
eventDTO.Id = Guid.Empty;
var createResult = await Create(eventDTO);
return createResult;
}
public EventDto EventById(Guid eventId)
{
var request = Context.Events
.Include(e => e.EventLocation)
.Include(e => e.Owners)
.ThenInclude(o => o.User)
.ThenInclude(u => u.Relationships)
.Include(e => e.Categories)
.ThenInclude(c => c.Category)
.Include(e => e.Inventories)
.ThenInclude(i => i.UnitOfMeasuring)
.Include(e => e.Visitors)
.ThenInclude(v => v.User)
.ThenInclude(u => u.Relationships)
.Include(e => e.StatusHistory)
.Include(e => e.EventSchedule)
.Include(e => e.ChildEvents)
.ThenInclude(e => e.ChildEvent)
.ThenInclude(e => e.EventLocation)
.FirstOrDefault(x => x.Id == eventId);
var res = Mapper.Map<EventDto>(request);
return res;
}
public IEnumerable<EventDto> GetAll(EventFilterViewModel model, out int count)
{
var events = Context.Events
.Include(e => e.EventLocation)
.Include(e => e.StatusHistory)
.Include(e => e.Owners)
.ThenInclude(o => o.User)
.Include(e => e.Categories)
.ThenInclude(c => c.Category)
.Include(e => e.Visitors)
.ThenInclude(v => v.User)
.ThenInclude(u => u.Relationships)
.Include(e => e.StatusHistory)
.AsNoTracking()
.AsQueryable();
events = events.Where(x => x.StatusHistory.OrderBy(h => h.CreatedOn).Last().EventStatus != EventStatus.Draft);
events = !string.IsNullOrEmpty(model.KeyWord)
? events.Where(x => x.Title.Contains(model.KeyWord)
|| x.Description.Contains(model.KeyWord))
: events;
events = (model.DateFrom != DateTime.MinValue)
? events.Where(x => x.DateFrom >= model.DateFrom)
: events;
events = (model.DateTo != DateTime.MinValue)
? events.Where(x => x.DateTo <= model.DateTo)
: events;
events = (model.OwnerId != null)
? events.Where(x => x.Owners.Any(c => c.UserId == model.OwnerId))
: events;
events = (model.VisitorId != null)
? events.Where(x => x.Visitors.Any(v => v.UserId == model.VisitorId))
: events;
events = (model.X != null && model.Y != null && model.Radius != null)
? events.Where(x => (x.EventLocation.Point.Distance(new Point((double)model.X, (double)model.Y) { SRID = 4326 }) / 1000) - (double)model.Radius <= 0)
: events;
events = (model.Statuses != null)
? events.Where(e => model.Statuses.Contains(e.StatusHistory
.OrderByDescending(n => n.CreatedOn)
.FirstOrDefault()
.EventStatus))
: events;
if (model.Categories != null)
{
List<Guid> categoryIds = model.Categories
.Select(x => Guid.TryParse(x, out Guid item) ? item : Guid.Empty)
.Where(x => x != Guid.Empty)
.ToList();
events = events.Where(x =>
x.Categories.Any(category =>
categoryIds.Contains(category.CategoryId)));
}
count = events.Count();
var result = events
.OrderBy(x => x.DateFrom)
.Skip((model.Page - 1) * model.PageSize)
.Take(model.PageSize).ToList();
return Mapper.Map<IEnumerable<EventDto>>(result);
}
public IEnumerable<EventDto> GetAllDraftEvents(int page, int pageSize, out int count)
{
var events = Context.Events
.Include(e => e.EventLocation)
.Include(e => e.StatusHistory)
.Include(e => e.Owners)
.ThenInclude(o => o.User)
.Include(e => e.Categories)
.ThenInclude(c => c.Category)
.Include(e => e.Visitors)
.AsNoTracking()
.AsQueryable();
events = events.Where(x => x.StatusHistory.OrderBy(h => h.CreatedOn).Last().EventStatus == EventStatus.Draft);
events = events.Where(x => x.Owners.Any(o => o.UserId == CurrentUserId()));
count = events.Count();
var result = events.OrderBy(x => x.DateFrom).Skip((page - 1) * pageSize).Take(pageSize).ToList();
return Mapper.Map<IEnumerable<Event>, IEnumerable<EventDto>>(result);
}
public IEnumerable<EventDto> FutureEventsByUserId(Guid userId, PaginationViewModel paginationViewModel)
{
var filter = new EventFilterViewModel
{
OwnerId = userId,
DateFrom = DateTime.Today,
Page = paginationViewModel.Page,
PageSize = paginationViewModel.PageSize,
};
var events = this.GetAll(filter, out int count);
paginationViewModel.Count = count;
return events;
}
public IEnumerable<EventDto> PastEventsByUserId(Guid userId, PaginationViewModel paginationViewModel)
{
var filter = new EventFilterViewModel
{
OwnerId = userId,
DateTo = DateTime.Today,
Page = paginationViewModel.Page,
PageSize = paginationViewModel.PageSize,
};
var events = this.GetAll(filter, out int count);
paginationViewModel.Count = count;
return events;
}
public IEnumerable<EventDto> VisitedEventsByUserId(Guid userId, PaginationViewModel paginationViewModel)
{
var filter = new EventFilterViewModel
{
VisitorId = userId,
DateTo = DateTime.Today,
Page = paginationViewModel.Page,
PageSize = paginationViewModel.PageSize,
};
var events = this.GetAll(filter, out int count);
paginationViewModel.Count = count;
return events;
}
public IEnumerable<EventDto> EventsToGoByUserId(Guid userId, PaginationViewModel paginationViewModel)
{
var filter = new EventFilterViewModel
{
VisitorId = userId,
DateFrom = DateTime.Today,
Page = paginationViewModel.Page,
PageSize = paginationViewModel.PageSize,
};
var events = this.GetAll(filter, out int count);
paginationViewModel.Count = count;
return events;
}
public IEnumerable<EventDto> GetEvents(List<Guid> eventIds, PaginationViewModel paginationViewModel)
{
var events = Context.Events
.Include(e => e.EventLocation)
.Include(e => e.Owners)
.ThenInclude(o => o.User)
.Include(e => e.Categories)
.ThenInclude(c => c.Category)
.Include(e => e.Visitors)
.Include(e => e.StatusHistory)
.Where(x => eventIds.Contains(x.Id))
.AsNoTracking()
.AsQueryable();
paginationViewModel.Count = events.Count();
events = events.Skip((paginationViewModel.Page - 1) * paginationViewModel.PageSize)
.Take(paginationViewModel.PageSize);
return Mapper.Map<IEnumerable<EventDto>>(events);
}
public async Task SetRate(Guid userId, Guid eventId, byte rate)
{
var ev = Context.Events
.Include(e => e.Rates)
.FirstOrDefault(e => e.Id == eventId);
ev.Rates ??= new List<Rate>();
var currentRate = ev.Rates.FirstOrDefault(x => x.UserFromId == userId && x.EventId == eventId);
if (currentRate == null)
{
ev.Rates.Add(new Rate { EventId = eventId, UserFromId = userId, Score = rate });
}
else
{
currentRate.Score = rate;
}
await Context.SaveChangesAsync();
}
public byte GetRateFromUser(Guid userId, Guid eventId)
{
return Context.Rates
.FirstOrDefault(r => r.UserFromId == userId && r.EventId == eventId)
?.Score ?? 0;
}
public double GetRate(Guid eventId)
{
try
{
return Context.Rates
.Where(r => r.EventId == eventId)
.Average(r => r.Score);
}
catch (Exception)
{
return 0;
}
}
public bool UserIsVisitor(Guid userId, Guid eventId) =>
Context.Events
.Include(e => e.Visitors)
.FirstOrDefault(e => e.Id == eventId)?.Visitors
?.FirstOrDefault(v => v.UserId == userId) != null;
public bool Exists(Guid eventId) => Context.Events.Find(eventId) != null;
private Guid CurrentUserId() =>
_securityContextService.GetCurrentUserId();
}
}