public async Task PayFee(Guid userId, Guid feeId, DateTime paymentDate) { var fee = await _feeRepository.GetById(feeId); if (fee == null) { throw new KeyNotFoundException($"Fee with id: {feeId} not found."); } if (fee.PaymentDate != null) { throw new InvalidOperationException($"Fee with id: {feeId} has already been paid."); } var feeList = (await _feeRepository.GetAll()).Where(x => x.OwnFeesId == fee.OwnFeesId).OrderBy(x => x.ExpirationDate); var previousFee = feeList.FirstOrDefault(x => x.ExpirationDate < fee.ExpirationDate); if (previousFee != null && previousFee.PaymentDate == null) { throw new InvalidOperationException($"The previous fee must be paid."); } fee.PaymentDate = paymentDate; await _feeRepository.Update(fee); await _feeRepository.CommitAsync(); }