Untitled

mail@pastecode.io avatar
unknown
plain_text
15 days ago
14 kB
3
Indexable
Never
using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using QUALTECH.Api.Utilities;
using QUALTECH.Domain.Abstractions.IServices;
using QUALTECH.Domain.Models.Dtos.PostPutDtos;
using QUALTECH.Domain.Models.Dtos.Responses;
using QUALTECH.Shared;

namespace QUALTECH.Api.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class TestCenterController : ControllerBase
    {
        private readonly ITestCenterService _testCenterService;
        private readonly IMapper _mapper;
        private readonly IUserService _userService;
        public TestCenterController(ITestCenterService testCenterService, IUserService userService, IMapper mapper)
        {
            _testCenterService = testCenterService;
            _userService = userService;
            _mapper = mapper;
        }

        [HttpPost("create-test-center")]
        [ProducesResponseType(StatusCodes.Status201Created)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status401Unauthorized)]
        public async Task<IActionResult> CreateTestCenter([FromBody] CreateTestCenterDto dto)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(new APPResponse(false, AppMessages.INVALID));
            }

            var authenticatedUser = _userService.GetAuthenticatedUser();
            if (authenticatedUser == null)
            {
                return Unauthorized(new APPResponse(false, AppMessages.UNATHORIZED));
            }

            var dtoSafe = StringHelper.TrimStringProperties(dto);
            var result = await _testCenterService.CreateTestCenterAsync(dtoSafe, authenticatedUser.Id);
            if (result != null)
            {
                return Ok(result);
            }

            return BadRequest(new APPResponse(false, AppMessages.FAILED));
        }

        [HttpPut("update-test-center")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status401Unauthorized)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<IActionResult> UpdateTestCenter([FromBody] UpdateTestCenterDto dto)
        {
            if (dto == null)
            {
                return BadRequest(new APPResponse(false, AppMessages.INVALID));
            }

            var authenticatedUser = _userService.GetAuthenticatedUser();
            if (authenticatedUser == null)
            {
                return Unauthorized(new APPResponse(false, AppMessages.UNATHORIZED));
            }

            var dtoSafe = StringHelper.TrimStringProperties(dto);
            var result = await _testCenterService.UpdateTestCenterAsync(dtoSafe, authenticatedUser.Id);
            if (result)
            {
                return Ok(new APPResponse(true, AppMessages.SUCCESSFUL));
            }

            return NotFound(new APPResponse(false, AppMessages.FAILED));
        }

        [HttpGet("get-all-test-centers")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<IActionResult> GetAllTestCentersAsync()
        {
            var response = new APPResponse(false, $"All {AppMessages.TEST_CENTER} {AppMessages.FETCHING} not {AppMessages.PERFORMED}");

            var testCenters = await _testCenterService.GetAll();

            if (testCenters != null)
            {
                response.ResultData = testCenters;
                response.Success = true;
                response.ResultMessage = $"{AppMessages.FETCHING} {AppMessages.TEST_CENTER}s was {AppMessages.SUCCESSFUL}";

                return Ok(response);
            }
            return NotFound(response);
        }

        [HttpDelete("delete-test-center/{testCenterId}")]
        [ProducesResponseType(StatusCodes.Status204NoContent)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        [ProducesResponseType(StatusCodes.Status401Unauthorized)]
        public async Task<IActionResult> DeleteTestCenter(int testCenterId)
        {
            var response = new APPResponse(false, $"{AppMessages.DELETE} {AppMessages.TEST_CENTER} {AppMessages.REQUEST} {AppMessages.FAILED}");

            var authenticatedUser = _userService.GetAuthenticatedUser();
            if (authenticatedUser == null)
            {
                response.ResultMessage = $"{AppMessages.AUTHENTICATED} {AppMessages.TEST_CENTER} or {AppMessages.USER} {AppMessages.NOT_EXISTS}";
                return BadRequest(response);
            }

            var result = await _testCenterService.DeleteById(testCenterId, authenticatedUser.Id);
            if (result)
            {
                response.Success = true;
                response.ResultMessage = $"{AppMessages.DELETE} {AppMessages.TEST_CENTER}s was {AppMessages.SUCCESSFUL}";
                return Ok(response);
            }
            else
            {
                response.ResultMessage = $"{AppMessages.USER} {AppMessages.NOT_EXISTS}";
                return NotFound(response);
            }
        }
    }
}


using QUALTECH.Domain.Models;
using QUALTECH.Domain.Models.Dtos.Responses;
using QUALTECH.Domain.Models.Dtos.PostPutDtos;

namespace QUALTECH.Domain.Abstractions.IServices
{
    public interface ITestCenterService
    {
        Task<IEnumerable<TestCenter>> GetAll();
        Task<bool> UpdateTestCenterAsync(UpdateTestCenterDto dto, string updatedBy);
        Task<bool> DeleteById(int testCenterId, string deletedBy);
        Task<APPResponse> CreateTestCenterAsync(CreateTestCenterDto dto, string createdBy);
    }
}


using AutoMapper;
using Microsoft.Extensions.Logging;
using QUALTECH.Domain.Abstractions;
using QUALTECH.Domain.Abstractions.IServices;
using QUALTECH.Domain.Models.Dtos.PostPutDtos;
using QUALTECH.Domain.Models.Dtos.Responses;
using QUALTECH.Shared;

namespace QUALTECH.Services.TestCenter
{
    public class TestCenterService : ITestCenterService
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly IMapper _mapper;
        private readonly ILogger<TestCenterService> _logger;
        public TestCenterService(IUnitOfWork unitOfWork, ILogger<TestCenterService> logger, IMapper mapper)
        {
            _logger = logger;
            _unitOfWork = unitOfWork;
            _mapper = mapper;
        }
        public async Task<bool> DeleteById(int id, string deletedBy)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(id.ToString()))
                    throw new ArgumentNullException(nameof(id), $"{AppMessages.INVALID} {AppMessages.ID} {AppMessages.PARAM} {AppMessages.PASSED}");

                if (string.IsNullOrWhiteSpace(deletedBy))
                    throw new ArgumentNullException(nameof(deletedBy), $"{AppMessages.INVALID} {AppMessages.DELETE}-by {AppMessages.PARAM} {AppMessages.PASSED}");

                var exTestC = await _unitOfWork.TestCenterRepository.GetByIdAsync(id);
                if (exTestC != null)
                {
                    exTestC.DeletedBy = deletedBy;
                    exTestC.DeletedAt = DateTime.UtcNow;

                    await _unitOfWork.TestCenterRepository.Update(exTestC);
                    var updateResult = await _unitOfWork.CompleteAsync();
                    if (updateResult > 0) return true;
                }
                return false;

            }
            catch (ArgumentNullException ex)
            {
                _logger.LogError(ex.Message, ex);
                return false;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message, ex);
                return false;
            }
        }

        public async Task<IEnumerable<Domain.Models.TestCenter>> GetAll()
        {
            var records = await _unitOfWork.TestCenterRepository.Get(null, null, "", null, null);
            var validRecords = records.Where(d => string.IsNullOrWhiteSpace(d.DeletedBy));
            return validRecords;
        }

        public async Task<APPResponse> CreateTestCenterAsync(CreateTestCenterDto dto, string createdBy)
        {
            if (dto == null)
                return new() { Success = false, ResultMessage = "Please supply a valid request body" };

            try
            {
                var newTestCenter = _mapper.Map<Domain.Models.TestCenter>(dto);
                newTestCenter.CreatedBy = createdBy;
                newTestCenter.CreatedAt = DateTime.UtcNow;

                await _unitOfWork.TestCenterRepository.AddAsync(newTestCenter);
                var result = await _unitOfWork.CompleteAsync();

                if (result > 0)
                {
                    return new APPResponse { Success = true, ResultMessage = "Test Center created successfully" };
                }
                else
                {
                    return new APPResponse { Success = false, ResultMessage = "Failed to create Test Center" };
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message, ex);
                return new APPResponse { Success = false, ResultMessage = "An error occurred while creating the Test Center" };
            }
        }

        public async Task<bool> UpdateTestCenterAsync(UpdateTestCenterDto dto, string updatedBy)
        {
            if (dto == null)
                throw new ArgumentNullException(nameof(dto), $"{AppMessages.INVALID} {AppMessages.PARAM} {AppMessages.PASSED}");

            if (string.IsNullOrWhiteSpace(updatedBy))
                throw new ArgumentNullException(nameof(updatedBy), $"{AppMessages.INVALID} {AppMessages.UPDATE}-by {AppMessages.PARAM} {AppMessages.PASSED}");

            try
            {
                var existingTestCenter = await _unitOfWork.TestCenterRepository.GetByIdAsync(dto.Id);
                if (existingTestCenter == null)
                    return false;

                _mapper.Map(dto, existingTestCenter);
                existingTestCenter.UpdatedBy = updatedBy;
                existingTestCenter.UpdatedAt = DateTime.UtcNow;

                await _unitOfWork.TestCenterRepository.Update(existingTestCenter);
                var updateResult = await _unitOfWork.CompleteAsync();

                return updateResult > 0;
            }
            catch (ArgumentNullException ex)
            {
                _logger.LogError(ex.Message, ex);
                return false;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message, ex);
                return false;
            }
        }
    }
}


using QUALTECH.Domain.Models;

namespace QUALTECH.Domain.Abstractions.IRepositories
{
    public interface ITestCenterRepository : IBaseRespository<TestCenter>
    {
    }
}

using QUALTECH.Domain.Abstractions.IRepositories;
using QUALTECH.Domain.Models;

namespace QUALTECH.Dal.Repositories
{
    public class TestCenterRepository : BaseRespository<TestCenter>, ITestCenterRepository
    {
        public TestCenterRepository(QAULTECHDBContext dbContext) : base(dbContext)
        {
        }
    }
}

using System.ComponentModel.DataAnnotations.Schema;

namespace QUALTECH.Domain.Models
{
    public class TestCenter
    {
        public int TestCenterId { get; set; }
        public string Name { get; set;}
        public DateTime CreatedAt { get; set; }
        public required string CreatedBy { get; set; }
        public DateTime? UpdatedAt { get; set; }
        public string? UpdatedBy { get; set; }
        public DateTime? DeletedAt { get; set; }
        public string? DeletedBy { get; set; }
        public int DivisionId { get; set; }
        public Division Division { get; set; }
    }
}


using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using QUALTECH.Domain.Models;

namespace QUALTECH.Dal.Configurations
{
    public class TestCenterConfiguration
    {
        public TestCenterConfiguration(EntityTypeBuilder<TestCenter> builder)
        {
            builder.HasKey(tc => tc.TestCenterId);
            
            builder.Property(tc => tc.Name)
                   .IsRequired()
                   .HasMaxLength(100);

            builder.Property(tc => tc.CreatedAt)
                   .IsRequired();

            builder.Property(tc => tc.CreatedBy)
                   .IsRequired()
                   .HasMaxLength(50);

            builder.Property(tc => tc.UpdatedAt)
                   .IsRequired(false);

            builder.Property(tc => tc.UpdatedBy)
                   .HasMaxLength(50);

            builder.Property(tc => tc.DeletedAt)
                   .IsRequired(false);

            builder.Property(tc => tc.DeletedBy)
                   .HasMaxLength(50);

            builder.HasOne(tc => tc.Division)
                   .WithMany(d => d.TestCenters)
                   .HasForeignKey(tc => tc.DivisionId)
                   .OnDelete(DeleteBehavior.ClientSetNull);

            builder.ToTable("TestCenters");
        }
    }
}

namespace QUALTECH.Domain.Models.Dtos.PostPutDtos
{
    public class CreateTestCenterDto
    {
        public string Name { get; set; }
        public int DivisionId { get; set; }
    }
}

namespace QUALTECH.Domain.Models.Dtos.PostPutDtos
{
    public class UpdateTestCenterDto
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int DivisionId { get; set; }
    }
}



 entity.HasKey(d => d.DivisionId);
                entity.HasMany(d => d.TestCenters)
                      .WithOne(tc => tc.Division)
                      .HasForeignKey(tc => tc.DivisionId);


 new TestCenterConfiguration(modelBuilder.Entity<TestCenter>());
Leave a Comment