49 lines
1.9 KiB
C#
49 lines
1.9 KiB
C#
using LiteCharms.Infrastructure.Database;
|
|
|
|
namespace LiteCharms.Features.Customers.Commands.Handlers;
|
|
|
|
public class CreateCustomerCommandHandler(IDbContextFactory<ShopDbContext> contextFactory) : IRequestHandler<CreateCustomerCommand, Result<Guid>>
|
|
{
|
|
public async ValueTask<Result<Guid>> Handle(CreateCustomerCommand request, CancellationToken cancellationToken)
|
|
{
|
|
try
|
|
{
|
|
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
|
|
|
var customerEmail = request.Email.ToLower().Trim();
|
|
|
|
if (await context.Customers.AnyAsync(c => c.Email == customerEmail, cancellationToken))
|
|
return Result.Fail<Guid>(new Error($"A customer with the email {customerEmail} already exists"));
|
|
|
|
var newCustomer = context.Customers.Add(new Entities.Customer
|
|
{
|
|
Company = request.Company,
|
|
Name = request.Name,
|
|
LastName = request.LastName,
|
|
Tax = request.Tax,
|
|
Email = customerEmail,
|
|
Discord = request.Discord,
|
|
Slack = request.Slack,
|
|
LinkedIn = request.LinkedIn,
|
|
Whatsapp = request.Whatsapp,
|
|
Website = request.Website,
|
|
Phone = request.Phone,
|
|
Address = request.Address,
|
|
City = request.City,
|
|
Region = request.Region,
|
|
Country = request.Country,
|
|
PostalCode = request.PostalCode,
|
|
Active = true,
|
|
});
|
|
|
|
return await context.SaveChangesAsync(cancellationToken) > 0
|
|
? Result.Ok(newCustomer.Entity.Id)
|
|
: Result.Fail<Guid>(new Error($"Failed to create customer {customerEmail}"));
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
return Result.Fail<Guid>(new Error(ex.Message).CausedBy(ex));
|
|
}
|
|
}
|
|
}
|