From 1ef8e0c0aaddde902220a0dc3f282581f4fca1a4 Mon Sep 17 00:00:00 2001 From: Phuc Nghi Date: Fri, 28 Jun 2024 07:59:28 +0700 Subject: [PATCH 1/3] update --- DeerCoffeeShop.API/.config/dotnet-tools.json | 12 + DeerCoffeeShop.API/.env | 1 - .../ApiVersionSwaggerGenOptions.cs | 4 +- .../ApiVersioningConfiguration.cs | 2 +- .../ApplicationSecurityConfiguration.cs | 10 +- .../Configuration/CorsConfiguration.cs | 2 +- .../ProblemDetailsConfiguration.cs | 8 +- .../Configuration/SwashbuckleConfiguration.cs | 26 +- .../Controllers/EmployeeController.cs | 17 +- .../EmployeeShift/EmployeeShiftController.cs | 278 ++++++++++-------- .../Controllers/Form/FormController.cs | 7 +- .../ImageController/ImageController.cs | 6 +- .../RestaurantChainController.cs | 21 +- .../RestaurantController.cs | 25 +- .../Controllers/Shift/ShiftController.cs | 13 +- DeerCoffeeShop.API/DeerCoffeeShop.API.csproj | 1 - .../Filters/AuthorizeCheckOperationFilter.cs | 9 +- DeerCoffeeShop.API/Filters/ExceptionFilter.cs | 2 +- DeerCoffeeShop.API/Program.cs | 19 +- .../Services/CurrentUserService.cs | 3 +- DeerCoffeeShop.API/Services/JwtService.cs | 10 +- .../Authentication/Login/LoginQueryHandler.cs | 10 +- .../Authentication/LoginDTO.cs | 2 +- .../LoginRestaurant/LoginRestaurantQuery.cs | 23 +- .../RefreshTokenCommandHandler.cs | 6 +- .../Behaviours/AuthorizationBehaviour.cs | 18 +- .../Common/Behaviours/LoggingBehaviour.cs | 6 +- .../Common/Behaviours/PerformanceBehaviour.cs | 10 +- .../Behaviours/UnhandledExceptionBehaviour.cs | 2 +- .../Common/Behaviours/UnitOfWorkBehaviour.cs | 6 +- .../Common/Behaviours/ValidationBehaviour.cs | 6 +- .../Common/Mappings/MappingProfile.cs | 10 +- .../PagedResultMappingExtensions.cs | 2 +- .../DependencyInjection.cs | 22 +- .../AssignEmployee/AssignEmployeeCommand.cs | 36 +++ .../CheckIn-Out/CheckIn/CheckInCommand.cs | 31 +- .../CheckIn-Out/CheckOut/CheckOutCommand.cs | 20 +- .../CreateEmployeeShiftCommandHandler.cs | 11 +- .../CreateEmployeeShiftCommandValidator.cs | 19 +- .../DeleteEmployeeShiftCommandHandler.cs | 4 +- .../DeleteEmployeeShiftCommandValidator.cs | 6 +- .../EmployeeShift/EmployeeShiftDto.cs | 5 +- .../EmployeeShiftDtoMappingExtension.cs | 4 +- .../EmployeeShift/EmployeeShiftDtoV2.cs | 10 +- .../GetAll/GetAllEmployeeShiftQueryHandler.cs | 8 +- .../GetAllEmployeeShiftQueryValidator.cs | 6 +- .../GetByDay/GetEmployeeShiftByDayQuery.cs | 11 +- .../GetEmployeeShiftByDayQueryHandler.cs | 12 +- .../GetEmployeeShiftByDayQueryValidator.cs | 11 +- ...etEmployeeShiftByEmployeeIdQueryHandler.cs | 8 +- ...EmployeeShiftByEmployeeIdQueryValidator.cs | 2 +- .../GetEmployeeShiftInAWeekQuery.cs | 36 +-- .../GetNeededReviewShiftQuery.cs | 50 ++++ .../UpdateEmployeeShiftCommand.cs | 9 +- .../UpdateEmployeeShiftCommandHandler.cs | 21 +- .../UpdateEmployeeShiftCommandValidator.cs | 15 +- .../CreateEmployeeCommandHandler.cs | 15 +- .../CreateEmployeeCommandValidator.cs | 6 +- .../DeleteEmployee/DeleteEmployeeCommand.cs | 1 - .../DeleteEmployeeCommandHandler.cs | 2 +- .../DeleteEmployeeCommandValidator.cs | 2 +- .../Employees/EmployeeDTO.cs | 6 +- .../Employees/EmployeeMappingExtensions.cs | 4 +- .../GetAllEmployeeQueryHandler.cs | 17 +- .../GetEmployee/GetEmployeeQueryHandler.cs | 10 +- .../GetEmployee/GetEmployeeQueryValidator.cs | 2 +- .../GetEmployeeInfo/GetEmployeeInfoQuery.cs | 11 +- .../UpdateEmployee/UpdateEmployeeCommand.cs | 1 - .../UpdateEmployeeCommandHandler.cs | 2 +- .../UpdateEmployeeCommandValidator.cs | 6 +- .../DetecFaceFromImageQuery.cs | 5 - .../FaceID/SaveImage/SaveImageCommand.cs | 8 +- ...cceptEmployeeAndGeneratePasswordCommand.cs | 13 +- .../AcceptFormAndSendMailCommand.cs | 11 +- DeerCoffeeShop.Application/Forms/FormDto.cs | 9 +- .../Forms/FromDtoMappingExstension.cs | 6 - .../GetAllPagination/GetAllFormPagination.cs | 26 +- .../CreateRestaurantChainCommandHandler.cs | 14 +- .../CreateRestaurantChainCommandValidator.cs | 8 +- .../DeleteRestaurantChainCommandHandler.cs | 14 +- .../DeleteRestaurantChainCommandValidator.cs | 2 +- .../GetRestaurantChainByAdminQuery.cs | 11 +- .../GetRestaurantChainByAdminQueryHandler.cs | 16 +- ...GetRestaurantChainByAdminQueryValidator.cs | 11 +- .../GetRestaurantChainByDeactiveQuery.cs | 9 +- ...etRestaurantChainByDeactiveQueryHandler.cs | 17 +- .../GetRestaurantChainByIDQuery.cs | 7 +- .../GetRestaurantChainByIDQueryHandler.cs | 15 +- .../GetRestaurantChainByIDQueryValidator.cs | 7 +- .../GetRestautantChainByNameQuery.cs | 4 +- .../GetRestautantChainByNameQueryHandler.cs | 20 +- .../GetRestautantChainByNameQueryValidator.cs | 4 +- .../InactiveRestaurantChainCommand.cs | 7 +- .../InactiveRestaurantChainCommandHandler.cs | 13 +- ...InactiveRestaurantChainCommandValidator.cs | 7 +- .../RestaurantChains/RestaurantChainDTO.cs | 2 +- .../UpdateRestautantChainCommand.cs | 2 +- .../UpdateRestautantChainCommandHandler.cs | 6 +- .../UpdateRestautantChainCommandValidator.cs | 2 +- .../AddManagerToRestaurantCommandHandler.cs | 14 +- .../AddStaffToRestaurantCommandValidator.cs | 4 +- .../CreateRestaurantCommandHandler.cs | 11 +- .../CreateRestaurantCommandValidator.cs | 8 +- .../DeleteRestaurantCommandHandler.cs | 10 +- .../DeleteRestaurantCommandValidator.cs | 2 +- .../FillterByReschainAndManagerIDQuery.cs | 4 +- ...llterByReschainAndManagerIDQueryHandler.cs | 12 +- .../Restaurants/Get/GetRestaurantQuery.cs | 9 +- .../GetAllRestaurantIsactiveHandler.cs | 11 +- .../GetAllRestaurantIsactiveQuery.cs | 7 +- .../GetRestaurantByDeactiveQuery.cs | 11 +- .../GetRestaurantByDeactiveQueryHandler.cs | 9 +- .../GetRestaurantIsLowEmpQueryHandler.cs | 4 +- .../GetRestaurantByIDQuery.cs | 3 +- .../GetRestaurantByIDQueryHandler.cs | 10 +- .../InactiveRestaurantCommand.cs | 7 +- .../InactiveRestaurantCommandHandler.cs | 11 +- .../InactiveRestaurantCommandValidator.cs | 7 +- .../Restaurants/RestaurantDTO.cs | 2 +- .../UpdateRestaurantCommand.cs | 10 +- .../UpdateRestaurantCommandHandler.cs | 10 +- .../UpdateRestaurantCommandValidator.cs | 2 +- .../Shift/Create/CreateShiftCommandHandler.cs | 4 +- .../Create/CreateShiftCommandValidator.cs | 10 +- .../Shift/Delete/DeleteShiftCommandHandler.cs | 2 +- .../Delete/DeleteShiftCommandValidator.cs | 2 +- .../Shift/GetAll/GetAllShiftQueryHandler.cs | 8 +- DeerCoffeeShop.Application/Shift/ShiftDto.cs | 2 +- .../Shift/Update/UpdateShiftCommandHandler.cs | 2 +- .../Update/UpdateShiftCommandValidator.cs | 6 +- DeerCoffeeShop.Application/Utils/MailBody.cs | 13 +- DeerCoffeeShop.Application/Utils/MailUtils.cs | 24 +- .../Exceptions/TimeCheckInToSoonException.cs | 8 +- .../Common/Method/GetWeekDates.cs | 23 ++ .../Constants/EmployeeRole.cs | 2 +- DeerCoffeeShop.Domain/Entities/Form.cs | 1 - DeerCoffeeShop.Domain/Entities/Shift.cs | 1 - DeerCoffeeShop.Domain/Enums/Form.cs | 10 +- .../Repositories/IAttdenceRepository.cs | 7 +- .../Repositories/IEmployeeRepository.cs | 2 +- .../Repositories/IEmployeeShiftRepository.cs | 2 +- .../Repositories/IFaceDetectionRepository.cs | 5 - .../Repositories/IFormRepository.cs | 5 - .../DeerCoffeeShop.Infrastructure.csproj | 1 - .../DependencyInjection.cs | 30 +- .../Configurations/ApplicationDbContext.cs | 34 +-- .../Configurations/AttendenceConfiguration.cs | 2 +- .../EmployeeShiftConfiguration.cs | 2 +- .../Configurations/RestaurantConfiguration.cs | 2 +- .../Repositories/EmployeeRepository.cs | 3 +- .../Repositories/EmployeeShiftRepository.cs | 6 +- .../Repositories/FaceDetectionRepository.cs | 31 +- .../Repositories/FormRepository.cs | 5 - .../Repositories/PagedList.cs | 10 +- .../Repositories/RepositoryBase.cs | 34 +-- 155 files changed, 796 insertions(+), 976 deletions(-) create mode 100644 DeerCoffeeShop.API/.config/dotnet-tools.json delete mode 100644 DeerCoffeeShop.API/.env create mode 100644 DeerCoffeeShop.Application/EmployeeShift/AssignEmployee/AssignEmployeeCommand.cs create mode 100644 DeerCoffeeShop.Application/EmployeeShift/GetNeededReviewShift/GetNeededReviewShiftQuery.cs create mode 100644 DeerCoffeeShop.Domain/Common/Method/GetWeekDates.cs diff --git a/DeerCoffeeShop.API/.config/dotnet-tools.json b/DeerCoffeeShop.API/.config/dotnet-tools.json new file mode 100644 index 0000000..b99844e --- /dev/null +++ b/DeerCoffeeShop.API/.config/dotnet-tools.json @@ -0,0 +1,12 @@ +{ + "version": 1, + "isRoot": true, + "tools": { + "dotnet-ef": { + "version": "8.0.6", + "commands": [ + "dotnet-ef" + ] + } + } +} \ No newline at end of file diff --git a/DeerCoffeeShop.API/.env b/DeerCoffeeShop.API/.env deleted file mode 100644 index 7d77278..0000000 --- a/DeerCoffeeShop.API/.env +++ /dev/null @@ -1 +0,0 @@ -CLOUDINARY_URL=cloudinary://176963282532847:kONanxuhiEwEmJKFPC72M1a2rUs@dmiueqpah \ No newline at end of file diff --git a/DeerCoffeeShop.API/Configuration/ApiVersionSwaggerGenOptions.cs b/DeerCoffeeShop.API/Configuration/ApiVersionSwaggerGenOptions.cs index ea6c637..ab38e4e 100644 --- a/DeerCoffeeShop.API/Configuration/ApiVersionSwaggerGenOptions.cs +++ b/DeerCoffeeShop.API/Configuration/ApiVersionSwaggerGenOptions.cs @@ -11,7 +11,7 @@ public class ApiVersionSwaggerGenOptions(IApiVersionDescriptionProvider provider public void Configure(SwaggerGenOptions options) { - foreach (var description in _provider.ApiVersionDescriptions.OrderByDescending(o => o.ApiVersion)) + foreach (ApiVersionDescription? description in _provider.ApiVersionDescriptions.OrderByDescending(o => o.ApiVersion)) { options.SwaggerDoc(description.GroupName, CreateInfoForApiVersion(description)); } @@ -19,7 +19,7 @@ public void Configure(SwaggerGenOptions options) private static OpenApiInfo CreateInfoForApiVersion(ApiVersionDescription description) { - var info = new OpenApiInfo() + OpenApiInfo info = new() { Title = "Deer Coffee Shop API", Version = description.ApiVersion.ToString() diff --git a/DeerCoffeeShop.API/Configuration/ApiVersioningConfiguration.cs b/DeerCoffeeShop.API/Configuration/ApiVersioningConfiguration.cs index b28d3ad..e7f5dce 100644 --- a/DeerCoffeeShop.API/Configuration/ApiVersioningConfiguration.cs +++ b/DeerCoffeeShop.API/Configuration/ApiVersioningConfiguration.cs @@ -6,7 +6,7 @@ public static class ApiVersioningConfiguration { public static IServiceCollection ConfigureApiVersioning(this IServiceCollection services) { - services.AddApiVersioning(options => + _ = services.AddApiVersioning(options => { options.AssumeDefaultVersionWhenUnspecified = true; options.ReportApiVersions = true; diff --git a/DeerCoffeeShop.API/Configuration/ApplicationSecurityConfiguration.cs b/DeerCoffeeShop.API/Configuration/ApplicationSecurityConfiguration.cs index 55e5e9b..e78d87b 100644 --- a/DeerCoffeeShop.API/Configuration/ApplicationSecurityConfiguration.cs +++ b/DeerCoffeeShop.API/Configuration/ApplicationSecurityConfiguration.cs @@ -14,10 +14,10 @@ public static IServiceCollection ConfigureApplicationSecurity( this IServiceCollection services, IConfiguration configuration) { - services.AddTransient(); - services.AddTransient(); + _ = services.AddTransient(); + _ = services.AddTransient(); JwtSecurityTokenHandler.DefaultMapInboundClaims = false; - services.AddHttpContextAccessor(); + _ = services.AddHttpContextAccessor(); //services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) @@ -30,7 +30,7 @@ public static IServiceCollection ConfigureApplicationSecurity( // options.TokenValidationParameters.RoleClaimType = "role"; // options.SaveToken = true; // }); - services.AddAuthentication(options => + _ = services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; @@ -49,7 +49,7 @@ public static IServiceCollection ConfigureApplicationSecurity( }; }); - services.AddAuthorization(ConfigureAuthorization); + _ = services.AddAuthorization(ConfigureAuthorization); return services; } diff --git a/DeerCoffeeShop.API/Configuration/CorsConfiguration.cs b/DeerCoffeeShop.API/Configuration/CorsConfiguration.cs index 850440a..0590662 100644 --- a/DeerCoffeeShop.API/Configuration/CorsConfiguration.cs +++ b/DeerCoffeeShop.API/Configuration/CorsConfiguration.cs @@ -4,7 +4,7 @@ public static class CorsConfiguration { public static IServiceCollection ConfigurationCors(this IServiceCollection services) { - services.AddCors(o => + _ = services.AddCors(o => { o.AddPolicy("CorsPolicy", builder => builder diff --git a/DeerCoffeeShop.API/Configuration/ProblemDetailsConfiguration.cs b/DeerCoffeeShop.API/Configuration/ProblemDetailsConfiguration.cs index c6dfb2e..c03a216 100644 --- a/DeerCoffeeShop.API/Configuration/ProblemDetailsConfiguration.cs +++ b/DeerCoffeeShop.API/Configuration/ProblemDetailsConfiguration.cs @@ -7,18 +7,18 @@ public static class ProblemDetailsConfiguration { public static IServiceCollection ConfigureProblemDetails(this IServiceCollection services) { - services.AddProblemDetails(conf => conf.CustomizeProblemDetails = context => + _ = services.AddProblemDetails(conf => conf.CustomizeProblemDetails = context => { context.ProblemDetails.Type = $"https://httpstatuses.io/{context.ProblemDetails.Status}"; if (context.ProblemDetails.Status != 500) { return; } context.ProblemDetails.Title = "Internal Server Error"; - context.ProblemDetails.Extensions.TryAdd("traceId", Activity.Current?.Id ?? context.HttpContext.TraceIdentifier); + _ = context.ProblemDetails.Extensions.TryAdd("traceId", Activity.Current?.Id ?? context.HttpContext.TraceIdentifier); - var env = context.HttpContext.RequestServices.GetService()!; + IWebHostEnvironment env = context.HttpContext.RequestServices.GetService()!; if (!env.IsDevelopment()) { return; } - var exceptionFeature = context.HttpContext.Features.Get(); + IExceptionHandlerFeature? exceptionFeature = context.HttpContext.Features.Get(); if (exceptionFeature is null) { return; } context.ProblemDetails.Detail = exceptionFeature.Error.ToString(); }); diff --git a/DeerCoffeeShop.API/Configuration/SwashbuckleConfiguration.cs b/DeerCoffeeShop.API/Configuration/SwashbuckleConfiguration.cs index 2c6f158..290c8a1 100644 --- a/DeerCoffeeShop.API/Configuration/SwashbuckleConfiguration.cs +++ b/DeerCoffeeShop.API/Configuration/SwashbuckleConfiguration.cs @@ -14,28 +14,28 @@ public static class SwashbuckleConfiguration { public static IServiceCollection ConfigureSwagger(this IServiceCollection services) { - services.AddTransient, ApiVersionSwaggerGenOptions>(); - services.AddSwaggerGen( + _ = services.AddTransient, ApiVersionSwaggerGenOptions>(); + _ = services.AddSwaggerGen( options => { options.SchemaFilter(); options.SupportNonNullableReferenceTypes(); options.CustomSchemaIds(x => x.FullName); - var apiXmlFile = Path.Combine(AppContext.BaseDirectory, $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"); + string apiXmlFile = Path.Combine(AppContext.BaseDirectory, $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"); if (File.Exists(apiXmlFile)) { options.IncludeXmlComments(apiXmlFile); } - var applicationXmlFile = Path.Combine(AppContext.BaseDirectory, $"{typeof(DependencyInjection).Assembly.GetName().Name}.xml"); + string applicationXmlFile = Path.Combine(AppContext.BaseDirectory, $"{typeof(DependencyInjection).Assembly.GetName().Name}.xml"); if (File.Exists(applicationXmlFile)) { options.IncludeXmlComments(applicationXmlFile); } options.OperationFilter(); - var securityScheme = new OpenApiSecurityScheme() + OpenApiSecurityScheme securityScheme = new() { Name = "Authorization", Description = "Enter a Bearer Token into the `Value` field to have it automatically prefixed with `Bearer ` and used as an `Authorization` header value for requests.", @@ -57,14 +57,14 @@ public static IServiceCollection ConfigureSwagger(this IServiceCollection servic { securityScheme, Array.Empty() } }); }); - services.AddRouting(options => options.LowercaseUrls = true); + _ = services.AddRouting(options => options.LowercaseUrls = true); return services; } public static void UseSwashbuckle(this IApplicationBuilder app) { - app.UseSwagger(); - app.UseSwaggerUI( + _ = app.UseSwagger(); + _ = app.UseSwaggerUI( options => { options.RoutePrefix = "swagger"; @@ -80,9 +80,9 @@ public static void UseSwashbuckle(this IApplicationBuilder app) private static void AddSwaggerEndpoints(IApplicationBuilder app, SwaggerUIOptions options) { - var provider = app.ApplicationServices.GetRequiredService(); + IApiVersionDescriptionProvider provider = app.ApplicationServices.GetRequiredService(); - foreach (var description in provider.ApiVersionDescriptions.OrderByDescending(o => o.ApiVersion)) + foreach (ApiVersionDescription? description in provider.ApiVersionDescriptions.OrderByDescending(o => o.ApiVersion)) { options.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json", $"{options.OAuthConfigObject.AppName} {description.GroupName}"); } @@ -93,13 +93,13 @@ internal class RequireNonNullablePropertiesSchemaFilter : ISchemaFilter { public void Apply(OpenApiSchema model, SchemaFilterContext context) { - var additionalRequiredProps = model.Properties + IEnumerable additionalRequiredProps = model.Properties .Where(x => !x.Value.Nullable && !model.Required.Contains(x.Key)) .Select(x => x.Key); - foreach (var propKey in additionalRequiredProps) + foreach (string? propKey in additionalRequiredProps) { - model.Required.Add(propKey); + _ = model.Required.Add(propKey); } } } diff --git a/DeerCoffeeShop.API/Controllers/EmployeeController.cs b/DeerCoffeeShop.API/Controllers/EmployeeController.cs index bf5ab42..dfdfb4a 100644 --- a/DeerCoffeeShop.API/Controllers/EmployeeController.cs +++ b/DeerCoffeeShop.API/Controllers/EmployeeController.cs @@ -1,14 +1,13 @@ using DeerCoffeeShop.API.Controllers.ResponseTypes; using DeerCoffeeShop.API.Services; using DeerCoffeeShop.Application.Authentication.Login; -using DeerCoffeeShop.Application.Common.Security; using DeerCoffeeShop.Application.Employees; using DeerCoffeeShop.Application.Employees.CreateEmployee; using DeerCoffeeShop.Application.Employees.DeleteEmployee; using DeerCoffeeShop.Application.Employees.GetAllEmployee; using DeerCoffeeShop.Application.Employees.GetEmployee; -using DeerCoffeeShop.Application.Employees.UpdateEmployee; using DeerCoffeeShop.Application.Employees.GetEmployeeInfo; +using DeerCoffeeShop.Application.Employees.UpdateEmployee; using MediatR; using Microsoft.AspNetCore.Mvc; @@ -20,7 +19,7 @@ public class EmployeeController(ISender sender, JwtService _jwtService) : BaseCo [HttpPut()] public async Task> UpdateEmployee(UpdateEmployeeCommand command, CancellationToken cancellationToken = default) { - var result = await _sender.Send(new UpdateEmployeeCommand(command.EmployeeID, command.Email, command.PhoneNumber, command.Address, command.RoleId, command.FullName, command.DateOfBirth, command.IsActive), cancellationToken); + string result = await _sender.Send(new UpdateEmployeeCommand(command.EmployeeID, command.Email, command.PhoneNumber, command.Address, command.RoleId, command.FullName, command.DateOfBirth, command.IsActive), cancellationToken); var response = new { Message = result, @@ -31,8 +30,8 @@ public async Task> UpdateEmployee(UpdateEmployeeCommand com [HttpPost("login")] public async Task Login(LoginQuery loginQuery, CancellationToken cancellationToken = default) { - var loginDTO = await _sender.Send(new LoginQuery(loginQuery.EmployeeID, loginQuery.Password), cancellationToken); - var token = _jwtService.CreateToken(loginDTO.Id, loginDTO.RoleName, loginDTO.RefreshToken,loginDTO.RestaurantID); + Application.Authentication.LoginDTO loginDTO = await _sender.Send(new LoginQuery(loginQuery.EmployeeID, loginQuery.Password), cancellationToken); + JwtService.Token token = _jwtService.CreateToken(loginDTO.Id, loginDTO.RoleName, loginDTO.RefreshToken, loginDTO.RestaurantID); token.EmployeeDto = await _sender.Send(new GetEmployeeInfoQuery(loginDTO.Id), cancellationToken); var response = new { @@ -45,14 +44,14 @@ public async Task Login(LoginQuery loginQuery, CancellationToken [HttpPost("apply")] public async Task> CreateEmployeeAplication([FromBody] CreateEmployeeCommand command, CancellationToken cancellationToken) { - var result = await _sender.Send(command, cancellationToken); + string result = await _sender.Send(command, cancellationToken); return Ok(result); } [HttpGet("{employee_id}")] public async Task> GetAll([FromRoute] string employee_id, CancellationToken cancellationToken) { - var result = await _sender.Send(new GetEmployeeQuery(employee_id), cancellationToken); + EmployeeDto result = await _sender.Send(new GetEmployeeQuery(employee_id), cancellationToken); var response = new { Message = "Get Employee Information Successfully !", @@ -64,7 +63,7 @@ public async Task> GetAll([FromRoute] string employee_ [HttpDelete("")] public async Task> Delete(DeleteEmployeeCommand command, CancellationToken cancellationToken = default) { - var result = await _sender.Send(new DeleteEmployeeCommand(command.EmployeeID), cancellationToken); + string result = await _sender.Send(new DeleteEmployeeCommand(command.EmployeeID), cancellationToken); var response = new { Message = result, @@ -76,7 +75,7 @@ public async Task> Delete(DeleteEmployeeCommand command, Ca [HttpGet("")] public async Task> GetAll([FromQuery] GetAllEmployeeQuery query, CancellationToken cancellationToken) { - var result = await _sender.Send(query, cancellationToken); + Application.Common.Pagination.PagedResult result = await _sender.Send(query, cancellationToken); var response = new { Message = "Get All Successfully", diff --git a/DeerCoffeeShop.API/Controllers/EmployeeShift/EmployeeShiftController.cs b/DeerCoffeeShop.API/Controllers/EmployeeShift/EmployeeShiftController.cs index 70972b4..d106c0e 100644 --- a/DeerCoffeeShop.API/Controllers/EmployeeShift/EmployeeShiftController.cs +++ b/DeerCoffeeShop.API/Controllers/EmployeeShift/EmployeeShiftController.cs @@ -2,6 +2,7 @@ using DeerCoffeeShop.API.Controllers.ResponseTypes; using DeerCoffeeShop.Application.Common.Pagination; using DeerCoffeeShop.Application.EmployeeShift; +using DeerCoffeeShop.Application.EmployeeShift.AssignEmployee; using DeerCoffeeShop.Application.EmployeeShift.CheckIn_Out.CheckIn; using DeerCoffeeShop.Application.EmployeeShift.CheckIn_Out.CheckOut; using DeerCoffeeShop.Application.EmployeeShift.Create; @@ -10,166 +11,187 @@ using DeerCoffeeShop.Application.EmployeeShift.GetByDay; using DeerCoffeeShop.Application.EmployeeShift.GetByEmployeeId; using DeerCoffeeShop.Application.EmployeeShift.GetEmployeeShiftInAWeek; -using DeerCoffeeShop.Application.EmployeeShift.UpdateEmployeeShift; +using DeerCoffeeShop.Application.EmployeeShift.GetNeededReviewShift; using MediatR; using Microsoft.AspNetCore.Mvc; using System.Net.Mime; -namespace DeerCoffeeShop.API.Controllers.EmployeeShift +namespace DeerCoffeeShop.API.Controllers.EmployeeShift; + +public class EmployeeShiftController(ISender sender) : BaseController(sender) { - public class EmployeeShiftController(ISender sender) : BaseController(sender) - { - private readonly ISender _mediator = sender; + private readonly ISender _mediator = sender; - [HttpGet] - [ProducesResponseType(typeof(PagedResult), StatusCodes.Status200OK)] - [ProducesResponseType(StatusCodes.Status401Unauthorized)] - [ProducesResponseType(StatusCodes.Status403Forbidden)] - [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)] + [HttpGet] + [ProducesResponseType(typeof(PagedResult), StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status401Unauthorized)] + [ProducesResponseType(StatusCodes.Status403Forbidden)] + [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)] - public async Task>>> GetAll - ([FromQuery] GetAllEmployeeShiftQuery query, CancellationToken cancellationToken) + public async Task>>> GetAll + ([FromQuery] GetAllEmployeeShiftQuery query, CancellationToken cancellationToken) + { + PagedResult result = await _mediator.Send(query, cancellationToken); + List list = new(); + foreach (EmployeeShiftDto? item in result.Data) { - var result = await _mediator.Send(query, cancellationToken); - var list = new List(); - foreach (var item in result.Data) - { - var testreturn = new - { - title = item.Employee.FullName ?? "Not Pick", - start = item.CheckIn, - end = item.CheckOut, - allDay = false, - resource = item - }; - list.Add(testreturn); - } + var testreturn = new + { + title = item.Employee.FullName ?? "Not Pick", + start = item.CheckIn, + end = item.CheckOut, + allDay = false, + resource = item + }; + list.Add(testreturn); + } - return Ok(list); - } - [HttpGet("week")] - public async Task GetEmployeeShiftInAWeekQuery([FromQuery] GetEmployeeShiftInAWeekQuery query, CancellationToken cancellationToken) + return Ok(list); + } + [HttpGet("week")] + public async Task GetEmployeeShiftInAWeekQuery([FromQuery] GetEmployeeShiftInAWeekQuery query, CancellationToken cancellationToken) + { + List result = await _mediator.Send(query, cancellationToken); + List list = new(); + foreach (EmployeeShiftDtoV2? item in result) { - var result = await _mediator.Send(query, cancellationToken); - var list = new List(); - foreach (var item in result) - { - var testreturn = new - { - title = item.Employee.FullName ?? "Not Pick", - start = item.CheckIn, - end = item.CheckOut, - allDay = false, - resource = item - }; - list.Add(testreturn); - } - var respond = new + var testreturn = new { - Message = "Get successfully", - Data = list + title = item.Employee.FullName ?? "Not Pick", + start = item.CheckIn, + end = item.CheckOut, + allDay = false, + resource = item }; - return Ok(respond); + list.Add(testreturn); } - [HttpGet("day")] - [ProducesResponseType(typeof(PagedResult), StatusCodes.Status200OK)] - [ProducesResponseType(StatusCodes.Status401Unauthorized)] - [ProducesResponseType(StatusCodes.Status403Forbidden)] - [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)] - - public async Task>>> GetByDay - ([FromQuery] GetEmployeeShiftByDayQuery query, CancellationToken cancellationToken) + var respond = new + { + Message = "Get successfully", + Data = list + }; + return Ok(respond); + } + [HttpGet("day")] + [ProducesResponseType(typeof(PagedResult), StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status401Unauthorized)] + [ProducesResponseType(StatusCodes.Status403Forbidden)] + [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)] + + public async Task>>> GetByDay + ([FromQuery] GetEmployeeShiftByDayQuery query, CancellationToken cancellationToken) + { + PagedResult result = await _mediator.Send(query, cancellationToken); + List list = new(); + foreach (EmployeeShiftDto? item in result.Data) { - var result = await _mediator.Send(query, cancellationToken); - var list = new List(); - foreach (var item in result.Data) - { - var testreturn = new - { - title = item.Employee.FullName ?? "Not Pick", - start = item.CheckIn, - end = item.CheckOut, - allDay = false, - resource = item - }; - list.Add(testreturn); - } - var respond = new + var testreturn = new { - Message = "Get successfully", - Data = list + title = item.Employee.FullName ?? "Not Pick", + start = item.CheckIn, + end = item.CheckOut, + allDay = false, + resource = item }; - return Ok(respond); + list.Add(testreturn); } - [HttpDelete] - [ProducesResponseType(typeof(string), StatusCodes.Status200OK)] - [ProducesResponseType(StatusCodes.Status401Unauthorized)] - [ProducesResponseType(StatusCodes.Status403Forbidden)] - [ProducesResponseType(StatusCodes.Status400BadRequest)] - [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)] - - public async Task>> DeleteEmployeeShift([FromBody] DeleteEmployeeShiftCommand command, CancellationToken cancellationToken) + var respond = new { - var result = await _mediator.Send(command, cancellationToken); - return Ok(new JsonResponse(result)); - } + Message = "Get successfully", + Data = list + }; + return Ok(respond); + } + [HttpDelete] + [ProducesResponseType(typeof(string), StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status401Unauthorized)] + [ProducesResponseType(StatusCodes.Status403Forbidden)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)] + + public async Task>> DeleteEmployeeShift([FromBody] DeleteEmployeeShiftCommand command, CancellationToken cancellationToken) + { + string result = await _mediator.Send(command, cancellationToken); + return Ok(new JsonResponse(result)); + } - [HttpGet("employee")] - [ProducesResponseType(typeof(PagedResult), StatusCodes.Status200OK)] - [ProducesResponseType(StatusCodes.Status401Unauthorized)] - [ProducesResponseType(StatusCodes.Status403Forbidden)] - [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)] + [HttpGet("employee")] + [ProducesResponseType(typeof(PagedResult), StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status401Unauthorized)] + [ProducesResponseType(StatusCodes.Status403Forbidden)] + [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)] - public async Task>>> GetId - ([FromQuery] GetEmployeeShiftByEmployeeIdQuery query, CancellationToken cancellationToken) + public async Task>>> GetId + ([FromQuery] GetEmployeeShiftByEmployeeIdQuery query, CancellationToken cancellationToken) + { + PagedResult result = await _mediator.Send(query, cancellationToken); + var respond = new { - var result = await _mediator.Send(query, cancellationToken); - var respond = new - { - Message = "Get successfully", - Data = result - }; - return Ok(respond); - } + Message = "Get successfully", + Data = result + }; + return Ok(respond); + } - [HttpPost] - [Produces(MediaTypeNames.Application.Json)] - [ProducesResponseType(typeof(JsonResponse), StatusCodes.Status201Created)] - [ProducesResponseType(typeof(JsonResponse), StatusCodes.Status200OK)] - [ProducesResponseType(StatusCodes.Status401Unauthorized)] - [ProducesResponseType(StatusCodes.Status400BadRequest)] - [ProducesResponseType(StatusCodes.Status403Forbidden)] - [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)] - public async Task>> Create([FromBody] CreateEmployeeShiftCommand command, CancellationToken cancellationToken) + [HttpPost] + [Produces(MediaTypeNames.Application.Json)] + [ProducesResponseType(typeof(JsonResponse), StatusCodes.Status201Created)] + [ProducesResponseType(typeof(JsonResponse), StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status401Unauthorized)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesResponseType(StatusCodes.Status403Forbidden)] + [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)] + public async Task>> Create([FromBody] CreateEmployeeShiftCommand command, CancellationToken cancellationToken) + { + string result = await _mediator.Send(command, cancellationToken); + var respond = new { - var result = await _mediator.Send(command, cancellationToken); - var respond = new - { - Message = "Create successfully", - Data = result - }; - return Ok(respond); - } + Message = "Create successfully", + Data = result + }; + return Ok(respond); + } - [HttpPost("CheckIn")] - public async Task>> CheckIn([FromForm] CheckInCommand command, CancellationToken cancellationToken) + [HttpPost("CheckIn")] + public async Task>> CheckIn([FromForm] CheckInCommand command, CancellationToken cancellationToken) + { + string result = await _mediator.Send(command, cancellationToken); + return Ok(result); + } + [HttpPost("CheckOut")] + public async Task>> CheckOut([FromForm] CheckOutCommand command, CancellationToken cancellationToken) + { + string result = await _mediator.Send(command, cancellationToken); + return Ok(result); + } + [HttpPost("assgin")] + public async Task>> AssignEmployee([FromBody] AssignEmployeeCommand command, CancellationToken cancellationToken) + { + string result = await _mediator.Send(command, cancellationToken); + var respond = new { - var result = await _mediator.Send(command, cancellationToken); - return Ok(result); - } - [HttpPost("CheckOut")] - public async Task>> CheckOut([FromForm] CheckOutCommand command, CancellationToken cancellationToken) + Message = "Assign successfully", + Data = result + }; + return Ok(respond); + } + [HttpGet("review")] + public async Task>>> GetNeededReviewShift([FromQuery] GetNeededReviewShiftQuery query, CancellationToken cancellationToken = default) + { + List result = await _mediator.Send(query, cancellationToken); + var respond = new { - var result = await _mediator.Send(command, cancellationToken); - return Ok(result); - } - + Message = "Get successfully", + Data = result + }; + return Ok(respond); } + } diff --git a/DeerCoffeeShop.API/Controllers/Form/FormController.cs b/DeerCoffeeShop.API/Controllers/Form/FormController.cs index eff2bf4..4545467 100644 --- a/DeerCoffeeShop.API/Controllers/Form/FormController.cs +++ b/DeerCoffeeShop.API/Controllers/Form/FormController.cs @@ -5,7 +5,6 @@ using DeerCoffeeShop.Application.Forms.Commands.AcceptFormAndSendMail; using DeerCoffeeShop.Application.Forms.Queries.GetAllPagination; using MediatR; -using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace DeerCoffeeShop.API.Controllers.Form; @@ -18,7 +17,7 @@ public class FormController(ISender sender) : BaseController(sender) [ProducesResponseType(StatusCodes.Status400BadRequest)] public async Task>> GetAll([FromQuery] int pageNumber, int PageSize) { - var result = await _sender.Send(new GetAllFormPagination(pageNumber: pageNumber, PageSize)); + PagedResult result = await _sender.Send(new GetAllFormPagination(pageNumber: pageNumber, PageSize)); var response = new { Message = "Get All Successfully", @@ -29,7 +28,7 @@ public async Task>> GetAll([FromQuery] int pag [HttpPost] public async Task ApproveForm(AcceptFormAndSendMailCommand command) { - var resutl = await _sender.Send(new AcceptFormAndSendMailCommand(command.FormID, command.RestaurantID, command.Date)); + string resutl = await _sender.Send(new AcceptFormAndSendMailCommand(command.FormID, command.RestaurantID, command.Date)); var response = new { Message = resutl @@ -39,7 +38,7 @@ public async Task ApproveForm(AcceptFormAndSendMailCommand comman [HttpPost("{id}")] public async Task SendPassword([FromRoute] string id) { - var resutl = await _sender.Send(new AcceptEmployeeAndGeneratePasswordCommand(id)); + string resutl = await _sender.Send(new AcceptEmployeeAndGeneratePasswordCommand(id)); var response = new { Message = resutl diff --git a/DeerCoffeeShop.API/Controllers/ImageController/ImageController.cs b/DeerCoffeeShop.API/Controllers/ImageController/ImageController.cs index b13222e..d4f9493 100644 --- a/DeerCoffeeShop.API/Controllers/ImageController/ImageController.cs +++ b/DeerCoffeeShop.API/Controllers/ImageController/ImageController.cs @@ -1,9 +1,7 @@ using DeerCoffeeShop.API.Controllers.ResponseTypes; using DeerCoffeeShop.Application.EmployeeShift.CheckIn_Out.CheckIn; -using DeerCoffeeShop.Application.FaceID.DetectFaceFromImage; using DeerCoffeeShop.Application.FaceID.SaveImage; using MediatR; -using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace DeerCoffeeShop.API.Controllers.ImageController; @@ -13,13 +11,13 @@ public class ImageController(ISender sender) : BaseController(sender) [HttpPost] public async Task SaveImage([FromForm] SaveImageCommand command) { - var result = await _sender.Send(command); + string result = await _sender.Send(command); return Ok(result); } [HttpPost("detect-image")] public async Task DetectFaceFromImage([FromForm] CheckInCommand query) { - var response = await _sender.Send(query); + string response = await _sender.Send(query); return Ok(response); } } diff --git a/DeerCoffeeShop.API/Controllers/RestaurantChainController/RestaurantChainController.cs b/DeerCoffeeShop.API/Controllers/RestaurantChainController/RestaurantChainController.cs index 8eb72ce..1934d66 100644 --- a/DeerCoffeeShop.API/Controllers/RestaurantChainController/RestaurantChainController.cs +++ b/DeerCoffeeShop.API/Controllers/RestaurantChainController/RestaurantChainController.cs @@ -1,7 +1,6 @@ using DeerCoffeeShop.Api.Controllers.ResponseTypes; using DeerCoffeeShop.API.Controllers.ResponseTypes; using DeerCoffeeShop.Application.Common.Pagination; -using DeerCoffeeShop.Application.Common.Security; using DeerCoffeeShop.Application.RestaurantChains; using DeerCoffeeShop.Application.RestaurantChains.CreateRestaurantChain; using DeerCoffeeShop.Application.RestaurantChains.DeleteRestaurantChain; @@ -11,9 +10,7 @@ using DeerCoffeeShop.Application.RestaurantChains.GetRestautantChainByName; using DeerCoffeeShop.Application.RestaurantChains.InactiveRestaurantChain; using DeerCoffeeShop.Application.Restaurants.UpdateRestautant; -using DeerCoffeeShop.Infrastructure.Repositories; using MediatR; -using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System.Net.Mime; @@ -35,7 +32,7 @@ public async Task>> createRestaurantChain( CreateRestaurantChainCommand command, CancellationToken cancellationToken = default) { - var result = await _mediator.Send(command, cancellationToken); + string result = await _mediator.Send(command, cancellationToken); return Ok(new JsonResponse(result)); } @@ -52,7 +49,7 @@ public async Task>>> g [FromRoute] string ID, [FromRoute] int pageNumber, [FromRoute] int pageSize, CancellationToken cancellationToken = default) { - var result = await _mediator.Send(new GetRestaurantChainByAdminQuery(pageNumber, pageSize, ID), cancellationToken); + PagedResult result = await _mediator.Send(new GetRestaurantChainByAdminQuery(pageNumber, pageSize, ID), cancellationToken); var response = new { Message = "Query Successful", @@ -73,7 +70,7 @@ public async Task>> getRestaurantC [FromRoute] string ID, CancellationToken cancellationToken = default) { - var result = await _mediator.Send(new GetRestaurantChainByIDQuery(ID), cancellationToken); + RestaurantChainDTO result = await _mediator.Send(new GetRestaurantChainByIDQuery(ID), cancellationToken); var response = new { Message = "Query Successful", @@ -94,7 +91,7 @@ public async Task>>> g [FromRoute] int pageNumber, [FromRoute] int pageSize, [FromRoute] string resName, CancellationToken cancellationToken = default) { - var result = await _mediator.Send(new GetRestautantChainByNameQuery(pageNumber,pageSize,resName), cancellationToken); + PagedResult result = await _mediator.Send(new GetRestautantChainByNameQuery(pageNumber, pageSize, resName), cancellationToken); var response = new { Message = "Query Successful", @@ -115,7 +112,7 @@ public async Task>>> g [FromRoute] int pageNumber, [FromRoute] int pageSize, CancellationToken cancellationToken = default) { - var result = await _mediator.Send(new GetRestaurantChainByDeactiveQuery(pageNumber, pageSize), cancellationToken); + PagedResult result = await _mediator.Send(new GetRestaurantChainByDeactiveQuery(pageNumber, pageSize), cancellationToken); var response = new { Message = "Query Successful", @@ -137,7 +134,7 @@ public async Task>> inactiveRestaurantChain( InactiveRestaurantChainCommand command, CancellationToken cancellationToken = default) { - var result = await _mediator.Send(command, cancellationToken); + string result = await _mediator.Send(command, cancellationToken); return Ok(new JsonResponse(result)); } //PUT api/ @@ -153,7 +150,7 @@ public async Task>> updateRestaurantChain( UpdateRestaurantCommand command, CancellationToken cancellationToken = default) { - var result = await _mediator.Send(command, cancellationToken); + string result = await _mediator.Send(command, cancellationToken); return Ok(new JsonResponse(result)); } @@ -169,8 +166,8 @@ public async Task>> updateRestaurantChain( public async Task>> deleteRestaurantchain( DeleteRestaurantChainCommand command, CancellationToken cancellationToken = default) - { - var result = await _mediator.Send(command, cancellationToken); + { + string result = await _mediator.Send(command, cancellationToken); return Ok(new JsonResponse(result)); } diff --git a/DeerCoffeeShop.API/Controllers/RestaurantController/RestaurantController.cs b/DeerCoffeeShop.API/Controllers/RestaurantController/RestaurantController.cs index e59564f..b271bea 100644 --- a/DeerCoffeeShop.API/Controllers/RestaurantController/RestaurantController.cs +++ b/DeerCoffeeShop.API/Controllers/RestaurantController/RestaurantController.cs @@ -2,22 +2,17 @@ using DeerCoffeeShop.API.Controllers.ResponseTypes; using DeerCoffeeShop.Application.Authentication.LoginRestaurant; using DeerCoffeeShop.Application.Common.Pagination; -using DeerCoffeeShop.Application.Common.Security; using DeerCoffeeShop.Application.Restaurants; using DeerCoffeeShop.Application.Restaurants.AddManagerToRestaurant; using DeerCoffeeShop.Application.Restaurants.CreateRestaurant; using DeerCoffeeShop.Application.Restaurants.DeleteRestaurant; using DeerCoffeeShop.Application.Restaurants.FillterByReschainAndManagerID; using DeerCoffeeShop.Application.Restaurants.Get; -using DeerCoffeeShop.Application.Restaurants.GetAllRestaurantIsactive; -using DeerCoffeeShop.Application.Restaurants.GetRestaurantByDeactive; -using DeerCoffeeShop.Application.Restaurants.GetRestaurantIsLowEmp; using DeerCoffeeShop.Application.Restaurants.GetRestautantByID; using DeerCoffeeShop.Application.Restaurants.InactiveRestaurant; using DeerCoffeeShop.Application.Restaurants.UpdateRestautant; using MediatR; using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.RazorPages; using System.Net.Mime; @@ -39,7 +34,7 @@ public async Task>> createRestaurant( CreateRestaurantCommand command, CancellationToken cancellationToken = default) { - var result = await _mediator.Send(command, cancellationToken); + string result = await _mediator.Send(command, cancellationToken); var response = new { Message = "Create Successfully", @@ -61,7 +56,7 @@ public async Task>> Get( [FromRoute] Guid ID, CancellationToken cancellationToken = default) { - var result = await _mediator.Send(new GetRestaurantByIDQuery(ID), cancellationToken); + RestaurantDTO result = await _mediator.Send(new GetRestaurantByIDQuery(ID), cancellationToken); return Ok(new JsonResponse(result)); } @@ -78,10 +73,10 @@ public async Task>>> fillte [FromRoute] int pageSize, [FromRoute] int pageNumber, [FromRoute] string managerID, [FromRoute] string resChainID, CancellationToken cancellationToken = default) { - var result = await _mediator.Send(new FillterByReschainAndManagerIDQuery(pageNumber, pageSize, managerID, resChainID), cancellationToken); + PagedResult result = await _mediator.Send(new FillterByReschainAndManagerIDQuery(pageNumber, pageSize, managerID, resChainID), cancellationToken); return Ok(new JsonResponse>(result)); } - + // PUT api/ [HttpPut("Inactive-Restaurant")] @@ -96,7 +91,7 @@ public async Task> inactiveRestaurant( InactiveRestaurantCommand command, CancellationToken cancellationToken = default) { - var result = await _mediator.Send(command, cancellationToken); + string result = await _mediator.Send(command, cancellationToken); return Ok(new JsonResponse(result)); } // PUT api/ @@ -112,7 +107,7 @@ public async Task>> updateRestaurant( UpdateRestaurantCommand command, CancellationToken cancellationToken = default) { - var result = await _mediator.Send(command, cancellationToken); + string result = await _mediator.Send(command, cancellationToken); return Ok(new JsonResponse(result)); } @@ -129,7 +124,7 @@ public async Task>> addStaffTorestaurant( AddManagerToRestaurantCommand command, CancellationToken cancellationToken = default) { - var result = await _mediator.Send(command, cancellationToken); + string result = await _mediator.Send(command, cancellationToken); return Ok(new JsonResponse(result)); } @@ -146,7 +141,7 @@ public async Task>> deleteRestaurant( [FromQuery] string ID, CancellationToken cancellationToken = default) { - var result = await _mediator.Send(new DeleteRestaurantCommand(ID), cancellationToken); + string result = await _mediator.Send(new DeleteRestaurantCommand(ID), cancellationToken); return Ok(new JsonResponse(result)); } [HttpPost("Login-Restaurant")] @@ -154,13 +149,13 @@ public async Task> LoginRestaurant( LoginRestaurantQuery query, CancellationToken cancellationToken = default) { - var result = await _mediator.Send(query, cancellationToken); + string result = await _mediator.Send(query, cancellationToken); return Ok(result); } [HttpGet] public async Task> GetAll([FromQuery] GetRestaurantQuery query, CancellationToken cancellationToken) { - var result = await _mediator.Send(query, cancellationToken); + PagedResult result = await _mediator.Send(query, cancellationToken); var response = new { Message = "Get All Successfully", diff --git a/DeerCoffeeShop.API/Controllers/Shift/ShiftController.cs b/DeerCoffeeShop.API/Controllers/Shift/ShiftController.cs index 4a16d19..6428640 100644 --- a/DeerCoffeeShop.API/Controllers/Shift/ShiftController.cs +++ b/DeerCoffeeShop.API/Controllers/Shift/ShiftController.cs @@ -1,5 +1,4 @@ -using Azure; -using DeerCoffeeShop.Api.Controllers.ResponseTypes; +using DeerCoffeeShop.Api.Controllers.ResponseTypes; using DeerCoffeeShop.API.Controllers.ResponseTypes; using DeerCoffeeShop.Application.Common.Pagination; using DeerCoffeeShop.Application.Common.Security; @@ -27,14 +26,14 @@ public class ShiftController(ISender sender) : BaseController(sender) public async Task>> GetAllShift([FromQuery] GetAllShiftQuery query, CancellationToken cancellationToken = default) { - var result = await _mediator.Send(query, cancellationToken); + PagedResult result = await _mediator.Send(query, cancellationToken); var respond = new { Message = "Get all shift successfully", Data = result }; return Ok(respond); - } + } [HttpPost] [Produces(MediaTypeNames.Application.Json)] @@ -46,7 +45,7 @@ public async Task>> GetAllShift([FromQuery] G [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)] public async Task>> CreateNewShift([FromBody] CreateShiftCommand command, CancellationToken cancellationToken = default) { - var result = await _mediator.Send(command, cancellationToken); + string result = await _mediator.Send(command, cancellationToken); return Ok(new JsonResponse(result)); } @@ -60,7 +59,7 @@ public async Task>> CreateNewShift([FromBody] [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)] public async Task>> UpdateShift([FromBody] UpdateShiftCommand command, CancellationToken cancellationToken = default) { - var result = await _mediator.Send(command, cancellationToken); + string result = await _mediator.Send(command, cancellationToken); return Ok(new JsonResponse(result)); } @@ -74,7 +73,7 @@ public async Task>> UpdateShift([FromBody] Upd [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)] public async Task>> RemoveShift([FromBody] DeleteShiftCommand command, CancellationToken cancellationToken = default) { - var result = await _mediator.Send(command, cancellationToken); + string result = await _mediator.Send(command, cancellationToken); return Ok(new JsonResponse(result)); } } diff --git a/DeerCoffeeShop.API/DeerCoffeeShop.API.csproj b/DeerCoffeeShop.API/DeerCoffeeShop.API.csproj index d56a68e..abc6d17 100644 --- a/DeerCoffeeShop.API/DeerCoffeeShop.API.csproj +++ b/DeerCoffeeShop.API/DeerCoffeeShop.API.csproj @@ -11,7 +11,6 @@ - diff --git a/DeerCoffeeShop.API/Filters/AuthorizeCheckOperationFilter.cs b/DeerCoffeeShop.API/Filters/AuthorizeCheckOperationFilter.cs index f8a147b..4e123a4 100644 --- a/DeerCoffeeShop.API/Filters/AuthorizeCheckOperationFilter.cs +++ b/DeerCoffeeShop.API/Filters/AuthorizeCheckOperationFilter.cs @@ -27,12 +27,9 @@ [new OpenApiSecurityScheme private static bool HasAuthorize(OperationFilterContext context) { - if (context.MethodInfo.GetCustomAttributes(true).OfType().Any()) - { - return true; - } - return context.MethodInfo.DeclaringType != null - && context.MethodInfo.DeclaringType.GetCustomAttributes(true).OfType().Any(); + return context.MethodInfo.GetCustomAttributes(true).OfType().Any() +|| (context.MethodInfo.DeclaringType != null + && context.MethodInfo.DeclaringType.GetCustomAttributes(true).OfType().Any()); } } } \ No newline at end of file diff --git a/DeerCoffeeShop.API/Filters/ExceptionFilter.cs b/DeerCoffeeShop.API/Filters/ExceptionFilter.cs index c1db969..bde5f91 100644 --- a/DeerCoffeeShop.API/Filters/ExceptionFilter.cs +++ b/DeerCoffeeShop.API/Filters/ExceptionFilter.cs @@ -15,7 +15,7 @@ public void OnException(ExceptionContext context) switch (context.Exception) { case ValidationException validationException: - foreach (var error in validationException.Errors) + foreach (FluentValidation.Results.ValidationFailure? error in validationException.Errors) { context.ModelState.AddModelError(error.PropertyName, error.ErrorMessage); } diff --git a/DeerCoffeeShop.API/Program.cs b/DeerCoffeeShop.API/Program.cs index 004b0e0..9c6091a 100644 --- a/DeerCoffeeShop.API/Program.cs +++ b/DeerCoffeeShop.API/Program.cs @@ -1,16 +1,11 @@ -using CloudinaryDotNet; using DeerCoffeeShop.API.Configuration; using DeerCoffeeShop.API.Filters; using DeerCoffeeShop.Application; - -using DeerCoffeeShop.Domain.Entities; -using DeerCoffeeShop.Domain.Repositories; using DeerCoffeeShop.Infrastructure; -using dotenv.net; using Serilog; // Create the builder -var builder = WebApplication.CreateBuilder(args); +WebApplicationBuilder builder = WebApplication.CreateBuilder(args); // Configure logging (Serilog) builder.Host.UseSerilog((context, services, configuration) => configuration @@ -23,7 +18,7 @@ // Add services builder.Services.AddControllers(opt => { - opt.Filters.Add(); + _ = opt.Filters.Add(); }); builder.Services.AddApplication(); // Note: 'Configuration' is available on the builder builder.Services.ConfigureApplicationSecurity(builder.Configuration); @@ -32,27 +27,25 @@ builder.Services.AddInfrastructure(builder.Configuration); builder.Services.ConfigureSwagger(); builder.Services.ConfigurationCors(); -DotEnv.Load(options: new DotEnvOptions(probeForEnv: true)); -Cloudinary cloudinary = new(Environment.GetEnvironmentVariable("CLOUDINARY_URL")); -cloudinary.Api.Secure = true; + //allow all cors builder.Services.AddCors(options => { options.AddDefaultPolicy( builder => { - builder.AllowAnyOrigin() + _ = builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader(); }); }); // Build the app -var app = builder.Build(); +WebApplication app = builder.Build(); // Configure the middleware pipeline if (app.Environment.IsDevelopment()) { - app.UseDeveloperExceptionPage(); + _ = app.UseDeveloperExceptionPage(); } app.UseSerilogRequestLogging(); diff --git a/DeerCoffeeShop.API/Services/CurrentUserService.cs b/DeerCoffeeShop.API/Services/CurrentUserService.cs index a45fc89..e3b278a 100644 --- a/DeerCoffeeShop.API/Services/CurrentUserService.cs +++ b/DeerCoffeeShop.API/Services/CurrentUserService.cs @@ -14,8 +14,7 @@ public class CurrentUserService(IHttpContextAccessor httpContextAccessor, IAutho public string? RestaurantID => _claimsPrincipal?.FindFirst("RestaurantID")?.Value; public async Task AuthorizeAsync(string policy) { - if (_claimsPrincipal == null) return false; - return (await authorizationService.AuthorizeAsync(_claimsPrincipal, policy)).Succeeded; + return _claimsPrincipal != null && (await authorizationService.AuthorizeAsync(_claimsPrincipal, policy)).Succeeded; } public async Task IsInRoleAsync(string role) diff --git a/DeerCoffeeShop.API/Services/JwtService.cs b/DeerCoffeeShop.API/Services/JwtService.cs index 8aa631a..344d70a 100644 --- a/DeerCoffeeShop.API/Services/JwtService.cs +++ b/DeerCoffeeShop.API/Services/JwtService.cs @@ -16,7 +16,7 @@ public class Token } public Token CreateToken(string ID, string roles, string refreshToken, string? RestaurantID) { - var claims = new List + List claims = new() { new(JwtRegisteredClaimNames.Sub, ID.ToString()), @@ -27,16 +27,16 @@ public Token CreateToken(string ID, string roles, string refreshToken, string? R - var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("Deer Coffee Shop @PI 123abc456 anh iu em")); - var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); + SymmetricSecurityKey key = new(Encoding.UTF8.GetBytes("Deer Coffee Shop @PI 123abc456 anh iu em")); + SigningCredentials creds = new(key, SecurityAlgorithms.HmacSha256); - var token = new JwtSecurityToken( + JwtSecurityToken token = new( issuer: "https://deercoffeesystem.azurewebsites.net/", audience: "api", claims: claims, expires: DateTime.Now.AddYears(1), signingCredentials: creds); - var re = new Token + Token re = new() { AccessToken = new JwtSecurityTokenHandler().WriteToken(token), RefreshToken = refreshToken diff --git a/DeerCoffeeShop.Application/Authentication/Login/LoginQueryHandler.cs b/DeerCoffeeShop.Application/Authentication/Login/LoginQueryHandler.cs index 0d3c540..24eaa10 100644 --- a/DeerCoffeeShop.Application/Authentication/Login/LoginQueryHandler.cs +++ b/DeerCoffeeShop.Application/Authentication/Login/LoginQueryHandler.cs @@ -10,8 +10,8 @@ internal class LoginQueryHandler(IRestaurantRepository _restaurantRepository, IE public async Task Handle(LoginQuery request, CancellationToken cancellationToken) { - var user = await _employeeRepository.FindAsync(_ => _.ID == request.EmployeeID && _.NgayXoa == null, cancellationToken) ?? throw new NotFoundException("User not found"); - var isTrue = _employeeRepository.VerifyPassword(request.Password, user.Password); + Domain.Entities.Employee user = await _employeeRepository.FindAsync(_ => _.ID == request.EmployeeID && _.NgayXoa == null, cancellationToken) ?? throw new NotFoundException("User not found"); + bool isTrue = _employeeRepository.VerifyPassword(request.Password, user.Password); if (!isTrue) { throw new IncorrectPasswordException("Password is incorrect"); @@ -24,10 +24,10 @@ public async Task Handle(LoginQuery request, CancellationToken cancell 3 => "Employee", _ => "Owner", }; - var refresh = sender.Send(new RefreshTokenCommand(), cancellationToken).Result.Token; + string refresh = sender.Send(new RefreshTokenCommand(), cancellationToken).Result.Token; user.RefreshToken = refresh; - var restaurant = await _restaurantRepository.FindAsync(_ => _.ManagerID == user.ID, cancellationToken); - await _employeeRepository.UnitOfWork.SaveChangesAsync(cancellationToken); + Domain.Entities.Restaurant? restaurant = await _restaurantRepository.FindAsync(_ => _.ManagerID == user.ID, cancellationToken); + _ = await _employeeRepository.UnitOfWork.SaveChangesAsync(cancellationToken); return LoginDTO.Create(user.ID, Role, refresh, restaurant?.ID); } diff --git a/DeerCoffeeShop.Application/Authentication/LoginDTO.cs b/DeerCoffeeShop.Application/Authentication/LoginDTO.cs index 6503bca..119f28d 100644 --- a/DeerCoffeeShop.Application/Authentication/LoginDTO.cs +++ b/DeerCoffeeShop.Application/Authentication/LoginDTO.cs @@ -9,7 +9,7 @@ public class LoginDTO : IMapFrom { public void Mapping(Profile profile) { - profile.CreateMap(); + _ = profile.CreateMap(); } public string Id { get; set; } diff --git a/DeerCoffeeShop.Application/Authentication/LoginRestaurant/LoginRestaurantQuery.cs b/DeerCoffeeShop.Application/Authentication/LoginRestaurant/LoginRestaurantQuery.cs index 187f874..9c6ee64 100644 --- a/DeerCoffeeShop.Application/Authentication/LoginRestaurant/LoginRestaurantQuery.cs +++ b/DeerCoffeeShop.Application/Authentication/LoginRestaurant/LoginRestaurantQuery.cs @@ -1,11 +1,6 @@ using DeerCoffeeShop.Domain.Common.Exceptions; using DeerCoffeeShop.Domain.Repositories; using MediatR; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace DeerCoffeeShop.Application.Authentication.LoginRestaurant; @@ -21,16 +16,12 @@ internal class LoginRestaurantQueryHandler(IRestaurantRepository restaurantRepos public async Task Handle(LoginRestaurantQuery request, CancellationToken cancellationToken) { - var restaurant = await _restaurantRepository.FindAsync(_ => _.ID == request.RetaurantID, cancellationToken) ?? throw new NotFoundException("Restaurant not found"); - var manager = await _employeeRepository.FindAsync(_ => _.ID == restaurant.ManagerID, cancellationToken); - if (manager == null) - { - throw new NotFoundException("Manager not found"); - } - if (_employeeRepository.VerifyPassword(request.Password, manager.Password)) - { - return restaurant.ID; - } - throw new IncorrectPasswordException("Password is incorrect"); + Domain.Entities.Restaurant restaurant = await _restaurantRepository.FindAsync(_ => _.ID == request.RetaurantID, cancellationToken) ?? throw new NotFoundException("Restaurant not found"); + Domain.Entities.Employee? manager = await _employeeRepository.FindAsync(_ => _.ID == restaurant.ManagerID, cancellationToken); + return manager == null + ? throw new NotFoundException("Manager not found") + : _employeeRepository.VerifyPassword(request.Password, manager.Password) + ? restaurant.ID + : throw new IncorrectPasswordException("Password is incorrect"); } } diff --git a/DeerCoffeeShop.Application/Authentication/Refrestoken/GenerateRefreshToken/RefreshTokenCommandHandler.cs b/DeerCoffeeShop.Application/Authentication/Refrestoken/GenerateRefreshToken/RefreshTokenCommandHandler.cs index 9c9ead3..981c824 100644 --- a/DeerCoffeeShop.Application/Authentication/Refrestoken/GenerateRefreshToken/RefreshTokenCommandHandler.cs +++ b/DeerCoffeeShop.Application/Authentication/Refrestoken/GenerateRefreshToken/RefreshTokenCommandHandler.cs @@ -8,13 +8,13 @@ public class RefreshTokenCommandHandler : IRequestHandler Handle(RefreshTokenCommand request, CancellationToken cancellationToken) { - var randome = new Byte[64]; - using (var rng = RandomNumberGenerator.Create()) + byte[] randome = new Byte[64]; + using (RandomNumberGenerator rng = RandomNumberGenerator.Create()) { rng.GetBytes(randome); } string token = Convert.ToBase64String(randome); - var refreshToken = new RefreshToken + RefreshToken refreshToken = new() { Token = token, Expired = DateTime.Now.AddDays(7) diff --git a/DeerCoffeeShop.Application/Common/Behaviours/AuthorizationBehaviour.cs b/DeerCoffeeShop.Application/Common/Behaviours/AuthorizationBehaviour.cs index 43758ee..a845019 100644 --- a/DeerCoffeeShop.Application/Common/Behaviours/AuthorizationBehaviour.cs +++ b/DeerCoffeeShop.Application/Common/Behaviours/AuthorizationBehaviour.cs @@ -12,7 +12,7 @@ public class AuthorizationBehaviour( { public async Task Handle(TRequest request, RequestHandlerDelegate next, CancellationToken cancellationToken) { - var authorizeAttributes = request.GetType().GetCustomAttributes(); + IEnumerable authorizeAttributes = request.GetType().GetCustomAttributes(); if (authorizeAttributes.Any()) { @@ -23,16 +23,16 @@ public async Task Handle(TRequest request, RequestHandlerDelegate !string.IsNullOrWhiteSpace(a.Roles)); + IEnumerable authorizeAttributesWithRoles = authorizeAttributes.Where(a => !string.IsNullOrWhiteSpace(a.Roles)); if (authorizeAttributesWithRoles.Any()) { - foreach (var roles in authorizeAttributesWithRoles.Select(a => a.Roles.Split(','))) + foreach (string[]? roles in authorizeAttributesWithRoles.Select(a => a.Roles.Split(','))) { - var authorized = false; - foreach (var role in roles) + bool authorized = false; + foreach (string? role in roles) { - var isInRole = await currentUserService.IsInRoleAsync(role.Trim()); + bool isInRole = await currentUserService.IsInRoleAsync(role.Trim()); if (isInRole) { authorized = true; @@ -49,12 +49,12 @@ public async Task Handle(TRequest request, RequestHandlerDelegate !string.IsNullOrWhiteSpace(a.Policy)); + IEnumerable authorizeAttributesWithPolicies = authorizeAttributes.Where(a => !string.IsNullOrWhiteSpace(a.Policy)); if (authorizeAttributesWithPolicies.Any()) { - foreach (var policy in authorizeAttributesWithPolicies.Select(a => a.Policy)) + foreach (string? policy in authorizeAttributesWithPolicies.Select(a => a.Policy)) { - var authorized = await currentUserService.AuthorizeAsync(policy); + bool authorized = await currentUserService.AuthorizeAsync(policy); if (!authorized) { diff --git a/DeerCoffeeShop.Application/Common/Behaviours/LoggingBehaviour.cs b/DeerCoffeeShop.Application/Common/Behaviours/LoggingBehaviour.cs index e8bb88f..6a7867d 100644 --- a/DeerCoffeeShop.Application/Common/Behaviours/LoggingBehaviour.cs +++ b/DeerCoffeeShop.Application/Common/Behaviours/LoggingBehaviour.cs @@ -11,9 +11,9 @@ public class LoggingBehaviour(ILogger logger, ICurrentUserSe public Task Process(TRequest request, CancellationToken cancellationToken) { - var requestName = typeof(TRequest).Name; - var userId = currentUserService.UserId ?? string.Empty; - var userName = currentUserService.UserName ?? string.Empty; + string requestName = typeof(TRequest).Name; + string userId = currentUserService.UserId ?? string.Empty; + string userName = currentUserService.UserName ?? string.Empty; _logger.LogInformation("TestCA9 Request: {Name} {@UserId} {@UserName} {@Request}", requestName, userId, userName, request); diff --git a/DeerCoffeeShop.Application/Common/Behaviours/PerformanceBehaviour.cs b/DeerCoffeeShop.Application/Common/Behaviours/PerformanceBehaviour.cs index d46f1fb..74555a9 100644 --- a/DeerCoffeeShop.Application/Common/Behaviours/PerformanceBehaviour.cs +++ b/DeerCoffeeShop.Application/Common/Behaviours/PerformanceBehaviour.cs @@ -16,17 +16,17 @@ public async Task Handle(TRequest request, RequestHandlerDelegate 500) { - var requestName = typeof(TRequest).Name; - var userId = currentUserService.UserId ?? string.Empty; - var userName = currentUserService.UserName ?? string.Empty; + string requestName = typeof(TRequest).Name; + string userId = currentUserService.UserId ?? string.Empty; + string userName = currentUserService.UserName ?? string.Empty; logger.LogWarning("DeerCoffeeShop Long Running Request: {Name} ({ElapsedMilliseconds} milliseconds) {@UserId} {@UserName} {@Request}", requestName, elapsedMilliseconds, userId, userName, request); diff --git a/DeerCoffeeShop.Application/Common/Behaviours/UnhandledExceptionBehaviour.cs b/DeerCoffeeShop.Application/Common/Behaviours/UnhandledExceptionBehaviour.cs index 39f2eb1..702fcce 100644 --- a/DeerCoffeeShop.Application/Common/Behaviours/UnhandledExceptionBehaviour.cs +++ b/DeerCoffeeShop.Application/Common/Behaviours/UnhandledExceptionBehaviour.cs @@ -14,7 +14,7 @@ public async Task Handle(TRequest request, RequestHandlerDelegate Handle( // locks are released, while write-locks are maintained for the duration of the // transaction). Learn more on this approach for EF Core: // https://docs.microsoft.com/en-us/ef/core/saving/transactions#using-systemtransactions - using var transaction = new TransactionScope(TransactionScopeOption.Required, + using TransactionScope transaction = new(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted }, TransactionScopeAsyncFlowOption.Enabled); - var response = await next(); + TResponse? response = await next(); // By calling SaveChanges at the last point in the transaction ensures that write- // locks in the database are created and then released as quickly as possible. This // helps optimize the application to handle a higher degree of concurrency. - await dataSource.SaveChangesAsync(cancellationToken); + _ = await dataSource.SaveChangesAsync(cancellationToken); // Commit transaction if everything succeeds, transaction will auto-rollback when // disposed if anything failed. diff --git a/DeerCoffeeShop.Application/Common/Behaviours/ValidationBehaviour.cs b/DeerCoffeeShop.Application/Common/Behaviours/ValidationBehaviour.cs index 7b60f3f..44f6c74 100644 --- a/DeerCoffeeShop.Application/Common/Behaviours/ValidationBehaviour.cs +++ b/DeerCoffeeShop.Application/Common/Behaviours/ValidationBehaviour.cs @@ -9,10 +9,10 @@ public async Task Handle(TRequest request, RequestHandlerDelegate(request); + ValidationContext context = new(request); - var validationResults = await Task.WhenAll(validators.Select(v => v.ValidateAsync(context, cancellationToken))); - var failures = validationResults.SelectMany(r => r.Errors).Where(f => f != null).ToList(); + FluentValidation.Results.ValidationResult[] validationResults = await Task.WhenAll(validators.Select(v => v.ValidateAsync(context, cancellationToken))); + List failures = validationResults.SelectMany(r => r.Errors).Where(f => f != null).ToList(); if (failures.Count != 0) throw new ValidationException(failures); diff --git a/DeerCoffeeShop.Application/Common/Mappings/MappingProfile.cs b/DeerCoffeeShop.Application/Common/Mappings/MappingProfile.cs index 709849f..553eefb 100644 --- a/DeerCoffeeShop.Application/Common/Mappings/MappingProfile.cs +++ b/DeerCoffeeShop.Application/Common/Mappings/MappingProfile.cs @@ -12,19 +12,19 @@ public MappingProfile() private void ApplyMappingsFromAssembly(Assembly assembly) { - var types = assembly.GetExportedTypes() + List types = assembly.GetExportedTypes() .Where(t => t.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IMapFrom<>))) .ToList(); - foreach (var type in types) + foreach (Type? type in types) { - var instance = Activator.CreateInstance(type, true); + object? instance = Activator.CreateInstance(type, true); - var methodInfo = type.GetMethod("Mapping") + MethodInfo? methodInfo = type.GetMethod("Mapping") ?? type.GetInterface("IMapFrom`1")?.GetMethod("Mapping"); - methodInfo?.Invoke(instance, [this]); + _ = (methodInfo?.Invoke(instance, [this])); } } } diff --git a/DeerCoffeeShop.Application/Common/Pagination/PagedResultMappingExtensions.cs b/DeerCoffeeShop.Application/Common/Pagination/PagedResultMappingExtensions.cs index dea28e2..1415b76 100644 --- a/DeerCoffeeShop.Application/Common/Pagination/PagedResultMappingExtensions.cs +++ b/DeerCoffeeShop.Application/Common/Pagination/PagedResultMappingExtensions.cs @@ -20,7 +20,7 @@ public static class PagedResultMappingExtensions /// A single page of DTO elements public static PagedResult MapToPagedResult(this IPagedResult pagedResult, Func mapFunc) { - var data = pagedResult.Select(mapFunc).ToList(); + List data = pagedResult.Select(mapFunc).ToList(); return PagedResult.Create( totalCount: pagedResult.TotalCount, diff --git a/DeerCoffeeShop.Application/DependencyInjection.cs b/DeerCoffeeShop.Application/DependencyInjection.cs index d533254..e0e6164 100644 --- a/DeerCoffeeShop.Application/DependencyInjection.cs +++ b/DeerCoffeeShop.Application/DependencyInjection.cs @@ -1,10 +1,8 @@ using DeerCoffeeShop.Application.Common.Behaviours; using DeerCoffeeShop.Application.Common.Validation; -using DeerCoffeeShop.Domain.Entities; using FluentValidation; using Microsoft.Extensions.DependencyInjection; using System.Reflection; -using Microsoft.Extensions.Configuration; namespace DeerCoffeeShop.Application { @@ -12,19 +10,19 @@ public static class DependencyInjection { public static IServiceCollection AddApplication(this IServiceCollection services) { - services.AddValidatorsFromAssembly(Assembly.GetExecutingAssembly(), lifetime: ServiceLifetime.Transient); - services.AddMediatR(cfg => + _ = services.AddValidatorsFromAssembly(Assembly.GetExecutingAssembly(), lifetime: ServiceLifetime.Transient); + _ = services.AddMediatR(cfg => { - cfg.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly()); - cfg.AddOpenBehavior(typeof(UnhandledExceptionBehaviour<,>)); - cfg.AddOpenBehavior(typeof(PerformanceBehaviour<,>)); - cfg.AddOpenBehavior(typeof(AuthorizationBehaviour<,>)); - cfg.AddOpenBehavior(typeof(ValidationBehaviour<,>)); - cfg.AddOpenBehavior(typeof(UnitOfWorkBehaviour<,>)); + _ = cfg.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly()); + _ = cfg.AddOpenBehavior(typeof(UnhandledExceptionBehaviour<,>)); + _ = cfg.AddOpenBehavior(typeof(PerformanceBehaviour<,>)); + _ = cfg.AddOpenBehavior(typeof(AuthorizationBehaviour<,>)); + _ = cfg.AddOpenBehavior(typeof(ValidationBehaviour<,>)); + _ = cfg.AddOpenBehavior(typeof(UnitOfWorkBehaviour<,>)); }); - services.AddAutoMapper(Assembly.GetExecutingAssembly()); - services.AddScoped(); + _ = services.AddAutoMapper(Assembly.GetExecutingAssembly()); + _ = services.AddScoped(); return services; } diff --git a/DeerCoffeeShop.Application/EmployeeShift/AssignEmployee/AssignEmployeeCommand.cs b/DeerCoffeeShop.Application/EmployeeShift/AssignEmployee/AssignEmployeeCommand.cs new file mode 100644 index 0000000..584cc77 --- /dev/null +++ b/DeerCoffeeShop.Application/EmployeeShift/AssignEmployee/AssignEmployeeCommand.cs @@ -0,0 +1,36 @@ +using DeerCoffeeShop.Application.Common.Interfaces; +using DeerCoffeeShop.Domain.Common.Exceptions; +using DeerCoffeeShop.Domain.Repositories; +using MediatR; + +namespace DeerCoffeeShop.Application.EmployeeShift.AssignEmployee; + +public class AssignEmployeeCommand : IRequest, ICommand +{ + public string EmployeeID { get; set; } + public string EmployeeShiftID { get; set; } + public DateTime CheckIn { get; set; } + public DateTime CheckOut { get; set; } +} +internal sealed class AssginEmployeeCommandHandler : IRequestHandler +{ + private readonly IEmployeeShiftRepository _employeeShiftRepository; + + public AssginEmployeeCommandHandler(IEmployeeShiftRepository employeeShiftRepository) + { + _employeeShiftRepository = employeeShiftRepository; + } + + public async Task Handle(AssignEmployeeCommand request, CancellationToken cancellationToken) + { + Domain.Entities.EmployeeShift Shift = await _employeeShiftRepository.FindAsync(x => x.ID == request.EmployeeShiftID, cancellationToken) ?? throw new NotFoundException("Employee Shift not found!"); + if (Shift.EmployeeID != null) + throw new DuplicatedObjectException("Employee already assigned to this shift!"); + Shift.EmployeeID = request.EmployeeID; + Shift.CheckIn = request.CheckIn; + Shift.CheckOut = request.CheckOut; + _employeeShiftRepository.Update(Shift); + return await _employeeShiftRepository.UnitOfWork.SaveChangesAsync(cancellationToken) > 0 ? "Employee assigned successfully!" : "Employee assigned failed!"; + + } +} diff --git a/DeerCoffeeShop.Application/EmployeeShift/CheckIn-Out/CheckIn/CheckInCommand.cs b/DeerCoffeeShop.Application/EmployeeShift/CheckIn-Out/CheckIn/CheckInCommand.cs index 9d9a004..22a0e87 100644 --- a/DeerCoffeeShop.Application/EmployeeShift/CheckIn-Out/CheckIn/CheckInCommand.cs +++ b/DeerCoffeeShop.Application/EmployeeShift/CheckIn-Out/CheckIn/CheckInCommand.cs @@ -7,11 +7,6 @@ using DeerCoffeeShop.Domain.Repositories; using MediatR; using Microsoft.AspNetCore.Http; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace DeerCoffeeShop.Application.EmployeeShift.CheckIn_Out.CheckIn; @@ -27,33 +22,27 @@ internal class CheckInCommandHandler(IEmployeeShiftRepository employeeShiftRepos private readonly IEmployeeRepository _employeeRepository = employeeRepository; private readonly IFaceDetectionRepository _faceDetectionRepository = faceDetectionRepository; private readonly IAttdenceRepository _attdenceRepository = attdenceRepository; - Cloudinary cloudinary = new(Environment.GetEnvironmentVariable("CLOUDINARY_URL")); + private readonly Cloudinary cloudinary = new("cloudinary://176963282532847:kONanxuhiEwEmJKFPC72M1a2rUs@dmiueqpah"); private readonly string[] _rootPath = Directory.GetDirectories(Directory.GetCurrentDirectory() + "/TrainedFaces/"); public async Task Handle(CheckInCommand request, CancellationToken cancellationToken) { #region Validate Employee - var EmployeeID = await _faceDetectionRepository.DetectFaceFromImage(request.Image, _rootPath); + string EmployeeID = await _faceDetectionRepository.DetectFaceFromImage(request.Image, _rootPath) ?? throw new NotFoundException("Employee not found!"); if (!await _employeeRepository.AnyAsync(x => x.ID == EmployeeID, cancellationToken)) throw new NotFoundException("Employee not found!"); #endregion #region Check Shift - var DateOfWork = DateOnly.FromDateTime(request.CheckIn); - var empShift = await _employeeShiftRepository.CheckShiftEmployee(EmployeeID, DateOfWork, cancellationToken); - var uploadResult = await UploadEmployeeImage(request.Image); - if (uploadResult == null) - throw new Exception("File upload failed!"); + DateOnly DateOfWork = DateOnly.FromDateTime(request.CheckIn); + Domain.Entities.EmployeeShift? empShift = await _employeeShiftRepository.CheckShiftEmployee(EmployeeID, DateOfWork, request.RestaurantID, cancellationToken) ?? throw new NotFoundException("Employee Shift not found!"); + ImageUploadResult uploadResult = await UploadEmployeeImage(request.Image) ?? throw new Exception("File upload failed!"); if (empShift != null && request.CheckIn.Subtract(empShift.CheckIn.Value).TotalHours > -1) { - //check if the checkintime from the request and the checkintime from the database is not 1 hour apart // this mean the employee work the normal shift not the extra shift - empShift.Actual_CheckIn = request.CheckIn; - var attendence = await _attdenceRepository.FindAsync(x => x.EmployeeShiftID == empShift.ID, cancellationToken); + Attendence? attendence = await _attdenceRepository.FindAsync(x => x.EmployeeShiftID == empShift.ID, cancellationToken); attendence.EmployeePictureUrlCheckIn = uploadResult.Url.ToString(); _employeeShiftRepository.Update(empShift); - - } else // This mean the employee work the extra shift in that same day { @@ -72,10 +61,8 @@ public async Task Handle(CheckInCommand request, CancellationToken cance IsEmpty = false, IsReviewRequired = true }; - - - var attendence = new Attendence + Attendence attendence = new() { EmployeeShiftID = empShift.ID, EmployeePictureUrlCheckIn = uploadResult.Url.ToString(), @@ -91,9 +78,9 @@ public async Task Handle(CheckInCommand request, CancellationToken cance } private async Task UploadEmployeeImage(IFormFile imageFile) { - using (var stream = imageFile.OpenReadStream()) + using (Stream stream = imageFile.OpenReadStream()) { - var uploadParams = new ImageUploadParams() + ImageUploadParams uploadParams = new() { File = new FileDescription(imageFile.FileName, stream), UseFilename = true, diff --git a/DeerCoffeeShop.Application/EmployeeShift/CheckIn-Out/CheckOut/CheckOutCommand.cs b/DeerCoffeeShop.Application/EmployeeShift/CheckIn-Out/CheckOut/CheckOutCommand.cs index a103ba9..eed10d5 100644 --- a/DeerCoffeeShop.Application/EmployeeShift/CheckIn-Out/CheckOut/CheckOutCommand.cs +++ b/DeerCoffeeShop.Application/EmployeeShift/CheckIn-Out/CheckOut/CheckOutCommand.cs @@ -1,5 +1,5 @@ -using CloudinaryDotNet.Actions; -using CloudinaryDotNet; +using CloudinaryDotNet; +using CloudinaryDotNet.Actions; using DeerCoffeeShop.Application.Common.Interfaces; using DeerCoffeeShop.Domain.Common.Exceptions; using DeerCoffeeShop.Domain.Repositories; @@ -20,23 +20,23 @@ internal class CheckOutCommandHandler(IEmployeeShiftRepository employeeShiftRepo private readonly IEmployeeRepository _employeeRepository = employeeRepository; private readonly IFaceDetectionRepository _faceDetectionRepository = faceDetectionRepository; private readonly IAttdenceRepository _attdenceRepository = attdenceRepository; - Cloudinary cloudinary = new(Environment.GetEnvironmentVariable("CLOUDINARY_URL")); + private readonly Cloudinary cloudinary = new("cloudinary://176963282532847:kONanxuhiEwEmJKFPC72M1a2rUs@dmiueqpah"); private readonly string[] _rootPath = Directory.GetDirectories(Directory.GetCurrentDirectory() + "/TrainedFaces/"); public async Task Handle(CheckOutCommand request, CancellationToken cancellationToken) { - var EmployeeID = await _faceDetectionRepository.DetectFaceFromImage(request.Image, _rootPath); + string EmployeeID = await _faceDetectionRepository.DetectFaceFromImage(request.Image, _rootPath); if (!await _employeeRepository.AnyAsync(x => x.ID == EmployeeID, cancellationToken)) throw new NotFoundException("Employee not found!"); - var DateOfWork = DateOnly.FromDateTime(request.CheckOut); - var empShift = await _employeeShiftRepository.CheckShiftEmployee(EmployeeID, DateOfWork, cancellationToken); + DateOnly DateOfWork = DateOnly.FromDateTime(request.CheckOut); + Domain.Entities.EmployeeShift empShift = await _employeeShiftRepository.CheckShiftEmployee(EmployeeID, DateOfWork, request.RestaurantID, cancellationToken); if (empShift != null) { - var uploadResult = await UploadEmployeeImage(request.Image); + ImageUploadResult uploadResult = await UploadEmployeeImage(request.Image); if (uploadResult == null) throw new Exception("File upload failed!"); empShift.Actual_CheckOut = request.CheckOut; - var attendence = await _attdenceRepository.FindAsync(x => x.EmployeeShiftID == empShift.ID, cancellationToken); + Domain.Entities.Attendence? attendence = await _attdenceRepository.FindAsync(x => x.EmployeeShiftID == empShift.ID, cancellationToken); attendence.EmployeePictureUrlCheckOut = uploadResult.Url.ToString(); _employeeShiftRepository.Update(empShift); @@ -45,9 +45,9 @@ public async Task Handle(CheckOutCommand request, CancellationToken canc } private async Task UploadEmployeeImage(IFormFile imageFile) { - using (var stream = imageFile.OpenReadStream()) + using (Stream stream = imageFile.OpenReadStream()) { - var uploadParams = new ImageUploadParams() + ImageUploadParams uploadParams = new() { File = new FileDescription(imageFile.FileName, stream), UseFilename = true, diff --git a/DeerCoffeeShop.Application/EmployeeShift/Create/CreateEmployeeShiftCommandHandler.cs b/DeerCoffeeShop.Application/EmployeeShift/Create/CreateEmployeeShiftCommandHandler.cs index af71a93..94b5853 100644 --- a/DeerCoffeeShop.Application/EmployeeShift/Create/CreateEmployeeShiftCommandHandler.cs +++ b/DeerCoffeeShop.Application/EmployeeShift/Create/CreateEmployeeShiftCommandHandler.cs @@ -1,5 +1,4 @@ using DeerCoffeeShop.Application.Common.Interfaces; -using DeerCoffeeShop.Domain.Common.Exceptions; using DeerCoffeeShop.Domain.Entities; using DeerCoffeeShop.Domain.Repositories; using MediatR; @@ -17,9 +16,9 @@ public class CreateEmployeeShiftCommandHandler(IEmployeeShiftRepository employee public async Task Handle(CreateEmployeeShiftCommand command, CancellationToken cancellationToken) { - var employee = await _employeeRepository.FindAsync(x => x.ID == _currentUserService.UserId, cancellationToken); - var restaurant = await _restaurantRepository.FindAsync(x => x.ManagerID == employee.ManagerID, cancellationToken); - var empShift = new Domain.Entities.EmployeeShift + Employee? employee = await _employeeRepository.FindAsync(x => x.ID == _currentUserService.UserId, cancellationToken); + Restaurant? restaurant = await _restaurantRepository.FindAsync(x => x.ManagerID == employee.ManagerID, cancellationToken); + Domain.Entities.EmployeeShift empShift = new() { RestaurantID = restaurant.ID, EmployeeID = _currentUserService.UserId, @@ -33,8 +32,8 @@ public async Task Handle(CreateEmployeeShiftCommand command, Cancellatio }; _employeeShiftRepository.Add(empShift); - await _employeeShiftRepository.UnitOfWork.SaveChangesAsync(cancellationToken); - var attdence = new Attendence + _ = await _employeeShiftRepository.UnitOfWork.SaveChangesAsync(cancellationToken); + Attendence attdence = new() { EmployeeShiftID = empShift.ID, EmployeePictureUrlCheckIn = "", diff --git a/DeerCoffeeShop.Application/EmployeeShift/Create/CreateEmployeeShiftCommandValidator.cs b/DeerCoffeeShop.Application/EmployeeShift/Create/CreateEmployeeShiftCommandValidator.cs index 50c15a7..a6db98e 100644 --- a/DeerCoffeeShop.Application/EmployeeShift/Create/CreateEmployeeShiftCommandValidator.cs +++ b/DeerCoffeeShop.Application/EmployeeShift/Create/CreateEmployeeShiftCommandValidator.cs @@ -1,37 +1,32 @@ using FluentValidation; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace DeerCoffeeShop.Application.EmployeeShift.Create { public class CreateEmployeeShiftCommandValidator : AbstractValidator { - public CreateEmployeeShiftCommandValidator() + public CreateEmployeeShiftCommandValidator() { Configure(); } public void Configure() { - - - RuleFor(x => x.DateOfWork) + + + _ = RuleFor(x => x.DateOfWork) .NotEmpty() .NotNull() .WithMessage("Date of work must not be empty!"); - - RuleFor(x => x.CheckIn) + + _ = RuleFor(x => x.CheckIn) .NotEmpty() .NotNull() .WithMessage("Check in time must not be empty!"); - RuleFor(x => x.CheckOut) + _ = RuleFor(x => x.CheckOut) .NotEmpty() .NotNull() .WithMessage("Check out time must not be empty!"); diff --git a/DeerCoffeeShop.Application/EmployeeShift/Delete/DeleteEmployeeShiftCommandHandler.cs b/DeerCoffeeShop.Application/EmployeeShift/Delete/DeleteEmployeeShiftCommandHandler.cs index 94f8740..44ba26b 100644 --- a/DeerCoffeeShop.Application/EmployeeShift/Delete/DeleteEmployeeShiftCommandHandler.cs +++ b/DeerCoffeeShop.Application/EmployeeShift/Delete/DeleteEmployeeShiftCommandHandler.cs @@ -12,9 +12,9 @@ public class DeleteEmployeeShiftCommandHandler(IEmployeeShiftRepository employee public async Task Handle(DeleteEmployeeShiftCommand request, CancellationToken cancellationToken) { - var foundObject = await _employeeShiftRepository.FindAsync(x => x.EmployeeID.Equals(request.EmployeeID) + Domain.Entities.EmployeeShift foundObject = await _employeeShiftRepository.FindAsync(x => x.EmployeeID.Equals(request.EmployeeID) && x.RestaurantID.Equals(request.RestaurantID) - + && x.NguoiXoaID == null) ?? throw new NotFoundException("None employee shift of restaurant was found!"); foundObject.EmployeeID = null; diff --git a/DeerCoffeeShop.Application/EmployeeShift/Delete/DeleteEmployeeShiftCommandValidator.cs b/DeerCoffeeShop.Application/EmployeeShift/Delete/DeleteEmployeeShiftCommandValidator.cs index 79c5e2a..ff1f71a 100644 --- a/DeerCoffeeShop.Application/EmployeeShift/Delete/DeleteEmployeeShiftCommandValidator.cs +++ b/DeerCoffeeShop.Application/EmployeeShift/Delete/DeleteEmployeeShiftCommandValidator.cs @@ -11,17 +11,17 @@ public DeleteEmployeeShiftCommandValidator() public void Configure() { - RuleFor(x => x.EmployeeID) + _ = RuleFor(x => x.EmployeeID) .NotEmpty() .NotNull() .WithMessage("Employee must not be empty!"); - RuleFor(x => x.RestaurantID) + _ = RuleFor(x => x.RestaurantID) .NotEmpty() .NotNull() .WithMessage("Restaurant must not be empty!"); - RuleFor(x => x.ShiftID) + _ = RuleFor(x => x.ShiftID) .NotEmpty() .NotNull() .WithMessage("Shift must not be empty!"); diff --git a/DeerCoffeeShop.Application/EmployeeShift/EmployeeShiftDto.cs b/DeerCoffeeShop.Application/EmployeeShift/EmployeeShiftDto.cs index f23d351..87588d2 100644 --- a/DeerCoffeeShop.Application/EmployeeShift/EmployeeShiftDto.cs +++ b/DeerCoffeeShop.Application/EmployeeShift/EmployeeShiftDto.cs @@ -1,14 +1,13 @@ using AutoMapper; using DeerCoffeeShop.Application.Common.Mappings; using DeerCoffeeShop.Application.Employees; -using DeerCoffeeShop.Application.Shift; using DeerCoffeeShop.Domain.Enums; namespace DeerCoffeeShop.Application.EmployeeShift { public class EmployeeShiftDto() : IMapFrom { - + public EmployeeDto Employee { get; set; } public DateOnly DateOfWork { get; set; } public int Month { get; set; } @@ -25,7 +24,7 @@ public class EmployeeShiftDto() : IMapFrom public void Mapping(Profile profile) { - profile.CreateMap(); + _ = profile.CreateMap(); } public static EmployeeShiftDto Create( diff --git a/DeerCoffeeShop.Application/EmployeeShift/EmployeeShiftDtoMappingExtension.cs b/DeerCoffeeShop.Application/EmployeeShift/EmployeeShiftDtoMappingExtension.cs index 663f721..133566f 100644 --- a/DeerCoffeeShop.Application/EmployeeShift/EmployeeShiftDtoMappingExtension.cs +++ b/DeerCoffeeShop.Application/EmployeeShift/EmployeeShiftDtoMappingExtension.cs @@ -1,7 +1,5 @@ using AutoMapper; using DeerCoffeeShop.Application.Employees; -using DeerCoffeeShop.Application.Shift; -using DeerCoffeeShop.Domain.Entities; namespace DeerCoffeeShop.Application.EmployeeShift { @@ -19,7 +17,7 @@ public static List MapToListEmployeeShiftDto(this IEnumerable< public static EmployeeShiftDto MapToEmployeeShiftDto(this Domain.Entities.EmployeeShift form, IMapper mapper , EmployeeDto employee) { - var dto = mapper.Map(form); + EmployeeShiftDto dto = mapper.Map(form); dto.Employee = employee; return dto; diff --git a/DeerCoffeeShop.Application/EmployeeShift/EmployeeShiftDtoV2.cs b/DeerCoffeeShop.Application/EmployeeShift/EmployeeShiftDtoV2.cs index 2ccc2bf..db95a68 100644 --- a/DeerCoffeeShop.Application/EmployeeShift/EmployeeShiftDtoV2.cs +++ b/DeerCoffeeShop.Application/EmployeeShift/EmployeeShiftDtoV2.cs @@ -2,13 +2,7 @@ using DeerCoffeeShop.Application.Common.Mappings; using DeerCoffeeShop.Application.Employees; using DeerCoffeeShop.Application.Shift; -using DeerCoffeeShop.Domain.Entities; using DeerCoffeeShop.Domain.Enums; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace DeerCoffeeShop.Application.EmployeeShift { @@ -31,7 +25,7 @@ public class EmployeeShiftDtoV2 : IMapFrom public string? Note { get; set; } public EmployeeDto Employee { get; set; } - public static EmployeeShiftDtoV2 Create(string ID,string RestaurantID, EmployeeDto employee, + public static EmployeeShiftDtoV2 Create(string ID, string RestaurantID, EmployeeDto employee, DateOnly dateOfWork, int month, int year, DateTime checkIn, DateTime checkOut, DateTime? actual_CheckIn , DateTime? actual_CheckOut, DateTime? totalHours, bool isOnTime, EmployeeShiftStatus status , int employeeNote, string? note) @@ -58,7 +52,7 @@ public static EmployeeShiftDtoV2 Create(string ID,string RestaurantID, EmployeeD public void Mapping(Profile profile) { - profile.CreateMap(); + _ = profile.CreateMap(); } } } diff --git a/DeerCoffeeShop.Application/EmployeeShift/GetAll/GetAllEmployeeShiftQueryHandler.cs b/DeerCoffeeShop.Application/EmployeeShift/GetAll/GetAllEmployeeShiftQueryHandler.cs index 2a14889..4637ac0 100644 --- a/DeerCoffeeShop.Application/EmployeeShift/GetAll/GetAllEmployeeShiftQueryHandler.cs +++ b/DeerCoffeeShop.Application/EmployeeShift/GetAll/GetAllEmployeeShiftQueryHandler.cs @@ -20,14 +20,14 @@ public class GetAllEmployeeShiftQueryHandler(IEmployeeShiftRepository employeeSh public async Task> Handle(GetAllEmployeeShiftQuery query, CancellationToken cancellationToken) { - var list = await _employeeShiftRepository.FindAllAsync(x => !x.IsDeleted && x.RestaurantID.Equals(query.RestaurantId), query.PageNo, query.PageSize, cancellationToken); + IPagedResult list = await _employeeShiftRepository.FindAllAsync(x => !x.IsDeleted && x.RestaurantID.Equals(query.RestaurantId), query.PageNo, query.PageSize, cancellationToken); if (list.TotalCount == 0) throw new NotFoundException("None employee shift was found!"); - var employee = await _employeeRepository.FindAllToDictionaryAsync(x => x.NgayXoa == null || x.NguoiXoaID == null, + Dictionary employee = await _employeeRepository.FindAllToDictionaryAsync(x => x.NgayXoa == null || x.NguoiXoaID == null, x => x.ID, x => x.MapToEmployeeDto(_mapper, EmployeeRole.EmployeeRoleDictionary), cancellationToken); - var shift = await _shiftRepository.FindAllToDictionaryAsync(x => x.IsActive, x => x.ID, x => x.MapToShiftDto(_mapper), cancellationToken); + Dictionary shift = await _shiftRepository.FindAllToDictionaryAsync(x => x.IsActive, x => x.ID, x => x.MapToShiftDto(_mapper), cancellationToken); return PagedResult.Create ( @@ -35,7 +35,7 @@ public async Task> Handle(GetAllEmployeeShiftQuery pageCount: list.PageCount, pageSize: list.PageSize, pageNumber: list.PageNo, - data: list.MapToListEmployeeShiftDto(_mapper, employee) + data: list.MapToListEmployeeShiftDto(_mapper, employee) ); } } diff --git a/DeerCoffeeShop.Application/EmployeeShift/GetAll/GetAllEmployeeShiftQueryValidator.cs b/DeerCoffeeShop.Application/EmployeeShift/GetAll/GetAllEmployeeShiftQueryValidator.cs index 8c9e062..7d4026a 100644 --- a/DeerCoffeeShop.Application/EmployeeShift/GetAll/GetAllEmployeeShiftQueryValidator.cs +++ b/DeerCoffeeShop.Application/EmployeeShift/GetAll/GetAllEmployeeShiftQueryValidator.cs @@ -11,17 +11,17 @@ public GetAllEmployeeShiftQueryValidator() public void Configure() { - RuleFor(x => x.PageNo) + _ = RuleFor(x => x.PageNo) .NotNull() .NotEmpty() .WithMessage("Page number must not be null!"); - RuleFor(x => x.PageSize) + _ = RuleFor(x => x.PageSize) .NotNull() .NotEmpty() .WithMessage("Page size must not be null!"); - RuleFor(x => x.RestaurantId) + _ = RuleFor(x => x.RestaurantId) .NotNull() .NotEmpty() .WithMessage("Restaurant must not be null!"); diff --git a/DeerCoffeeShop.Application/EmployeeShift/GetByDay/GetEmployeeShiftByDayQuery.cs b/DeerCoffeeShop.Application/EmployeeShift/GetByDay/GetEmployeeShiftByDayQuery.cs index b67b8f3..feb4c29 100644 --- a/DeerCoffeeShop.Application/EmployeeShift/GetByDay/GetEmployeeShiftByDayQuery.cs +++ b/DeerCoffeeShop.Application/EmployeeShift/GetByDay/GetEmployeeShiftByDayQuery.cs @@ -1,21 +1,16 @@ using DeerCoffeeShop.Application.Common.Interfaces; using DeerCoffeeShop.Application.Common.Pagination; using MediatR; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace DeerCoffeeShop.Application.EmployeeShift.GetByDay { public class GetEmployeeShiftByDayQuery() : IRequest>, IQuery { - public int PageNo { get; set; } + public int PageNo { get; set; } - public int PageSize { get; set; } + public int PageSize { get; set; } - public DateTime DateOfWork { get; set; } + public DateTime DateOfWork { get; set; } } } diff --git a/DeerCoffeeShop.Application/EmployeeShift/GetByDay/GetEmployeeShiftByDayQueryHandler.cs b/DeerCoffeeShop.Application/EmployeeShift/GetByDay/GetEmployeeShiftByDayQueryHandler.cs index d5e3577..54257e8 100644 --- a/DeerCoffeeShop.Application/EmployeeShift/GetByDay/GetEmployeeShiftByDayQueryHandler.cs +++ b/DeerCoffeeShop.Application/EmployeeShift/GetByDay/GetEmployeeShiftByDayQueryHandler.cs @@ -1,17 +1,9 @@ using AutoMapper; using DeerCoffeeShop.Application.Common.Interfaces; using DeerCoffeeShop.Application.Common.Pagination; -using DeerCoffeeShop.Application.Employees; -using DeerCoffeeShop.Application.Shift; using DeerCoffeeShop.Domain.Common.Exceptions; -using DeerCoffeeShop.Domain.Constants; using DeerCoffeeShop.Domain.Repositories; using MediatR; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace DeerCoffeeShop.Application.EmployeeShift.GetByDay { @@ -27,12 +19,12 @@ public class GetEmployeeShiftByDayQueryHandler(IEmployeeShiftRepository employee public async Task> Handle(GetEmployeeShiftByDayQuery query, CancellationToken cancellationToken) { - var list = await _employeeShiftRepository.FindAllAsync(x => !x.IsDeleted + IPagedResult list = await _employeeShiftRepository.FindAllAsync(x => !x.IsDeleted && x.DateOfWork.Day == query.DateOfWork.Day && x.RestaurantID.Equals(_currentUserService.RestaurantID), query.PageNo, query.PageSize, cancellationToken); if (list.TotalCount == 0) throw new NotFoundException("None employee shift was found!"); - foreach (var item in list) + foreach (Domain.Entities.EmployeeShift item in list) { item.Employee = await _employeeRepository.FindAsync(x => x.ID.Equals(item.EmployeeID), cancellationToken); diff --git a/DeerCoffeeShop.Application/EmployeeShift/GetByDay/GetEmployeeShiftByDayQueryValidator.cs b/DeerCoffeeShop.Application/EmployeeShift/GetByDay/GetEmployeeShiftByDayQueryValidator.cs index 62e4b7b..8a52db7 100644 --- a/DeerCoffeeShop.Application/EmployeeShift/GetByDay/GetEmployeeShiftByDayQueryValidator.cs +++ b/DeerCoffeeShop.Application/EmployeeShift/GetByDay/GetEmployeeShiftByDayQueryValidator.cs @@ -1,9 +1,4 @@ using FluentValidation; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace DeerCoffeeShop.Application.EmployeeShift.GetByDay { @@ -16,18 +11,18 @@ public GetEmployeeShiftByDayQueryValidator() public void Configure() { - RuleFor(x => x.PageNo) + _ = RuleFor(x => x.PageNo) .NotNull() .NotEmpty() .WithMessage("Page number must not be null!"); - RuleFor(x => x.PageSize) + _ = RuleFor(x => x.PageSize) .NotNull() .NotEmpty() .WithMessage("Page size must not be null!"); - RuleFor(x => x.DateOfWork) + _ = RuleFor(x => x.DateOfWork) .NotNull() .NotEmpty() .WithMessage("Date of work must not be null!"); diff --git a/DeerCoffeeShop.Application/EmployeeShift/GetByEmployeeId/GetEmployeeShiftByEmployeeIdQueryHandler.cs b/DeerCoffeeShop.Application/EmployeeShift/GetByEmployeeId/GetEmployeeShiftByEmployeeIdQueryHandler.cs index 9916777..8ecd2d4 100644 --- a/DeerCoffeeShop.Application/EmployeeShift/GetByEmployeeId/GetEmployeeShiftByEmployeeIdQueryHandler.cs +++ b/DeerCoffeeShop.Application/EmployeeShift/GetByEmployeeId/GetEmployeeShiftByEmployeeIdQueryHandler.cs @@ -22,15 +22,15 @@ public class GetEmployeeShiftByEmployeeIdQueryHandler(IEmployeeShiftRepository e public async Task> Handle(GetEmployeeShiftByEmployeeIdQuery query, CancellationToken cancellationToken) { - var list = await _employeeShiftRepository.FindAllAsync(x => !x.IsDeleted, query.PageNo, query.PageSize, cancellationToken); + IPagedResult list = await _employeeShiftRepository.FindAllAsync(x => !x.IsDeleted, query.PageNo, query.PageSize, cancellationToken); if (list.TotalCount == 0) throw new NotFoundException("None employee shift was found!"); - var employee = await _employeeRepository.FindAllToDictionaryAsync(x => x.NgayXoa == null || x.NguoiXoaID == null, + Dictionary employee = await _employeeRepository.FindAllToDictionaryAsync(x => x.NgayXoa == null || x.NguoiXoaID == null, x => x.ID, x => x.MapToEmployeeDto(_mapper, EmployeeRole.EmployeeRoleDictionary), cancellationToken); - var shift = await _shiftRepository.FindAllToDictionaryAsync(x => x.IsActive == true, x => x.ID, x => x.MapToShiftDto(_mapper), cancellationToken); + Dictionary shift = await _shiftRepository.FindAllToDictionaryAsync(x => x.IsActive == true, x => x.ID, x => x.MapToShiftDto(_mapper), cancellationToken); return PagedResult.Create ( @@ -38,7 +38,7 @@ public async Task> Handle(GetEmployeeShiftByEmploy pageCount: list.PageCount, pageSize: list.PageSize, pageNumber: list.PageNo, - data: list.MapToListEmployeeShiftDto(_mapper, employee) + data: list.MapToListEmployeeShiftDto(_mapper, employee) ); } } diff --git a/DeerCoffeeShop.Application/EmployeeShift/GetByEmployeeId/GetEmployeeShiftByEmployeeIdQueryValidator.cs b/DeerCoffeeShop.Application/EmployeeShift/GetByEmployeeId/GetEmployeeShiftByEmployeeIdQueryValidator.cs index 0d14ebe..d2fe8a2 100644 --- a/DeerCoffeeShop.Application/EmployeeShift/GetByEmployeeId/GetEmployeeShiftByEmployeeIdQueryValidator.cs +++ b/DeerCoffeeShop.Application/EmployeeShift/GetByEmployeeId/GetEmployeeShiftByEmployeeIdQueryValidator.cs @@ -11,7 +11,7 @@ public GetEmployeeShiftByEmployeeIdQueryValidator() public void Configure() { - RuleFor(x => x.EmployeeId) + _ = RuleFor(x => x.EmployeeId) .NotNull() .NotEmpty() .WithMessage("Employee must be not empty!"); diff --git a/DeerCoffeeShop.Application/EmployeeShift/GetEmployeeShiftInAWeek/GetEmployeeShiftInAWeekQuery.cs b/DeerCoffeeShop.Application/EmployeeShift/GetEmployeeShiftInAWeek/GetEmployeeShiftInAWeekQuery.cs index f96076b..a04b2e3 100644 --- a/DeerCoffeeShop.Application/EmployeeShift/GetEmployeeShiftInAWeek/GetEmployeeShiftInAWeekQuery.cs +++ b/DeerCoffeeShop.Application/EmployeeShift/GetEmployeeShiftInAWeek/GetEmployeeShiftInAWeekQuery.cs @@ -1,7 +1,7 @@ using AutoMapper; using DeerCoffeeShop.Application.Common.Interfaces; using DeerCoffeeShop.Application.Common.Security; -using DeerCoffeeShop.Application.Employees; +using DeerCoffeeShop.Domain.Common.Method; using DeerCoffeeShop.Domain.Entities; using DeerCoffeeShop.Domain.Repositories; using MediatR; @@ -25,22 +25,22 @@ internal class GetEmployeeShiftInAWeekQueryHandler(IEmployeeShiftRepository empl public async Task> Handle(GetEmployeeShiftInAWeekQuery request, CancellationToken cancellationToken) { List employeeShifts; - var UserID = _currentUserService.UserId; - var isManager = await _currentUserService.IsInRoleAsync("Manager"); - var ManagerIDOfRestaurant = await _restaurantRepository.FindAsync(_ => _.ManagerID == UserID, cancellationToken); + string? UserID = _currentUserService.UserId; + bool isManager = await _currentUserService.IsInRoleAsync("Manager"); + Restaurant? ManagerIDOfRestaurant = await _restaurantRepository.FindAsync(_ => _.ManagerID == UserID, cancellationToken); if (!request.IsMonth) { - var weekDates = GetWeekDates(request.Date); + List weekDates = GetWeekDates.Get(request.Date); if (isManager) { employeeShifts = await _employeeShiftRepository.FindAllAsync(x => x.DateOfWork >= weekDates[0] && x.DateOfWork <= weekDates[weekDates.Count - 1] && x.RestaurantID == ManagerIDOfRestaurant.ID, cancellationToken); } else { - var User = await _employeeRepository.FindAsync(x => x.ID == UserID, cancellationToken); - var RestaurantID = await _restaurantRepository.FindAsync(x => x.ManagerID == User.ManagerID, cancellationToken); + Employee? User = await _employeeRepository.FindAsync(x => x.ID == UserID, cancellationToken); + Restaurant? RestaurantID = await _restaurantRepository.FindAsync(x => x.ManagerID == User.ManagerID, cancellationToken); employeeShifts = await _employeeShiftRepository.FindAllAsync(x => x.DateOfWork >= weekDates[0] && x.DateOfWork <= weekDates[weekDates.Count - 1] && x.RestaurantID == RestaurantID.ID && x.EmployeeID == UserID, cancellationToken); } @@ -51,7 +51,7 @@ public async Task> Handle(GetEmployeeShiftInAWeekQuery } // Retrieve employee details - foreach (var item in employeeShifts) + foreach (Domain.Entities.EmployeeShift item in employeeShifts) { item.Employee = await _employeeRepository.FindAsync(x => x.ID == item.EmployeeID, cancellationToken); } @@ -65,26 +65,6 @@ public async Task> Handle(GetEmployeeShiftInAWeekQuery } - - private static List GetWeekDates(DateOnly date) - { - List weekDates = []; - - // Get the day of the week as an integer (0 = Sunday, 1 = Monday, ..., 6 = Saturday) - int dayOfWeek = (int)date.DayOfWeek; - - // Calculate the previous Sunday - DateOnly startOfWeek = date.AddDays(-dayOfWeek); - - // Add each day from the previous Sunday to the next Saturday to the list - for (int i = 0; i < 7; i++) - { - weekDates.Add(startOfWeek.AddDays(i)); - } - - return weekDates; - } - } diff --git a/DeerCoffeeShop.Application/EmployeeShift/GetNeededReviewShift/GetNeededReviewShiftQuery.cs b/DeerCoffeeShop.Application/EmployeeShift/GetNeededReviewShift/GetNeededReviewShiftQuery.cs new file mode 100644 index 0000000..6bcfc4f --- /dev/null +++ b/DeerCoffeeShop.Application/EmployeeShift/GetNeededReviewShift/GetNeededReviewShiftQuery.cs @@ -0,0 +1,50 @@ +using AutoMapper; +using DeerCoffeeShop.Application.Common.Interfaces; +using DeerCoffeeShop.Domain.Common.Method; +using DeerCoffeeShop.Domain.Repositories; +using MediatR; + +namespace DeerCoffeeShop.Application.EmployeeShift.GetNeededReviewShift; + +public class GetNeededReviewShiftQuery(DateOnly date, bool isMonth) : IRequest>, IQuery +{ + public DateOnly Date { get; set; } = date; + public bool IsMonth { get; set; } = isMonth; +} + +internal sealed class GetNeededReviewShiftQueryHandler : IRequestHandler> +{ + private readonly IEmployeeShiftRepository _employeeShiftRepository; + private readonly IEmployeeRepository _employeeRepository; + private readonly IMapper _mapper; + + public GetNeededReviewShiftQueryHandler(IEmployeeShiftRepository employeeShiftRepository, IEmployeeRepository employeeRepository, IMapper mapper) + { + _employeeShiftRepository = employeeShiftRepository; + _employeeRepository = employeeRepository; + _mapper = mapper; + } + + public async Task> Handle(GetNeededReviewShiftQuery request, CancellationToken cancellationToken) + { + List employeeShifts; + if (!request.IsMonth) + { + List weekDates = GetWeekDates.Get(request.Date); + employeeShifts = await _employeeShiftRepository.FindAllAsync(x => x.DateOfWork >= weekDates[0] && x.DateOfWork <= weekDates[weekDates.Count - 1] && x.IsReviewRequired, cancellationToken); + } + else + { + employeeShifts = await _employeeShiftRepository.FindAllAsync(x => x.Month == request.Date.Month && x.IsReviewRequired, cancellationToken); + } + + // Retrieve employee details + foreach (Domain.Entities.EmployeeShift item in employeeShifts) + { + item.Employee = await _employeeRepository.FindAsync(x => x.ID == item.EmployeeID, cancellationToken); + } + + return _mapper.Map>(employeeShifts); + } +} + diff --git a/DeerCoffeeShop.Application/EmployeeShift/UpdateEmployeeShift/UpdateEmployeeShiftCommand.cs b/DeerCoffeeShop.Application/EmployeeShift/UpdateEmployeeShift/UpdateEmployeeShiftCommand.cs index d4c61d8..c34a7a2 100644 --- a/DeerCoffeeShop.Application/EmployeeShift/UpdateEmployeeShift/UpdateEmployeeShiftCommand.cs +++ b/DeerCoffeeShop.Application/EmployeeShift/UpdateEmployeeShift/UpdateEmployeeShiftCommand.cs @@ -1,10 +1,5 @@ using DeerCoffeeShop.Application.Common.Interfaces; using MediatR; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace DeerCoffeeShop.Application.EmployeeShift.UpdateEmployeeShift { @@ -18,9 +13,9 @@ public class UpdateEmployeeShiftCommand() : IRequest, ICommand public required DateTime DateOfWork { get; set; } - public DateTime? ActualCheckIn { get; set; } + public DateTime? ActualCheckIn { get; set; } - public DateTime? ActualCheckOut { get; set; } + public DateTime? ActualCheckOut { get; set; } public string? Note { get; set; } } diff --git a/DeerCoffeeShop.Application/EmployeeShift/UpdateEmployeeShift/UpdateEmployeeShiftCommandHandler.cs b/DeerCoffeeShop.Application/EmployeeShift/UpdateEmployeeShift/UpdateEmployeeShiftCommandHandler.cs index 876ff65..937ad09 100644 --- a/DeerCoffeeShop.Application/EmployeeShift/UpdateEmployeeShift/UpdateEmployeeShiftCommandHandler.cs +++ b/DeerCoffeeShop.Application/EmployeeShift/UpdateEmployeeShift/UpdateEmployeeShiftCommandHandler.cs @@ -1,11 +1,6 @@ using DeerCoffeeShop.Domain.Common.Exceptions; using DeerCoffeeShop.Domain.Repositories; using MediatR; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace DeerCoffeeShop.Application.EmployeeShift.UpdateEmployeeShift { @@ -15,7 +10,7 @@ public class UpdateEmployeeShiftCommandHandler(IEmployeeShiftRepository employee public async Task Handle(UpdateEmployeeShiftCommand command, CancellationToken cancellationToken) { - var foundObject = await _employeeShiftRepository.FindAsync(x => x.RestaurantID.Equals(command.RestaurantID) + Domain.Entities.EmployeeShift foundObject = await _employeeShiftRepository.FindAsync(x => x.RestaurantID.Equals(command.RestaurantID) && x.EmployeeID.Equals(command.EmployeeID) && x.DateOfWork.Equals(command.DateOfWork) @@ -24,16 +19,12 @@ public async Task Handle(UpdateEmployeeShiftCommand command, Cancellatio foundObject.Actual_CheckIn = command.ActualCheckIn; foundObject.Actual_CheckOut = command.ActualCheckOut; - if (!command.ActualCheckIn.HasValue && !command.ActualCheckOut.HasValue) - foundObject.Status = Domain.Enums.EmployeeShiftStatus.Absent; + foundObject.Status = !command.ActualCheckIn.HasValue && !command.ActualCheckOut.HasValue + ? Domain.Enums.EmployeeShiftStatus.Absent + : Domain.Enums.EmployeeShiftStatus.OnTime; - - - else - foundObject.Status = Domain.Enums.EmployeeShiftStatus.OnTime; - - var totalHour = command.ActualCheckIn - command.ActualCheckOut; - var employeeNote = command.ActualCheckIn - foundObject.CheckIn; + TimeSpan? totalHour = command.ActualCheckIn - command.ActualCheckOut; + TimeSpan? employeeNote = command.ActualCheckIn - foundObject.CheckIn; // foundObject.TotalHours = foundObject.DateOfWork + totalHour; foundObject.EmployeeNote = employeeNote.Value.Hours; diff --git a/DeerCoffeeShop.Application/EmployeeShift/UpdateEmployeeShift/UpdateEmployeeShiftCommandValidator.cs b/DeerCoffeeShop.Application/EmployeeShift/UpdateEmployeeShift/UpdateEmployeeShiftCommandValidator.cs index 0dbe54b..ccc6d44 100644 --- a/DeerCoffeeShop.Application/EmployeeShift/UpdateEmployeeShift/UpdateEmployeeShiftCommandValidator.cs +++ b/DeerCoffeeShop.Application/EmployeeShift/UpdateEmployeeShift/UpdateEmployeeShiftCommandValidator.cs @@ -1,37 +1,32 @@ using FluentValidation; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace DeerCoffeeShop.Application.EmployeeShift.UpdateEmployeeShift { public class UpdateEmployeeShiftCommandValidator : AbstractValidator { - public UpdateEmployeeShiftCommandValidator() + public UpdateEmployeeShiftCommandValidator() { Configure(); } public void Configure() { - RuleFor(x => x.RestaurantID) + _ = RuleFor(x => x.RestaurantID) .NotEmpty() .NotNull() .WithMessage("Restaurant must not be empty!"); - RuleFor(x => x.ShiftID) + _ = RuleFor(x => x.ShiftID) .NotEmpty() .NotNull() .WithMessage("Shift must not be empty!"); - RuleFor(x => x.DateOfWork) + _ = RuleFor(x => x.DateOfWork) .NotEmpty() .NotNull() .WithMessage("Date of work must not be empty!"); - RuleFor(x => x.EmployeeID) + _ = RuleFor(x => x.EmployeeID) .NotEmpty() .NotNull() .WithMessage("Employee must not be empty!"); diff --git a/DeerCoffeeShop.Application/Employees/CreateEmployee/CreateEmployeeCommandHandler.cs b/DeerCoffeeShop.Application/Employees/CreateEmployee/CreateEmployeeCommandHandler.cs index 1a81b24..12bfdbe 100644 --- a/DeerCoffeeShop.Application/Employees/CreateEmployee/CreateEmployeeCommandHandler.cs +++ b/DeerCoffeeShop.Application/Employees/CreateEmployee/CreateEmployeeCommandHandler.cs @@ -1,7 +1,6 @@ using DeerCoffeeShop.Application.Utils; using DeerCoffeeShop.Domain.Common.Exceptions; using DeerCoffeeShop.Domain.Entities; -using DeerCoffeeShop.Domain.Enums; using DeerCoffeeShop.Domain.Repositories; using MediatR; using System.Dynamic; @@ -23,10 +22,10 @@ public CreateEmployeeCommandHandler(IEmployeeRepository employeeRepository, IRol public async Task Handle(CreateEmployeeCommand request, CancellationToken cancellationToken) { - var isError = false; + bool isError = false; dynamic errorData = new ExpandoObject(); - var existed = await _employeeRepository.FindAsync(x => x.Email == request.Email, cancellationToken); - var date = DateTime.Parse(request.DateOfBirth); + Employee? existed = await _employeeRepository.FindAsync(x => x.Email == request.Email, cancellationToken); + DateTime date = DateTime.Parse(request.DateOfBirth); if (existed?.Email != null) { errorData.Email = "Email already exist !"; @@ -61,7 +60,7 @@ public async Task Handle(CreateEmployeeCommand request, CancellationToke } - var emp = new Employee + Employee emp = new() { Address = request.Address, DateOfBirth = DateTime.Parse(request.DateOfBirth), @@ -74,15 +73,15 @@ public async Task Handle(CreateEmployeeCommand request, CancellationToke }; _employeeRepository.Add(emp); - await _employeeRepository.UnitOfWork.SaveChangesAsync(cancellationToken); + _ = await _employeeRepository.UnitOfWork.SaveChangesAsync(cancellationToken); - var enity = await _employeeRepository.FindAsync(x => x.Email == request.Email, cancellationToken); + Employee? enity = await _employeeRepository.FindAsync(x => x.Email == request.Email, cancellationToken); await MailUtils.SendEmailAsync(request.FullName, request.Email, request.Address, request.PhoneNumber, $"{date.Day}/{date.Month}/{date.Year}", "Đơn Xác Nhận Đăng Ký"); - var form = new Domain.Entities.Form + Form form = new() { EmployeeID = enity?.ID, FormType = Domain.Enums.FormTypeEnum.JOB_APPLICATION, diff --git a/DeerCoffeeShop.Application/Employees/CreateEmployee/CreateEmployeeCommandValidator.cs b/DeerCoffeeShop.Application/Employees/CreateEmployee/CreateEmployeeCommandValidator.cs index e58bc17..10c40c4 100644 --- a/DeerCoffeeShop.Application/Employees/CreateEmployee/CreateEmployeeCommandValidator.cs +++ b/DeerCoffeeShop.Application/Employees/CreateEmployee/CreateEmployeeCommandValidator.cs @@ -8,11 +8,11 @@ public class CreateEmployeeCommandValidator : AbstractValidator x).Custom((command, context) => + _ = RuleFor(x => x).Custom((command, context) => { bool isError = false; dynamic errorData = new ExpandoObject(); - var errorDictionary = (IDictionary)errorData; + IDictionary errorDictionary = (IDictionary)errorData; if (string.IsNullOrEmpty(command.Email) || !IsValidEmail(command.Email)) { errorDictionary["Email"] = "Email must be a valid email address."; @@ -53,7 +53,7 @@ private bool IsValidEmail(string email) { try { - var addr = new System.Net.Mail.MailAddress(email); + System.Net.Mail.MailAddress addr = new(email); return addr.Address == email; } catch diff --git a/DeerCoffeeShop.Application/Employees/DeleteEmployee/DeleteEmployeeCommand.cs b/DeerCoffeeShop.Application/Employees/DeleteEmployee/DeleteEmployeeCommand.cs index 2cdbaf2..1c91210 100644 --- a/DeerCoffeeShop.Application/Employees/DeleteEmployee/DeleteEmployeeCommand.cs +++ b/DeerCoffeeShop.Application/Employees/DeleteEmployee/DeleteEmployeeCommand.cs @@ -1,5 +1,4 @@ using DeerCoffeeShop.Application.Common.Interfaces; -using DeerCoffeeShop.Application.Common.Security; using MediatR; namespace DeerCoffeeShop.Application.Employees.DeleteEmployee diff --git a/DeerCoffeeShop.Application/Employees/DeleteEmployee/DeleteEmployeeCommandHandler.cs b/DeerCoffeeShop.Application/Employees/DeleteEmployee/DeleteEmployeeCommandHandler.cs index 4fdc4a6..7c00969 100644 --- a/DeerCoffeeShop.Application/Employees/DeleteEmployee/DeleteEmployeeCommandHandler.cs +++ b/DeerCoffeeShop.Application/Employees/DeleteEmployee/DeleteEmployeeCommandHandler.cs @@ -13,7 +13,7 @@ public class DeleteEmployeeCommandHandler(IEmployeeRepository employeeRepository public async Task Handle(DeleteEmployeeCommand request, CancellationToken cancellationToken) { - var foundObject = await _employeeRepository.FindAsync(x => x.ID.Equals(request.EmployeeID) + Domain.Entities.Employee? foundObject = await _employeeRepository.FindAsync(x => x.ID.Equals(request.EmployeeID) ); if (foundObject == null) throw new NotFoundException("None employee shift of restaurant was found!"); diff --git a/DeerCoffeeShop.Application/Employees/DeleteEmployee/DeleteEmployeeCommandValidator.cs b/DeerCoffeeShop.Application/Employees/DeleteEmployee/DeleteEmployeeCommandValidator.cs index 1664595..0d7cf21 100644 --- a/DeerCoffeeShop.Application/Employees/DeleteEmployee/DeleteEmployeeCommandValidator.cs +++ b/DeerCoffeeShop.Application/Employees/DeleteEmployee/DeleteEmployeeCommandValidator.cs @@ -11,7 +11,7 @@ public DeleteEmployeeCommandValidator() public void Configure() { - RuleFor(x => x.EmployeeID) + _ = RuleFor(x => x.EmployeeID) .NotEmpty() .NotNull() .WithMessage("Employee must not be empty!"); diff --git a/DeerCoffeeShop.Application/Employees/EmployeeDTO.cs b/DeerCoffeeShop.Application/Employees/EmployeeDTO.cs index 725fee9..c19ccd0 100644 --- a/DeerCoffeeShop.Application/Employees/EmployeeDTO.cs +++ b/DeerCoffeeShop.Application/Employees/EmployeeDTO.cs @@ -23,7 +23,7 @@ public static EmployeeDto Create(string iD, string fullName, string email, strin { return new EmployeeDto { - + ID = iD, FullName = fullName, Email = email, @@ -51,8 +51,8 @@ public static EmployeeDto CreateDtoLogin(string fullName, string roleID, string? public void Mapping(Profile profile) { - profile.CreateMap(); - + _ = profile.CreateMap(); + } } }; diff --git a/DeerCoffeeShop.Application/Employees/EmployeeMappingExtensions.cs b/DeerCoffeeShop.Application/Employees/EmployeeMappingExtensions.cs index 1168b98..6f61dda 100644 --- a/DeerCoffeeShop.Application/Employees/EmployeeMappingExtensions.cs +++ b/DeerCoffeeShop.Application/Employees/EmployeeMappingExtensions.cs @@ -7,14 +7,14 @@ public static class EmployeeMappingExtensions { public static EmployeeDto MapToEmployeeDto(this Employee entity, IMapper mapper, string roleName) { - var dto = mapper.Map(entity); + EmployeeDto dto = mapper.Map(entity); dto.RoleName = roleName; return dto; } public static EmployeeDto MapToEmployeeDto(this Employee entity, IMapper mapper, Dictionary Role) { - var dto = mapper.Map(entity); + EmployeeDto dto = mapper.Map(entity); dto.RoleName = Role.ContainsKey(entity.RoleID) ? Role[entity.RoleID] : "Error"; return dto; } diff --git a/DeerCoffeeShop.Application/Employees/GetAllEmployee/GetAllEmployeeQueryHandler.cs b/DeerCoffeeShop.Application/Employees/GetAllEmployee/GetAllEmployeeQueryHandler.cs index fdaf76a..0018214 100644 --- a/DeerCoffeeShop.Application/Employees/GetAllEmployee/GetAllEmployeeQueryHandler.cs +++ b/DeerCoffeeShop.Application/Employees/GetAllEmployee/GetAllEmployeeQueryHandler.cs @@ -24,19 +24,10 @@ public GetAllEmployeeQueryHandler(IEmployeeRepository employeeRepository, IRoleR public async Task> Handle(GetAllEmployeeQuery request, CancellationToken cancellationToken) { - var role = await _currentUserService.IsInRoleAsync("Admin"); - IPagedResult? list = null; - if (role) - { - list = await _employeeRepository.FindAllAsync(x => !x.IsDeleted && x.ManagerID == _currentUserService.UserId, request.PageNumber, request.PageSize, cancellationToken); - - } - else - { - list = await _employeeRepository.FindAllAsync(x => !x.IsDeleted && x.RoleID == 2, request.PageNumber, request.PageSize, cancellationToken); - } - - + bool role = await _currentUserService.IsInRoleAsync("Admin"); + IPagedResult? list = role + ? await _employeeRepository.FindAllAsync(x => !x.IsDeleted && x.ManagerID == _currentUserService.UserId, request.PageNumber, request.PageSize, cancellationToken) + : await _employeeRepository.FindAllAsync(x => !x.IsDeleted && x.RoleID == 2, request.PageNumber, request.PageSize, cancellationToken); return PagedResult.Create(totalCount: list.TotalCount, pageCount: list.PageCount, pageSize: list.PageSize, diff --git a/DeerCoffeeShop.Application/Employees/GetEmployee/GetEmployeeQueryHandler.cs b/DeerCoffeeShop.Application/Employees/GetEmployee/GetEmployeeQueryHandler.cs index b8de084..349907c 100644 --- a/DeerCoffeeShop.Application/Employees/GetEmployee/GetEmployeeQueryHandler.cs +++ b/DeerCoffeeShop.Application/Employees/GetEmployee/GetEmployeeQueryHandler.cs @@ -20,12 +20,10 @@ public GetEmployeeQueryHandler(IEmployeeRepository employeeRepository, IRoleRepo public async Task Handle(GetEmployeeQuery request, CancellationToken cancellationToken) { - var employee = await _employeeRepository.FindAsync(x => x.ID.Equals(request.EmployeeId), cancellationToken); - if (employee == null) - { - throw new NotFoundException("Employee is not exist !"); - } - return employee.MapToEmployeeDto(_mapper, EmployeeRole.EmployeeRoleDictionary[employee.RoleID]); + Domain.Entities.Employee? employee = await _employeeRepository.FindAsync(x => x.ID.Equals(request.EmployeeId), cancellationToken); + return employee == null + ? throw new NotFoundException("Employee is not exist !") + : employee.MapToEmployeeDto(_mapper, EmployeeRole.EmployeeRoleDictionary[employee.RoleID]); } } } \ No newline at end of file diff --git a/DeerCoffeeShop.Application/Employees/GetEmployee/GetEmployeeQueryValidator.cs b/DeerCoffeeShop.Application/Employees/GetEmployee/GetEmployeeQueryValidator.cs index de1c6b4..2ae4333 100644 --- a/DeerCoffeeShop.Application/Employees/GetEmployee/GetEmployeeQueryValidator.cs +++ b/DeerCoffeeShop.Application/Employees/GetEmployee/GetEmployeeQueryValidator.cs @@ -12,7 +12,7 @@ public GetEmployeeQueryValidator() public void Configure() { - RuleFor(x => x.EmployeeId) + _ = RuleFor(x => x.EmployeeId) .NotNull() .NotEmpty() .WithMessage("Employee must be not empty!"); diff --git a/DeerCoffeeShop.Application/Employees/GetEmployeeInfo/GetEmployeeInfoQuery.cs b/DeerCoffeeShop.Application/Employees/GetEmployeeInfo/GetEmployeeInfoQuery.cs index 452430d..221c3f5 100644 --- a/DeerCoffeeShop.Application/Employees/GetEmployeeInfo/GetEmployeeInfoQuery.cs +++ b/DeerCoffeeShop.Application/Employees/GetEmployeeInfo/GetEmployeeInfoQuery.cs @@ -2,11 +2,6 @@ using DeerCoffeeShop.Domain.Constants; using DeerCoffeeShop.Domain.Repositories; using MediatR; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace DeerCoffeeShop.Application.Employees.GetEmployeeInfo { @@ -21,14 +16,14 @@ internal class GetEmployeeInfoQueryHandler(IEmployeeRepository employeeRepositor public async Task Handle(GetEmployeeInfoQuery request, CancellationToken cancellationToken) { - var employee = await _employeeRepository.FindAsync(_ => _.ID == request.EmployeeID && _.NgayXoa == null, cancellationToken); + Domain.Entities.Employee? employee = await _employeeRepository.FindAsync(_ => _.ID == request.EmployeeID && _.NgayXoa == null, cancellationToken); if (employee.RoleID == 2) { - var ResID = await _restaurantRepository.FindAsync(_ => _.ManagerID == employee.ID && _.NgayXoa == null, cancellationToken); + Domain.Entities.Restaurant? ResID = await _restaurantRepository.FindAsync(_ => _.ManagerID == employee.ID && _.NgayXoa == null, cancellationToken); return EmployeeDto.CreateDtoLogin(employee.FullName, EmployeeRole.EmployeeRoleDictionary[employee.RoleID], employee.AvatarUrl, ResID?.ID); } - return EmployeeDto.CreateDtoLogin(employee.FullName, EmployeeRole.EmployeeRoleDictionary[employee.RoleID], employee.AvatarUrl,null); + return EmployeeDto.CreateDtoLogin(employee.FullName, EmployeeRole.EmployeeRoleDictionary[employee.RoleID], employee.AvatarUrl, null); } } } diff --git a/DeerCoffeeShop.Application/Employees/UpdateEmployee/UpdateEmployeeCommand.cs b/DeerCoffeeShop.Application/Employees/UpdateEmployee/UpdateEmployeeCommand.cs index b1a5593..fc5a812 100644 --- a/DeerCoffeeShop.Application/Employees/UpdateEmployee/UpdateEmployeeCommand.cs +++ b/DeerCoffeeShop.Application/Employees/UpdateEmployee/UpdateEmployeeCommand.cs @@ -1,5 +1,4 @@ using DeerCoffeeShop.Application.Common.Interfaces; -using DeerCoffeeShop.Application.Common.Security; using MediatR; namespace DeerCoffeeShop.Application.Employees.UpdateEmployee diff --git a/DeerCoffeeShop.Application/Employees/UpdateEmployee/UpdateEmployeeCommandHandler.cs b/DeerCoffeeShop.Application/Employees/UpdateEmployee/UpdateEmployeeCommandHandler.cs index 4f1c3be..a71b176 100644 --- a/DeerCoffeeShop.Application/Employees/UpdateEmployee/UpdateEmployeeCommandHandler.cs +++ b/DeerCoffeeShop.Application/Employees/UpdateEmployee/UpdateEmployeeCommandHandler.cs @@ -13,7 +13,7 @@ public class UpdateEmployeeCommandHandler(IEmployeeRepository employeeRepository public async Task Handle(UpdateEmployeeCommand command, CancellationToken cancellationToken) { - var foundObject = await _employeeRepository.FindAsync(x => x.ID.Equals(command.EmployeeID) + Domain.Entities.Employee? foundObject = await _employeeRepository.FindAsync(x => x.ID.Equals(command.EmployeeID) ); if (foundObject == null) throw new NotFoundException("None shift was found!"); diff --git a/DeerCoffeeShop.Application/Employees/UpdateEmployee/UpdateEmployeeCommandValidator.cs b/DeerCoffeeShop.Application/Employees/UpdateEmployee/UpdateEmployeeCommandValidator.cs index 8ebd9bb..77ee09a 100644 --- a/DeerCoffeeShop.Application/Employees/UpdateEmployee/UpdateEmployeeCommandValidator.cs +++ b/DeerCoffeeShop.Application/Employees/UpdateEmployee/UpdateEmployeeCommandValidator.cs @@ -8,11 +8,11 @@ public class UpdateEmployeeCommandValidator : AbstractValidator x).Custom((command, context) => + _ = RuleFor(x => x).Custom((command, context) => { bool isError = false; dynamic errorData = new ExpandoObject(); - var errorDictionary = (IDictionary)errorData; + IDictionary errorDictionary = (IDictionary)errorData; if (string.IsNullOrEmpty(command.Email)) { errorDictionary["Email"] = "Email can not be Empty."; @@ -99,7 +99,7 @@ private bool IsValidEmail(string email) { try { - var addr = new System.Net.Mail.MailAddress(email); + System.Net.Mail.MailAddress addr = new(email); return addr.Address == email; } catch diff --git a/DeerCoffeeShop.Application/FaceID/DetectFaceFromImage/DetecFaceFromImageQuery.cs b/DeerCoffeeShop.Application/FaceID/DetectFaceFromImage/DetecFaceFromImageQuery.cs index 159d484..9e378d0 100644 --- a/DeerCoffeeShop.Application/FaceID/DetectFaceFromImage/DetecFaceFromImageQuery.cs +++ b/DeerCoffeeShop.Application/FaceID/DetectFaceFromImage/DetecFaceFromImageQuery.cs @@ -2,11 +2,6 @@ using DeerCoffeeShop.Domain.Repositories; using MediatR; using Microsoft.AspNetCore.Http; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace DeerCoffeeShop.Application.FaceID.DetectFaceFromImage; diff --git a/DeerCoffeeShop.Application/FaceID/SaveImage/SaveImageCommand.cs b/DeerCoffeeShop.Application/FaceID/SaveImage/SaveImageCommand.cs index 92c4417..d9b23ef 100644 --- a/DeerCoffeeShop.Application/FaceID/SaveImage/SaveImageCommand.cs +++ b/DeerCoffeeShop.Application/FaceID/SaveImage/SaveImageCommand.cs @@ -1,13 +1,7 @@ using DeerCoffeeShop.Application.Common.Interfaces; -using DeerCoffeeShop.Domain.Common.Exceptions; using DeerCoffeeShop.Domain.Repositories; using MediatR; using Microsoft.AspNetCore.Http; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace DeerCoffeeShop.Application.FaceID.SaveImage; @@ -29,7 +23,7 @@ public SaveImageCommandHandler(IFaceDetectionRepository faceDetectionRepository) public async Task Handle(SaveImageCommand request, CancellationToken cancellationToken) { // Construct the path to the employee's folder - var employeeFolderPath = Path.Combine(_rootPath, "TrainedFaces", request.EmployeeID); + string employeeFolderPath = Path.Combine(_rootPath, "TrainedFaces", request.EmployeeID); return await _faceDetectionRepository.SaveImage(request.Image, request.EmployeeID, employeeFolderPath, cancellationToken); diff --git a/DeerCoffeeShop.Application/Forms/Commands/AcceptEmployeeAndGeneratePassword/AcceptEmployeeAndGeneratePasswordCommand.cs b/DeerCoffeeShop.Application/Forms/Commands/AcceptEmployeeAndGeneratePassword/AcceptEmployeeAndGeneratePasswordCommand.cs index a03d21b..0857e78 100644 --- a/DeerCoffeeShop.Application/Forms/Commands/AcceptEmployeeAndGeneratePassword/AcceptEmployeeAndGeneratePasswordCommand.cs +++ b/DeerCoffeeShop.Application/Forms/Commands/AcceptEmployeeAndGeneratePassword/AcceptEmployeeAndGeneratePasswordCommand.cs @@ -3,11 +3,6 @@ using DeerCoffeeShop.Domain.Common.Exceptions; using DeerCoffeeShop.Domain.Repositories; using MediatR; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace DeerCoffeeShop.Application.Forms.Commands.AcceptEmployeeAndGeneratePassword; @@ -30,15 +25,15 @@ public AcceptEmployeeAndGeneratePasswordCommandHandler(IEmployeeRepository emplo } public async Task Handle(AcceptEmployeeAndGeneratePasswordCommand request, CancellationToken cancellationToken) { - var form = await _formRepository.FindAsync(x => x.ID == request.ID, cancellationToken) ?? throw new NotFoundException("Form not found"); - var employee = await _employeeRepository.FindAsync(x => x.ID == form.EmployeeID, cancellationToken) ?? throw new NotFoundException("Employee ID not found"); + Domain.Entities.Form form = await _formRepository.FindAsync(x => x.ID == request.ID, cancellationToken) ?? throw new NotFoundException("Form not found"); + Domain.Entities.Employee employee = await _employeeRepository.FindAsync(x => x.ID == form.EmployeeID, cancellationToken) ?? throw new NotFoundException("Employee ID not found"); employee.IsActive = true; form.FormType = Domain.Enums.FormTypeEnum.ACCEPPTED; employee.Password = "$2a$11$dRZA37NpS.thXR9anJXBZehaTb7ezji2i2E5WbHGA2cwMeW4wEXAy"; _employeeRepository.Update(employee); _formRepository.Update(form); - await _employeeRepository.UnitOfWork.SaveChangesAsync(cancellationToken); - await MailUtils.SendPasswordAsync(employee.Email, employee.FullName, employee.ID,"HCM"); + _ = await _employeeRepository.UnitOfWork.SaveChangesAsync(cancellationToken); + await MailUtils.SendPasswordAsync(employee.Email, employee.FullName, employee.ID, "HCM"); return "Check Your Email!"; } } diff --git a/DeerCoffeeShop.Application/Forms/Commands/AcceptFormAndSendMail/AcceptFormAndSendMailCommand.cs b/DeerCoffeeShop.Application/Forms/Commands/AcceptFormAndSendMail/AcceptFormAndSendMailCommand.cs index 8f2954c..2c15088 100644 --- a/DeerCoffeeShop.Application/Forms/Commands/AcceptFormAndSendMail/AcceptFormAndSendMailCommand.cs +++ b/DeerCoffeeShop.Application/Forms/Commands/AcceptFormAndSendMail/AcceptFormAndSendMailCommand.cs @@ -2,11 +2,6 @@ using DeerCoffeeShop.Application.Utils; using DeerCoffeeShop.Domain.Repositories; using MediatR; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace DeerCoffeeShop.Application.Forms.Commands.AcceptFormAndSendMail; @@ -30,8 +25,8 @@ public AcceptFormAndSendMailCommandHandler(IFormRepository formRepository, IRest public async Task Handle(AcceptFormAndSendMailCommand request, CancellationToken cancellationToken) { - var from = await _formRepository.FindAsync(x => x.ID == request.FormID, cancellationToken); - var restaurant = await _restaurantRepository.FindAsync(x => x.ID == request.RestaurantID, cancellationToken); + Domain.Entities.Form? from = await _formRepository.FindAsync(x => x.ID == request.FormID, cancellationToken); + Domain.Entities.Restaurant? restaurant = await _restaurantRepository.FindAsync(x => x.ID == request.RestaurantID, cancellationToken); if (from == null) { return "Form not found"; @@ -45,7 +40,7 @@ public async Task Handle(AcceptFormAndSendMailCommand request, Cancellat from.Date = DateTime.Now; await MailUtils.SendEmailAsync(from.Employee.FullName, from.Employee.Email, "Thư mời phỏng vấn", request.Date, restaurant.RestaurantAddress); _formRepository.Update(from); - await _formRepository.UnitOfWork.SaveChangesAsync(cancellationToken); + _ = await _formRepository.UnitOfWork.SaveChangesAsync(cancellationToken); //send mail return "Check Your Email!"; diff --git a/DeerCoffeeShop.Application/Forms/FormDto.cs b/DeerCoffeeShop.Application/Forms/FormDto.cs index c990916..7ded92c 100644 --- a/DeerCoffeeShop.Application/Forms/FormDto.cs +++ b/DeerCoffeeShop.Application/Forms/FormDto.cs @@ -2,11 +2,6 @@ using DeerCoffeeShop.Application.Common.Mappings; using DeerCoffeeShop.Application.Employees; using DeerCoffeeShop.Domain.Entities; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace DeerCoffeeShop.Application.Forms; @@ -20,9 +15,9 @@ public class FormDto : IMapFrom
public bool IsApproved { get; set; } public void Mapping(Profile profile) { - profile.CreateMap(); + _ = profile.CreateMap(); } - public static FormDto Create(string FormID, EmployeeDto employee, Domain.Enums.FormTypeEnum formType, string content, DateTime date, bool isApproved) + public static FormDto Create(string FormID, EmployeeDto employee, Domain.Enums.FormTypeEnum formType, string content, DateTime date, bool isApproved) { return new FormDto { diff --git a/DeerCoffeeShop.Application/Forms/FromDtoMappingExstension.cs b/DeerCoffeeShop.Application/Forms/FromDtoMappingExstension.cs index 4804590..58195f4 100644 --- a/DeerCoffeeShop.Application/Forms/FromDtoMappingExstension.cs +++ b/DeerCoffeeShop.Application/Forms/FromDtoMappingExstension.cs @@ -1,11 +1,5 @@ using AutoMapper; using DeerCoffeeShop.Domain.Entities; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -using System.Threading.Tasks; namespace DeerCoffeeShop.Application.Forms; diff --git a/DeerCoffeeShop.Application/Forms/Queries/GetAllPagination/GetAllFormPagination.cs b/DeerCoffeeShop.Application/Forms/Queries/GetAllPagination/GetAllFormPagination.cs index 51ccf8b..61b6658 100644 --- a/DeerCoffeeShop.Application/Forms/Queries/GetAllPagination/GetAllFormPagination.cs +++ b/DeerCoffeeShop.Application/Forms/Queries/GetAllPagination/GetAllFormPagination.cs @@ -2,15 +2,9 @@ using DeerCoffeeShop.Application.Common.Interfaces; using DeerCoffeeShop.Application.Common.Pagination; using DeerCoffeeShop.Application.Common.Security; -using DeerCoffeeShop.Application.Forms; using DeerCoffeeShop.Domain.Entities; using DeerCoffeeShop.Domain.Repositories; using MediatR; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace DeerCoffeeShop.Application.Forms.Queries.GetAllPagination; [Authorize(Roles = "Admin,Manager")] @@ -34,11 +28,11 @@ internal class GetAllFormPaginationHandler(ICurrentUserService currentUserServic private readonly IEmployeeRepository _employeeRepository = employeeRepository; public async Task> Handle(GetAllFormPagination request, CancellationToken cancellationToken) { - var role = await _currentUserService.IsInRoleAsync("Admin"); + bool role = await _currentUserService.IsInRoleAsync("Admin"); if (role) { - var list = await _formRepository.FindAllAsync(x => x.FormType == Domain.Enums.FormTypeEnum.JOB_APPLICATION|| x.FormType == Domain.Enums.FormTypeEnum.ACCEPPTED, request.PageNumber, request.PageSize, cancellationToken); - foreach (var item in list) + IPagedResult list = await _formRepository.FindAllAsync(x => x.FormType == Domain.Enums.FormTypeEnum.JOB_APPLICATION || x.FormType == Domain.Enums.FormTypeEnum.ACCEPPTED, request.PageNumber, request.PageSize, cancellationToken); + foreach (Form item in list) { item.Employee = await _employeeRepository.FindAsync(x => x.ID == item.EmployeeID, cancellationToken); } @@ -52,17 +46,17 @@ public async Task> Handle(GetAllFormPagination request, Can } else { - var list = await _formRepository.FindAllAsync(x => x.FormType != Domain.Enums.FormTypeEnum.JOB_APPLICATION && x.FormType != Domain.Enums.FormTypeEnum.ACCEPPTED, request.PageNumber, request.PageSize, cancellationToken); - foreach (var item in list) + IPagedResult list = await _formRepository.FindAllAsync(x => x.FormType != Domain.Enums.FormTypeEnum.JOB_APPLICATION && x.FormType != Domain.Enums.FormTypeEnum.ACCEPPTED, request.PageNumber, request.PageSize, cancellationToken); + foreach (Form item in list) { item.Employee = await _employeeRepository.FindAsync(x => x.ID == item.EmployeeID, cancellationToken); } return PagedResult.Create( - list.TotalCount, - list.PageCount, - list.PageSize, - list.PageNo, - list.MapToFormDtoList(_mapper) ); + list.TotalCount, + list.PageCount, + list.PageSize, + list.PageNo, + list.MapToFormDtoList(_mapper)); } diff --git a/DeerCoffeeShop.Application/RestaurantChains/CreateRestaurantChain/CreateRestaurantChainCommandHandler.cs b/DeerCoffeeShop.Application/RestaurantChains/CreateRestaurantChain/CreateRestaurantChainCommandHandler.cs index 93bff1e..1d22c05 100644 --- a/DeerCoffeeShop.Application/RestaurantChains/CreateRestaurantChain/CreateRestaurantChainCommandHandler.cs +++ b/DeerCoffeeShop.Application/RestaurantChains/CreateRestaurantChain/CreateRestaurantChainCommandHandler.cs @@ -20,16 +20,16 @@ public async Task Handle(CreateRestaurantChainCommand request, Cancellat { try { - var restaurantChain = await this._restaurantChainRepository.FindAsync(x => x.RestaurantChainName.Equals(request.RestaurantChainName) - && x.RestaurantChainType.Equals(request.RestaurantChainType) + RestaurantChain? restaurantChain = await this._restaurantChainRepository.FindAsync(x => x.RestaurantChainName.Equals(request.RestaurantChainName) + && x.RestaurantChainType.Equals(request.RestaurantChainType) && x.RestaurantChainHQAddress.Equals(request.RestaurantChainHQAddress) , cancellationToken); - if(restaurantChain != null) + if (restaurantChain != null) throw new DuplicateNameException($"restaurantChain existed ID is {restaurantChain.ID}"); - + if ((await this._employeeRepository.FindAsync(x => x.ID.Equals(request.RestaurantChain_AdminID), cancellationToken)).RoleID != 1) throw new NotFoundException($"Not found admin by ID {request.RestaurantChain_AdminID}"); - + this._restaurantChainRepository.Add(new RestaurantChain() { RestaurantChainHQAddress = request.RestaurantChainHQAddress, @@ -39,11 +39,11 @@ public async Task Handle(CreateRestaurantChainCommand request, Cancellat RestaurantChainType = request.RestaurantChainType, RestaurantChain_AdminID = request.RestaurantChain_AdminID, }); - await this._restaurantChainRepository.UnitOfWork.SaveChangesAsync(cancellationToken); + _ = await this._restaurantChainRepository.UnitOfWork.SaveChangesAsync(cancellationToken); return $"Successfully created RestaurantChain Name {request.RestaurantChainName}"; } catch (Exception ex) - { + { throw new Exception($"{ex.Message}"); } } diff --git a/DeerCoffeeShop.Application/RestaurantChains/CreateRestaurantChain/CreateRestaurantChainCommandValidator.cs b/DeerCoffeeShop.Application/RestaurantChains/CreateRestaurantChain/CreateRestaurantChainCommandValidator.cs index 3eda87b..99b2de1 100644 --- a/DeerCoffeeShop.Application/RestaurantChains/CreateRestaurantChain/CreateRestaurantChainCommandValidator.cs +++ b/DeerCoffeeShop.Application/RestaurantChains/CreateRestaurantChain/CreateRestaurantChainCommandValidator.cs @@ -13,13 +13,13 @@ public CreateRestaurantChainCommandValidator(IRestaurantChainRepository restaura } private void configureValidatorRule() { - RuleFor(x => x.RestaurantChainHQAddress) + _ = RuleFor(x => x.RestaurantChainHQAddress) .NotEmpty().NotNull().WithMessage("please fill in the restaurantChainHQAddress"); - RuleFor(x => x.RestaurantChainName) + _ = RuleFor(x => x.RestaurantChainName) .NotNull().NotEmpty().WithMessage("please fill in the restaurantChainName"); - RuleFor(x => x.RestaurantChain_AdminID) + _ = RuleFor(x => x.RestaurantChain_AdminID) .NotEmpty().NotNull().WithMessage("please chose a admin"); - RuleFor(x => x.RestaurantChainType) + _ = RuleFor(x => x.RestaurantChainType) .NotEmpty().NotNull().WithMessage("please chose a restaurnatType"); } } diff --git a/DeerCoffeeShop.Application/RestaurantChains/DeleteRestaurantChain/DeleteRestaurantChainCommandHandler.cs b/DeerCoffeeShop.Application/RestaurantChains/DeleteRestaurantChain/DeleteRestaurantChainCommandHandler.cs index 8308e3d..1d1b621 100644 --- a/DeerCoffeeShop.Application/RestaurantChains/DeleteRestaurantChain/DeleteRestaurantChainCommandHandler.cs +++ b/DeerCoffeeShop.Application/RestaurantChains/DeleteRestaurantChain/DeleteRestaurantChainCommandHandler.cs @@ -13,7 +13,7 @@ public class DeleteRestaurantChainCommandHandler : IRequestHandler Handle(DeleteRestaurantChainCommand request, Cancellat { try { - var resChain = await this._restaurantChainRepository.FindAsync(x => x.ID.Equals(request.resChainID) && x.IsDeleted == false, cancellationToken); + Domain.Entities.RestaurantChain? resChain = await this._restaurantChainRepository.FindAsync(x => x.ID.Equals(request.resChainID) && x.IsDeleted == false, cancellationToken); if (resChain == null) throw new NotFoundException($"Not found restaurantChain ID {request.resChainID}"); - var resList = await this._restaurantRepository.FindAllAsync(x => x.RestaurantChainID.Equals(resChain.ID), cancellationToken); - foreach (var res in resList) + List resList = await this._restaurantRepository.FindAllAsync(x => x.RestaurantChainID.Equals(resChain.ID), cancellationToken); + foreach (Domain.Entities.Restaurant res in resList) { - await _metiator.Send(new DeleteRestaurantCommand(res.ID), cancellationToken); + _ = await _metiator.Send(new DeleteRestaurantCommand(res.ID), cancellationToken); } resChain.NgayXoa = DateTime.UtcNow; resChain.NguoiXoaID = this._currentUserService.UserId; resChain.IsDeleted = true; this._restaurantChainRepository.Update(resChain); - await this._restaurantChainRepository.UnitOfWork.SaveChangesAsync(cancellationToken); + _ = await this._restaurantChainRepository.UnitOfWork.SaveChangesAsync(cancellationToken); return $"Deleted restaurantChain ID {request.resChainID}."; } - catch (Exception ex) + catch (Exception ex) { throw new Exception($"{ex.Message}"); } diff --git a/DeerCoffeeShop.Application/RestaurantChains/DeleteRestaurantChain/DeleteRestaurantChainCommandValidator.cs b/DeerCoffeeShop.Application/RestaurantChains/DeleteRestaurantChain/DeleteRestaurantChainCommandValidator.cs index 9ab1050..5c03db1 100644 --- a/DeerCoffeeShop.Application/RestaurantChains/DeleteRestaurantChain/DeleteRestaurantChainCommandValidator.cs +++ b/DeerCoffeeShop.Application/RestaurantChains/DeleteRestaurantChain/DeleteRestaurantChainCommandValidator.cs @@ -13,7 +13,7 @@ public DeleteRestaurantChainCommandValidator(IRestaurantChainRepository restaura } private void configureValidatorRule() { - RuleFor(x => x.resChainID) + _ = RuleFor(x => x.resChainID) .NotEmpty().NotNull().WithMessage("please chose restaurantChain"); } diff --git a/DeerCoffeeShop.Application/RestaurantChains/GetRestaurantChainByAdmin/GetRestaurantChainByAdminQuery.cs b/DeerCoffeeShop.Application/RestaurantChains/GetRestaurantChainByAdmin/GetRestaurantChainByAdminQuery.cs index 696ee8c..3f36029 100644 --- a/DeerCoffeeShop.Application/RestaurantChains/GetRestaurantChainByAdmin/GetRestaurantChainByAdminQuery.cs +++ b/DeerCoffeeShop.Application/RestaurantChains/GetRestaurantChainByAdmin/GetRestaurantChainByAdminQuery.cs @@ -1,21 +1,16 @@ using DeerCoffeeShop.Application.Common.Interfaces; using DeerCoffeeShop.Application.Common.Pagination; using MediatR; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace DeerCoffeeShop.Application.RestaurantChains.GetRestaurantChainByAdmin { public class GetRestaurantChainByAdminQuery : IRequest>, IQuery { - public int pageNumber { get; set; } + public int pageNumber { get; set; } public int pageSize { get; set; } - public string adminID { get; set; } + public string adminID { get; set; } public GetRestaurantChainByAdminQuery() { } - public GetRestaurantChainByAdminQuery(int pageNumber, int pageSize, string adminID) + public GetRestaurantChainByAdminQuery(int pageNumber, int pageSize, string adminID) { this.pageNumber = pageNumber; this.pageSize = pageSize; diff --git a/DeerCoffeeShop.Application/RestaurantChains/GetRestaurantChainByAdmin/GetRestaurantChainByAdminQueryHandler.cs b/DeerCoffeeShop.Application/RestaurantChains/GetRestaurantChainByAdmin/GetRestaurantChainByAdminQueryHandler.cs index e9d8b66..5a5f7e4 100644 --- a/DeerCoffeeShop.Application/RestaurantChains/GetRestaurantChainByAdmin/GetRestaurantChainByAdminQueryHandler.cs +++ b/DeerCoffeeShop.Application/RestaurantChains/GetRestaurantChainByAdmin/GetRestaurantChainByAdminQueryHandler.cs @@ -2,13 +2,7 @@ using DeerCoffeeShop.Application.Common.Pagination; using DeerCoffeeShop.Domain.Common.Exceptions; using DeerCoffeeShop.Domain.Repositories; -using FluentValidation; using MediatR; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace DeerCoffeeShop.Application.RestaurantChains.GetRestaurantChainByAdmin { @@ -26,10 +20,10 @@ public async Task> Handle(GetRestaurantChainByAd { try { - var resChainList = await this._restaurantChinRepository.FindAllAsync(x => x.RestaurantChain_AdminID.Equals(request.adminID) && x.IsDeleted == false, pageNo:request.pageNumber, pageSize:request.pageSize,cancellationToken); - if (resChainList.Count() == 0) - throw new NotFoundException($"Not found any restaurantChin was managed by admin ID {request.adminID}"); - return PagedResult.Create( + IPagedResult resChainList = await this._restaurantChinRepository.FindAllAsync(x => x.RestaurantChain_AdminID.Equals(request.adminID) && x.IsDeleted == false, pageNo: request.pageNumber, pageSize: request.pageSize, cancellationToken); + return resChainList.Count() == 0 + ? throw new NotFoundException($"Not found any restaurantChin was managed by admin ID {request.adminID}") + : PagedResult.Create( totalCount: resChainList.TotalCount, pageCount: resChainList.PageCount, pageSize: resChainList.PageSize, @@ -37,7 +31,7 @@ public async Task> Handle(GetRestaurantChainByAd data: resChainList.MapToRestaurantChainDTOList(_mapper) ); } - catch (Exception ex) + catch (Exception ex) { throw new Exception($"{ex.Message}"); } diff --git a/DeerCoffeeShop.Application/RestaurantChains/GetRestaurantChainByAdmin/GetRestaurantChainByAdminQueryValidator.cs b/DeerCoffeeShop.Application/RestaurantChains/GetRestaurantChainByAdmin/GetRestaurantChainByAdminQueryValidator.cs index 586d6ee..105e782 100644 --- a/DeerCoffeeShop.Application/RestaurantChains/GetRestaurantChainByAdmin/GetRestaurantChainByAdminQueryValidator.cs +++ b/DeerCoffeeShop.Application/RestaurantChains/GetRestaurantChainByAdmin/GetRestaurantChainByAdminQueryValidator.cs @@ -1,10 +1,5 @@ using DeerCoffeeShop.Domain.Repositories; using FluentValidation; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace DeerCoffeeShop.Application.RestaurantChains.GetRestaurantChainByAdmin { @@ -18,11 +13,11 @@ public GetRestaurantChainByAdminQueryValidator(IRestaurantChainRepository restau } private void configureValidatorRule() { - RuleFor(x => x.pageNumber) + _ = RuleFor(x => x.pageNumber) .NotEmpty().NotNull().WithMessage("please fill in pageNumber"); - RuleFor(x => x.pageSize) + _ = RuleFor(x => x.pageSize) .NotEmpty().NotNull().WithMessage("please fill in pageSize"); - RuleFor(x => x.adminID) + _ = RuleFor(x => x.adminID) .NotNull().NotEmpty().WithMessage("please chose a admin"); } } diff --git a/DeerCoffeeShop.Application/RestaurantChains/GetRestaurantChainByDeactive/GetRestaurantChainByDeactiveQuery.cs b/DeerCoffeeShop.Application/RestaurantChains/GetRestaurantChainByDeactive/GetRestaurantChainByDeactiveQuery.cs index 6be3132..e9800b5 100644 --- a/DeerCoffeeShop.Application/RestaurantChains/GetRestaurantChainByDeactive/GetRestaurantChainByDeactiveQuery.cs +++ b/DeerCoffeeShop.Application/RestaurantChains/GetRestaurantChainByDeactive/GetRestaurantChainByDeactiveQuery.cs @@ -1,22 +1,17 @@ using DeerCoffeeShop.Application.Common.Interfaces; using DeerCoffeeShop.Application.Common.Pagination; using MediatR; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace DeerCoffeeShop.Application.RestaurantChains.GetRestaurantChainByDeactive { public class GetRestaurantChainByDeactiveQuery : IRequest>, IQuery { - public int pageNumber { get; set; } + public int pageNumber { get; set; } public int pageSize { get; set; } public GetRestaurantChainByDeactiveQuery(int pageNumber, int pageSize) { this.pageNumber = pageNumber; this.pageSize = pageSize; - } + } } } diff --git a/DeerCoffeeShop.Application/RestaurantChains/GetRestaurantChainByDeactive/GetRestaurantChainByDeactiveQueryHandler.cs b/DeerCoffeeShop.Application/RestaurantChains/GetRestaurantChainByDeactive/GetRestaurantChainByDeactiveQueryHandler.cs index 91cfd62..bec5fcf 100644 --- a/DeerCoffeeShop.Application/RestaurantChains/GetRestaurantChainByDeactive/GetRestaurantChainByDeactiveQueryHandler.cs +++ b/DeerCoffeeShop.Application/RestaurantChains/GetRestaurantChainByDeactive/GetRestaurantChainByDeactiveQueryHandler.cs @@ -3,11 +3,6 @@ using DeerCoffeeShop.Domain.Common.Exceptions; using DeerCoffeeShop.Domain.Repositories; using MediatR; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace DeerCoffeeShop.Application.RestaurantChains.GetRestaurantChainByDeactive { @@ -24,18 +19,18 @@ public async Task> Handle(GetRestaurantChainByDe { try { - var restaurantChain = await this._restaurantChainRepository.FindAllAsync(x => x.IsDeleted == true, pageNo:request.pageNumber, pageSize:request.pageSize, cancellationToken); - if (restaurantChain.Count() == 0) - throw new NotFoundException("Not found any resChain had been deleted"); - return PagedResult.Create( + IPagedResult restaurantChain = await this._restaurantChainRepository.FindAllAsync(x => x.IsDeleted == true, pageNo: request.pageNumber, pageSize: request.pageSize, cancellationToken); + return restaurantChain.Count() == 0 + ? throw new NotFoundException("Not found any resChain had been deleted") + : PagedResult.Create( totalCount: restaurantChain.TotalCount, pageCount: restaurantChain.PageCount, pageNumber: restaurantChain.PageNo, - pageSize: restaurantChain.PageSize, + pageSize: restaurantChain.PageSize, data: restaurantChain.MapToRestaurantChainDTOList(_mapper) ); } - catch (Exception ex) + catch (Exception ex) { throw new Exception($"{ex.Message}"); } diff --git a/DeerCoffeeShop.Application/RestaurantChains/GetRestaurantChainByID/GetRestaurantChainByIDQuery.cs b/DeerCoffeeShop.Application/RestaurantChains/GetRestaurantChainByID/GetRestaurantChainByIDQuery.cs index 9102f84..15ebafd 100644 --- a/DeerCoffeeShop.Application/RestaurantChains/GetRestaurantChainByID/GetRestaurantChainByIDQuery.cs +++ b/DeerCoffeeShop.Application/RestaurantChains/GetRestaurantChainByID/GetRestaurantChainByIDQuery.cs @@ -1,16 +1,11 @@ using DeerCoffeeShop.Application.Common.Interfaces; using MediatR; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace DeerCoffeeShop.Application.RestaurantChains.GetRestaurantChainByID { public class GetRestaurantChainByIDQuery : IRequest, IQuery { - public string resChainID { get; set; } + public string resChainID { get; set; } public GetRestaurantChainByIDQuery(string resChainID) { this.resChainID = resChainID; diff --git a/DeerCoffeeShop.Application/RestaurantChains/GetRestaurantChainByID/GetRestaurantChainByIDQueryHandler.cs b/DeerCoffeeShop.Application/RestaurantChains/GetRestaurantChainByID/GetRestaurantChainByIDQueryHandler.cs index 6623fe7..ffb70a4 100644 --- a/DeerCoffeeShop.Application/RestaurantChains/GetRestaurantChainByID/GetRestaurantChainByIDQueryHandler.cs +++ b/DeerCoffeeShop.Application/RestaurantChains/GetRestaurantChainByID/GetRestaurantChainByIDQueryHandler.cs @@ -2,11 +2,6 @@ using DeerCoffeeShop.Domain.Common.Exceptions; using DeerCoffeeShop.Domain.Repositories; using MediatR; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace DeerCoffeeShop.Application.RestaurantChains.GetRestaurantChainByID { @@ -23,12 +18,12 @@ public async Task Handle(GetRestaurantChainByIDQuery request { try { - var resChain = await this._restaurantChainRepository.FindAsync(x => x.ID.Equals(request.resChainID) && x.IsDeleted == false, cancellationToken); - if (resChain == null) - throw new NotFoundException($"Not found restaurantChain with ID {request.resChainID}"); - return resChain.MapToRestaurantChainDTO(_mapper); + Domain.Entities.RestaurantChain? resChain = await this._restaurantChainRepository.FindAsync(x => x.ID.Equals(request.resChainID) && x.IsDeleted == false, cancellationToken); + return resChain == null + ? throw new NotFoundException($"Not found restaurantChain with ID {request.resChainID}") + : resChain.MapToRestaurantChainDTO(_mapper); } - catch (Exception ex) + catch (Exception ex) { throw new Exception($"{ex.Message}"); } diff --git a/DeerCoffeeShop.Application/RestaurantChains/GetRestaurantChainByID/GetRestaurantChainByIDQueryValidator.cs b/DeerCoffeeShop.Application/RestaurantChains/GetRestaurantChainByID/GetRestaurantChainByIDQueryValidator.cs index aa5e1c5..09802ef 100644 --- a/DeerCoffeeShop.Application/RestaurantChains/GetRestaurantChainByID/GetRestaurantChainByIDQueryValidator.cs +++ b/DeerCoffeeShop.Application/RestaurantChains/GetRestaurantChainByID/GetRestaurantChainByIDQueryValidator.cs @@ -1,10 +1,5 @@ using DeerCoffeeShop.Domain.Repositories; using FluentValidation; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace DeerCoffeeShop.Application.RestaurantChains.GetRestaurantChainByID { @@ -18,7 +13,7 @@ public GetRestaurantChainByIDQueryValidator(IRestaurantChainRepository restauran } private void confuguraValidatorRule() { - RuleFor(x => x.resChainID) + _ = RuleFor(x => x.resChainID) .NotEmpty().NotNull().WithMessage("please fill in an restaurantChainID"); } } diff --git a/DeerCoffeeShop.Application/RestaurantChains/GetRestautantChainByName/GetRestautantChainByNameQuery.cs b/DeerCoffeeShop.Application/RestaurantChains/GetRestautantChainByName/GetRestautantChainByNameQuery.cs index e09fcd7..12cfe24 100644 --- a/DeerCoffeeShop.Application/RestaurantChains/GetRestautantChainByName/GetRestautantChainByNameQuery.cs +++ b/DeerCoffeeShop.Application/RestaurantChains/GetRestautantChainByName/GetRestautantChainByNameQuery.cs @@ -6,9 +6,9 @@ namespace DeerCoffeeShop.Application.RestaurantChains.GetRestautantChainByName { public class GetRestautantChainByNameQuery : IRequest>, IQuery { - public int pageNumber { get; set; } + public int pageNumber { get; set; } public int pageSize { get; set; } - public string resChainName { get; set; } + public string resChainName { get; set; } public GetRestautantChainByNameQuery(int pageNumber, int pageSize, string resChainName) { this.pageNumber = pageNumber; diff --git a/DeerCoffeeShop.Application/RestaurantChains/GetRestautantChainByName/GetRestautantChainByNameQueryHandler.cs b/DeerCoffeeShop.Application/RestaurantChains/GetRestautantChainByName/GetRestautantChainByNameQueryHandler.cs index d8d45e4..7c11cac 100644 --- a/DeerCoffeeShop.Application/RestaurantChains/GetRestautantChainByName/GetRestautantChainByNameQueryHandler.cs +++ b/DeerCoffeeShop.Application/RestaurantChains/GetRestautantChainByName/GetRestautantChainByNameQueryHandler.cs @@ -20,18 +20,18 @@ public async Task> Handle(GetRestautantChainByNa { try { - var resChainList = await this._restaurantChainRepository.FindAllAsync(x => x.RestaurantChainName.Contains(request.resChainName) && x.IsDeleted == false,pageNo:request.pageNumber,pageSize:request.pageSize, cancellationToken); - if (resChainList.Count() == 0) - throw new NotFoundException($"Not found any restaurantChain with name {request.resChainName}"); - return PagedResult.Create( - totalCount:resChainList.TotalCount, - pageCount:resChainList.PageCount, - pageSize:resChainList.PageSize, - pageNumber:resChainList.PageNo, - data:resChainList.MapToRestaurantChainDTOList(_mapper) + IPagedResult resChainList = await this._restaurantChainRepository.FindAllAsync(x => x.RestaurantChainName.Contains(request.resChainName) && x.IsDeleted == false, pageNo: request.pageNumber, pageSize: request.pageSize, cancellationToken); + return resChainList.Count() == 0 + ? throw new NotFoundException($"Not found any restaurantChain with name {request.resChainName}") + : PagedResult.Create( + totalCount: resChainList.TotalCount, + pageCount: resChainList.PageCount, + pageSize: resChainList.PageSize, + pageNumber: resChainList.PageNo, + data: resChainList.MapToRestaurantChainDTOList(_mapper) ); } - catch (Exception ex) + catch (Exception ex) { throw new Exception($"{ex.Message}"); } diff --git a/DeerCoffeeShop.Application/RestaurantChains/GetRestautantChainByName/GetRestautantChainByNameQueryValidator.cs b/DeerCoffeeShop.Application/RestaurantChains/GetRestautantChainByName/GetRestautantChainByNameQueryValidator.cs index acdf3e0..0f0182f 100644 --- a/DeerCoffeeShop.Application/RestaurantChains/GetRestautantChainByName/GetRestautantChainByNameQueryValidator.cs +++ b/DeerCoffeeShop.Application/RestaurantChains/GetRestautantChainByName/GetRestautantChainByNameQueryValidator.cs @@ -13,9 +13,9 @@ public GetRestautantChainByNameQueryValidator(IRestaurantChainRepository restaur } private void configuraValidatorRule() { - RuleFor(x => x.pageNumber) + _ = RuleFor(x => x.pageNumber) .NotEmpty().NotNull().WithMessage("please fill in pageNumber"); - RuleFor(x => x.pageSize) + _ = RuleFor(x => x.pageSize) .NotEmpty().NotNull().WithMessage("please fill in pageSize"); } } diff --git a/DeerCoffeeShop.Application/RestaurantChains/InactiveRestaurantChain/InactiveRestaurantChainCommand.cs b/DeerCoffeeShop.Application/RestaurantChains/InactiveRestaurantChain/InactiveRestaurantChainCommand.cs index 4f75a5d..c21ca7b 100644 --- a/DeerCoffeeShop.Application/RestaurantChains/InactiveRestaurantChain/InactiveRestaurantChainCommand.cs +++ b/DeerCoffeeShop.Application/RestaurantChains/InactiveRestaurantChain/InactiveRestaurantChainCommand.cs @@ -1,16 +1,11 @@ using DeerCoffeeShop.Application.Common.Interfaces; using MediatR; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace DeerCoffeeShop.Application.RestaurantChains.InactiveRestaurantChain { public class InactiveRestaurantChainCommand : IRequest, ICommand { - public string ID { get; set; } + public string ID { get; set; } public InactiveRestaurantChainCommand(string iD) { ID = iD; diff --git a/DeerCoffeeShop.Application/RestaurantChains/InactiveRestaurantChain/InactiveRestaurantChainCommandHandler.cs b/DeerCoffeeShop.Application/RestaurantChains/InactiveRestaurantChain/InactiveRestaurantChainCommandHandler.cs index ab39dec..b6a02a5 100644 --- a/DeerCoffeeShop.Application/RestaurantChains/InactiveRestaurantChain/InactiveRestaurantChainCommandHandler.cs +++ b/DeerCoffeeShop.Application/RestaurantChains/InactiveRestaurantChain/InactiveRestaurantChainCommandHandler.cs @@ -1,11 +1,6 @@ using DeerCoffeeShop.Domain.Common.Exceptions; using DeerCoffeeShop.Domain.Repositories; using MediatR; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace DeerCoffeeShop.Application.RestaurantChains.InactiveRestaurantChain { @@ -20,15 +15,15 @@ public async Task Handle(InactiveRestaurantChainCommand request, Cancell { try { - var restaurantChain = await this._restaurantChainRepository.FindAsync(x => x.ID.Equals(request.ID) && x.IsDeleted == true, cancellationToken); - if(restaurantChain == null) + Domain.Entities.RestaurantChain? restaurantChain = await this._restaurantChainRepository.FindAsync(x => x.ID.Equals(request.ID) && x.IsDeleted == true, cancellationToken); + if (restaurantChain == null) throw new NotFoundException($"RestaurantChain ID {request.ID} was not found"); restaurantChain.IsDeleted = false; this._restaurantChainRepository.Update(restaurantChain); - await this._restaurantChainRepository.UnitOfWork.SaveChangesAsync(cancellationToken); + _ = await this._restaurantChainRepository.UnitOfWork.SaveChangesAsync(cancellationToken); return $"RestaurantChain ID {request.ID} is Active now"; } - catch (Exception ex) + catch (Exception ex) { throw new Exception($"{ex.Message}"); } diff --git a/DeerCoffeeShop.Application/RestaurantChains/InactiveRestaurantChain/InactiveRestaurantChainCommandValidator.cs b/DeerCoffeeShop.Application/RestaurantChains/InactiveRestaurantChain/InactiveRestaurantChainCommandValidator.cs index b5be322..97d8e48 100644 --- a/DeerCoffeeShop.Application/RestaurantChains/InactiveRestaurantChain/InactiveRestaurantChainCommandValidator.cs +++ b/DeerCoffeeShop.Application/RestaurantChains/InactiveRestaurantChain/InactiveRestaurantChainCommandValidator.cs @@ -1,10 +1,5 @@ using DeerCoffeeShop.Domain.Repositories; using FluentValidation; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace DeerCoffeeShop.Application.RestaurantChains.InactiveRestaurantChain { @@ -14,7 +9,7 @@ public class InactiveRestaurantChainCommandValidator : AbstractValidator x.ID).NotEmpty().NotNull().WithMessage("Please chose restaurantChain."); + _ = RuleFor(x => x.ID).NotEmpty().NotNull().WithMessage("Please chose restaurantChain."); } } } diff --git a/DeerCoffeeShop.Application/RestaurantChains/RestaurantChainDTO.cs b/DeerCoffeeShop.Application/RestaurantChains/RestaurantChainDTO.cs index 3edef22..aa84619 100644 --- a/DeerCoffeeShop.Application/RestaurantChains/RestaurantChainDTO.cs +++ b/DeerCoffeeShop.Application/RestaurantChains/RestaurantChainDTO.cs @@ -20,7 +20,7 @@ public class RestaurantChainDTO : IMapFrom public RestaurantChainDTO() { } public void Mapping(Profile profile) { - profile.CreateMap(); + _ = profile.CreateMap(); } public static RestaurantChainDTO Create(string resChainID, string resChainAdminID, string resChainName, string resChainType, string resChainAddress, int resTotalBrand, int resChainTotalEmp, bool isDelete) diff --git a/DeerCoffeeShop.Application/RestaurantChains/UpdateRestautantChain/UpdateRestautantChainCommand.cs b/DeerCoffeeShop.Application/RestaurantChains/UpdateRestautantChain/UpdateRestautantChainCommand.cs index e4e25e9..3e70edf 100644 --- a/DeerCoffeeShop.Application/RestaurantChains/UpdateRestautantChain/UpdateRestautantChainCommand.cs +++ b/DeerCoffeeShop.Application/RestaurantChains/UpdateRestautantChain/UpdateRestautantChainCommand.cs @@ -5,7 +5,7 @@ namespace DeerCoffeeShop.Application.RestaurantChains.UpdateRestautantChain { public class UpdateRestautantChainCommand : IRequest, ICommand { - public string resChainID { get; set; } + public string resChainID { get; set; } public string RestaurantChain_AdminID { get; set; } public string RestaurantChainName { get; set; } public string RestaurantChainHQAddress { get; set; } diff --git a/DeerCoffeeShop.Application/RestaurantChains/UpdateRestautantChain/UpdateRestautantChainCommandHandler.cs b/DeerCoffeeShop.Application/RestaurantChains/UpdateRestautantChain/UpdateRestautantChainCommandHandler.cs index 9b4cfd2..45b2d4f 100644 --- a/DeerCoffeeShop.Application/RestaurantChains/UpdateRestautantChain/UpdateRestautantChainCommandHandler.cs +++ b/DeerCoffeeShop.Application/RestaurantChains/UpdateRestautantChain/UpdateRestautantChainCommandHandler.cs @@ -20,7 +20,7 @@ public async Task Handle(UpdateRestautantChainCommand request, Cancellat { try { - var resChain = await this._restaurantChainRepository.FindAsync(x => x.ID.Equals(request.resChainID) && x.IsDeleted == false, cancellationToken); + Domain.Entities.RestaurantChain? resChain = await this._restaurantChainRepository.FindAsync(x => x.ID.Equals(request.resChainID) && x.IsDeleted == false, cancellationToken); if (resChain == null) throw new NotFoundException($"Not found restaurantChain ID {request.resChainID}"); if (request.RestaurantChain_AdminID != null) @@ -37,10 +37,10 @@ public async Task Handle(UpdateRestautantChainCommand request, Cancellat resChain.RestaurantChainType = request.RestaurantChainType ?? resChain.RestaurantChainType; resChain.RestaurantChain_AdminID = request.RestaurantChain_AdminID ?? resChain.RestaurantChain_AdminID; this._restaurantChainRepository.Update(resChain); - await this._restaurantChainRepository.UnitOfWork.SaveChangesAsync(cancellationToken); + _ = await this._restaurantChainRepository.UnitOfWork.SaveChangesAsync(cancellationToken); return $"Updated restaurantChain ID {request.resChainID}"; } - catch (Exception ex) + catch (Exception ex) { throw new Exception($"{ex.Message}"); } diff --git a/DeerCoffeeShop.Application/RestaurantChains/UpdateRestautantChain/UpdateRestautantChainCommandValidator.cs b/DeerCoffeeShop.Application/RestaurantChains/UpdateRestautantChain/UpdateRestautantChainCommandValidator.cs index 5189fcb..e83092f 100644 --- a/DeerCoffeeShop.Application/RestaurantChains/UpdateRestautantChain/UpdateRestautantChainCommandValidator.cs +++ b/DeerCoffeeShop.Application/RestaurantChains/UpdateRestautantChain/UpdateRestautantChainCommandValidator.cs @@ -13,7 +13,7 @@ public UpdateRestautantChainCommandValidator(IRestaurantChainRepository restaura } private void configuraValidatorRule() { - RuleFor(x => x.resChainID) + _ = RuleFor(x => x.resChainID) .NotEmpty().NotNull().WithMessage("please chose an restaurantChain"); } } diff --git a/DeerCoffeeShop.Application/Restaurants/AddManagerToRestaurant/AddManagerToRestaurantCommandHandler.cs b/DeerCoffeeShop.Application/Restaurants/AddManagerToRestaurant/AddManagerToRestaurantCommandHandler.cs index c039b9d..033a586 100644 --- a/DeerCoffeeShop.Application/Restaurants/AddManagerToRestaurant/AddManagerToRestaurantCommandHandler.cs +++ b/DeerCoffeeShop.Application/Restaurants/AddManagerToRestaurant/AddManagerToRestaurantCommandHandler.cs @@ -19,25 +19,25 @@ public async Task Handle(AddManagerToRestaurantCommand request, Cancella { try { - var Employee = await _employeeRepository.FindAsync(x => x.ID == request.ManagerID, cancellationToken) ?? throw new NotFoundException("Employee not found"); - var Restaurant = await _restaurantRepository.FindAsync(x => x.ID == request.resID, cancellationToken) ?? throw new NotFoundException("Restaurant not found"); - var isManager = await _restaurantRepository.AnyAsync(x => x.ManagerID == Employee.ID, cancellationToken); + Domain.Entities.Employee Employee = await _employeeRepository.FindAsync(x => x.ID == request.ManagerID, cancellationToken) ?? throw new NotFoundException("Employee not found"); + Domain.Entities.Restaurant Restaurant = await _restaurantRepository.FindAsync(x => x.ID == request.resID, cancellationToken) ?? throw new NotFoundException("Restaurant not found"); + bool isManager = await _restaurantRepository.AnyAsync(x => x.ManagerID == Employee.ID, cancellationToken); if (isManager) { - return ("Employee is already a manager of another restaurant"); + return "Employee is already a manager of another restaurant"; } - var RestaurantChain = await _restaurantChainRepository.FindAsync(x => x.ID == Restaurant.RestaurantChainID, cancellationToken); + Domain.Entities.RestaurantChain? RestaurantChain = await _restaurantChainRepository.FindAsync(x => x.ID == Restaurant.RestaurantChainID, cancellationToken); if (RestaurantChain == null) { throw new NotFoundException("Restaurant Chain not found"); } if (Employee.RoleID != 2) { - return ("Employee is not a manager"); + return "Employee is not a manager"; } Restaurant.ManagerID = Employee.ID; _restaurantRepository.Update(Restaurant); - await _restaurantRepository.UnitOfWork.SaveChangesAsync(cancellationToken); + _ = await _restaurantRepository.UnitOfWork.SaveChangesAsync(cancellationToken); return "Add manager to restaurant successfully"; } catch (Exception ex) diff --git a/DeerCoffeeShop.Application/Restaurants/AddManagerToRestaurant/AddStaffToRestaurantCommandValidator.cs b/DeerCoffeeShop.Application/Restaurants/AddManagerToRestaurant/AddStaffToRestaurantCommandValidator.cs index 715a7db..f1e40dd 100644 --- a/DeerCoffeeShop.Application/Restaurants/AddManagerToRestaurant/AddStaffToRestaurantCommandValidator.cs +++ b/DeerCoffeeShop.Application/Restaurants/AddManagerToRestaurant/AddStaffToRestaurantCommandValidator.cs @@ -15,8 +15,8 @@ public AddStaffToRestaurantCommandValidator(IRestaurantRepository restaurantRepo } private void configuraValidatorRule() { - RuleFor(x => x.ManagerID).NotEmpty().NotNull().WithMessage("please chose staff."); - RuleFor(x => x.resID).NotEmpty().NotNull().WithMessage("please chose restaurant."); + _ = RuleFor(x => x.ManagerID).NotEmpty().NotNull().WithMessage("please chose staff."); + _ = RuleFor(x => x.resID).NotEmpty().NotNull().WithMessage("please chose restaurant."); } } } diff --git a/DeerCoffeeShop.Application/Restaurants/CreateRestaurant/CreateRestaurantCommandHandler.cs b/DeerCoffeeShop.Application/Restaurants/CreateRestaurant/CreateRestaurantCommandHandler.cs index 81ca8f2..77406be 100644 --- a/DeerCoffeeShop.Application/Restaurants/CreateRestaurant/CreateRestaurantCommandHandler.cs +++ b/DeerCoffeeShop.Application/Restaurants/CreateRestaurant/CreateRestaurantCommandHandler.cs @@ -3,7 +3,6 @@ using DeerCoffeeShop.Domain.Entities; using DeerCoffeeShop.Domain.Repositories; using MediatR; -using System.Data; namespace DeerCoffeeShop.Application.Restaurants.CreateRestaurant { @@ -26,11 +25,11 @@ public async Task Handle(CreateRestaurantCommand request, CancellationTo if (await _restaurantRepository.FindAsync(x => x.RestaurantName.Equals(request.RestaurantName) && x.RestaurantChainID.Equals(request.RestaurantChainID), cancellationToken) != null) throw new NotFoundException("dulicate restaurant name in this restaurantChain."); - var resChain = await _restaurantChainRepository.FindAsync(x => x.ID.Equals(request.RestaurantChainID), cancellationToken); + RestaurantChain? resChain = await _restaurantChainRepository.FindAsync(x => x.ID.Equals(request.RestaurantChainID), cancellationToken); if (resChain == null) throw new NotFoundException("Not found restaurantChain that had been chosen."); - var emp = await _employeeRepository.FindAsync(x => x.ID.Equals(request.ManagerID), cancellationToken); + Employee? emp = await _employeeRepository.FindAsync(x => x.ID.Equals(request.ManagerID), cancellationToken); if (emp.RoleID == 2) //2 là manager đúng hong ta :vv throw new NotFoundException("Not found manager had been chosen."); if (await _restaurantRepository.AnyAsync(x => x.ManagerID.Equals(request.ManagerID), cancellationToken)) @@ -38,8 +37,8 @@ public async Task Handle(CreateRestaurantCommand request, CancellationTo resChain.RestaurantChainTotalBranches += 1; resChain.RestaurantChainTotalEmployees += 1; _restaurantChainRepository.Update(resChain); - await _restaurantChainRepository.UnitOfWork.SaveChangesAsync(cancellationToken); - var restaurant = new Restaurant + _ = await _restaurantChainRepository.UnitOfWork.SaveChangesAsync(cancellationToken); + Restaurant restaurant = new() { IsDeleted = false, @@ -52,7 +51,7 @@ public async Task Handle(CreateRestaurantCommand request, CancellationTo TotalEmployees = 1, }; _restaurantRepository.Add(restaurant); - await _restaurantRepository.UnitOfWork.SaveChangesAsync(); + _ = await _restaurantRepository.UnitOfWork.SaveChangesAsync(); return $"Create new restaurantName: {request.RestaurantName} of restaurantChain: {(await _restaurantChainRepository.FindAsync(x => x.ID.Equals(request.RestaurantChainID), cancellationToken)).RestaurantChainName} successful."; diff --git a/DeerCoffeeShop.Application/Restaurants/CreateRestaurant/CreateRestaurantCommandValidator.cs b/DeerCoffeeShop.Application/Restaurants/CreateRestaurant/CreateRestaurantCommandValidator.cs index 6f210b4..f6fbe13 100644 --- a/DeerCoffeeShop.Application/Restaurants/CreateRestaurant/CreateRestaurantCommandValidator.cs +++ b/DeerCoffeeShop.Application/Restaurants/CreateRestaurant/CreateRestaurantCommandValidator.cs @@ -13,15 +13,15 @@ public CreateRestaurantCommandValidator(IRestaurantRepository restaurantReposito } private void ConfiguraValidatorRule() { - RuleFor(x => x.RestaurantAddress) + _ = RuleFor(x => x.RestaurantAddress) .NotEmpty().NotNull().WithMessage("please fill in a HQAdress.") .MaximumLength(300).WithMessage("the restairant was too long try again."); - RuleFor(x => x.RestaurantName) + _ = RuleFor(x => x.RestaurantName) .NotEmpty().NotNull().WithMessage("please fill in a restaurant's name.") .MaximumLength(50).WithMessage("the restaurant's name was too long try again."); - RuleFor(x => x.ManagerID) + _ = RuleFor(x => x.ManagerID) .NotEmpty().NotNull().WithMessage("please chose your restaurant owner."); - RuleFor(x => x.RestaurantChainID) + _ = RuleFor(x => x.RestaurantChainID) .NotEmpty().NotNull().WithMessage("please chose your restaurant chain owner."); } } diff --git a/DeerCoffeeShop.Application/Restaurants/DeleteRestaurant/DeleteRestaurantCommandHandler.cs b/DeerCoffeeShop.Application/Restaurants/DeleteRestaurant/DeleteRestaurantCommandHandler.cs index ada650b..4ffdba2 100644 --- a/DeerCoffeeShop.Application/Restaurants/DeleteRestaurant/DeleteRestaurantCommandHandler.cs +++ b/DeerCoffeeShop.Application/Restaurants/DeleteRestaurant/DeleteRestaurantCommandHandler.cs @@ -21,21 +21,21 @@ public async Task Handle(DeleteRestaurantCommand request, CancellationTo { try { - var restaurant = await _restaurantRepository.FindAsync(x => x.ID.Equals(request.resID) && !x.IsDeleted, cancellationToken) ?? throw new NotFoundException($"Not found restaurant ID: {request.resID}"); + Domain.Entities.Restaurant restaurant = await _restaurantRepository.FindAsync(x => x.ID.Equals(request.resID) && !x.IsDeleted, cancellationToken) ?? throw new NotFoundException($"Not found restaurant ID: {request.resID}"); //var manager = await this._employeeRepository.FindAsync(x => x.ID.Equals(restaurant.ManagerID),cancellationToken); - var listStaff = await _employeeRepository.FindAllAsync(x => x.ManagerID.Equals(restaurant.ManagerID), cancellationToken); - foreach (var employee in listStaff) + List listStaff = await _employeeRepository.FindAllAsync(x => x.ManagerID.Equals(restaurant.ManagerID), cancellationToken); + foreach (Domain.Entities.Employee employee in listStaff) { employee.ManagerID = null; _employeeRepository.Update(employee); } - await _employeeRepository.UnitOfWork.SaveChangesAsync(cancellationToken); + _ = await _employeeRepository.UnitOfWork.SaveChangesAsync(cancellationToken); restaurant.NgayXoa = DateTime.UtcNow; restaurant.NguoiXoaID = _currentUserService.UserId; restaurant.IsDeleted = true; _restaurantRepository.Update(restaurant); - await _restaurantRepository.UnitOfWork.SaveChangesAsync(cancellationToken); + _ = await _restaurantRepository.UnitOfWork.SaveChangesAsync(cancellationToken); return $"success delete restaurant ID : {request.resID}"; } catch (Exception ex) diff --git a/DeerCoffeeShop.Application/Restaurants/DeleteRestaurant/DeleteRestaurantCommandValidator.cs b/DeerCoffeeShop.Application/Restaurants/DeleteRestaurant/DeleteRestaurantCommandValidator.cs index fd604f9..65c20c1 100644 --- a/DeerCoffeeShop.Application/Restaurants/DeleteRestaurant/DeleteRestaurantCommandValidator.cs +++ b/DeerCoffeeShop.Application/Restaurants/DeleteRestaurant/DeleteRestaurantCommandValidator.cs @@ -13,7 +13,7 @@ public DeleteRestaurantCommandValidator(IRestaurantRepository restaurantReposito } private void configuraValidatorRule() { - RuleFor(x => x.resID) + _ = RuleFor(x => x.resID) .NotEmpty().NotNull().WithMessage("please chose a restaurant."); } diff --git a/DeerCoffeeShop.Application/Restaurants/FillterByReschainAndManagerID/FillterByReschainAndManagerIDQuery.cs b/DeerCoffeeShop.Application/Restaurants/FillterByReschainAndManagerID/FillterByReschainAndManagerIDQuery.cs index 49e5471..a863533 100644 --- a/DeerCoffeeShop.Application/Restaurants/FillterByReschainAndManagerID/FillterByReschainAndManagerIDQuery.cs +++ b/DeerCoffeeShop.Application/Restaurants/FillterByReschainAndManagerID/FillterByReschainAndManagerIDQuery.cs @@ -6,10 +6,10 @@ namespace DeerCoffeeShop.Application.Restaurants.FillterByReschainAndManagerID { public class FillterByReschainAndManagerIDQuery : IRequest>, IQuery { - public int pageNumber { get; set; } + public int pageNumber { get; set; } public int pageSize { get; set; } public string managerID { get; set; } - public string resChainID { get; set; } + public string resChainID { get; set; } public FillterByReschainAndManagerIDQuery() { } public FillterByReschainAndManagerIDQuery(int pageNumber, int pageSize, string managerID, string resChainID) diff --git a/DeerCoffeeShop.Application/Restaurants/FillterByReschainAndManagerID/FillterByReschainAndManagerIDQueryHandler.cs b/DeerCoffeeShop.Application/Restaurants/FillterByReschainAndManagerID/FillterByReschainAndManagerIDQueryHandler.cs index 06c51d3..38282ce 100644 --- a/DeerCoffeeShop.Application/Restaurants/FillterByReschainAndManagerID/FillterByReschainAndManagerIDQueryHandler.cs +++ b/DeerCoffeeShop.Application/Restaurants/FillterByReschainAndManagerID/FillterByReschainAndManagerIDQueryHandler.cs @@ -23,20 +23,20 @@ public async Task> Handle(FillterByReschainAndManager { Func, IQueryable> querys = query => { - if (request.resChainID != null) + if (request.resChainID != null) { query = query.Where(x => x.RestaurantChainID.Equals(request.resChainID) && x.IsDeleted == false); } - if (request.managerID != null) + if (request.managerID != null) { query = query.Where(x => x.ManagerID.Equals(request.managerID) && x.IsDeleted == false); } return query; }; - var result = await this._restaurantRepository.FindAllAsync(pageNo:request.pageNumber, pageSize:request.pageSize , querys); - if(result.Count() == 0) - throw new NotFoundException($"Not found any restaurant that belong to restaurantChain ID : {request.resChainID} and managed by manager ID :{request.managerID}"); - return PagedResult.Create( + IPagedResult result = await this._restaurantRepository.FindAllAsync(pageNo: request.pageNumber, pageSize: request.pageSize, querys); + return result.Count() == 0 + ? throw new NotFoundException($"Not found any restaurant that belong to restaurantChain ID : {request.resChainID} and managed by manager ID :{request.managerID}") + : PagedResult.Create( totalCount: result.TotalCount, pageCount: result.PageCount, pageSize: result.PageSize, diff --git a/DeerCoffeeShop.Application/Restaurants/Get/GetRestaurantQuery.cs b/DeerCoffeeShop.Application/Restaurants/Get/GetRestaurantQuery.cs index dddd5d5..2d943f5 100644 --- a/DeerCoffeeShop.Application/Restaurants/Get/GetRestaurantQuery.cs +++ b/DeerCoffeeShop.Application/Restaurants/Get/GetRestaurantQuery.cs @@ -5,11 +5,6 @@ using DeerCoffeeShop.Domain.Entities; using DeerCoffeeShop.Domain.Repositories; using MediatR; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace DeerCoffeeShop.Application.Restaurants.Get; [Authorize(Roles = "Admin")] @@ -56,8 +51,8 @@ IQueryable queryOptions(IQueryable query) return query; } - var list = await _restaurantRepository.FindAllAsync(request.PageNumber, request.PageSize, queryOptions, cancellationToken); - foreach (var item in list) + IPagedResult list = await _restaurantRepository.FindAllAsync(request.PageNumber, request.PageSize, queryOptions, cancellationToken); + foreach (Restaurant item in list) { item.Manager = await _employeeRepository.FindAsync(x => x.ID == item.ManagerID, cancellationToken); } diff --git a/DeerCoffeeShop.Application/Restaurants/GetAllRestaurantIsactive/GetAllRestaurantIsactiveHandler.cs b/DeerCoffeeShop.Application/Restaurants/GetAllRestaurantIsactive/GetAllRestaurantIsactiveHandler.cs index 215a0b3..5d3ab89 100644 --- a/DeerCoffeeShop.Application/Restaurants/GetAllRestaurantIsactive/GetAllRestaurantIsactiveHandler.cs +++ b/DeerCoffeeShop.Application/Restaurants/GetAllRestaurantIsactive/GetAllRestaurantIsactiveHandler.cs @@ -3,11 +3,6 @@ using DeerCoffeeShop.Domain.Common.Exceptions; using DeerCoffeeShop.Domain.Repositories; using MediatR; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace DeerCoffeeShop.Application.Restaurants.GetAllRestaurantIsactive { @@ -24,10 +19,10 @@ public async Task> Handle(GetAllRestaurantIsactiveQue { try { - var restaurantList = await this._restaurantRepository.FindAllAsync(x => x.IsDeleted == false, request.pageNumber, request.pageSize, cancellationToken); + IPagedResult restaurantList = await this._restaurantRepository.FindAllAsync(x => x.IsDeleted == false, request.pageNumber, request.pageSize, cancellationToken); if (restaurantList.Count() == 0) throw new NotFoundException("Not found any restauratn with the condition."); - var result = restaurantList.MapToRestaurantDTOList(_mapper); + List result = restaurantList.MapToRestaurantDTOList(_mapper); return PagedResult.Create( totalCount: restaurantList.TotalCount, pageCount: restaurantList.PageCount, @@ -36,7 +31,7 @@ public async Task> Handle(GetAllRestaurantIsactiveQue data: result ); } - catch (Exception ex) + catch (Exception ex) { throw new Exception($"{ex.Message}"); } diff --git a/DeerCoffeeShop.Application/Restaurants/GetAllRestaurantIsactive/GetAllRestaurantIsactiveQuery.cs b/DeerCoffeeShop.Application/Restaurants/GetAllRestaurantIsactive/GetAllRestaurantIsactiveQuery.cs index 4947bf7..00e0c03 100644 --- a/DeerCoffeeShop.Application/Restaurants/GetAllRestaurantIsactive/GetAllRestaurantIsactiveQuery.cs +++ b/DeerCoffeeShop.Application/Restaurants/GetAllRestaurantIsactive/GetAllRestaurantIsactiveQuery.cs @@ -1,11 +1,6 @@ using DeerCoffeeShop.Application.Common.Interfaces; using DeerCoffeeShop.Application.Common.Pagination; using MediatR; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace DeerCoffeeShop.Application.Restaurants.GetAllRestaurantIsactive { @@ -13,7 +8,7 @@ public class GetAllRestaurantIsactiveQuery : IRequest { public int pageNumber { get; set; } public int pageSize { get; set; } - public GetAllRestaurantIsactiveQuery(int pageNumber, int pageSize) + public GetAllRestaurantIsactiveQuery(int pageNumber, int pageSize) { this.pageNumber = pageNumber; this.pageSize = pageSize; diff --git a/DeerCoffeeShop.Application/Restaurants/GetRestaurantByDeactive/GetRestaurantByDeactiveQuery.cs b/DeerCoffeeShop.Application/Restaurants/GetRestaurantByDeactive/GetRestaurantByDeactiveQuery.cs index 69ef058..e5c23a9 100644 --- a/DeerCoffeeShop.Application/Restaurants/GetRestaurantByDeactive/GetRestaurantByDeactiveQuery.cs +++ b/DeerCoffeeShop.Application/Restaurants/GetRestaurantByDeactive/GetRestaurantByDeactiveQuery.cs @@ -1,19 +1,14 @@ using DeerCoffeeShop.Application.Common.Interfaces; using DeerCoffeeShop.Application.Common.Pagination; using MediatR; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace DeerCoffeeShop.Application.Restaurants.GetRestaurantByDeactive { public class GetRestaurantByDeactiveQuery : IRequest>, IQuery { - public int pageNumber { get; set;} - public int pageSize { get; set;} - public GetRestaurantByDeactiveQuery(int pageNumber, int pageSize) + public int pageNumber { get; set; } + public int pageSize { get; set; } + public GetRestaurantByDeactiveQuery(int pageNumber, int pageSize) { this.pageNumber = pageNumber; this.pageSize = pageSize; diff --git a/DeerCoffeeShop.Application/Restaurants/GetRestaurantByDeactive/GetRestaurantByDeactiveQueryHandler.cs b/DeerCoffeeShop.Application/Restaurants/GetRestaurantByDeactive/GetRestaurantByDeactiveQueryHandler.cs index 41209c2..713359c 100644 --- a/DeerCoffeeShop.Application/Restaurants/GetRestaurantByDeactive/GetRestaurantByDeactiveQueryHandler.cs +++ b/DeerCoffeeShop.Application/Restaurants/GetRestaurantByDeactive/GetRestaurantByDeactiveQueryHandler.cs @@ -2,11 +2,6 @@ using DeerCoffeeShop.Application.Common.Pagination; using DeerCoffeeShop.Domain.Repositories; using MediatR; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace DeerCoffeeShop.Application.Restaurants.GetRestaurantByDeactive { @@ -23,7 +18,7 @@ public async Task> Handle(GetRestaurantByDeactiveQuer { try { - var restaurantList = await this._restaurantRepository.FindAllAsync(x => x.IsDeleted == true, pageNo:request.pageNumber, pageSize:request.pageSize, cancellationToken); + IPagedResult restaurantList = await this._restaurantRepository.FindAllAsync(x => x.IsDeleted == true, pageNo: request.pageNumber, pageSize: request.pageSize, cancellationToken); return PagedResult.Create( totalCount: restaurantList.TotalCount, pageCount: restaurantList.PageCount, @@ -32,7 +27,7 @@ public async Task> Handle(GetRestaurantByDeactiveQuer data: restaurantList.MapToRestaurantDTOList(_mapper) ); } - catch (Exception ex) + catch (Exception ex) { throw new Exception($"{ex.Message}"); } diff --git a/DeerCoffeeShop.Application/Restaurants/GetRestaurantIsLowEmp/GetRestaurantIsLowEmpQueryHandler.cs b/DeerCoffeeShop.Application/Restaurants/GetRestaurantIsLowEmp/GetRestaurantIsLowEmpQueryHandler.cs index 1c1bd25..900d475 100644 --- a/DeerCoffeeShop.Application/Restaurants/GetRestaurantIsLowEmp/GetRestaurantIsLowEmpQueryHandler.cs +++ b/DeerCoffeeShop.Application/Restaurants/GetRestaurantIsLowEmp/GetRestaurantIsLowEmpQueryHandler.cs @@ -19,7 +19,7 @@ public async Task> Handle(GetRestaurantIsLowEmpQuery { try { - var restaurants = await this._restaurantRepository.FindAllAsync(x => x.TotalEmployees < 10 && x.IsDeleted == false, pageNo:request.pageNumber, pageSize:request.pageSize, cancellationToken); + IPagedResult restaurants = await this._restaurantRepository.FindAllAsync(x => x.TotalEmployees < 10 && x.IsDeleted == false, pageNo: request.pageNumber, pageSize: request.pageSize, cancellationToken); return PagedResult.Create ( totalCount: restaurants.TotalCount, @@ -29,7 +29,7 @@ public async Task> Handle(GetRestaurantIsLowEmpQuery data: restaurants.MapToRestaurantDTOList(_mapper) ); } - catch (Exception ex) + catch (Exception ex) { throw new Exception($"{ex.Message}"); diff --git a/DeerCoffeeShop.Application/Restaurants/GetRestautantByID/GetRestaurantByIDQuery.cs b/DeerCoffeeShop.Application/Restaurants/GetRestautantByID/GetRestaurantByIDQuery.cs index 8dabebd..21aba76 100644 --- a/DeerCoffeeShop.Application/Restaurants/GetRestautantByID/GetRestaurantByIDQuery.cs +++ b/DeerCoffeeShop.Application/Restaurants/GetRestautantByID/GetRestaurantByIDQuery.cs @@ -1,12 +1,11 @@ using DeerCoffeeShop.Application.Common.Interfaces; -using DeerCoffeeShop.Application.Common.Pagination; using MediatR; namespace DeerCoffeeShop.Application.Restaurants.GetRestautantByID { public class GetRestaurantByIDQuery : IRequest, IQuery { - public Guid resID { get; set; } + public Guid resID { get; set; } public GetRestaurantByIDQuery(Guid resID) { this.resID = resID; diff --git a/DeerCoffeeShop.Application/Restaurants/GetRestautantByID/GetRestaurantByIDQueryHandler.cs b/DeerCoffeeShop.Application/Restaurants/GetRestautantByID/GetRestaurantByIDQueryHandler.cs index 41b00cf..e249a98 100644 --- a/DeerCoffeeShop.Application/Restaurants/GetRestautantByID/GetRestaurantByIDQueryHandler.cs +++ b/DeerCoffeeShop.Application/Restaurants/GetRestautantByID/GetRestaurantByIDQueryHandler.cs @@ -19,12 +19,12 @@ public async Task Handle(GetRestaurantByIDQuery request, Cancella try { - var restaurant = await this._restaurantRepository.FindAsync(x => x.ID.Equals(request.resID) && x.IsDeleted == false, cancellationToken); - if (restaurant == null) - throw new NotFoundException($"Not found restaurant that had ID {request.resID}"); - return restaurant.MapToRestaurantDTO(_mapper); + Domain.Entities.Restaurant? restaurant = await this._restaurantRepository.FindAsync(x => x.ID.Equals(request.resID) && x.IsDeleted == false, cancellationToken); + return restaurant == null + ? throw new NotFoundException($"Not found restaurant that had ID {request.resID}") + : restaurant.MapToRestaurantDTO(_mapper); } - catch (Exception ex) + catch (Exception ex) { throw new Exception($"{ex.Message}"); } diff --git a/DeerCoffeeShop.Application/Restaurants/InactiveRestaurant/InactiveRestaurantCommand.cs b/DeerCoffeeShop.Application/Restaurants/InactiveRestaurant/InactiveRestaurantCommand.cs index ec40a81..bd05e92 100644 --- a/DeerCoffeeShop.Application/Restaurants/InactiveRestaurant/InactiveRestaurantCommand.cs +++ b/DeerCoffeeShop.Application/Restaurants/InactiveRestaurant/InactiveRestaurantCommand.cs @@ -1,16 +1,11 @@ using DeerCoffeeShop.Application.Common.Interfaces; using MediatR; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace DeerCoffeeShop.Application.Restaurants.InactiveRestaurant { public class InactiveRestaurantCommand : IRequest, ICommand { - public string ID { get; set; } + public string ID { get; set; } public InactiveRestaurantCommand(string iD) { ID = iD; diff --git a/DeerCoffeeShop.Application/Restaurants/InactiveRestaurant/InactiveRestaurantCommandHandler.cs b/DeerCoffeeShop.Application/Restaurants/InactiveRestaurant/InactiveRestaurantCommandHandler.cs index 9eb804c..2e57fc6 100644 --- a/DeerCoffeeShop.Application/Restaurants/InactiveRestaurant/InactiveRestaurantCommandHandler.cs +++ b/DeerCoffeeShop.Application/Restaurants/InactiveRestaurant/InactiveRestaurantCommandHandler.cs @@ -1,11 +1,6 @@ using DeerCoffeeShop.Domain.Common.Exceptions; using DeerCoffeeShop.Domain.Repositories; using MediatR; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace DeerCoffeeShop.Application.Restaurants.InactiveRestaurant { @@ -21,15 +16,15 @@ public async Task Handle(InactiveRestaurantCommand request, Cancellation { try { - var restaurant = await this._restaurantRepository.FindAsync(x => x.ID.Equals(request.ID) && x.IsDeleted == true, cancellationToken); + Domain.Entities.Restaurant? restaurant = await this._restaurantRepository.FindAsync(x => x.ID.Equals(request.ID) && x.IsDeleted == true, cancellationToken); if (restaurant == null) throw new NotFoundException($"restaurant ID {request.ID} was not found."); restaurant.IsDeleted = false; this._restaurantRepository.Update(restaurant); - await this._restaurantRepository.UnitOfWork.SaveChangesAsync(cancellationToken); + _ = await this._restaurantRepository.UnitOfWork.SaveChangesAsync(cancellationToken); return $"restaurant ID {request.ID} is Active now."; } - catch (Exception ex) + catch (Exception ex) { throw new Exception($"{ex.Message}"); } diff --git a/DeerCoffeeShop.Application/Restaurants/InactiveRestaurant/InactiveRestaurantCommandValidator.cs b/DeerCoffeeShop.Application/Restaurants/InactiveRestaurant/InactiveRestaurantCommandValidator.cs index 8154f9f..f7d2d1f 100644 --- a/DeerCoffeeShop.Application/Restaurants/InactiveRestaurant/InactiveRestaurantCommandValidator.cs +++ b/DeerCoffeeShop.Application/Restaurants/InactiveRestaurant/InactiveRestaurantCommandValidator.cs @@ -1,10 +1,5 @@ using DeerCoffeeShop.Domain.Repositories; using FluentValidation; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace DeerCoffeeShop.Application.Restaurants.InactiveRestaurant { @@ -14,7 +9,7 @@ public class InactiveRestaurantCommandValidator : AbstractValidator x.ID).NotEmpty().NotNull().WithMessage("Please chose a restaurant"); + _ = RuleFor(x => x.ID).NotEmpty().NotNull().WithMessage("Please chose a restaurant"); } } } diff --git a/DeerCoffeeShop.Application/Restaurants/RestaurantDTO.cs b/DeerCoffeeShop.Application/Restaurants/RestaurantDTO.cs index b9c7ca1..ae6f017 100644 --- a/DeerCoffeeShop.Application/Restaurants/RestaurantDTO.cs +++ b/DeerCoffeeShop.Application/Restaurants/RestaurantDTO.cs @@ -19,7 +19,7 @@ public class RestaurantDTO : IMapFrom public RestaurantDTO() { } public void Mapping(Profile profile) { - profile.CreateMap(); + _ = profile.CreateMap(); } public static RestaurantDTO Create(string ID, string resChainID, string resName, string resAddress, int totalEmp, EmployeeDto employeeDto) diff --git a/DeerCoffeeShop.Application/Restaurants/UpdateRestautant/UpdateRestaurantCommand.cs b/DeerCoffeeShop.Application/Restaurants/UpdateRestautant/UpdateRestaurantCommand.cs index 6c89aa5..efea329 100644 --- a/DeerCoffeeShop.Application/Restaurants/UpdateRestautant/UpdateRestaurantCommand.cs +++ b/DeerCoffeeShop.Application/Restaurants/UpdateRestautant/UpdateRestaurantCommand.cs @@ -5,11 +5,11 @@ namespace DeerCoffeeShop.Application.Restaurants.UpdateRestautant { public class UpdateRestaurantCommand : IRequest, ICommand { - public string resID { get; set; } - public string manageID { get; set; } - public string resName { get; set; } - public string resAddress { get; set; } - public string resChainID { get; set; } + public string resID { get; set; } + public string manageID { get; set; } + public string resName { get; set; } + public string resAddress { get; set; } + public string resChainID { get; set; } public UpdateRestaurantCommand(string resID, string manageID, string resName, string resAddress, string resChainID) { this.resID = resID; diff --git a/DeerCoffeeShop.Application/Restaurants/UpdateRestautant/UpdateRestaurantCommandHandler.cs b/DeerCoffeeShop.Application/Restaurants/UpdateRestautant/UpdateRestaurantCommandHandler.cs index 4b14fe5..9b93058 100644 --- a/DeerCoffeeShop.Application/Restaurants/UpdateRestautant/UpdateRestaurantCommandHandler.cs +++ b/DeerCoffeeShop.Application/Restaurants/UpdateRestautant/UpdateRestaurantCommandHandler.cs @@ -19,22 +19,22 @@ public async Task Handle(UpdateRestaurantCommand request, CancellationTo { try { - var restaurant = await _restaurantRepository.FindAsync(x => x.ID.Equals(request.resID) && !x.IsDeleted, cancellationToken) ?? throw new NotFoundException($"Not found restaurant had ID : {request.resID} or it had been deleted ."); + Domain.Entities.Restaurant restaurant = await _restaurantRepository.FindAsync(x => x.ID.Equals(request.resID) && !x.IsDeleted, cancellationToken) ?? throw new NotFoundException($"Not found restaurant had ID : {request.resID} or it had been deleted ."); if ((await _employeeRepository.FindAsync(x => x.ID.Equals(request.manageID) && x.IsDeleted == false, cancellationToken)).RoleID != 2) throw new NotFoundException($"Not found manager with ID {request.manageID}"); restaurant.ManagerID = request.manageID ?? restaurant.ManagerID; if (request.resChainID != null) { restaurant.RestaurantChainID = request.resChainID; - var curResChain = await _restaurantChainRepository.FindAsync(x => x.ID.Equals(restaurant.RestaurantChainID) && !x.IsDeleted, cancellationToken); - var newResChain = await _restaurantChainRepository.FindAsync(x => x.ID.Equals(request.resChainID) && !x.IsDeleted, cancellationToken); + Domain.Entities.RestaurantChain? curResChain = await _restaurantChainRepository.FindAsync(x => x.ID.Equals(restaurant.RestaurantChainID) && !x.IsDeleted, cancellationToken); + Domain.Entities.RestaurantChain? newResChain = await _restaurantChainRepository.FindAsync(x => x.ID.Equals(request.resChainID) && !x.IsDeleted, cancellationToken); curResChain.RestaurantChainTotalBranches -= 1; curResChain.RestaurantChainTotalEmployees -= restaurant.TotalEmployees; newResChain.RestaurantChainTotalBranches += 1; newResChain.RestaurantChainTotalEmployees += restaurant.TotalEmployees; _restaurantChainRepository.Update(newResChain); _restaurantChainRepository.Update(curResChain); - await _restaurantChainRepository.UnitOfWork.SaveChangesAsync(cancellationToken); + _ = await _restaurantChainRepository.UnitOfWork.SaveChangesAsync(cancellationToken); } else { @@ -43,7 +43,7 @@ public async Task Handle(UpdateRestaurantCommand request, CancellationTo restaurant.RestaurantAddress = request.resAddress ?? restaurant.RestaurantAddress; restaurant.RestaurantName = request.resName ?? restaurant.RestaurantName; _restaurantRepository.Update(restaurant); - await _restaurantRepository.UnitOfWork.SaveChangesAsync(cancellationToken); + _ = await _restaurantRepository.UnitOfWork.SaveChangesAsync(cancellationToken); return $"Update restaurant ID {request.resID} successful."; } catch (Exception ex) diff --git a/DeerCoffeeShop.Application/Restaurants/UpdateRestautant/UpdateRestaurantCommandValidator.cs b/DeerCoffeeShop.Application/Restaurants/UpdateRestautant/UpdateRestaurantCommandValidator.cs index 7ec6b0c..70dc7d9 100644 --- a/DeerCoffeeShop.Application/Restaurants/UpdateRestautant/UpdateRestaurantCommandValidator.cs +++ b/DeerCoffeeShop.Application/Restaurants/UpdateRestautant/UpdateRestaurantCommandValidator.cs @@ -13,7 +13,7 @@ public UpdateRestaurantCommandValidator(IRestaurantRepository restaurantReposito } private void configuraValidatorRule() { - RuleFor(x => x.resID) + _ = RuleFor(x => x.resID) .NotEmpty().NotNull().WithMessage("please chose a restaurant during updating."); } } diff --git a/DeerCoffeeShop.Application/Shift/Create/CreateShiftCommandHandler.cs b/DeerCoffeeShop.Application/Shift/Create/CreateShiftCommandHandler.cs index 38f407e..0195336 100644 --- a/DeerCoffeeShop.Application/Shift/Create/CreateShiftCommandHandler.cs +++ b/DeerCoffeeShop.Application/Shift/Create/CreateShiftCommandHandler.cs @@ -12,12 +12,12 @@ public class CreateShiftCommandHandler(IShiftRepostiry shiftRepostory, ICurrentU public async Task Handle(CreateShiftCommand request, CancellationToken cancellationToken) { - var checkDuplicated = await _shiftRepostory.AnyAsync(x => x.Name.Equals(request.shift_name) + bool checkDuplicated = await _shiftRepostory.AnyAsync(x => x.Name.Equals(request.shift_name) && x.ShiftStart.CompareTo(request.shift_start) == 0 && x.ShiftEnd.CompareTo(request.shift_end) == 0, cancellationToken); if (checkDuplicated) throw new DuplicatedObjectException("This shift has been exist"); - var shift = new Domain.Entities.Shift() + Domain.Entities.Shift shift = new() { Name = request.shift_name, ShiftStart = request.shift_start, diff --git a/DeerCoffeeShop.Application/Shift/Create/CreateShiftCommandValidator.cs b/DeerCoffeeShop.Application/Shift/Create/CreateShiftCommandValidator.cs index b05aae2..8f4b1d4 100644 --- a/DeerCoffeeShop.Application/Shift/Create/CreateShiftCommandValidator.cs +++ b/DeerCoffeeShop.Application/Shift/Create/CreateShiftCommandValidator.cs @@ -11,26 +11,26 @@ public CreateShiftCommandValidator() public void Configure() { - RuleFor(x => x.shift_end) + _ = RuleFor(x => x.shift_end) .GreaterThan(x => x.shift_start) .WithMessage("Shift end must later than shift start!"); - RuleFor(x => x.shift_start) + _ = RuleFor(x => x.shift_start) .NotNull() .NotEmpty() .WithMessage("Shift's start times must not be empty!"); - RuleFor(x => x.shift_end) + _ = RuleFor(x => x.shift_end) .NotNull() .NotEmpty() .WithMessage("Shift's end times must not be empty!"); - RuleFor(x => x.shift_name) + _ = RuleFor(x => x.shift_name) .NotEmpty() .NotNull() .WithMessage("Shift's name must not be empty!"); - RuleFor(x => x.shift_description) + _ = RuleFor(x => x.shift_description) .NotEmpty() .NotNull() .WithMessage("Shift's description must not be empty!"); diff --git a/DeerCoffeeShop.Application/Shift/Delete/DeleteShiftCommandHandler.cs b/DeerCoffeeShop.Application/Shift/Delete/DeleteShiftCommandHandler.cs index a2c0351..ba51ffc 100644 --- a/DeerCoffeeShop.Application/Shift/Delete/DeleteShiftCommandHandler.cs +++ b/DeerCoffeeShop.Application/Shift/Delete/DeleteShiftCommandHandler.cs @@ -12,7 +12,7 @@ public class DeleteShiftCommandHandler(IShiftRepostiry shiftRepostiry, ICurrentU public async Task Handle(DeleteShiftCommand request, CancellationToken cancellationToken) { - var foundObject = await _shiftRepository.FindAsync(x => x.ID == request.Id, cancellationToken); + Domain.Entities.Shift? foundObject = await _shiftRepository.FindAsync(x => x.ID == request.Id, cancellationToken); if (foundObject == null) throw new NotFoundException("Shift was not found!"); foundObject.IsActive = false; diff --git a/DeerCoffeeShop.Application/Shift/Delete/DeleteShiftCommandValidator.cs b/DeerCoffeeShop.Application/Shift/Delete/DeleteShiftCommandValidator.cs index 986c5fa..7279b21 100644 --- a/DeerCoffeeShop.Application/Shift/Delete/DeleteShiftCommandValidator.cs +++ b/DeerCoffeeShop.Application/Shift/Delete/DeleteShiftCommandValidator.cs @@ -11,7 +11,7 @@ public DeleteShiftCommandValidator() public void Configure() { - RuleFor(x => x.Id) + _ = RuleFor(x => x.Id) .NotEmpty() .NotNull() .WithMessage("Shift must not be empty!"); diff --git a/DeerCoffeeShop.Application/Shift/GetAll/GetAllShiftQueryHandler.cs b/DeerCoffeeShop.Application/Shift/GetAll/GetAllShiftQueryHandler.cs index a1a23fd..1cc4c5f 100644 --- a/DeerCoffeeShop.Application/Shift/GetAll/GetAllShiftQueryHandler.cs +++ b/DeerCoffeeShop.Application/Shift/GetAll/GetAllShiftQueryHandler.cs @@ -13,10 +13,10 @@ public class GetAllShiftQueryHandler(IShiftRepostiry shiftRepository, IMapper ma public async Task> Handle(GetAllShiftQuery query, CancellationToken cancellationToken) { - var shiftList = await _shiftRepository.FindAllAsync(x => x.IsActive == true, query.PageNo, query.PageSize, cancellationToken); - if (shiftList.TotalCount == 0) - throw new NotFoundException("None shift was found!"); - return PagedResult.Create + IPagedResult shiftList = await _shiftRepository.FindAllAsync(x => x.IsActive == true, query.PageNo, query.PageSize, cancellationToken); + return shiftList.TotalCount == 0 + ? throw new NotFoundException("None shift was found!") + : PagedResult.Create ( totalCount: shiftList.TotalCount, pageCount: shiftList.PageCount, diff --git a/DeerCoffeeShop.Application/Shift/ShiftDto.cs b/DeerCoffeeShop.Application/Shift/ShiftDto.cs index 8c39ef5..b65112c 100644 --- a/DeerCoffeeShop.Application/Shift/ShiftDto.cs +++ b/DeerCoffeeShop.Application/Shift/ShiftDto.cs @@ -32,7 +32,7 @@ public static ShiftDto Create(string name, int shiftStart, int shiftEnd public void Mapping(Profile profile) { - profile.CreateMap(); + _ = profile.CreateMap(); } } } diff --git a/DeerCoffeeShop.Application/Shift/Update/UpdateShiftCommandHandler.cs b/DeerCoffeeShop.Application/Shift/Update/UpdateShiftCommandHandler.cs index 6668b7f..182dce5 100644 --- a/DeerCoffeeShop.Application/Shift/Update/UpdateShiftCommandHandler.cs +++ b/DeerCoffeeShop.Application/Shift/Update/UpdateShiftCommandHandler.cs @@ -12,7 +12,7 @@ public class UpdateShiftCommandHandler(IShiftRepostiry shiftRepository, ICurrent public async Task Handle(UpdateShiftCommand request, CancellationToken cancellationToken) { - var foundObject = await _shiftRepository.FindAsync(x => x.ID == request.shift_id, cancellationToken); + Domain.Entities.Shift? foundObject = await _shiftRepository.FindAsync(x => x.ID == request.shift_id, cancellationToken); if (foundObject == null) throw new NotFoundException("None shift was found!"); foundObject.Name = request.shift_name ?? foundObject.Name; diff --git a/DeerCoffeeShop.Application/Shift/Update/UpdateShiftCommandValidator.cs b/DeerCoffeeShop.Application/Shift/Update/UpdateShiftCommandValidator.cs index 768e5be..ede5799 100644 --- a/DeerCoffeeShop.Application/Shift/Update/UpdateShiftCommandValidator.cs +++ b/DeerCoffeeShop.Application/Shift/Update/UpdateShiftCommandValidator.cs @@ -11,16 +11,16 @@ public UpdateShiftCommandValidator() public void Configure() { - RuleFor(x => x.shift_end) + _ = RuleFor(x => x.shift_end) .GreaterThan(x => x.shift_start) .WithMessage("Shift end must later than shift start!"); - RuleFor(x => x.shift_start) + _ = RuleFor(x => x.shift_start) .NotNull() .NotEmpty() .WithMessage("Shift's start times must not be empty!"); - RuleFor(x => x.shift_end) + _ = RuleFor(x => x.shift_end) .NotNull() .NotEmpty() .WithMessage("Shift's end times must not be empty!"); diff --git a/DeerCoffeeShop.Application/Utils/MailBody.cs b/DeerCoffeeShop.Application/Utils/MailBody.cs index b103e1b..f385ba3 100644 --- a/DeerCoffeeShop.Application/Utils/MailBody.cs +++ b/DeerCoffeeShop.Application/Utils/MailBody.cs @@ -1,10 +1,3 @@ -using System.Net; -using System.Net.Mail; -using DeerCoffeeShop.Domain.Entities; -using MailKit.Security; -using Microsoft.Extensions.Configuration; -using MimeKit; - namespace DeerCoffeeShop.Application.Utils { public static class MailBody @@ -12,7 +5,7 @@ public static class MailBody public static string getConfirmEmail(string userName, string userEmail, string address, string phoneNumber, string dateOfBirth, string companyName) { - var htmlTemplate = @" + string htmlTemplate = @" @@ -154,7 +147,7 @@ @media only screen and (max-width: 600px) { } public static string getApprovedEmail(string userName, string userEmail, string companyName, DateTime date, string company_address) { - var htmlTemplate = @" + string htmlTemplate = @" @@ -295,7 +288,7 @@ @media only screen and (max-width: 600px) { } public static string getPasswordEmail(string userName, string userID, DateTime date, string companyName) { - var htmlTemplate = @" + string htmlTemplate = @" diff --git a/DeerCoffeeShop.Application/Utils/MailUtils.cs b/DeerCoffeeShop.Application/Utils/MailUtils.cs index 0dac35f..d7822b9 100644 --- a/DeerCoffeeShop.Application/Utils/MailUtils.cs +++ b/DeerCoffeeShop.Application/Utils/MailUtils.cs @@ -1,5 +1,3 @@ -using System.Net; -using System.Net.Mail; using DeerCoffeeShop.Domain.Entities; using MailKit.Security; using Microsoft.Extensions.Configuration; @@ -11,34 +9,34 @@ public static class MailUtils { public static async Task SendMail(MailContent mailContent) { - var dic = Directory.GetCurrentDirectory(); + _ = Directory.GetCurrentDirectory(); IConfiguration config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", true, true) .Build(); - var result = Directory.GetCurrentDirectory(); - var mailSettings = config.GetSection("MailSettings").Get(); + _ = Directory.GetCurrentDirectory(); + MailSettings? mailSettings = config.GetSection("MailSettings").Get(); - var email = new MimeMessage(); + MimeMessage email = new(); email.Sender = new MailboxAddress(mailSettings?.DisplayName, mailSettings?.Mail); email.From.Add(new MailboxAddress(mailSettings?.DisplayName, mailSettings?.Mail)); email.To.Add(MailboxAddress.Parse(mailContent.To)); email.Subject = mailContent.Subject; - var builder = new BodyBuilder(); + BodyBuilder builder = new(); builder.HtmlBody = mailContent.Body; email.Body = builder.ToMessageBody(); // dùng SmtpClient của MailKit - using var smtp = new MailKit.Net.Smtp.SmtpClient(); + using MailKit.Net.Smtp.SmtpClient smtp = new(); try { smtp.Connect(mailSettings?.Host, mailSettings.Port | 587, SecureSocketOptions.StartTls); smtp.Authenticate(mailSettings.Mail, mailSettings.Password); - await smtp.SendAsync(email); + _ = await smtp.SendAsync(email); } catch (Exception ex) { @@ -59,7 +57,7 @@ public static async Task SendMail(MailContent mailContent) public static async Task SendEmailAsync(string userName, string userEmail, string address, string phoneNumber, string dateOfBirth, string subject) { - var body = MailBody.getConfirmEmail(userName, userEmail, address, phoneNumber, dateOfBirth, "Deer Coffee"); + string body = MailBody.getConfirmEmail(userName, userEmail, address, phoneNumber, dateOfBirth, "Deer Coffee"); await SendMail(new MailContent() { To = userEmail, @@ -69,7 +67,7 @@ await SendMail(new MailContent() } public static async Task SendEmailAsync(string userName, string userEmail, string subject, DateTime date, string address) { - var body = MailBody.getApprovedEmail(userName, userEmail, "Deer Coffee", date, address); + string body = MailBody.getApprovedEmail(userName, userEmail, "Deer Coffee", date, address); await SendMail(new MailContent() { To = userEmail, @@ -77,9 +75,9 @@ await SendMail(new MailContent() Body = body }); } - public static async Task SendPasswordAsync(string userEmail, string userName, string userID,string companyName) + public static async Task SendPasswordAsync(string userEmail, string userName, string userID, string companyName) { - var body = MailBody.getPasswordEmail(userName, userID, DateTime.Now,companyName); + string body = MailBody.getPasswordEmail(userName, userID, DateTime.Now, companyName); await SendMail(new MailContent() { To = userEmail, diff --git a/DeerCoffeeShop.Domain/Common/Exceptions/TimeCheckInToSoonException.cs b/DeerCoffeeShop.Domain/Common/Exceptions/TimeCheckInToSoonException.cs index 17d3b10..d3de90f 100644 --- a/DeerCoffeeShop.Domain/Common/Exceptions/TimeCheckInToSoonException.cs +++ b/DeerCoffeeShop.Domain/Common/Exceptions/TimeCheckInToSoonException.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace DeerCoffeeShop.Domain.Common.Exceptions; +namespace DeerCoffeeShop.Domain.Common.Exceptions; public class TimeCheckInToSoonException(string message) : Exception(message) { diff --git a/DeerCoffeeShop.Domain/Common/Method/GetWeekDates.cs b/DeerCoffeeShop.Domain/Common/Method/GetWeekDates.cs new file mode 100644 index 0000000..0db6554 --- /dev/null +++ b/DeerCoffeeShop.Domain/Common/Method/GetWeekDates.cs @@ -0,0 +1,23 @@ +namespace DeerCoffeeShop.Domain.Common.Method; + +public static class GetWeekDates +{ + public static List Get(DateOnly date) + { + List weekDates = []; + + // Get the day of the week as an integer (0 = Sunday, 1 = Monday, ..., 6 = Saturday) + int dayOfWeek = (int)date.DayOfWeek; + + // Calculate the previous Sunday + DateOnly startOfWeek = date.AddDays(-dayOfWeek); + + // Add each day from the previous Sunday to the next Saturday to the list + for (int i = 0; i < 7; i++) + { + weekDates.Add(startOfWeek.AddDays(i)); + } + + return weekDates; + } +} diff --git a/DeerCoffeeShop.Domain/Constants/EmployeeRole.cs b/DeerCoffeeShop.Domain/Constants/EmployeeRole.cs index a3564f9..63d82df 100644 --- a/DeerCoffeeShop.Domain/Constants/EmployeeRole.cs +++ b/DeerCoffeeShop.Domain/Constants/EmployeeRole.cs @@ -2,7 +2,7 @@ namespace DeerCoffeeShop.Domain.Constants { public static class EmployeeRole { - public static readonly Dictionary EmployeeRoleDictionary = new Dictionary + public static readonly Dictionary EmployeeRoleDictionary = new() { { 1, "Admin" }, { 2, "Manager" }, diff --git a/DeerCoffeeShop.Domain/Entities/Form.cs b/DeerCoffeeShop.Domain/Entities/Form.cs index 1562728..02e2725 100644 --- a/DeerCoffeeShop.Domain/Entities/Form.cs +++ b/DeerCoffeeShop.Domain/Entities/Form.cs @@ -1,5 +1,4 @@ using DeerCoffeeShop.Domain.Entities.Base; -using DeerCoffeeShop.Domain.Enums; namespace DeerCoffeeShop.Domain.Entities; diff --git a/DeerCoffeeShop.Domain/Entities/Shift.cs b/DeerCoffeeShop.Domain/Entities/Shift.cs index 377f68e..f8fe85e 100644 --- a/DeerCoffeeShop.Domain/Entities/Shift.cs +++ b/DeerCoffeeShop.Domain/Entities/Shift.cs @@ -1,5 +1,4 @@ using DeerCoffeeShop.Domain.Entities.Base; -using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace DeerCoffeeShop.Domain.Entities diff --git a/DeerCoffeeShop.Domain/Enums/Form.cs b/DeerCoffeeShop.Domain/Enums/Form.cs index 89e74c4..82470dd 100644 --- a/DeerCoffeeShop.Domain/Enums/Form.cs +++ b/DeerCoffeeShop.Domain/Enums/Form.cs @@ -1,16 +1,10 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace DeerCoffeeShop.Domain.Enums +namespace DeerCoffeeShop.Domain.Enums { public enum FormTypeEnum { JOB_APPLICATION = 1, DAY_OFF_UNWANTED_SHIFT = 2, DAY_OFF_EMMERGENCY = 3, - ACCEPPTED= 4, + ACCEPPTED = 4, } } diff --git a/DeerCoffeeShop.Domain/Repositories/IAttdenceRepository.cs b/DeerCoffeeShop.Domain/Repositories/IAttdenceRepository.cs index b61eb69..5f79271 100644 --- a/DeerCoffeeShop.Domain/Repositories/IAttdenceRepository.cs +++ b/DeerCoffeeShop.Domain/Repositories/IAttdenceRepository.cs @@ -1,12 +1,7 @@ using DeerCoffeeShop.Domain.Entities; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace DeerCoffeeShop.Domain.Repositories; -public interface IAttdenceRepository : IEFRepository +public interface IAttdenceRepository : IEFRepository { } diff --git a/DeerCoffeeShop.Domain/Repositories/IEmployeeRepository.cs b/DeerCoffeeShop.Domain/Repositories/IEmployeeRepository.cs index 4be66fb..d9eeb09 100644 --- a/DeerCoffeeShop.Domain/Repositories/IEmployeeRepository.cs +++ b/DeerCoffeeShop.Domain/Repositories/IEmployeeRepository.cs @@ -7,5 +7,5 @@ public interface IEmployeeRepository : IEFRepository string HashPassword(string password); bool VerifyPassword(string password, string hash); - + } diff --git a/DeerCoffeeShop.Domain/Repositories/IEmployeeShiftRepository.cs b/DeerCoffeeShop.Domain/Repositories/IEmployeeShiftRepository.cs index 75b5bd2..e3fc397 100644 --- a/DeerCoffeeShop.Domain/Repositories/IEmployeeShiftRepository.cs +++ b/DeerCoffeeShop.Domain/Repositories/IEmployeeShiftRepository.cs @@ -4,6 +4,6 @@ namespace DeerCoffeeShop.Domain.Repositories { public interface IEmployeeShiftRepository : IEFRepository { - Task CheckShiftEmployee(string EmployeeID, DateOnly DateOfWork, CancellationToken cancellationToken = default); + Task CheckShiftEmployee(string EmployeeID, DateOnly DateOfWork, string RestaurantID, CancellationToken cancellationToken = default); } } diff --git a/DeerCoffeeShop.Domain/Repositories/IFaceDetectionRepository.cs b/DeerCoffeeShop.Domain/Repositories/IFaceDetectionRepository.cs index 9f889b7..ebf1818 100644 --- a/DeerCoffeeShop.Domain/Repositories/IFaceDetectionRepository.cs +++ b/DeerCoffeeShop.Domain/Repositories/IFaceDetectionRepository.cs @@ -1,9 +1,4 @@ using Microsoft.AspNetCore.Http; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace DeerCoffeeShop.Domain.Repositories; diff --git a/DeerCoffeeShop.Domain/Repositories/IFormRepository.cs b/DeerCoffeeShop.Domain/Repositories/IFormRepository.cs index 7055273..7613c37 100644 --- a/DeerCoffeeShop.Domain/Repositories/IFormRepository.cs +++ b/DeerCoffeeShop.Domain/Repositories/IFormRepository.cs @@ -1,9 +1,4 @@ using DeerCoffeeShop.Domain.Entities; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace DeerCoffeeShop.Domain.Repositories { diff --git a/DeerCoffeeShop.Infrastructure/DeerCoffeeShop.Infrastructure.csproj b/DeerCoffeeShop.Infrastructure/DeerCoffeeShop.Infrastructure.csproj index bdab274..2c9bf0c 100644 --- a/DeerCoffeeShop.Infrastructure/DeerCoffeeShop.Infrastructure.csproj +++ b/DeerCoffeeShop.Infrastructure/DeerCoffeeShop.Infrastructure.csproj @@ -11,7 +11,6 @@ - diff --git a/DeerCoffeeShop.Infrastructure/DependencyInjection.cs b/DeerCoffeeShop.Infrastructure/DependencyInjection.cs index 0137de2..49262ad 100644 --- a/DeerCoffeeShop.Infrastructure/DependencyInjection.cs +++ b/DeerCoffeeShop.Infrastructure/DependencyInjection.cs @@ -12,29 +12,29 @@ public static class DependencyInjection { public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration configuration) { - services.AddDbContext((sp, options) => + _ = services.AddDbContext((sp, options) => { - options.UseSqlServer( + _ = options.UseSqlServer( configuration.GetConnectionString("Azure"), b => { - b.MigrationsAssembly(typeof(ApplicationDbContext).Assembly.FullName); - b.UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery); + _ = b.MigrationsAssembly(typeof(ApplicationDbContext).Assembly.FullName); + _ = b.UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery); }); - options.UseLazyLoadingProxies(); + _ = options.UseLazyLoadingProxies(); }); - services.AddScoped(provider => provider.GetRequiredService()); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); + _ = services.AddScoped(provider => provider.GetRequiredService()); + _ = services.AddScoped(); + _ = services.AddScoped(); + _ = services.AddScoped(); + _ = services.AddScoped(); + _ = services.AddScoped(); + _ = services.AddScoped(); + _ = services.AddScoped(); + _ = services.AddScoped(); + _ = services.AddScoped(); return services; } diff --git a/DeerCoffeeShop.Infrastructure/Persistence/Configurations/ApplicationDbContext.cs b/DeerCoffeeShop.Infrastructure/Persistence/Configurations/ApplicationDbContext.cs index ee0df92..f240c74 100644 --- a/DeerCoffeeShop.Infrastructure/Persistence/Configurations/ApplicationDbContext.cs +++ b/DeerCoffeeShop.Infrastructure/Persistence/Configurations/ApplicationDbContext.cs @@ -19,18 +19,18 @@ public class ApplicationDbContext(DbContextOptions options public virtual DbSet Forms { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { - modelBuilder.ApplyConfigurationsFromAssembly(typeof(ApplicationDbContext).Assembly); + _ = modelBuilder.ApplyConfigurationsFromAssembly(typeof(ApplicationDbContext).Assembly); base.OnModelCreating(modelBuilder); - modelBuilder.ApplyConfiguration(new RestaurantConfiguration()); - modelBuilder.ApplyConfiguration(new EmployeeShiftConfiguration()); - modelBuilder.ApplyConfiguration(new AttendenceConfiguration()); + _ = modelBuilder.ApplyConfiguration(new RestaurantConfiguration()); + _ = modelBuilder.ApplyConfiguration(new EmployeeShiftConfiguration()); + _ = modelBuilder.ApplyConfiguration(new AttendenceConfiguration()); ConfigureModel(modelBuilder); } private static void ConfigureModel(ModelBuilder modelBuilder) { #region Employee - modelBuilder.Entity().HasData( + _ = modelBuilder.Entity().HasData( new Role { ID = 1, @@ -52,7 +52,7 @@ private static void ConfigureModel(ModelBuilder modelBuilder) NguoiTaoID = "1", NgayTao = DateTime.Now, }); - modelBuilder.Entity().HasData( + _ = modelBuilder.Entity().HasData( new Employee { ID = "1", @@ -134,7 +134,7 @@ private static void ConfigureModel(ModelBuilder modelBuilder) }); #endregion #region Form - modelBuilder.Entity().HasData( + _ = modelBuilder.Entity().HasData( new Form { ID = Guid.NewGuid().ToString(), @@ -192,7 +192,7 @@ private static void ConfigureModel(ModelBuilder modelBuilder) }); #endregion #region RestaurantChain - modelBuilder.Entity().HasData( + _ = modelBuilder.Entity().HasData( new RestaurantChain { ID = "ChuoiNhaHang1", @@ -223,7 +223,7 @@ private static void ConfigureModel(ModelBuilder modelBuilder) }); #endregion #region Restaurant - modelBuilder.Entity().HasData( + _ = modelBuilder.Entity().HasData( new Restaurant { ID = "NhaHang1", @@ -265,10 +265,10 @@ private static void ConfigureModel(ModelBuilder modelBuilder) }); #endregion #region shift - modelBuilder.Entity().HasData( + _ = modelBuilder.Entity().HasData( new Shift { - ID=1, + ID = 1, Name = "Sang 07-15", ShiftStart = 7, ShiftEnd = 15, @@ -279,7 +279,7 @@ private static void ConfigureModel(ModelBuilder modelBuilder) }, new Shift { - ID=2, + ID = 2, Name = "Chieu 15-22", ShiftStart = 15, ShiftEnd = 22, @@ -301,13 +301,13 @@ private static void ConfigureModel(ModelBuilder modelBuilder) #endregion #region EmployeeShift - modelBuilder.Entity().HasData( + _ = modelBuilder.Entity().HasData( new EmployeeShift { ID = Guid.NewGuid().ToString(), EmployeeID = "1", RestaurantID = "NhaHang1", - + DateOfWork = DateOnly.FromDateTime(DateTime.Now), Month = DateTime.Now.Month, Year = DateTime.Now.Year, @@ -321,7 +321,7 @@ private static void ConfigureModel(ModelBuilder modelBuilder) ID = Guid.NewGuid().ToString(), EmployeeID = "1", RestaurantID = "NhaHang2", - + DateOfWork = DateOnly.FromDateTime(DateTime.Now), Month = DateTime.Now.Month, Year = DateTime.Now.Year, @@ -335,7 +335,7 @@ private static void ConfigureModel(ModelBuilder modelBuilder) ID = Guid.NewGuid().ToString(), EmployeeID = "3", RestaurantID = "NhaHang3", - + DateOfWork = DateOnly.FromDateTime(DateTime.Now), Month = DateTime.Now.Month, Year = DateTime.Now.Year, @@ -349,7 +349,7 @@ private static void ConfigureModel(ModelBuilder modelBuilder) ID = Guid.NewGuid().ToString(), EmployeeID = "1", RestaurantID = "NhaHang1", - + DateOfWork = DateOnly.FromDateTime(DateTime.Now), Month = DateTime.Now.Month, Year = DateTime.Now.Year, diff --git a/DeerCoffeeShop.Infrastructure/Persistence/Configurations/AttendenceConfiguration.cs b/DeerCoffeeShop.Infrastructure/Persistence/Configurations/AttendenceConfiguration.cs index 845db8c..2b74e80 100644 --- a/DeerCoffeeShop.Infrastructure/Persistence/Configurations/AttendenceConfiguration.cs +++ b/DeerCoffeeShop.Infrastructure/Persistence/Configurations/AttendenceConfiguration.cs @@ -8,7 +8,7 @@ internal class AttendenceConfiguration : IEntityTypeConfiguration { public void Configure(EntityTypeBuilder builder) { - + } } } diff --git a/DeerCoffeeShop.Infrastructure/Persistence/Configurations/EmployeeShiftConfiguration.cs b/DeerCoffeeShop.Infrastructure/Persistence/Configurations/EmployeeShiftConfiguration.cs index 2e5cc3d..dfe8f52 100644 --- a/DeerCoffeeShop.Infrastructure/Persistence/Configurations/EmployeeShiftConfiguration.cs +++ b/DeerCoffeeShop.Infrastructure/Persistence/Configurations/EmployeeShiftConfiguration.cs @@ -8,7 +8,7 @@ internal class EmployeeShiftConfiguration : IEntityTypeConfiguration builder) { - builder.HasOne(es => es.Employee) + _ = builder.HasOne(es => es.Employee) .WithMany() .HasForeignKey(es => es.EmployeeID) .OnDelete(DeleteBehavior.NoAction); diff --git a/DeerCoffeeShop.Infrastructure/Persistence/Configurations/RestaurantConfiguration.cs b/DeerCoffeeShop.Infrastructure/Persistence/Configurations/RestaurantConfiguration.cs index 19f771f..ebd5056 100644 --- a/DeerCoffeeShop.Infrastructure/Persistence/Configurations/RestaurantConfiguration.cs +++ b/DeerCoffeeShop.Infrastructure/Persistence/Configurations/RestaurantConfiguration.cs @@ -8,7 +8,7 @@ internal class RestaurantConfiguration : IEntityTypeConfiguration { public void Configure(EntityTypeBuilder builder) { - builder.HasOne(r => r.RestaurantChain) + _ = builder.HasOne(r => r.RestaurantChain) .WithMany() .HasForeignKey(r => r.RestaurantChainID) .OnDelete(DeleteBehavior.NoAction); diff --git a/DeerCoffeeShop.Infrastructure/Repositories/EmployeeRepository.cs b/DeerCoffeeShop.Infrastructure/Repositories/EmployeeRepository.cs index 5d6e681..74fabc0 100644 --- a/DeerCoffeeShop.Infrastructure/Repositories/EmployeeRepository.cs +++ b/DeerCoffeeShop.Infrastructure/Repositories/EmployeeRepository.cs @@ -2,7 +2,6 @@ using DeerCoffeeShop.Domain.Entities; using DeerCoffeeShop.Domain.Repositories; using DeerCoffeeShop.Infrastructure.Persistence.Configurations; -using Microsoft.EntityFrameworkCore; namespace DeerCoffeeShop.Infrastructure.Repositories; @@ -15,5 +14,5 @@ public bool VerifyPassword(string password, string hash) public string HashPassword(string password) => BCrypt.Net.BCrypt.HashPassword(password); - + } diff --git a/DeerCoffeeShop.Infrastructure/Repositories/EmployeeShiftRepository.cs b/DeerCoffeeShop.Infrastructure/Repositories/EmployeeShiftRepository.cs index 21184b0..b774b0e 100644 --- a/DeerCoffeeShop.Infrastructure/Repositories/EmployeeShiftRepository.cs +++ b/DeerCoffeeShop.Infrastructure/Repositories/EmployeeShiftRepository.cs @@ -7,12 +7,12 @@ namespace DeerCoffeeShop.Infrastructure.Repositories { public class EmployeeShiftRepository(ApplicationDbContext context, IMapper mapper) : RepositoryBase(context, mapper), IEmployeeShiftRepository { - public async Task CheckShiftEmployee(string EmployeeID, DateOnly DateOfWork, CancellationToken cancellationToken = default) + public async Task CheckShiftEmployee(string EmployeeID, DateOnly DateOfWork, string RestaurantID, CancellationToken cancellationToken = default) { - var empShift = await FindAllAsync(x => x.EmployeeID == EmployeeID && x.DateOfWork == DateOfWork&&(x.Actual_CheckIn==null||x.Actual_CheckOut==null), cancellationToken); + List empShift = await FindAllAsync(x => x.EmployeeID == EmployeeID && x.DateOfWork == DateOfWork && x.RestaurantID == RestaurantID && (x.Actual_CheckIn == null || x.Actual_CheckOut == null), cancellationToken); if (empShift == null) return null; - foreach (var item in empShift.OrderBy(x => x.CheckIn)) + foreach (EmployeeShift? item in empShift.OrderBy(x => x.CheckIn)) { if (item.Actual_CheckIn == null || (item.Actual_CheckIn != null && item.Actual_CheckOut == null)) return item; diff --git a/DeerCoffeeShop.Infrastructure/Repositories/FaceDetectionRepository.cs b/DeerCoffeeShop.Infrastructure/Repositories/FaceDetectionRepository.cs index 2072e4c..66ce6ba 100644 --- a/DeerCoffeeShop.Infrastructure/Repositories/FaceDetectionRepository.cs +++ b/DeerCoffeeShop.Infrastructure/Repositories/FaceDetectionRepository.cs @@ -6,7 +6,6 @@ using Emgu.CV.Structure; using Emgu.CV.Util; using Microsoft.AspNetCore.Http; -using Microsoft.IdentityModel.Tokens; using System.Drawing; @@ -41,39 +40,39 @@ public async Task DetectFaceFromImage(IFormFile image, string[] director } ContTrain = labels.Count; - var filePath = await SaveImage(image, "UnknowEmployee", "UnknowEmployeeFolder"); + string filePath = await SaveImage(image, "UnknowEmployee", "UnknowEmployeeFolder"); // Take the latest image from the UnknowEmployeeFolder - var inputImage = new Image(filePath); + Image grayImage = new Image(filePath).Convert(); // Convert the IFormFile to Image - Image grayImage = inputImage.Convert(); + // Face Detector - var facesDetected = faceClassifier.DetectMultiScale( + Rectangle[] facesDetected = faceClassifier.DetectMultiScale( grayImage, 1.2, 10, new Size(20, 20), Size.Empty); - foreach (var faceRect in facesDetected) + foreach (Rectangle faceRect in facesDetected) { Image result = grayImage.Copy(faceRect).Resize(100, 100, Inter.Cubic); if (trainingImages.Count != 0) { // Create the Eigen face recognizer - var recognizer = new EigenFaceRecognizer(); - using (var imagesVector = new VectorOfMat(trainingImages.Select(img => img.Mat).ToArray())) - using (var labelsVector = new VectorOfInt(Enumerable.Range(0, labels.Count).ToArray())) + EigenFaceRecognizer recognizer = new(); + using (VectorOfMat imagesVector = new(trainingImages.Select(img => img.Mat).ToArray())) + using (VectorOfInt labelsVector = new(Enumerable.Range(0, labels.Count).ToArray())) { recognizer.Train(imagesVector, labelsVector); } - var resultRecognized = recognizer.Predict(result); + FaceRecognizer.PredictionResult resultRecognized = recognizer.Predict(result); if (resultRecognized.Label != -1) { - string name = labels[resultRecognized.Label]; + string name = labels[resultRecognized.Label]; recognizedNames = name; } } @@ -82,7 +81,7 @@ public async Task DetectFaceFromImage(IFormFile image, string[] director // Print recognized names if (string.IsNullOrEmpty(recognizedNames)) { - return "No faces recognized."; + return ""; } } catch (Exception ex) @@ -97,7 +96,7 @@ public async Task SaveImage(IFormFile image, string employeeID, string e { if (!Directory.Exists(employeeFolderPath)) { - Directory.CreateDirectory(employeeFolderPath); + _ = Directory.CreateDirectory(employeeFolderPath); } // Check if the image is not empty @@ -107,12 +106,12 @@ public async Task SaveImage(IFormFile image, string employeeID, string e } // Construct the path to save the image inside the employee's folder - var uniqueFileName = $"{Guid.NewGuid()}.bmp"; - var filePath = Path.Combine(employeeFolderPath, uniqueFileName); + string uniqueFileName = $"{Guid.NewGuid()}.bmp"; + string filePath = Path.Combine(employeeFolderPath, uniqueFileName); try { - using var stream = new FileStream(filePath, FileMode.Create); + using FileStream stream = new(filePath, FileMode.Create); await image.CopyToAsync(stream, cancellationToken); return filePath; } diff --git a/DeerCoffeeShop.Infrastructure/Repositories/FormRepository.cs b/DeerCoffeeShop.Infrastructure/Repositories/FormRepository.cs index f891c94..0791bbc 100644 --- a/DeerCoffeeShop.Infrastructure/Repositories/FormRepository.cs +++ b/DeerCoffeeShop.Infrastructure/Repositories/FormRepository.cs @@ -2,11 +2,6 @@ using DeerCoffeeShop.Domain.Entities; using DeerCoffeeShop.Domain.Repositories; using DeerCoffeeShop.Infrastructure.Persistence.Configurations; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace DeerCoffeeShop.Infrastructure.Repositories { diff --git a/DeerCoffeeShop.Infrastructure/Repositories/PagedList.cs b/DeerCoffeeShop.Infrastructure/Repositories/PagedList.cs index 25e0b55..d8e68f9 100644 --- a/DeerCoffeeShop.Infrastructure/Repositories/PagedList.cs +++ b/DeerCoffeeShop.Infrastructure/Repositories/PagedList.cs @@ -11,7 +11,7 @@ public PagedList(IQueryable source, int pageNo, int pageSize) PageCount = PagedList.GetPageCount(pageSize, TotalCount); PageNo = pageNo; PageSize = pageSize; - var skip = ((PageNo - 1) * PageSize); + int skip = (PageNo - 1) * PageSize; AddRange( [.. source @@ -39,7 +39,7 @@ private static int GetPageCount(int pageSize, int totalCount) { return 0; } - var remainder = totalCount % pageSize; + int remainder = totalCount % pageSize; return (totalCount / pageSize) + (remainder == 0 ? 0 : 1); } @@ -49,10 +49,10 @@ public static async Task> CreateAsync( int pageSize, CancellationToken cancellationToken = default) { - var count = await source.CountAsync(cancellationToken); - var skip = ((pageNo - 1) * pageSize); + int count = await source.CountAsync(cancellationToken); + int skip = (pageNo - 1) * pageSize; - var results = await source + List results = await source .Skip(skip) .Take(pageSize) .ToListAsync(cancellationToken); diff --git a/DeerCoffeeShop.Infrastructure/Repositories/RepositoryBase.cs b/DeerCoffeeShop.Infrastructure/Repositories/RepositoryBase.cs index cc8fa15..f9b564b 100644 --- a/DeerCoffeeShop.Infrastructure/Repositories/RepositoryBase.cs +++ b/DeerCoffeeShop.Infrastructure/Repositories/RepositoryBase.cs @@ -18,17 +18,17 @@ public class RepositoryBase(TDbContext dbCont public virtual void Remove(TDomain entity) { - GetSet().Remove((TPersistence)entity); + _ = GetSet().Remove((TPersistence)entity); } public virtual void Add(TDomain entity) { - GetSet().Add((TPersistence)entity); + _ = GetSet().Add((TPersistence)entity); } public virtual void Update(TDomain entity) { - GetSet().Update((TPersistence)entity); + _ = GetSet().Update((TPersistence)entity); } public virtual async Task FindAsync( @@ -71,7 +71,7 @@ public virtual async Task> FindAllAsync( int pageSize, CancellationToken cancellationToken = default) { - var query = QueryInternal(x => true); + IQueryable query = QueryInternal(x => true); return await PagedList.CreateAsync( query, pageNo, @@ -85,7 +85,7 @@ public virtual async Task> FindAllAsync( int pageSize, CancellationToken cancellationToken = default) { - var query = QueryInternal(filterExpression); + IQueryable query = QueryInternal(filterExpression); return await PagedList.CreateAsync( query, pageNo, @@ -100,7 +100,7 @@ public virtual async Task> FindAllAsync( Func, IQueryable> queryOptions, CancellationToken cancellationToken = default) { - var query = QueryInternal(filterExpression, queryOptions); + IQueryable query = QueryInternal(filterExpression, queryOptions); return await PagedList.CreateAsync( query, pageNo, @@ -147,7 +147,7 @@ public virtual async Task> FindAllAsync( Func, IQueryable> queryOptions, CancellationToken cancellationToken = default) { - var query = QueryInternal(queryOptions); + IQueryable query = QueryInternal(queryOptions); return await PagedList.CreateAsync( query, pageNo, @@ -171,7 +171,7 @@ public virtual async Task AnyAsync( protected virtual IQueryable QueryInternal(Expression>? filterExpression) { - var queryable = CreateQuery(); + IQueryable queryable = CreateQuery(); if (filterExpression != null) { queryable = queryable.Where(filterExpression); @@ -183,15 +183,15 @@ protected virtual IQueryable QueryInternal( Expression> filterExpression, Func, IQueryable> queryOptions) { - var queryable = CreateQuery(); + IQueryable queryable = CreateQuery(); queryable = queryable.Where(filterExpression); - var result = queryOptions(queryable); + IQueryable result = queryOptions(queryable); return result; } protected virtual IQueryable QueryInternal(Func, IQueryable>? queryOptions) { - var queryable = CreateQuery(); + IQueryable queryable = CreateQuery(); if (queryOptions != null) { queryable = queryOptions(queryable); @@ -218,8 +218,8 @@ public async Task> FindAllProjectToAsync( Func, IQueryable>? queryOptions = default, CancellationToken cancellationToken = default) { - var queryable = QueryInternal(queryOptions); - var projection = queryable.ProjectTo(mapper.ConfigurationProvider); + IQueryable queryable = QueryInternal(queryOptions); + IQueryable projection = queryable.ProjectTo(mapper.ConfigurationProvider); return await projection.ToListAsync(cancellationToken); } @@ -229,8 +229,8 @@ public async Task> FindAllProjectToAsync( Func, IQueryable>? queryOptions = default, CancellationToken cancellationToken = default) { - var queryable = QueryInternal(queryOptions); - var projection = queryable.ProjectTo(mapper.ConfigurationProvider); + IQueryable queryable = QueryInternal(queryOptions); + IQueryable projection = queryable.ProjectTo(mapper.ConfigurationProvider); return await PagedList.CreateAsync( projection, pageNo, @@ -242,8 +242,8 @@ public async Task> FindAllProjectToAsync( Func, IQueryable> queryOptions, CancellationToken cancellationToken = default) { - var queryable = QueryInternal(queryOptions); - var projection = queryable.ProjectTo(mapper.ConfigurationProvider); + IQueryable queryable = QueryInternal(queryOptions); + IQueryable projection = queryable.ProjectTo(mapper.ConfigurationProvider); return await projection.FirstOrDefaultAsync(cancellationToken); } public async Task> FindAllToDictionaryAsync( From 57575158a57835bc8988989f3b8b621fface98a8 Mon Sep 17 00:00:00 2001 From: Phuc Nghi Date: Sun, 30 Jun 2024 17:59:12 +0700 Subject: [PATCH 2/3] update --- .../EmployeeShift/EmployeeShiftController.cs | 27 ++++++++-- .../AssignEmployee/AssignEmployeeCommand.cs | 1 + .../CheckIn-Out/CheckOut/CheckOutCommand.cs | 31 ++++++++++- .../CreateEmployeeShiftCommandHandler.cs | 6 +++ .../GetByDay/GetEmployeeShiftByDayQuery.cs | 2 +- .../GetEmployeeShiftByDayQueryHandler.cs | 5 +- .../GetNeededReviewShiftQuery.cs | 6 +-- .../EmployeeShift/LockDay/LockDayCommand.cs | 52 +++++++++++++++++++ .../Entities/EmployeeShift.cs | 3 +- .../DependencyInjection.cs | 2 +- .../Repositories/FaceDetectionRepository.cs | 6 +-- 11 files changed, 125 insertions(+), 16 deletions(-) create mode 100644 DeerCoffeeShop.Application/EmployeeShift/LockDay/LockDayCommand.cs diff --git a/DeerCoffeeShop.API/Controllers/EmployeeShift/EmployeeShiftController.cs b/DeerCoffeeShop.API/Controllers/EmployeeShift/EmployeeShiftController.cs index d106c0e..478251f 100644 --- a/DeerCoffeeShop.API/Controllers/EmployeeShift/EmployeeShiftController.cs +++ b/DeerCoffeeShop.API/Controllers/EmployeeShift/EmployeeShiftController.cs @@ -12,6 +12,7 @@ using DeerCoffeeShop.Application.EmployeeShift.GetByEmployeeId; using DeerCoffeeShop.Application.EmployeeShift.GetEmployeeShiftInAWeek; using DeerCoffeeShop.Application.EmployeeShift.GetNeededReviewShift; +using DeerCoffeeShop.Application.EmployeeShift.LockDay; using MediatR; using Microsoft.AspNetCore.Mvc; using System.Net.Mime; @@ -86,7 +87,7 @@ public async Task>>> Get ([FromQuery] GetEmployeeShiftByDayQuery query, CancellationToken cancellationToken) { PagedResult result = await _mediator.Send(query, cancellationToken); - List list = new(); + List data = new(); foreach (EmployeeShiftDto? item in result.Data) { @@ -98,12 +99,21 @@ public async Task>>> Get allDay = false, resource = item }; - list.Add(testreturn); + data.Add(testreturn); } + var paging = new + { + result.TotalCount, + result.PageSize, + result.PageCount, + result.PageNumber, + data + + }; var respond = new { Message = "Get successfully", - Data = list + Data = paging }; return Ok(respond); } @@ -193,5 +203,16 @@ public async Task>>> GetNeededR }; return Ok(respond); } + [HttpPost("lockday")] + public async Task>> LockDay([FromBody] LockDayCommand command, CancellationToken cancellationToken) + { + string result = await _mediator.Send(command, cancellationToken); + var respond = new + { + Message = "Lock successfully", + Data = result + }; + return Ok(respond); + } } diff --git a/DeerCoffeeShop.Application/EmployeeShift/AssignEmployee/AssignEmployeeCommand.cs b/DeerCoffeeShop.Application/EmployeeShift/AssignEmployee/AssignEmployeeCommand.cs index 584cc77..d159102 100644 --- a/DeerCoffeeShop.Application/EmployeeShift/AssignEmployee/AssignEmployeeCommand.cs +++ b/DeerCoffeeShop.Application/EmployeeShift/AssignEmployee/AssignEmployeeCommand.cs @@ -29,6 +29,7 @@ public async Task Handle(AssignEmployeeCommand request, CancellationToke Shift.EmployeeID = request.EmployeeID; Shift.CheckIn = request.CheckIn; Shift.CheckOut = request.CheckOut; + Shift.IsReviewRequired = false; _employeeShiftRepository.Update(Shift); return await _employeeShiftRepository.UnitOfWork.SaveChangesAsync(cancellationToken) > 0 ? "Employee assigned successfully!" : "Employee assigned failed!"; diff --git a/DeerCoffeeShop.Application/EmployeeShift/CheckIn-Out/CheckOut/CheckOutCommand.cs b/DeerCoffeeShop.Application/EmployeeShift/CheckIn-Out/CheckOut/CheckOutCommand.cs index eed10d5..cef08ff 100644 --- a/DeerCoffeeShop.Application/EmployeeShift/CheckIn-Out/CheckOut/CheckOutCommand.cs +++ b/DeerCoffeeShop.Application/EmployeeShift/CheckIn-Out/CheckOut/CheckOutCommand.cs @@ -2,6 +2,7 @@ using CloudinaryDotNet.Actions; using DeerCoffeeShop.Application.Common.Interfaces; using DeerCoffeeShop.Domain.Common.Exceptions; +using DeerCoffeeShop.Domain.Enums; using DeerCoffeeShop.Domain.Repositories; using MediatR; using Microsoft.AspNetCore.Http; @@ -36,6 +37,35 @@ public async Task Handle(CheckOutCommand request, CancellationToken canc if (uploadResult == null) throw new Exception("File upload failed!"); empShift.Actual_CheckOut = request.CheckOut; + empShift.TotalHours = empShift.Actual_CheckOut.Value.Hour - request.CheckOut.Hour; + //check if the check in/out match the actual check in/out + if (empShift.CheckIn != null && empShift.CheckOut != null) + { + empShift.IsOnTime = empShift.CheckIn.Value.Hour == empShift.Actual_CheckIn.Value.Hour && empShift.CheckOut.Value.Hour == request.CheckOut.Hour; + //base on the check in/out time, set the status of the employee + if (empShift.IsOnTime) + { + empShift.Status = EmployeeShiftStatus.OnTime; + } + else if (empShift.CheckIn.Value.Hour < empShift.Actual_CheckIn.Value.Hour) + { + empShift.Status = EmployeeShiftStatus.Late; + } + else if (empShift.CheckOut.Value.Hour > request.CheckOut.Hour) + { + empShift.Status = EmployeeShiftStatus.EarlyLeave; + } + // set the note for the employee if late then negative and positive if early leave and the value will be the time difference + empShift.EmployeeNote = empShift.Status switch + { + EmployeeShiftStatus.Late => empShift.CheckIn.Value.Hour - empShift.Actual_CheckIn.Value.Hour, + EmployeeShiftStatus.EarlyLeave => request.CheckOut.Hour - empShift.CheckOut.Value.Hour, + _ => 0 + }; + + } + + Domain.Entities.Attendence? attendence = await _attdenceRepository.FindAsync(x => x.EmployeeShiftID == empShift.ID, cancellationToken); attendence.EmployeePictureUrlCheckOut = uploadResult.Url.ToString(); _employeeShiftRepository.Update(empShift); @@ -63,7 +93,6 @@ public async Task Handle(CheckOutCommand request, CancellationToken canc catch (Exception ex) { // Log the exception or handle it as necessary - Console.WriteLine($"File upload error: {ex.Message}"); return null; } } diff --git a/DeerCoffeeShop.Application/EmployeeShift/Create/CreateEmployeeShiftCommandHandler.cs b/DeerCoffeeShop.Application/EmployeeShift/Create/CreateEmployeeShiftCommandHandler.cs index 94b5853..92200c2 100644 --- a/DeerCoffeeShop.Application/EmployeeShift/Create/CreateEmployeeShiftCommandHandler.cs +++ b/DeerCoffeeShop.Application/EmployeeShift/Create/CreateEmployeeShiftCommandHandler.cs @@ -18,6 +18,11 @@ public async Task Handle(CreateEmployeeShiftCommand command, Cancellatio { Employee? employee = await _employeeRepository.FindAsync(x => x.ID == _currentUserService.UserId, cancellationToken); Restaurant? restaurant = await _restaurantRepository.FindAsync(x => x.ManagerID == employee.ManagerID, cancellationToken); + var IsLocked = await _employeeShiftRepository.FindAllAsync(x => x.DateOfWork == command.DateOfWork && x.RestaurantID == restaurant.ID && x.IsLocked == true, cancellationToken); + if (IsLocked.Count > 0) + { + return "This day is locked!"; + } Domain.Entities.EmployeeShift empShift = new() { RestaurantID = restaurant.ID, @@ -29,6 +34,7 @@ public async Task Handle(CreateEmployeeShiftCommand command, Cancellatio CheckOut = command.CheckOut, Status = Domain.Enums.EmployeeShiftStatus.Absent, IsOnTime = false, + IsDeleted = false, }; _employeeShiftRepository.Add(empShift); diff --git a/DeerCoffeeShop.Application/EmployeeShift/GetByDay/GetEmployeeShiftByDayQuery.cs b/DeerCoffeeShop.Application/EmployeeShift/GetByDay/GetEmployeeShiftByDayQuery.cs index feb4c29..d9b7d15 100644 --- a/DeerCoffeeShop.Application/EmployeeShift/GetByDay/GetEmployeeShiftByDayQuery.cs +++ b/DeerCoffeeShop.Application/EmployeeShift/GetByDay/GetEmployeeShiftByDayQuery.cs @@ -10,7 +10,7 @@ public class GetEmployeeShiftByDayQuery() : IRequest> + public class GetEmployeeShiftByDayQueryHandler(IEmployeeShiftRepository employeeShiftRepository, IEmployeeRepository employeeRepository, IMapper mapper, ICurrentUserService currentUserService) : IRequestHandler> { private readonly IEmployeeShiftRepository _employeeShiftRepository = employeeShiftRepository; private readonly IEmployeeRepository _employeeRepository = employeeRepository; @@ -20,7 +19,7 @@ public async Task> Handle(GetEmployeeShiftByDayQue { IPagedResult list = await _employeeShiftRepository.FindAllAsync(x => !x.IsDeleted - && x.DateOfWork.Day == query.DateOfWork.Day + && x.DateOfWork == query.DateOfWork && x.RestaurantID.Equals(_currentUserService.RestaurantID), query.PageNo, query.PageSize, cancellationToken); if (list.TotalCount == 0) throw new NotFoundException("None employee shift was found!"); diff --git a/DeerCoffeeShop.Application/EmployeeShift/GetNeededReviewShift/GetNeededReviewShiftQuery.cs b/DeerCoffeeShop.Application/EmployeeShift/GetNeededReviewShift/GetNeededReviewShiftQuery.cs index 6bcfc4f..7801e9f 100644 --- a/DeerCoffeeShop.Application/EmployeeShift/GetNeededReviewShift/GetNeededReviewShiftQuery.cs +++ b/DeerCoffeeShop.Application/EmployeeShift/GetNeededReviewShift/GetNeededReviewShiftQuery.cs @@ -6,10 +6,10 @@ namespace DeerCoffeeShop.Application.EmployeeShift.GetNeededReviewShift; -public class GetNeededReviewShiftQuery(DateOnly date, bool isMonth) : IRequest>, IQuery +public record GetNeededReviewShiftQuery : IRequest>, IQuery { - public DateOnly Date { get; set; } = date; - public bool IsMonth { get; set; } = isMonth; + public DateOnly Date { get; set; } + public bool IsMonth { get; set; } } internal sealed class GetNeededReviewShiftQueryHandler : IRequestHandler> diff --git a/DeerCoffeeShop.Application/EmployeeShift/LockDay/LockDayCommand.cs b/DeerCoffeeShop.Application/EmployeeShift/LockDay/LockDayCommand.cs new file mode 100644 index 0000000..de27b0d --- /dev/null +++ b/DeerCoffeeShop.Application/EmployeeShift/LockDay/LockDayCommand.cs @@ -0,0 +1,52 @@ +using DeerCoffeeShop.Application.Common.Interfaces; +using DeerCoffeeShop.Domain.Repositories; +using MediatR; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DeerCoffeeShop.Application.EmployeeShift.LockDay; + +public record LockDayCommand : IRequest +{ + public DateOnly DateOfWork { get; init; } + public DateTime Start { get; init; } + public DateTime End { get; init; } + public bool IsLocked { get; init; } +} +internal sealed class LockDayCommandHandler : IRequestHandler +{ + private readonly ICurrentUserService _currentUserService; + private readonly IEmployeeShiftRepository _employeeShiftRepository; + + public LockDayCommandHandler(ICurrentUserService currentUserService, IEmployeeShiftRepository employeeShiftRepository) + { + _currentUserService = currentUserService; + _employeeShiftRepository = employeeShiftRepository; + } + + public async Task Handle(LockDayCommand request, CancellationToken cancellationToken) + { + var list = await _employeeShiftRepository.FindAllAsync(x => x.DateOfWork == request.DateOfWork && x.CheckIn == request.Start && x.CheckOut == request.End && !x.NgayXoa.HasValue && x.RestaurantID == _currentUserService.RestaurantID, cancellationToken); + if (request.IsLocked) + { + foreach (var item in list) + { + item.IsLocked = true; + _employeeShiftRepository.Update(item); + } + } + else + { + foreach (var item in list) + { + item.IsLocked = false; + _employeeShiftRepository.Update(item); + } + } + return await _employeeShiftRepository.UnitOfWork.SaveChangesAsync(cancellationToken) > 0 ? "Lock day successfully!" : "Lock day failed"; + + } +} diff --git a/DeerCoffeeShop.Domain/Entities/EmployeeShift.cs b/DeerCoffeeShop.Domain/Entities/EmployeeShift.cs index 832e75c..2950dd6 100644 --- a/DeerCoffeeShop.Domain/Entities/EmployeeShift.cs +++ b/DeerCoffeeShop.Domain/Entities/EmployeeShift.cs @@ -26,7 +26,7 @@ public class EmployeeShift : Entity, ISoftDelete [DataType(DataType.Time)] public DateTime? Actual_CheckOut { get; set; } [DataType(DataType.Time)] - public DateTime? TotalHours { get; set; } + public int? TotalHours { get; set; } public required bool IsOnTime { get; set; } = false; public required EmployeeShiftStatus Status { get; set; } = EmployeeShiftStatus.Absent; public int EmployeeNote { get; set; } = 0; @@ -38,5 +38,6 @@ public class EmployeeShift : Entity, ISoftDelete public virtual Employee? NguoiXoa { get; set; } public bool IsDeleted { get; set; } = false; public bool IsReviewRequired { get; set; } = false; + public bool IsLocked { get; set; } = false; } } diff --git a/DeerCoffeeShop.Infrastructure/DependencyInjection.cs b/DeerCoffeeShop.Infrastructure/DependencyInjection.cs index 49262ad..c49223e 100644 --- a/DeerCoffeeShop.Infrastructure/DependencyInjection.cs +++ b/DeerCoffeeShop.Infrastructure/DependencyInjection.cs @@ -15,7 +15,7 @@ public static IServiceCollection AddInfrastructure(this IServiceCollection servi _ = services.AddDbContext((sp, options) => { _ = options.UseSqlServer( - configuration.GetConnectionString("Azure"), + configuration.GetConnectionString("1"), b => { _ = b.MigrationsAssembly(typeof(ApplicationDbContext).Assembly.FullName); diff --git a/DeerCoffeeShop.Infrastructure/Repositories/FaceDetectionRepository.cs b/DeerCoffeeShop.Infrastructure/Repositories/FaceDetectionRepository.cs index 66ce6ba..4390756 100644 --- a/DeerCoffeeShop.Infrastructure/Repositories/FaceDetectionRepository.cs +++ b/DeerCoffeeShop.Infrastructure/Repositories/FaceDetectionRepository.cs @@ -113,11 +113,11 @@ public async Task SaveImage(IFormFile image, string employeeID, string e { using FileStream stream = new(filePath, FileMode.Create); await image.CopyToAsync(stream, cancellationToken); - return filePath; + return "Success"; } - catch (Exception ex) + catch { - throw new Exception($"{ex.Message}"); + return "Fail"; } } } From f6e9a134e2f20c218e93c8d0ea38157ebf836cd7 Mon Sep 17 00:00:00 2001 From: Phuc Nghi Date: Mon, 8 Jul 2024 10:13:36 +0700 Subject: [PATCH 3/3] update something --- .../Controllers/EmployeeController.cs | 11 +++ .../EmployeeShift/EmployeeShiftController.cs | 12 +++ .../Controllers/Form/FormController.cs | 35 +++++++++ .../Authentication/Login/LoginQuery.cs | 2 - .../CheckIn-Out/CheckOut/CheckOutCommand.cs | 34 ++++---- .../Delete/DeleteEmployeeShiftCommand.cs | 4 +- .../DeleteEmployeeShiftCommandHandler.cs | 8 +- .../DeleteEmployeeShiftCommandValidator.cs | 15 +--- .../EmployeeShift/EmployeeShiftDtoV2.cs | 8 +- .../GetEmployeeShiftInAWeekQuery.cs | 21 ++--- .../GetShiftByID/GetShiftByIDQuery.cs | 34 ++++++++ .../AddDeviceToken/AddDeviceTokenCommand.cs | 29 +++++++ .../Commands/AbsentForm/AbsentFormCommand.cs | 58 ++++++++++++++ .../ChangeFormStatusCommand.cs | 62 +++++++++++++++ DeerCoffeeShop.Application/Forms/FormDto.cs | 7 +- .../GetAbsentFormQuery.cs | 78 +++++++++++++++++++ .../GetAbsentForms/GetAbsentFormQuery.cs | 64 +++++++++++++++ DeerCoffeeShop.Domain/Entities/Employee.cs | 1 + DeerCoffeeShop.Domain/Entities/Form.cs | 3 +- .../DependencyInjection.cs | 2 +- 20 files changed, 430 insertions(+), 58 deletions(-) create mode 100644 DeerCoffeeShop.Application/EmployeeShift/GetShiftByID/GetShiftByIDQuery.cs create mode 100644 DeerCoffeeShop.Application/Employees/AddDeviceToken/AddDeviceTokenCommand.cs create mode 100644 DeerCoffeeShop.Application/Forms/Commands/AbsentForm/AbsentFormCommand.cs create mode 100644 DeerCoffeeShop.Application/Forms/Commands/ChangeFormStatus/ChangeFormStatusCommand.cs create mode 100644 DeerCoffeeShop.Application/Forms/Queries/GetAbsentFormEmployee/GetAbsentFormQuery.cs create mode 100644 DeerCoffeeShop.Application/Forms/Queries/GetAbsentForms/GetAbsentFormQuery.cs diff --git a/DeerCoffeeShop.API/Controllers/EmployeeController.cs b/DeerCoffeeShop.API/Controllers/EmployeeController.cs index dfdfb4a..73cda21 100644 --- a/DeerCoffeeShop.API/Controllers/EmployeeController.cs +++ b/DeerCoffeeShop.API/Controllers/EmployeeController.cs @@ -2,6 +2,7 @@ using DeerCoffeeShop.API.Services; using DeerCoffeeShop.Application.Authentication.Login; using DeerCoffeeShop.Application.Employees; +using DeerCoffeeShop.Application.Employees.AddDeviceToken; using DeerCoffeeShop.Application.Employees.CreateEmployee; using DeerCoffeeShop.Application.Employees.DeleteEmployee; using DeerCoffeeShop.Application.Employees.GetAllEmployee; @@ -83,5 +84,15 @@ public async Task> GetAll([FromQuery] GetAllEmployeeQu }; return Ok(response); } + [HttpPost("add-token")] + public async Task> AddDeviceToken(AddDeviceTokenCommand command, CancellationToken cancellationToken) + { + string result = await _sender.Send(command, cancellationToken); + var response = new + { + Message = result, + }; + return Ok(response); + } } diff --git a/DeerCoffeeShop.API/Controllers/EmployeeShift/EmployeeShiftController.cs b/DeerCoffeeShop.API/Controllers/EmployeeShift/EmployeeShiftController.cs index 478251f..e55f668 100644 --- a/DeerCoffeeShop.API/Controllers/EmployeeShift/EmployeeShiftController.cs +++ b/DeerCoffeeShop.API/Controllers/EmployeeShift/EmployeeShiftController.cs @@ -12,6 +12,7 @@ using DeerCoffeeShop.Application.EmployeeShift.GetByEmployeeId; using DeerCoffeeShop.Application.EmployeeShift.GetEmployeeShiftInAWeek; using DeerCoffeeShop.Application.EmployeeShift.GetNeededReviewShift; +using DeerCoffeeShop.Application.EmployeeShift.GetShiftByID; using DeerCoffeeShop.Application.EmployeeShift.LockDay; using MediatR; using Microsoft.AspNetCore.Mvc; @@ -214,5 +215,16 @@ public async Task>> LockDay([FromBody] LockDay }; return Ok(respond); } + [HttpGet("getbyid")] + public async Task>> GetShiftByID([FromQuery] GetShiftByIDQuery query, CancellationToken cancellationToken) + { + var result = await _mediator.Send(query, cancellationToken); + var respond = new + { + Message = "Get successfully", + Data = result + }; + return Ok(respond); + } } diff --git a/DeerCoffeeShop.API/Controllers/Form/FormController.cs b/DeerCoffeeShop.API/Controllers/Form/FormController.cs index 4545467..c6070a1 100644 --- a/DeerCoffeeShop.API/Controllers/Form/FormController.cs +++ b/DeerCoffeeShop.API/Controllers/Form/FormController.cs @@ -1,8 +1,11 @@ using DeerCoffeeShop.API.Controllers.ResponseTypes; using DeerCoffeeShop.Application.Common.Pagination; using DeerCoffeeShop.Application.Forms; +using DeerCoffeeShop.Application.Forms.Commands.AbsentForm; using DeerCoffeeShop.Application.Forms.Commands.AcceptEmployeeAndGeneratePassword; using DeerCoffeeShop.Application.Forms.Commands.AcceptFormAndSendMail; +using DeerCoffeeShop.Application.Forms.Commands.ChangeFormStatus; +using DeerCoffeeShop.Application.Forms.Queries.GetAbsentFormEmployee; using DeerCoffeeShop.Application.Forms.Queries.GetAllPagination; using MediatR; using Microsoft.AspNetCore.Mvc; @@ -45,4 +48,36 @@ public async Task SendPassword([FromRoute] string id) }; return Ok(response); } + [HttpPost("day-off")] + public async Task DayOffForm(AbsentFormCommand command) + { + string resutl = await _sender.Send(new AbsentFormCommand(command.ShiftID, command.Reason, command.FormType)); + var response = new + { + Message = resutl + }; + return Ok(response); + } + [HttpGet("absent-forms")] + public async Task>> GetAbsentForm([FromQuery] int pageNumber, int pageSize) + { + var result = await _sender.Send(new GetAbsentFormQuery(pageNumber, pageSize)); + var response = new + { + Message = "Get Absent Form Successfully", + Data = result + }; + return Ok(response); + } + [HttpPost("approve")] + public async Task> GetChangeShiftForm(ChangeFormStatusCommand command) + { + var result = await _sender.Send(new ChangeFormStatusCommand(command.FormID, command.IsApprove,command.Response)); + var response = new + { + Message = "Get Change Shift Form Successfully", + Data = result + }; + return Ok(response); + } } diff --git a/DeerCoffeeShop.Application/Authentication/Login/LoginQuery.cs b/DeerCoffeeShop.Application/Authentication/Login/LoginQuery.cs index bb183be..cc81403 100644 --- a/DeerCoffeeShop.Application/Authentication/Login/LoginQuery.cs +++ b/DeerCoffeeShop.Application/Authentication/Login/LoginQuery.cs @@ -7,6 +7,4 @@ public record LoginQuery(string EmployeeID, string Password) : IRequest Handle(CheckOutCommand request, CancellationToken canc } private async Task UploadEmployeeImage(IFormFile imageFile) { - using (Stream stream = imageFile.OpenReadStream()) + using Stream stream = imageFile.OpenReadStream(); + ImageUploadParams uploadParams = new() { - ImageUploadParams uploadParams = new() - { - File = new FileDescription(imageFile.FileName, stream), - UseFilename = true, - UniqueFilename = false, - Folder = "EmployeeCheckIn", - Overwrite = true - }; + File = new FileDescription(imageFile.FileName, stream), + UseFilename = true, + UniqueFilename = false, + Folder = "EmployeeCheckIn", + Overwrite = true + }; - try - { - return await cloudinary.UploadAsync(uploadParams); - } - catch (Exception ex) - { - // Log the exception or handle it as necessary - return null; - } + try + { + return await cloudinary.UploadAsync(uploadParams); + } + catch (Exception ex) + { + // Log the exception or handle it as necessary + return null; } } diff --git a/DeerCoffeeShop.Application/EmployeeShift/Delete/DeleteEmployeeShiftCommand.cs b/DeerCoffeeShop.Application/EmployeeShift/Delete/DeleteEmployeeShiftCommand.cs index 9966dd7..3c5b6f5 100644 --- a/DeerCoffeeShop.Application/EmployeeShift/Delete/DeleteEmployeeShiftCommand.cs +++ b/DeerCoffeeShop.Application/EmployeeShift/Delete/DeleteEmployeeShiftCommand.cs @@ -7,8 +7,6 @@ namespace DeerCoffeeShop.Application.EmployeeShift.Delete [Authorize] public class DeleteEmployeeShiftCommand() : IRequest, ICommand { - public string EmployeeID { get; set; } - public string RestaurantID { get; set; } - public int ShiftID { get; set; } + public string ShiftID { get; set; } } } diff --git a/DeerCoffeeShop.Application/EmployeeShift/Delete/DeleteEmployeeShiftCommandHandler.cs b/DeerCoffeeShop.Application/EmployeeShift/Delete/DeleteEmployeeShiftCommandHandler.cs index 44ba26b..cb50562 100644 --- a/DeerCoffeeShop.Application/EmployeeShift/Delete/DeleteEmployeeShiftCommandHandler.cs +++ b/DeerCoffeeShop.Application/EmployeeShift/Delete/DeleteEmployeeShiftCommandHandler.cs @@ -12,14 +12,10 @@ public class DeleteEmployeeShiftCommandHandler(IEmployeeShiftRepository employee public async Task Handle(DeleteEmployeeShiftCommand request, CancellationToken cancellationToken) { - Domain.Entities.EmployeeShift foundObject = await _employeeShiftRepository.FindAsync(x => x.EmployeeID.Equals(request.EmployeeID) - && x.RestaurantID.Equals(request.RestaurantID) + var shift = await _employeeShiftRepository.FindAsync(x => x.ID == request.ShiftID, cancellationToken)?? throw new NotFoundException("Shift not found"); + _employeeShiftRepository.Remove(shift); - && x.NguoiXoaID == null) ?? throw new NotFoundException("None employee shift of restaurant was found!"); - foundObject.EmployeeID = null; - foundObject.NguoiXoaID = _currentUserService.UserId; - foundObject.NgayXoa = DateTime.Now; return await _employeeShiftRepository.UnitOfWork.SaveChangesAsync(cancellationToken) > 0 ? "Xóa thành công" : "Xóa thất bại"; } diff --git a/DeerCoffeeShop.Application/EmployeeShift/Delete/DeleteEmployeeShiftCommandValidator.cs b/DeerCoffeeShop.Application/EmployeeShift/Delete/DeleteEmployeeShiftCommandValidator.cs index ff1f71a..f960844 100644 --- a/DeerCoffeeShop.Application/EmployeeShift/Delete/DeleteEmployeeShiftCommandValidator.cs +++ b/DeerCoffeeShop.Application/EmployeeShift/Delete/DeleteEmployeeShiftCommandValidator.cs @@ -11,20 +11,7 @@ public DeleteEmployeeShiftCommandValidator() public void Configure() { - _ = RuleFor(x => x.EmployeeID) - .NotEmpty() - .NotNull() - .WithMessage("Employee must not be empty!"); - - _ = RuleFor(x => x.RestaurantID) - .NotEmpty() - .NotNull() - .WithMessage("Restaurant must not be empty!"); - - _ = RuleFor(x => x.ShiftID) - .NotEmpty() - .NotNull() - .WithMessage("Shift must not be empty!"); + } } } diff --git a/DeerCoffeeShop.Application/EmployeeShift/EmployeeShiftDtoV2.cs b/DeerCoffeeShop.Application/EmployeeShift/EmployeeShiftDtoV2.cs index db95a68..805560f 100644 --- a/DeerCoffeeShop.Application/EmployeeShift/EmployeeShiftDtoV2.cs +++ b/DeerCoffeeShop.Application/EmployeeShift/EmployeeShiftDtoV2.cs @@ -24,12 +24,14 @@ public class EmployeeShiftDtoV2 : IMapFrom public int EmployeeNote { get; set; } public string? Note { get; set; } public EmployeeDto Employee { get; set; } + public string? CheckInUrl { get; set; } + public string? CheckOutUrl { get; set; } public static EmployeeShiftDtoV2 Create(string ID, string RestaurantID, EmployeeDto employee, DateOnly dateOfWork, int month, int year, DateTime checkIn, DateTime checkOut, DateTime? actual_CheckIn , DateTime? actual_CheckOut, DateTime? totalHours, bool isOnTime, EmployeeShiftStatus status - , int employeeNote, string? note) - { + , int employeeNote, string? note, string? CheckInUrl, string? CheckOutUrl) + { return new EmployeeShiftDtoV2() { ID = ID, @@ -47,6 +49,8 @@ public static EmployeeShiftDtoV2 Create(string ID, string RestaurantID, Employee Status = status, EmployeeNote = employeeNote, Note = note, + CheckInUrl = CheckInUrl, + CheckOutUrl = CheckOutUrl }; } diff --git a/DeerCoffeeShop.Application/EmployeeShift/GetEmployeeShiftInAWeek/GetEmployeeShiftInAWeekQuery.cs b/DeerCoffeeShop.Application/EmployeeShift/GetEmployeeShiftInAWeek/GetEmployeeShiftInAWeekQuery.cs index a04b2e3..48c7789 100644 --- a/DeerCoffeeShop.Application/EmployeeShift/GetEmployeeShiftInAWeek/GetEmployeeShiftInAWeekQuery.cs +++ b/DeerCoffeeShop.Application/EmployeeShift/GetEmployeeShiftInAWeek/GetEmployeeShiftInAWeekQuery.cs @@ -14,12 +14,13 @@ public record GetEmployeeShiftInAWeekQuery : IRequest>, public DateOnly Date { get; set; } public bool IsMonth { get; set; } } -internal class GetEmployeeShiftInAWeekQueryHandler(IEmployeeShiftRepository employeeShiftRepository, ICurrentUserService currentUserService, IMapper mapper, IRestaurantRepository restaurantRepository, IEmployeeRepository employeeRepository) : IRequestHandler> +internal class GetEmployeeShiftInAWeekQueryHandler(IEmployeeShiftRepository employeeShiftRepository, ICurrentUserService currentUserService, IMapper mapper, IRestaurantRepository restaurantRepository, IEmployeeRepository employeeRepository, IAttdenceRepository attdenceRepository) : IRequestHandler> { private readonly IEmployeeShiftRepository _employeeShiftRepository = employeeShiftRepository; private readonly ICurrentUserService _currentUserService = currentUserService; private readonly IRestaurantRepository _restaurantRepository = restaurantRepository; private readonly IEmployeeRepository _employeeRepository = employeeRepository; + private readonly IAttdenceRepository _attdenceRepository = attdenceRepository; private readonly IMapper _mapper = mapper; public async Task> Handle(GetEmployeeShiftInAWeekQuery request, CancellationToken cancellationToken) @@ -47,7 +48,8 @@ public async Task> Handle(GetEmployeeShiftInAWeekQuery } else { - employeeShifts = await _employeeShiftRepository.FindAllAsync(x => x.Month == request.Date.Month && x.RestaurantID == ManagerIDOfRestaurant.ID, cancellationToken); + Employee? User = await _employeeRepository.FindAsync(x => x.ID == UserID, cancellationToken); + employeeShifts = await _employeeShiftRepository.FindAllAsync(x => x.Month == request.Date.Month && x.RestaurantID == User.ManagerID, cancellationToken); } // Retrieve employee details @@ -55,13 +57,14 @@ public async Task> Handle(GetEmployeeShiftInAWeekQuery { item.Employee = await _employeeRepository.FindAsync(x => x.ID == item.EmployeeID, cancellationToken); } - //var task = employeeShifts.Select(async item => - //{ - // item.Employee = await _employeeRepository.FindAsync(x => x.ID == item.EmployeeID, cancellationToken); - //} - // ); - //await Task.WhenAll(task); - return _mapper.Map>(employeeShifts); + + var map = _mapper.Map>(employeeShifts); + + foreach (var item in map) + { + var attdence = await _attdenceRepository.FindAsync(x => x.EmployeeShiftID == item.ID, cancellationToken); + } + return map; } diff --git a/DeerCoffeeShop.Application/EmployeeShift/GetShiftByID/GetShiftByIDQuery.cs b/DeerCoffeeShop.Application/EmployeeShift/GetShiftByID/GetShiftByIDQuery.cs new file mode 100644 index 0000000..53a6c26 --- /dev/null +++ b/DeerCoffeeShop.Application/EmployeeShift/GetShiftByID/GetShiftByIDQuery.cs @@ -0,0 +1,34 @@ +using AutoMapper; +using DeerCoffeeShop.Domain.Common.Exceptions; +using DeerCoffeeShop.Domain.Repositories; +using MediatR; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DeerCoffeeShop.Application.EmployeeShift.GetShiftByID; + +public record GetShiftByIDQuery : IRequest +{ + public string ShiftID { get; set; } + +} +internal sealed class GetShiftByIDQueryHandler : IRequestHandler +{ + private readonly IEmployeeShiftRepository _employeeShiftRepository; + private readonly IMapper _mapper; + + public GetShiftByIDQueryHandler(IEmployeeShiftRepository employeeShiftRepository, IMapper mapper) + { + _employeeShiftRepository = employeeShiftRepository; + _mapper = mapper; + } + + public async Task Handle(GetShiftByIDQuery request, CancellationToken cancellationToken) + { + var shift = await _employeeShiftRepository.FindAsync(x => x.ID == request.ShiftID, cancellationToken) ?? throw new NotFoundException("Shift not found"); + return _mapper.Map(shift); + } +} diff --git a/DeerCoffeeShop.Application/Employees/AddDeviceToken/AddDeviceTokenCommand.cs b/DeerCoffeeShop.Application/Employees/AddDeviceToken/AddDeviceTokenCommand.cs new file mode 100644 index 0000000..3c3d781 --- /dev/null +++ b/DeerCoffeeShop.Application/Employees/AddDeviceToken/AddDeviceTokenCommand.cs @@ -0,0 +1,29 @@ +using DeerCoffeeShop.Domain.Repositories; +using MediatR; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DeerCoffeeShop.Application.Employees.AddDeviceToken; + +public record AddDeviceTokenCommand : IRequest +{ + public string EmployeeID { get; set; } + public string DeviceToken { get; set; } +} +internal sealed class AddDeviceTokenCommandHandler(IEmployeeRepository employeeRepository) : IRequestHandler +{ + private readonly IEmployeeRepository _employeeRepository = employeeRepository; + public async Task Handle(AddDeviceTokenCommand request, CancellationToken cancellationToken) + { + var employee = await _employeeRepository.FindAsync(x => x.ID == request.EmployeeID, cancellationToken); + employee.DeviceToken = request.DeviceToken; + _employeeRepository.Update(employee); + _ = await _employeeRepository.UnitOfWork.SaveChangesAsync(cancellationToken); + return "Add device token successfully!"; + + } +} + diff --git a/DeerCoffeeShop.Application/Forms/Commands/AbsentForm/AbsentFormCommand.cs b/DeerCoffeeShop.Application/Forms/Commands/AbsentForm/AbsentFormCommand.cs new file mode 100644 index 0000000..946afbd --- /dev/null +++ b/DeerCoffeeShop.Application/Forms/Commands/AbsentForm/AbsentFormCommand.cs @@ -0,0 +1,58 @@ +using DeerCoffeeShop.Application.Common.Interfaces; +using DeerCoffeeShop.Application.Common.Security; +using DeerCoffeeShop.Domain.Repositories; +using MediatR; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DeerCoffeeShop.Application.Forms.Commands.AbsentForm +{ + [Authorize] + public record AbsentFormCommand : IRequest + { + public string ShiftID { get; set; } + public string Reason { get; set; } + public int FormType { get; set; } + public AbsentFormCommand(string shiftID, string reason, int formType) + { + ShiftID = shiftID; + Reason = reason; + FormType = formType; + } + } + internal sealed class AbsentFormCommandHandlder : IRequestHandler + { + private readonly ICurrentUserService _currentUserService; + private readonly IEmployeeRepository _employeeRepository; + private readonly IFormRepository _formRepository; + + public AbsentFormCommandHandlder(ICurrentUserService currentUserService, IEmployeeRepository employeeRepository, IFormRepository formRepository) + { + _currentUserService = currentUserService; + _employeeRepository = employeeRepository; + _formRepository = formRepository; + } + + public async Task Handle(AbsentFormCommand request, CancellationToken cancellationToken) + { + string? UserID = _currentUserService.UserId; + + var form = new Domain.Entities.Form + { + EmployeeID = UserID, + ShiftID = request.ShiftID, + FormType = (Domain.Enums.FormTypeEnum)request.FormType, + Content = request.Reason, + Date = DateTimeOffset.UtcNow.ToOffset(TimeSpan.FromHours(7)).DateTime, + }; + _formRepository.Add(form); + return await _formRepository.UnitOfWork.SaveChangesAsync(cancellationToken) > 0 ? "Sucess" : "Failed"; + + + + } + } +} diff --git a/DeerCoffeeShop.Application/Forms/Commands/ChangeFormStatus/ChangeFormStatusCommand.cs b/DeerCoffeeShop.Application/Forms/Commands/ChangeFormStatus/ChangeFormStatusCommand.cs new file mode 100644 index 0000000..af21ead --- /dev/null +++ b/DeerCoffeeShop.Application/Forms/Commands/ChangeFormStatus/ChangeFormStatusCommand.cs @@ -0,0 +1,62 @@ +using DeerCoffeeShop.Application.Common.Interfaces; +using DeerCoffeeShop.Domain.Repositories; +using MediatR; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DeerCoffeeShop.Application.Forms.Commands.ChangeFormStatus; + +public record ChangeFormStatusCommand : IRequest +{ + public ChangeFormStatusCommand(string formID, bool isApprove, string response) + { + FormID = formID; + IsApprove = isApprove; + Response = response; + } + + public string FormID { get; set; } + public bool IsApprove { get; set; } + public string Response { get; set; } = ""; + +} +internal sealed class ChangeFormStatusCommandHandler : IRequestHandler +{ + private readonly IFormRepository _formRepository; + private readonly ICurrentUserService _currentUserService; + private readonly IEmployeeShiftRepository _employeeShiftRepository; + + public ChangeFormStatusCommandHandler(IFormRepository formRepository, ICurrentUserService currentUserService, IEmployeeShiftRepository employeeShiftRepository) + { + _formRepository = formRepository; + _currentUserService = currentUserService; + _employeeShiftRepository = employeeShiftRepository; + } + + public async Task Handle(ChangeFormStatusCommand request, CancellationToken cancellationToken) + { + var form = await _formRepository.FindAsync(x => x.ID == request.FormID, cancellationToken); + if (form == null) + { + return "Form not found"; + } + form.Content = request.Response; + form.IsApproved = request.IsApprove; + var shift = await _employeeShiftRepository.FindAsync(x => x.ID == form.ShiftID, cancellationToken); + if (shift == null) + { + return "Shift not found"; + } + if (!request.IsApprove) + { + _employeeShiftRepository.Remove(shift); + + } + _employeeShiftRepository.Update(shift); + await _formRepository.UnitOfWork.SaveChangesAsync(cancellationToken); + return "Success"; + } +} diff --git a/DeerCoffeeShop.Application/Forms/FormDto.cs b/DeerCoffeeShop.Application/Forms/FormDto.cs index 7ded92c..489934b 100644 --- a/DeerCoffeeShop.Application/Forms/FormDto.cs +++ b/DeerCoffeeShop.Application/Forms/FormDto.cs @@ -13,11 +13,13 @@ public class FormDto : IMapFrom public string? Content { get; set; } public DateTime? Date { get; set; } public bool IsApproved { get; set; } + public string Response { get; set; } + public void Mapping(Profile profile) { _ = profile.CreateMap(); } - public static FormDto Create(string FormID, EmployeeDto employee, Domain.Enums.FormTypeEnum formType, string content, DateTime date, bool isApproved) + public static FormDto Create(string FormID, EmployeeDto employee, Domain.Enums.FormTypeEnum formType, string content, DateTime date, bool isApproved,string Response) { return new FormDto { @@ -26,7 +28,8 @@ public static FormDto Create(string FormID, EmployeeDto employee, Domain.Enums.F FormType = formType, Content = content, Date = date, - IsApproved = isApproved + IsApproved = isApproved, + Response=Response }; } diff --git a/DeerCoffeeShop.Application/Forms/Queries/GetAbsentFormEmployee/GetAbsentFormQuery.cs b/DeerCoffeeShop.Application/Forms/Queries/GetAbsentFormEmployee/GetAbsentFormQuery.cs new file mode 100644 index 0000000..1d23289 --- /dev/null +++ b/DeerCoffeeShop.Application/Forms/Queries/GetAbsentFormEmployee/GetAbsentFormQuery.cs @@ -0,0 +1,78 @@ +using AutoMapper; +using DeerCoffeeShop.Application.Common.Interfaces; +using DeerCoffeeShop.Application.Common.Pagination; +using DeerCoffeeShop.Application.Common.Security; +using DeerCoffeeShop.Domain.Enums; +using DeerCoffeeShop.Domain.Repositories; +using MediatR; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DeerCoffeeShop.Application.Forms.Queries.GetAbsentFormEmployee; +[Authorize] +public record GetAbsentFormQuery : IRequest> +{ + public int PageNumber { get; set; } + public int PageSize { get; set; } + public GetAbsentFormQuery(int pageNumber, int pageSize) + { + PageNumber = pageNumber; + PageSize = pageSize; + } + +} +internal sealed class GetAbsentFormQueryHandler : IRequestHandler> +{ + private readonly IFormRepository _formRepository; + private readonly ICurrentUserService _currentUserService; + private readonly IMapper _mapper; + private readonly IEmployeeRepository _employeeRepository; + + public GetAbsentFormQueryHandler(IFormRepository formRepository, ICurrentUserService currentUserService, IMapper mapper, IEmployeeRepository employeeRepository) + { + _formRepository = formRepository; + _currentUserService = currentUserService; + _mapper = mapper; + _employeeRepository = employeeRepository; + } + + public async Task> Handle(GetAbsentFormQuery request, CancellationToken cancellationToken) + { + string? UserID = _currentUserService.UserId; + var isManager = await _currentUserService.IsInRoleAsync("Manager"); + var Employees = await _employeeRepository.FindAllAsync(x => x.ManagerID == UserID, cancellationToken); + if (isManager) + { + var employeeIds = Employees.Select(e => e.ID).ToList(); + var forms = await _formRepository.FindAllAsync( + x => (x.FormType == FormTypeEnum.DAY_OFF_UNWANTED_SHIFT || x.FormType == FormTypeEnum.DAY_OFF_EMMERGENCY) + && employeeIds.Contains(x.ID), + request.PageNumber, + request.PageSize, + cancellationToken); + return PagedResult.Create + ( + totalCount: forms.TotalCount, + pageCount: forms.PageCount, + pageSize: forms.PageSize, + pageNumber: forms.PageNo, + data: forms.MapToFormDtoList(_mapper) + ); + } + else + { + var forms = await _formRepository.FindAllAsync(x => x.EmployeeID == UserID && (x.FormType == FormTypeEnum.DAY_OFF_UNWANTED_SHIFT || x.FormType == FormTypeEnum.DAY_OFF_EMMERGENCY), request.PageNumber, request.PageSize, cancellationToken); + return PagedResult.Create + ( + totalCount: forms.TotalCount, + pageCount: forms.PageCount, + pageSize: forms.PageSize, + pageNumber: forms.PageNo, + data: forms.MapToFormDtoList(_mapper) + ); + } + } +} diff --git a/DeerCoffeeShop.Application/Forms/Queries/GetAbsentForms/GetAbsentFormQuery.cs b/DeerCoffeeShop.Application/Forms/Queries/GetAbsentForms/GetAbsentFormQuery.cs new file mode 100644 index 0000000..950aedf --- /dev/null +++ b/DeerCoffeeShop.Application/Forms/Queries/GetAbsentForms/GetAbsentFormQuery.cs @@ -0,0 +1,64 @@ +using AutoMapper; +using DeerCoffeeShop.Application.Common.Interfaces; +using DeerCoffeeShop.Application.Common.Pagination; +using DeerCoffeeShop.Application.Employees; +using DeerCoffeeShop.Domain.Repositories; +using MediatR; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DeerCoffeeShop.Application.Forms.Queries.GetAbsentForms; + +public record GetAbsentFormQuery : IRequest> +{ + public int PageNumber { get; set; } + public int PageSize { get; set; } +} +internal sealed class GetAbsentFormQueryHandler : IRequestHandler> +{ + private readonly IFormRepository _formRepository; + private readonly ICurrentUserService _currentUserService; + private readonly IMapper _mapper; + private readonly IEmployeeRepository _employeeRepository; + + public GetAbsentFormQueryHandler(IFormRepository formRepository, ICurrentUserService currentUserService, IMapper mapper, IEmployeeRepository employeeRepository) + { + _formRepository = formRepository; + _currentUserService = currentUserService; + _mapper = mapper; + _employeeRepository = employeeRepository; + } + + public async Task> Handle(GetAbsentFormQuery request, CancellationToken cancellationToken) + { + string? UserID = _currentUserService.UserId; + bool isManager = await _currentUserService.IsInRoleAsync("Manager"); + if (!isManager) + { + var forms = await _formRepository.FindAllAsync(x => x.EmployeeID == UserID && (x.FormType == Domain.Enums.FormTypeEnum.DAY_OFF_UNWANTED_SHIFT || x.FormType == Domain.Enums.FormTypeEnum.DAY_OFF_EMMERGENCY), request.PageNumber, request.PageSize, cancellationToken); + var map = _mapper.Map>(forms); + foreach (var item in map.Data) + { + var employee = await _employeeRepository.FindAsync(x => x.ID == _currentUserService.UserId, cancellationToken); + item.Employee = _mapper.Map(employee); + } + return map; + } + else + { + var forms = await _formRepository.FindAllAsync(x => x.FormType == Domain.Enums.FormTypeEnum.DAY_OFF_UNWANTED_SHIFT || x.FormType == Domain.Enums.FormTypeEnum.DAY_OFF_EMMERGENCY, request.PageNumber, request.PageSize, cancellationToken); + var map = _mapper.Map>(forms); + foreach (var item in forms) + { + map.Data.Where(x => x.ID == item.ID).FirstOrDefault().Employee = _mapper.Map(await _employeeRepository.FindAsync(x => x.ID == item.EmployeeID, cancellationToken)); + } + return map; + } + + + } +} + diff --git a/DeerCoffeeShop.Domain/Entities/Employee.cs b/DeerCoffeeShop.Domain/Entities/Employee.cs index a12f0f8..2170470 100644 --- a/DeerCoffeeShop.Domain/Entities/Employee.cs +++ b/DeerCoffeeShop.Domain/Entities/Employee.cs @@ -48,5 +48,6 @@ public class Employee : Entity, ISoftDelete public string RefreshToken { get; set; } = string.Empty; public DateTime RefreshTokenExpiryTime { get; set; } public bool IsMailed { get; set; } + public string DeviceToken { get; set; } = ""; } } diff --git a/DeerCoffeeShop.Domain/Entities/Form.cs b/DeerCoffeeShop.Domain/Entities/Form.cs index 02e2725..325b847 100644 --- a/DeerCoffeeShop.Domain/Entities/Form.cs +++ b/DeerCoffeeShop.Domain/Entities/Form.cs @@ -10,5 +10,6 @@ public class Form : Entity public string? Content { get; set; } public DateTime? Date { get; set; } public bool IsApproved { get; set; } = false; - + public string Response { get; set; } = ""; + public string ShiftID { get; set; }= ""; } diff --git a/DeerCoffeeShop.Infrastructure/DependencyInjection.cs b/DeerCoffeeShop.Infrastructure/DependencyInjection.cs index c49223e..49262ad 100644 --- a/DeerCoffeeShop.Infrastructure/DependencyInjection.cs +++ b/DeerCoffeeShop.Infrastructure/DependencyInjection.cs @@ -15,7 +15,7 @@ public static IServiceCollection AddInfrastructure(this IServiceCollection servi _ = services.AddDbContext((sp, options) => { _ = options.UseSqlServer( - configuration.GetConnectionString("1"), + configuration.GetConnectionString("Azure"), b => { _ = b.MigrationsAssembly(typeof(ApplicationDbContext).Assembly.FullName);