| | | 1 | | using MechanicsSoftware.Application.Abstractions; |
| | | 2 | | using MechanicsSoftware.Application.UseCases.Customers.Commands; |
| | | 3 | | using MechanicsSoftware.Domain.Entities; |
| | | 4 | | using MechanicsSoftware.Domain.Exceptions; |
| | | 5 | | using MechanicsSoftware.Domain.ValueObjects; |
| | | 6 | | using Microsoft.EntityFrameworkCore; |
| | | 7 | | |
| | | 8 | | namespace MechanicsSoftware.Application.UseCases.Customers.Handlers; |
| | | 9 | | |
| | 4 | 10 | | public sealed class CreateCustomerHandler(IAppDbContext db) |
| | | 11 | | { |
| | | 12 | | public async Task<CustomerResponse> ExecuteAsync(CreateCustomerCommand command, CancellationToken cancellationToken |
| | 4 | 13 | | { |
| | 4 | 14 | | var documentVo = new TaxId(command.DocumentValue, command.PersonType); |
| | | 15 | | |
| | 4 | 16 | | var customerExisting = await db.Customers |
| | 4 | 17 | | .AnyAsync(c => c.Document == documentVo, cancellationToken); |
| | | 18 | | |
| | 4 | 19 | | if (customerExisting) |
| | 2 | 20 | | throw new DomainException($"A customer with document '{command.DocumentValue}' already exists."); |
| | | 21 | | |
| | 2 | 22 | | var customer = Customer.Create( |
| | 2 | 23 | | id: Guid.NewGuid(), |
| | 2 | 24 | | personType: command.PersonType, |
| | 2 | 25 | | taxId: command.DocumentValue, |
| | 2 | 26 | | name: command.Name, |
| | 2 | 27 | | email: command.Email, |
| | 2 | 28 | | phone: command.Phone); |
| | | 29 | | |
| | 2 | 30 | | db.Customers.Add(customer); |
| | 2 | 31 | | await db.SaveChangesAsync(cancellationToken); |
| | | 32 | | |
| | 2 | 33 | | return CustomerResponse.From(customer); |
| | 2 | 34 | | } |
| | | 35 | | } |