| | | 1 | | using System.Globalization; |
| | | 2 | | using LifeChart.Application.DTOs; |
| | | 3 | | using LifeChart.Domain.Medications; |
| | | 4 | | |
| | | 5 | | namespace LifeChart.Application.UseCases.Medications; |
| | | 6 | | |
| | | 7 | | public class SaveMedicationUseCase |
| | | 8 | | { |
| | | 9 | | private readonly IMedicationRepository _repository; |
| | | 10 | | |
| | 4 | 11 | | public SaveMedicationUseCase(IMedicationRepository repository) |
| | 4 | 12 | | => _repository = repository; |
| | | 13 | | |
| | | 14 | | public async Task ExecuteAsync(SaveMedicationDto dto) |
| | | 15 | | { |
| | 4 | 16 | | var intakeTimes = dto.IntakeTimes |
| | 5 | 17 | | .Select(i => new IntakeTime(TimeOnly.Parse(i.Time, CultureInfo.CurrentCulture), i.DoseCount)) |
| | 4 | 18 | | .ToList(); |
| | | 19 | | |
| | 4 | 20 | | if (dto.Id == 0) |
| | | 21 | | { |
| | 2 | 22 | | var medication = new Medication( |
| | 2 | 23 | | dto.Name, |
| | 2 | 24 | | dto.Dosage, |
| | 2 | 25 | | dto.MinStock, |
| | 2 | 26 | | dto.CurrentStock, |
| | 2 | 27 | | intakeTimes); |
| | | 28 | | |
| | 2 | 29 | | await _repository.SaveAsync(medication); |
| | | 30 | | } |
| | | 31 | | else |
| | | 32 | | { |
| | 2 | 33 | | var existing = await _repository.GetByIdAsync(dto.Id) |
| | 2 | 34 | | ?? throw new InvalidOperationException( |
| | 2 | 35 | | $"Medikament mit Id {dto.Id} nicht gefunden."); |
| | | 36 | | |
| | 1 | 37 | | existing.Update( |
| | 1 | 38 | | dto.Name, |
| | 1 | 39 | | dto.Dosage, |
| | 1 | 40 | | dto.MinStock, |
| | 1 | 41 | | dto.CurrentStock, |
| | 1 | 42 | | intakeTimes); |
| | | 43 | | |
| | 1 | 44 | | await _repository.SaveAsync(existing); |
| | | 45 | | } |
| | 3 | 46 | | } |
| | | 47 | | } |