Skip to content

Commit

Permalink
Workshop service uses automapper everywhere
Browse files Browse the repository at this point in the history
  • Loading branch information
Bogdan-Hasanov committed Sep 27, 2021
1 parent 121e997 commit 069cd96
Show file tree
Hide file tree
Showing 7 changed files with 42 additions and 35 deletions.
4 changes: 3 additions & 1 deletion OutOfSchool/OutOfSchool.DataAccess/Models/DateTimeRange.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using OutOfSchool.Services.Enums;

namespace OutOfSchool.Services.Models
Expand All @@ -13,7 +14,8 @@ public class DateTimeRange
public TimeSpan EndTime { get; set; }

public long WorkshopId { get; set; }


[Required]
public List<DaysBitMask> Workdays { get; set; }
}
}
4 changes: 2 additions & 2 deletions OutOfSchool/OutOfSchool.DataAccess/OutOfSchoolDbContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -123,8 +123,8 @@ protected override void OnModelCreating(ModelBuilder builder)

builder.Entity<DateTimeRange>()
.Property(range => range.Workdays)
.HasConversion<byte>(
list => (byte) list.Aggregate((prev, next) => prev | next),
.HasConversion(
list => (byte)list.Aggregate((prev, next) => prev | next),
mask =>
Enum.GetValues(typeof(DaysBitMask)).Cast<DaysBitMask>().ToList()
.Where(amenity => amenity != 0 && ((DaysBitMask) mask).HasFlag(amenity)).ToList(),
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ protected override void Up(MigrationBuilder migrationBuilder)
StartTime = table.Column<TimeSpan>(type: "time", nullable: false),
EndTime = table.Column<TimeSpan>(type: "time", nullable: false),
WorkshopId = table.Column<long>(type: "bigint", nullable: false),
Workdays = table.Column<byte>(type: "tinyint", nullable: true)
Workdays = table.Column<byte>(type: "tinyint", nullable: false)
},
constraints: table =>
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -440,7 +440,7 @@ protected override void BuildModel(ModelBuilder modelBuilder)
b.Property<TimeSpan>("StartTime")
.HasColumnType("time");

b.Property<byte?>("Workdays")
b.Property<byte>("Workdays")
.HasColumnType("tinyint");

b.Property<long>("WorkshopId")
Expand Down
7 changes: 7 additions & 0 deletions OutOfSchool/OutOfSchool.WebApi/Models/WorkshopDTO.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using Castle.Core.Internal;
using OutOfSchool.Services.Enums;

namespace OutOfSchool.WebApi.Models
Expand Down Expand Up @@ -118,6 +119,12 @@ public IEnumerable<ValidationResult> Validate(ValidationContext validationContex
"End date can't be earlier that start date");
}

if (dateTimeRange.Workdays.IsNullOrEmpty())
{
yield return new ValidationResult(
"Workdays are required");
}

var daysHs = new HashSet<DaysBitMask>();
if (!dateTimeRange.Workdays.All(daysHs.Add))
{
Expand Down
54 changes: 26 additions & 28 deletions OutOfSchool/OutOfSchool.WebApi/Services/Database/WorkshopService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -68,35 +68,34 @@ public async Task<WorkshopDTO> Create(WorkshopDTO dto)
// In case if DirectionId and DepartmentId does not match ClassId
await this.FillDirectionsFields(dto).ConfigureAwait(false);

Func<Task<Workshop>> operation = async () => await workshopRepository.Create(dto.ToDomain()).ConfigureAwait(false);
Func<Task<Workshop>> operation = async () =>
await workshopRepository.Create(mapper.Map<Workshop>(dto)).ConfigureAwait(false);

var newWorkshop = await workshopRepository.RunInTransaction(operation).ConfigureAwait(false);

logger.LogInformation($"Workshop with Id = {newWorkshop?.Id} created successfully.");

return newWorkshop.ToModel();
return mapper.Map<WorkshopDTO>(newWorkshop);
}

/// <inheritdoc/>
public async Task<SearchResult<WorkshopDTO>> GetAll(OffsetFilter offsetFilter)
{
logger.LogInformation("Getting all Workshops started.");

if (offsetFilter is null)
{
offsetFilter = new OffsetFilter();
}
offsetFilter ??= new OffsetFilter();

var count = await workshopRepository.Count().ConfigureAwait(false);
var workshops = workshopRepository.Get<long>(skip: offsetFilter.From, take: offsetFilter.Size, orderBy: x => x.Id, ascending: true).ToList();
var workshops = workshopRepository.Get<long>(skip: offsetFilter.From, take: offsetFilter.Size,
orderBy: x => x.Id, ascending: true).ToList();

logger.LogInformation(!workshops.Any()
? "Workshop table is empty."
: $"All {workshops.Count} records were successfully received from the Workshop table");

var workshopsDTO = workshops.Select(x => x.ToModel()).ToList();
var workshopsDTO = mapper.Map<List<WorkshopDTO>>(workshops);
var workshopsWithRating = GetWorkshopsWithAverageRating(workshopsDTO);
return new SearchResult<WorkshopDTO>() { TotalAmount = count, Entities = workshopsWithRating };
return new SearchResult<WorkshopDTO>() {TotalAmount = count, Entities = workshopsWithRating};
}

/// <inheritdoc/>
Expand Down Expand Up @@ -134,7 +133,7 @@ public async Task<IEnumerable<WorkshopDTO>> GetByProviderId(long id)
? $"There aren't Workshops for Provider with Id = {id}."
: $"From Workshop table were successfully received {workshops.Count()} records.");

var workshopsDTO = workshops.Select(x => x.ToModel()).ToList();
var workshopsDTO = mapper.Map<List<WorkshopDTO>>(workshops);

return GetWorkshopsWithAverageRating(workshopsDTO);
}
Expand All @@ -146,7 +145,15 @@ public async Task<WorkshopDTO> Update(WorkshopDTO dto)
{
logger.LogInformation($"Updating Workshop with Id = {dto?.Id} started.");

// In case if DirectionId and DepartmentId does not match ClassId
await this.FillDirectionsFields(dto).ConfigureAwait(false);

var currentWorkshop = await workshopRepository.GetWithNavigations(dto!.Id).ConfigureAwait(false);

// In case if AddressId was changed. AddresId is one and unique for workshop.
dto.AddressId = currentWorkshop.AddressId;
dto.Address.Id = currentWorkshop.AddressId;

mapper.Map(dto, currentWorkshop);
try
{
Expand All @@ -156,20 +163,8 @@ public async Task<WorkshopDTO> Update(WorkshopDTO dto)
{
logger.LogError($"Updating failed. Exception: {exception.Message}");
throw;
}

// // In case if DirectionId and DepartmentId does not match ClassId
// await this.FillDirectionsFields(dto).ConfigureAwait(false);
//
// // In case if AddressId was changed. AddresId is one and unique for workshop.
// dto.AddressId = workshop.AddressId;
// dto.Address.Id = workshop.AddressId;
//
// // In case if WorkshopId of teachers was changed.
// foreach (var teacher in dto.Teachers)
// {
// teacher.WorkshopId = workshop.Id;
// }
}

return mapper.Map<WorkshopDTO>(currentWorkshop);
}

Expand Down Expand Up @@ -209,13 +204,14 @@ public async Task<SearchResult<WorkshopDTO>> GetByFilter(WorkshopFilter filter =
var orderBy = GetOrderParameter(filter);

var workshopsCount = await workshopRepository.Count(where: filterPredicate).ConfigureAwait(false);
var workshops = workshopRepository.Get<dynamic>(filter.From, filter.Size, string.Empty, filterPredicate, orderBy.Item1, orderBy.Item2).ToList();
var workshops = workshopRepository.Get<dynamic>(filter.From, filter.Size, string.Empty, filterPredicate,
orderBy.Item1, orderBy.Item2).ToList();

logger.LogInformation(!workshops.Any()
? "There was no matching entity found."
: $"All matching {workshops.Count} records were successfully received from the Workshop table");

var workshopsDTO = workshops.Select(x => x.ToModel()).ToList();
var workshopsDTO = mapper.Map<List<WorkshopDTO>>(workshops);

var result = new SearchResult<WorkshopDTO>()
{
Expand Down Expand Up @@ -269,7 +265,8 @@ private Expression<Func<Workshop, bool>> PredicateBuild(WorkshopFilter filter)
}
else if (filter.IsFree && !(filter.MinPrice == 0 && filter.MaxPrice == int.MaxValue))
{
predicate = predicate.And(x => (x.Price >= filter.MinPrice && x.Price <= filter.MaxPrice) || x.Price == 0);
predicate = predicate.And(x =>
(x.Price >= filter.MinPrice && x.Price <= filter.MaxPrice) || x.Price == 0);
}

if (filter.MinAge != 0 || filter.MaxAge != 100)
Expand Down Expand Up @@ -336,7 +333,8 @@ private async Task FillDirectionsFields(WorkshopDTO dto)

private List<WorkshopDTO> GetWorkshopsWithAverageRating(List<WorkshopDTO> workshopsDTOs)
{
var averageRatings = ratingService.GetAverageRatingForRange(workshopsDTOs.Select(p => p.Id), RatingType.Workshop);
var averageRatings =
ratingService.GetAverageRatingForRange(workshopsDTOs.Select(p => p.Id), RatingType.Workshop);

if (averageRatings != null)
{
Expand Down

0 comments on commit 069cd96

Please sign in to comment.