| | | 1 | | using MechanicsSoftware.Application.Abstractions; |
| | | 2 | | using MechanicsSoftware.Application.UseCases.Inventory.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.Inventory.Handlers; |
| | | 9 | | |
| | 6 | 10 | | public sealed class CreatePartHandler(IAppDbContext context) |
| | | 11 | | { |
| | | 12 | | public async Task<PartOutput> ExecuteAsync(CreatePartCommand command, CancellationToken cancellationToken = default) |
| | 6 | 13 | | { |
| | 6 | 14 | | var existing = await context.Parts |
| | 6 | 15 | | .FirstOrDefaultAsync(p => p.Code == command.Code, cancellationToken); |
| | | 16 | | |
| | 6 | 17 | | if (existing is not null) |
| | 2 | 18 | | throw new DomainException($"A part with code '{command.Code}' already exists."); |
| | | 19 | | |
| | 4 | 20 | | var part = Part.Create( |
| | 4 | 21 | | Guid.NewGuid(), |
| | 4 | 22 | | command.Code, |
| | 4 | 23 | | command.Name, |
| | 4 | 24 | | command.Description, |
| | 4 | 25 | | new Money(command.UnitPriceInCents), |
| | 4 | 26 | | command.InitialStock |
| | 4 | 27 | | ); |
| | | 28 | | |
| | 4 | 29 | | context.Parts.Add(part); |
| | 4 | 30 | | await context.SaveChangesAsync(cancellationToken); |
| | 4 | 31 | | return PartOutput.From(part); |
| | 4 | 32 | | } |
| | | 33 | | } |