81 lines
2.8 KiB
C#
81 lines
2.8 KiB
C#
using Indotalent.ConfigBackEnd.Exceptions;
|
|
using Indotalent.ConfigBackEnd.Extensions;
|
|
using Indotalent.Infrastructure.Database;
|
|
using MediatR;
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
namespace Indotalent.Features.Leave.LeaveBalance.Cqrs;
|
|
|
|
public class CreateLeaveBalanceRequest
|
|
{
|
|
public string EmployeeId { get; set; } = string.Empty;
|
|
public string LeaveCategoryId { get; set; } = string.Empty;
|
|
public int Entitlement { get; set; }
|
|
public int Used { get; set; }
|
|
public int Pending { get; set; }
|
|
public int Remaining { get; set; }
|
|
public int Year { get; set; }
|
|
public DateTime ValidFrom { get; set; }
|
|
public DateTime ValidTo { get; set; }
|
|
public int CarryForward { get; set; }
|
|
}
|
|
|
|
public class CreateLeaveBalanceResponse
|
|
{
|
|
public string? Id { get; set; }
|
|
public string? AutoNumber { get; set; }
|
|
}
|
|
|
|
public record CreateLeaveBalanceCommand(CreateLeaveBalanceRequest Data) : IRequest<CreateLeaveBalanceResponse>;
|
|
|
|
public class CreateLeaveBalanceHandler : IRequestHandler<CreateLeaveBalanceCommand, CreateLeaveBalanceResponse>
|
|
{
|
|
private readonly AppDbContext _context;
|
|
|
|
public CreateLeaveBalanceHandler(AppDbContext context) => _context = context;
|
|
|
|
public async Task<CreateLeaveBalanceResponse> Handle(CreateLeaveBalanceCommand request, CancellationToken cancellationToken)
|
|
{
|
|
var isExists = await _context.LeaveBalance
|
|
.AnyAsync(x => x.EmployeeId == request.Data.EmployeeId &&
|
|
x.LeaveCategoryId == request.Data.LeaveCategoryId &&
|
|
x.Year == request.Data.Year, cancellationToken);
|
|
|
|
if (isExists)
|
|
{
|
|
throw new AlreadyExistsException("Leave Balance", $"{request.Data.EmployeeId} for Year {request.Data.Year}");
|
|
}
|
|
|
|
var entityName = nameof(Data.Entities.LeaveBalance);
|
|
|
|
var autoNo = await _context.GenerateAutoNumberAsync(
|
|
entityName: entityName,
|
|
prefixTemplate: $"{entityName.ToShortNameConsonant(3)}/{{Year}}/",
|
|
ct: cancellationToken
|
|
);
|
|
|
|
var entity = new Data.Entities.LeaveBalance
|
|
{
|
|
AutoNumber = autoNo,
|
|
EmployeeId = request.Data.EmployeeId,
|
|
LeaveCategoryId = request.Data.LeaveCategoryId,
|
|
Entitlement = request.Data.Entitlement,
|
|
Used = request.Data.Used,
|
|
Pending = request.Data.Pending,
|
|
Remaining = request.Data.Remaining,
|
|
Year = request.Data.Year,
|
|
ValidFrom = request.Data.ValidFrom,
|
|
ValidTo = request.Data.ValidTo,
|
|
CarryForward = request.Data.CarryForward
|
|
};
|
|
|
|
_context.LeaveBalance.Add(entity);
|
|
await _context.SaveChangesAsync(cancellationToken);
|
|
|
|
return new CreateLeaveBalanceResponse
|
|
{
|
|
Id = entity.Id,
|
|
AutoNumber = entity.AutoNumber
|
|
};
|
|
}
|
|
} |