70 lines
2.3 KiB
C#
70 lines
2.3 KiB
C#
using Indotalent.ConfigBackEnd.Exceptions;
|
|
using Indotalent.Infrastructure.Database;
|
|
using MediatR;
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
namespace Indotalent.Features.Organization.Branch.Cqrs;
|
|
|
|
public class UpdateBranchRequest : CreateBranchRequest
|
|
{
|
|
public string? Id { get; set; }
|
|
public DateTimeOffset? CreatedAt { get; set; }
|
|
public string? CreatedBy { get; set; }
|
|
public DateTimeOffset? UpdatedAt { get; set; }
|
|
public string? UpdatedBy { get; set; }
|
|
}
|
|
|
|
public class UpdateBranchResponse
|
|
{
|
|
public string? Id { get; set; }
|
|
public bool Success { get; set; }
|
|
}
|
|
|
|
public record UpdateBranchCommand(UpdateBranchRequest Data) : IRequest<UpdateBranchResponse>;
|
|
|
|
public class UpdateBranchHandler : IRequestHandler<UpdateBranchCommand, UpdateBranchResponse>
|
|
{
|
|
private readonly AppDbContext _context;
|
|
|
|
public UpdateBranchHandler(AppDbContext context) => _context = context;
|
|
|
|
public async Task<UpdateBranchResponse> Handle(UpdateBranchCommand request, CancellationToken cancellationToken)
|
|
{
|
|
var isExists = await _context.Branch
|
|
.AnyAsync(x => x.Code == request.Data.Code && x.Id != request.Data.Id, cancellationToken);
|
|
|
|
if (isExists)
|
|
{
|
|
throw new AlreadyExistsException("Branch", request.Data.Code ?? string.Empty);
|
|
}
|
|
|
|
var entity = await _context.Branch
|
|
.FirstOrDefaultAsync(x => x.Id == request.Data.Id, cancellationToken);
|
|
|
|
if (entity == null)
|
|
{
|
|
return new UpdateBranchResponse { Id = request.Data.Id, Success = false };
|
|
}
|
|
|
|
entity.Code = request.Data.Code;
|
|
entity.Name = request.Data.Name;
|
|
entity.Description = request.Data.Description;
|
|
entity.StreetAddress = request.Data.StreetAddress;
|
|
entity.City = request.Data.City;
|
|
entity.StateProvince = request.Data.StateProvince;
|
|
entity.ZipCode = request.Data.ZipCode;
|
|
entity.Phone = request.Data.Phone;
|
|
entity.Email = request.Data.Email;
|
|
entity.OtherInformation1 = request.Data.OtherInformation1;
|
|
entity.OtherInformation2 = request.Data.OtherInformation2;
|
|
entity.OtherInformation3 = request.Data.OtherInformation3;
|
|
|
|
await _context.SaveChangesAsync(cancellationToken);
|
|
|
|
return new UpdateBranchResponse
|
|
{
|
|
Id = entity.Id,
|
|
Success = true
|
|
};
|
|
}
|
|
} |