73 lines
2.5 KiB
C#
73 lines
2.5 KiB
C#
using Indotalent.ConfigBackEnd.Exceptions;
|
|
using Indotalent.ConfigBackEnd.Extensions;
|
|
using Indotalent.Infrastructure.Database;
|
|
using MediatR;
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
namespace Indotalent.Features.Organization.Department.Cqrs;
|
|
|
|
public class CreateDepartmentRequest
|
|
{
|
|
public string? CostCenter { get; set; }
|
|
public string? Name { get; set; }
|
|
public string? Description { get; set; }
|
|
public string HeadOfDeptartment { get; set; } = string.Empty;
|
|
public string OtherInformation1 { get; set; } = string.Empty;
|
|
public string OtherInformation2 { get; set; } = string.Empty;
|
|
public string OtherInformation3 { get; set; } = string.Empty;
|
|
}
|
|
|
|
public class CreateDepartmentResponse
|
|
{
|
|
public string? Id { get; set; }
|
|
public string? CostCenter { get; set; }
|
|
}
|
|
|
|
public record CreateDepartmentCommand(CreateDepartmentRequest Data) : IRequest<CreateDepartmentResponse>;
|
|
|
|
public class CreateDepartmentHandler : IRequestHandler<CreateDepartmentCommand, CreateDepartmentResponse>
|
|
{
|
|
private readonly AppDbContext _context;
|
|
|
|
public CreateDepartmentHandler(AppDbContext context) => _context = context;
|
|
|
|
public async Task<CreateDepartmentResponse> Handle(CreateDepartmentCommand request, CancellationToken cancellationToken)
|
|
{
|
|
var isExists = await _context.Department
|
|
.AnyAsync(x => x.CostCenter == request.Data.CostCenter, cancellationToken);
|
|
|
|
if (isExists)
|
|
{
|
|
throw new AlreadyExistsException("Department", request.Data.CostCenter ?? string.Empty);
|
|
}
|
|
|
|
var entityName = nameof(Data.Entities.Department);
|
|
|
|
var autoNo = await _context.GenerateAutoNumberAsync(
|
|
entityName: entityName,
|
|
prefixTemplate: $"{entityName.ToShortNameConsonant(3)}/{{Year}}/",
|
|
ct: cancellationToken
|
|
);
|
|
|
|
var entity = new Data.Entities.Department
|
|
{
|
|
AutoNumber = autoNo,
|
|
CostCenter = request.Data.CostCenter,
|
|
Name = request.Data.Name,
|
|
Description = request.Data.Description,
|
|
HeadOfDeptartment = request.Data.HeadOfDeptartment,
|
|
OtherInformation1 = request.Data.OtherInformation1,
|
|
OtherInformation2 = request.Data.OtherInformation2,
|
|
OtherInformation3 = request.Data.OtherInformation3
|
|
};
|
|
|
|
_context.Department.Add(entity);
|
|
await _context.SaveChangesAsync(cancellationToken);
|
|
|
|
return new CreateDepartmentResponse
|
|
{
|
|
Id = entity.Id,
|
|
CostCenter = entity.CostCenter
|
|
};
|
|
}
|
|
} |