diff --git a/Hotel.Domain/Handlers/AdminHandlers/HandleCreateAdmin.cs b/Hotel.Domain/Handlers/AdminHandlers/HandleCreateAdmin.cs index f3304a5..88a1fe3 100644 --- a/Hotel.Domain/Handlers/AdminHandlers/HandleCreateAdmin.cs +++ b/Hotel.Domain/Handlers/AdminHandlers/HandleCreateAdmin.cs @@ -17,12 +17,14 @@ public partial class AdminHandler : GenericUserHandler, private readonly IAdminRepository _repository; private readonly IPermissionRepository _permissionRepository; private readonly IEmailService _emailService; + private readonly ILogger _logger; - public AdminHandler(IAdminRepository repository, IPermissionRepository permissionRepository, IEmailService emailService) : base(repository, emailService) + public AdminHandler(IAdminRepository repository, IPermissionRepository permissionRepository, IEmailService emailService, ILogger logger) : base(repository, emailService) { _repository = repository; _permissionRepository = permissionRepository; _emailService = emailService; + _logger = logger; } public async Task HandleCreateAsync(CreateUser model, string? code) @@ -60,10 +62,16 @@ public async Task HandleCreateAsync(CreateUser model, string? code) { if (innerException.Contains("Email")) + { + _logger.LogError("Erro ao cadastradar administrador pois o email já está cadastrado"); throw new ArgumentException("Esse email já está cadastrado."); + } if (innerException.Contains("Phone")) + { + _logger.LogError("Erro ao cadastradar administrador pois o telefone já está cadastrado"); throw new ArgumentException("Esse telefone já está cadastrado."); + } } } diff --git a/Hotel.Domain/Handlers/AdminHandlers/HandleUpdateAdmin.cs b/Hotel.Domain/Handlers/AdminHandlers/HandleUpdateAdmin.cs index 0147d51..246d94f 100644 --- a/Hotel.Domain/Handlers/AdminHandlers/HandleUpdateAdmin.cs +++ b/Hotel.Domain/Handlers/AdminHandlers/HandleUpdateAdmin.cs @@ -32,10 +32,16 @@ public async Task HandleUpdateAsync(UpdateUser model, Guid adminId) { if (innerException.Contains("Email")) + { + _logger.LogError("Erro ao cadastradar administrador pois o email já está cadastrado"); throw new ArgumentException("Esse email já está cadastrado."); + } if (innerException.Contains("Phone")) + { + _logger.LogError("Erro ao cadastradar administrador pois o telefone já está cadastrado"); throw new ArgumentException("Esse telefone já está cadastrado."); + } } } diff --git a/Hotel.Domain/Handlers/CustomerHandlers/HandleCreateCustomer.cs b/Hotel.Domain/Handlers/CustomerHandlers/HandleCreateCustomer.cs index c6d52fd..6529bc5 100644 --- a/Hotel.Domain/Handlers/CustomerHandlers/HandleCreateCustomer.cs +++ b/Hotel.Domain/Handlers/CustomerHandlers/HandleCreateCustomer.cs @@ -16,12 +16,14 @@ public partial class CustomerHandler : GenericUserHandler _logger; - public CustomerHandler(ICustomerRepository repository, IEmailService emailService, IStripeService stripeService) : base(repository, emailService) + public CustomerHandler(ICustomerRepository repository, IEmailService emailService, IStripeService stripeService, ILogger logger) : base(repository, emailService) { _repository = repository; _emailService = emailService; _stripeService = stripeService; + _logger = logger; } public async Task HandleCreateAsync(CreateUser model, string? code) @@ -57,14 +59,19 @@ public async Task HandleCreateAsync(CreateUser model, string? code) if (innerException != null) { - if (innerException.Contains("Email")) + { + _logger.LogError("Erro ao cadastradar cliente pois o email já está cadastrado"); throw new ArgumentException("Esse email já está cadastrado."); + } if (innerException.Contains("Phone")) + { + _logger.LogError("Erro ao cadastradar cliente pois o telefone já está cadastrado"); throw new ArgumentException("Esse telefone já está cadastrado."); + } } - throw new DbUpdateException("Ocorreu um erro ao criar o cliente no banco de dados"); + throw; } try @@ -76,6 +83,7 @@ public async Task HandleCreateAsync(CreateUser model, string? code) } catch (StripeException) { + _logger.LogError("Erro ao criar cliente no stripe"); throw new StripeException("Ocorreu um erro ao criar o cliente no Stripe"); } diff --git a/Hotel.Domain/Handlers/CustomerHandlers/HandleDeleteCustomer.cs b/Hotel.Domain/Handlers/CustomerHandlers/HandleDeleteCustomer.cs index 7f49b6e..eac0510 100644 --- a/Hotel.Domain/Handlers/CustomerHandlers/HandleDeleteCustomer.cs +++ b/Hotel.Domain/Handlers/CustomerHandlers/HandleDeleteCustomer.cs @@ -23,6 +23,7 @@ public async Task HandleDeleteAsync(Guid id) } catch (DbUpdateException) { + _logger.LogError("Erro ao deletar cliente do banco de dados"); throw new DbUpdateException("Ocorreu um erro ao deletar o usuário do banco de dados"); } @@ -32,6 +33,7 @@ public async Task HandleDeleteAsync(Guid id) } catch (StripeException) { + _logger.LogError("Erro ao deletar cliente do stripe"); throw new StripeException("Ocorreu um erro ao deletar o cliente no Stripe"); } diff --git a/Hotel.Domain/Handlers/CustomerHandlers/HandleUpdateCustomer.cs b/Hotel.Domain/Handlers/CustomerHandlers/HandleUpdateCustomer.cs index e214fc6..1b89b41 100644 --- a/Hotel.Domain/Handlers/CustomerHandlers/HandleUpdateCustomer.cs +++ b/Hotel.Domain/Handlers/CustomerHandlers/HandleUpdateCustomer.cs @@ -35,12 +35,17 @@ public async Task HandleUpdateAsync(UpdateUser model, Guid id) if (innerException != null) { - if (innerException.Contains("Email")) - return new Response("Esse email já está cadastrado."); + { + _logger.LogError("Erro ao cadastradar cliente pois o email já está cadastrado"); + throw new ArgumentException("Esse email já está cadastrado."); + } if (innerException.Contains("Phone")) - return new Response("Esse telefone já está cadastrado."); + { + _logger.LogError("Erro ao cadastradar cliente pois o telefone já está cadastrado"); + throw new ArgumentException("Esse telefone já está cadastrado."); + } } throw; } @@ -51,6 +56,7 @@ public async Task HandleUpdateAsync(UpdateUser model, Guid id) } catch (StripeException) { + _logger.LogError("Erro ao atualizar cliente no stripe"); throw new StripeException("Ocorreu um erro ao atualizar o usuário no Stripe"); } diff --git a/Hotel.Domain/Handlers/CustomerHandlers/HandleUpdateCustomerAddress.cs b/Hotel.Domain/Handlers/CustomerHandlers/HandleUpdateCustomerAddress.cs index 0448c04..9795da0 100644 --- a/Hotel.Domain/Handlers/CustomerHandlers/HandleUpdateCustomerAddress.cs +++ b/Hotel.Domain/Handlers/CustomerHandlers/HandleUpdateCustomerAddress.cs @@ -25,6 +25,7 @@ public partial class CustomerHandler } catch (StripeException) { + _logger.LogError("Erro ao atualizar cliente no stripe"); throw new StripeException("Ocorreu um erro ao atualizar o cliente no Stripe"); } diff --git a/Hotel.Domain/Handlers/CustomerHandlers/HandleUpdateCustomerEmail.cs b/Hotel.Domain/Handlers/CustomerHandlers/HandleUpdateCustomerEmail.cs index 83a5da5..5b7ae87 100644 --- a/Hotel.Domain/Handlers/CustomerHandlers/HandleUpdateCustomerEmail.cs +++ b/Hotel.Domain/Handlers/CustomerHandlers/HandleUpdateCustomerEmail.cs @@ -28,6 +28,7 @@ public partial class CustomerHandler } catch (StripeException) { + _logger.LogError("Erro ao atualizar cliente no stripe"); throw new StripeException("Ocorreu um erro ao atualizar o cliente no Stripe"); } diff --git a/Hotel.Domain/Handlers/CustomerHandlers/HandleUpdateCustomerName.cs b/Hotel.Domain/Handlers/CustomerHandlers/HandleUpdateCustomerName.cs index befeb91..1ac406b 100644 --- a/Hotel.Domain/Handlers/CustomerHandlers/HandleUpdateCustomerName.cs +++ b/Hotel.Domain/Handlers/CustomerHandlers/HandleUpdateCustomerName.cs @@ -26,6 +26,7 @@ public partial class CustomerHandler } catch (StripeException) { + _logger.LogError("Erro ao atualizar cliente no stripe"); throw new StripeException("Ocorreu um erro ao atualizar o cliente no Stripe"); } diff --git a/Hotel.Domain/Handlers/CustomerHandlers/HandleUpdateCustomerPhone.cs b/Hotel.Domain/Handlers/CustomerHandlers/HandleUpdateCustomerPhone.cs index b23f1b8..1712aaf 100644 --- a/Hotel.Domain/Handlers/CustomerHandlers/HandleUpdateCustomerPhone.cs +++ b/Hotel.Domain/Handlers/CustomerHandlers/HandleUpdateCustomerPhone.cs @@ -27,6 +27,7 @@ public partial class CustomerHandler } catch (StripeException) { + _logger.LogError("Erro ao atualizar cliente no stripe"); throw new StripeException("Ocorreu um erro ao atualizar o cliente no Stripe"); } diff --git a/Hotel.Domain/Handlers/EmployeeHandlers/HandleCreateEmployee.cs b/Hotel.Domain/Handlers/EmployeeHandlers/HandleCreateEmployee.cs index 1b985a2..3af9fde 100644 --- a/Hotel.Domain/Handlers/EmployeeHandlers/HandleCreateEmployee.cs +++ b/Hotel.Domain/Handlers/EmployeeHandlers/HandleCreateEmployee.cs @@ -18,13 +18,15 @@ public partial class EmployeeHandler : GenericUserHandler _logger; - public EmployeeHandler(IEmployeeRepository repository, IResponsibilityRepository responsibilityRepository, IPermissionRepository permissionRepository, IEmailService emailService) : base(repository, emailService) + public EmployeeHandler(IEmployeeRepository repository, IResponsibilityRepository responsibilityRepository, IPermissionRepository permissionRepository, IEmailService emailService, ILogger logger) : base(repository, emailService) { _repository = repository; _responsibilityRepository = responsibilityRepository; _permissionRepository = permissionRepository; _emailService = emailService; + _logger = logger; } public async Task HandleCreateAsync(CreateEmployee model, string? code) @@ -58,14 +60,19 @@ public async Task HandleCreateAsync(CreateEmployee model, string? code if (innerException != null) { if (innerException.Contains("Email")) + { + _logger.LogError("Erro ao cadastradar administrador pois o email já está cadastrado"); throw new ArgumentException("Esse email já está cadastrado."); + } if (innerException.Contains("Phone")) + { + _logger.LogError("Erro ao cadastradar administrador pois o telefone já está cadastrado"); throw new ArgumentException("Esse telefone já está cadastrado."); + } } } - return new Response("Funcionário cadastrado com sucesso!", new { employee.Id }); } } \ No newline at end of file diff --git a/Hotel.Domain/Handlers/EmployeeHandlers/HandleUpdateEmployee.cs b/Hotel.Domain/Handlers/EmployeeHandlers/HandleUpdateEmployee.cs index 2e58789..653d070 100644 --- a/Hotel.Domain/Handlers/EmployeeHandlers/HandleUpdateEmployee.cs +++ b/Hotel.Domain/Handlers/EmployeeHandlers/HandleUpdateEmployee.cs @@ -11,7 +11,7 @@ public partial class EmployeeHandler public async Task HandleUpdateAsync(UpdateEmployee model, Guid id) { var employee = await _repository.GetEntityByIdAsync(id) - ?? throw new NotFoundException("Funcionário não encontrado."); + ?? throw new NotFoundException("Funcionário não encontrado."); employee.ChangeName(new Name(model.FirstName, model.LastName)); employee.ChangePhone(new Phone(model.Phone)); @@ -31,12 +31,17 @@ public async Task HandleUpdateAsync(UpdateEmployee model, Guid id) if (innerException != null) { - if (innerException.Contains("Email")) - return new Response("Esse email já está cadastrado."); + { + _logger.LogError("Erro ao cadastradar administrador pois o email já está cadastrado"); + throw new ArgumentException("Esse email já está cadastrado."); + } if (innerException.Contains("Phone")) - return new Response("Esse telefone já está cadastrado."); + { + _logger.LogError("Erro ao cadastradar administrador pois o telefone já está cadastrado"); + throw new ArgumentException("Esse telefone já está cadastrado."); + } } } diff --git a/Hotel.Domain/Handlers/FeedbackHandlers/Deslikes/HandleAddFeedbackDislike.cs b/Hotel.Domain/Handlers/FeedbackHandlers/Deslikes/HandleAddFeedbackDislike.cs index 8b8bddd..fe99acc 100644 --- a/Hotel.Domain/Handlers/FeedbackHandlers/Deslikes/HandleAddFeedbackDislike.cs +++ b/Hotel.Domain/Handlers/FeedbackHandlers/Deslikes/HandleAddFeedbackDislike.cs @@ -25,7 +25,14 @@ public async Task HandleAddDeslikeAsync(Guid feedbackId, Guid customer await _dislikeRepository.CreateDeslike(dislike); - await _feedbackRepository.SaveChangesAsync(); + try + { + await _feedbackRepository.SaveChangesAsync(); + } + catch (Exception ex) + { + _logger.LogError($"Ocorreu um erro ao criar um dislike: {ex.Message}"); + } return new Response("Deslike adicionado com sucesso!"); } diff --git a/Hotel.Domain/Handlers/FeedbackHandlers/Deslikes/HandleRemoveFeedbackDislike.cs b/Hotel.Domain/Handlers/FeedbackHandlers/Deslikes/HandleRemoveFeedbackDislike.cs index d16c5bc..62062bd 100644 --- a/Hotel.Domain/Handlers/FeedbackHandlers/Deslikes/HandleRemoveFeedbackDislike.cs +++ b/Hotel.Domain/Handlers/FeedbackHandlers/Deslikes/HandleRemoveFeedbackDislike.cs @@ -13,7 +13,14 @@ public async Task HandleRemoveDeslikeAsync(Guid feedbackId, Guid custo _dislikeRepository.RemoveDeslike(dislike); - await _feedbackRepository.SaveChangesAsync(); + try + { + await _feedbackRepository.SaveChangesAsync(); + } + catch (Exception ex) + { + _logger.LogError($"Ocorreu um erro ao deletar um dislike: {ex.Message}"); + } return new Response("Deslike removido com sucesso!"); } diff --git a/Hotel.Domain/Handlers/FeedbackHandlers/HandleCreateFeedback.cs b/Hotel.Domain/Handlers/FeedbackHandlers/HandleCreateFeedback.cs index 3721846..50e7dbd 100644 --- a/Hotel.Domain/Handlers/FeedbackHandlers/HandleCreateFeedback.cs +++ b/Hotel.Domain/Handlers/FeedbackHandlers/HandleCreateFeedback.cs @@ -14,8 +14,10 @@ public partial class FeedbackHandler : IHandler private readonly IRoomRepository _roomRepository; private readonly ILikeRepository _likeRepository; private readonly IDeslikeRepository _dislikeRepository; + private readonly ILogger _logger; - public FeedbackHandler(IFeedbackRepository feedbackRepository, ICustomerRepository customerRepository, IReservationRepository reservationRepository, IRoomRepository roomRepository, ILikeRepository likeRepository, IDeslikeRepository dislikeRepository) + + public FeedbackHandler(IFeedbackRepository feedbackRepository, ICustomerRepository customerRepository, IReservationRepository reservationRepository, IRoomRepository roomRepository, ILikeRepository likeRepository, IDeslikeRepository dislikeRepository, ILogger logger) { _feedbackRepository = feedbackRepository; _customerRepository = customerRepository; @@ -23,6 +25,7 @@ public FeedbackHandler(IFeedbackRepository feedbackRepository, ICustomerReposito _roomRepository = roomRepository; _likeRepository = likeRepository; _dislikeRepository = dislikeRepository; + _logger = logger; } public async Task HandleCreateAsync(CreateFeedback model, Guid userId) @@ -43,8 +46,16 @@ public async Task HandleCreateAsync(CreateFeedback model, Guid userId) model.Comment, model.Rate, customer.Id, model.ReservationId, room.Id, reservation //vai validar se o cliente que está criando o feedback está na reserva ); - await _feedbackRepository.CreateAsync(feedback); - await _feedbackRepository.SaveChangesAsync(); + try + { + await _feedbackRepository.CreateAsync(feedback); + await _feedbackRepository.SaveChangesAsync(); + } + catch (Exception ex) + { + _logger.LogError($"Ocorreu um erro ao criar o feedback no banco de dados: {ex.Message}"); + } + return new Response("Feedback criado com sucesso!", new { feedback.Id }); } diff --git a/Hotel.Domain/Handlers/FeedbackHandlers/HandleDeleteFeedback.cs b/Hotel.Domain/Handlers/FeedbackHandlers/HandleDeleteFeedback.cs index c7ba11d..a706634 100644 --- a/Hotel.Domain/Handlers/FeedbackHandlers/HandleDeleteFeedback.cs +++ b/Hotel.Domain/Handlers/FeedbackHandlers/HandleDeleteFeedback.cs @@ -13,8 +13,16 @@ public async Task HandleDeleteAsync(Guid id, Guid customerId) if (feedback.CustomerId != customerId) throw new ArgumentException("Apenas o autor do feedback pode excluí-lo."); - _feedbackRepository.Delete(feedback); - await _feedbackRepository.SaveChangesAsync(); + try + { + _feedbackRepository.Delete(feedback); + await _feedbackRepository.SaveChangesAsync(); + } + catch (Exception ex) + { + _logger.LogError($"Ocorreu um erro ao deletar o feedback no banco de dados: {ex.Message}"); + } + return new Response("Feedback deletado com sucesso!.", new { id }); } } \ No newline at end of file diff --git a/Hotel.Domain/Handlers/FeedbackHandlers/HandleUpdateFeedback.cs b/Hotel.Domain/Handlers/FeedbackHandlers/HandleUpdateFeedback.cs index be7ee4c..6d4536a 100644 --- a/Hotel.Domain/Handlers/FeedbackHandlers/HandleUpdateFeedback.cs +++ b/Hotel.Domain/Handlers/FeedbackHandlers/HandleUpdateFeedback.cs @@ -17,8 +17,15 @@ public async Task HandleUpdateAsync(UpdateFeedback model, Guid id, Gui feedback.ChangeComment(model.Comment); feedback.ChangeRate(model.Rate); - _feedbackRepository.Update(feedback); - await _feedbackRepository.SaveChangesAsync(); + try + { + _feedbackRepository.Update(feedback); + await _feedbackRepository.SaveChangesAsync(); + } + catch (Exception ex) + { + _logger.LogError($"Ocorreu um erro ao atualizar o feedback no banco de dados: {ex.Message}"); + } return new Response("Feedback atualizado com sucesso!", new { feedback.Id }); } diff --git a/Hotel.Domain/Handlers/FeedbackHandlers/HandleUpdateFeedbackComment.cs b/Hotel.Domain/Handlers/FeedbackHandlers/HandleUpdateFeedbackComment.cs index a47a85d..1ac1d43 100644 --- a/Hotel.Domain/Handlers/FeedbackHandlers/HandleUpdateFeedbackComment.cs +++ b/Hotel.Domain/Handlers/FeedbackHandlers/HandleUpdateFeedbackComment.cs @@ -15,7 +15,14 @@ public async Task HandleUpdateCommentAsync(Guid id, string comment, Gu feedback.ChangeComment(comment); - await _feedbackRepository.SaveChangesAsync(); + try + { + await _feedbackRepository.SaveChangesAsync(); + } + catch (Exception ex) + { + _logger.LogError($"Ocorreu um erro ao atualizar o feedback no banco de dados: {ex.Message}"); + } return new Response("Feedback atualizado com sucesso!"); } diff --git a/Hotel.Domain/Handlers/FeedbackHandlers/HandleUpdateFeedbackRate.cs b/Hotel.Domain/Handlers/FeedbackHandlers/HandleUpdateFeedbackRate.cs index c924706..6a957d4 100644 --- a/Hotel.Domain/Handlers/FeedbackHandlers/HandleUpdateFeedbackRate.cs +++ b/Hotel.Domain/Handlers/FeedbackHandlers/HandleUpdateFeedbackRate.cs @@ -15,7 +15,14 @@ public async Task HandleUpdateRateAsync(Guid id, int rate, Guid custom feedback.ChangeRate(rate); - await _feedbackRepository.SaveChangesAsync(); + try + { + await _feedbackRepository.SaveChangesAsync(); + } + catch (Exception ex) + { + _logger.LogError($"Ocorreu um erro ao atualizar o feedback no banco de dados: {ex.Message}"); + } return new Response("Feedback atualizado com sucesso!"); } diff --git a/Hotel.Domain/Handlers/FeedbackHandlers/Likes/HandleAddFeedbackLike.cs b/Hotel.Domain/Handlers/FeedbackHandlers/Likes/HandleAddFeedbackLike.cs index 32bfe9d..22896ff 100644 --- a/Hotel.Domain/Handlers/FeedbackHandlers/Likes/HandleAddFeedbackLike.cs +++ b/Hotel.Domain/Handlers/FeedbackHandlers/Likes/HandleAddFeedbackLike.cs @@ -24,7 +24,14 @@ public async Task HandleAddLikeAsync(Guid feedbackId, Guid customerId) await _likeRepository.CreateLike(like); - await _feedbackRepository.SaveChangesAsync(); + try + { + await _feedbackRepository.SaveChangesAsync(); + } + catch (Exception ex) + { + _logger.LogError($"Ocorreu um erro ao criar um like no banco de dados: {ex.Message}"); + } return new Response("Like adicionado com sucesso!"); } diff --git a/Hotel.Domain/Handlers/FeedbackHandlers/Likes/HandleRemoveFeedbackLike.cs b/Hotel.Domain/Handlers/FeedbackHandlers/Likes/HandleRemoveFeedbackLike.cs index 9693508..ba6aedc 100644 --- a/Hotel.Domain/Handlers/FeedbackHandlers/Likes/HandleRemoveFeedbackLike.cs +++ b/Hotel.Domain/Handlers/FeedbackHandlers/Likes/HandleRemoveFeedbackLike.cs @@ -11,7 +11,14 @@ public async Task HandleRemoveLikeAsync(Guid feedbackId, Guid customer _likeRepository.RemoveLike(like); - await _feedbackRepository.SaveChangesAsync(); + try + { + await _feedbackRepository.SaveChangesAsync(); + } + catch (Exception ex) + { + _logger.LogError($"Ocorreu um erro ao deletar um like no banco de dados: {ex.Message}"); + } return new Response("Like removido com sucesso!"); } diff --git a/Hotel.Domain/Handlers/ReportHandlers/HandleCreateReport.cs b/Hotel.Domain/Handlers/ReportHandlers/HandleCreateReport.cs index 12f0075..e59de6e 100644 --- a/Hotel.Domain/Handlers/ReportHandlers/HandleCreateReport.cs +++ b/Hotel.Domain/Handlers/ReportHandlers/HandleCreateReport.cs @@ -11,10 +11,12 @@ public partial class ReportHandler : IHandler { private readonly IReportRepository _repository; private readonly IEmployeeRepository _employeeRepository; - public ReportHandler(IReportRepository repository, IEmployeeRepository employeeRepository) + private readonly ILogger _logger; + public ReportHandler(IReportRepository repository, IEmployeeRepository employeeRepository, ILogger logger) { _employeeRepository = employeeRepository; _repository = repository; + _logger = logger; } @@ -25,8 +27,15 @@ public async Task HandleCreateAsync(EditorReport model) var report = new Report(model.Summary, model.Description, model.Priority, employee, model.Resolution); - await _repository.CreateAsync(report); - await _repository.SaveChangesAsync(); + try + { + await _repository.CreateAsync(report); + await _repository.SaveChangesAsync(); + } + catch (Exception ex) + { + _logger.LogError($"Ocorreu um erro ao criar um relatório no banco de dados: {ex.Message}"); + } return new Response("Relatório criado com sucesso!", new { report.Id }); } diff --git a/Hotel.Domain/Handlers/ReportHandlers/HandleDeleteReport.cs b/Hotel.Domain/Handlers/ReportHandlers/HandleDeleteReport.cs index 98945aa..3dbbd16 100644 --- a/Hotel.Domain/Handlers/ReportHandlers/HandleDeleteReport.cs +++ b/Hotel.Domain/Handlers/ReportHandlers/HandleDeleteReport.cs @@ -13,8 +13,15 @@ public async Task HandleDeleteAsync(Guid id, Guid userId) if (report.EmployeeId != userId) throw new UnauthorizedAccessException("Você não tem permissão para deletar relatório alheio!"); - _repository.Delete(report); - await _repository.SaveChangesAsync(); + try + { + _repository.Delete(report); + await _repository.SaveChangesAsync(); + } + catch (Exception ex) + { + _logger.LogError($"Ocorreu um erro ao deletar um relatório no banco de dados: {ex.Message}"); + } return new Response("Relatório deletado com sucesso!", new { id }); } diff --git a/Hotel.Domain/Handlers/ReportHandlers/HandleFinishReport.cs b/Hotel.Domain/Handlers/ReportHandlers/HandleFinishReport.cs index 8244a80..9106159 100644 --- a/Hotel.Domain/Handlers/ReportHandlers/HandleFinishReport.cs +++ b/Hotel.Domain/Handlers/ReportHandlers/HandleFinishReport.cs @@ -12,7 +12,15 @@ public async Task HandleFinishAsync(Guid id) report.Finish(); - await _repository.SaveChangesAsync(); + try + { + await _repository.SaveChangesAsync(); + } + catch (Exception ex) + { + _logger.LogError($"Ocorreu um erro ao atualizar um relatório no banco de dados: {ex.Message}"); + } + return new Response("Relatório finalizado com sucesso!", new { report.Id }); } } \ No newline at end of file diff --git a/Hotel.Domain/Handlers/ReportHandlers/HandleUpdateReport.cs b/Hotel.Domain/Handlers/ReportHandlers/HandleUpdateReport.cs index 13d5f8c..8932b59 100644 --- a/Hotel.Domain/Handlers/ReportHandlers/HandleUpdateReport.cs +++ b/Hotel.Domain/Handlers/ReportHandlers/HandleUpdateReport.cs @@ -21,8 +21,15 @@ public async Task HandleUpdateAsync(EditorReport model, Guid id) report.ChangeEmployee(employee); - _repository.Update(report); - await _repository.SaveChangesAsync(); + try + { + _repository.Update(report); + await _repository.SaveChangesAsync(); + } + catch (Exception ex) + { + _logger.LogError($"Ocorreu um erro ao atualizar um relatório no banco de dados: {ex.Message}"); + } return new Response("Relatório atualizado com sucesso!", new { report.Id }); } diff --git a/Hotel.Domain/Handlers/ReportHandlers/HandleUpdateReportPriority.cs b/Hotel.Domain/Handlers/ReportHandlers/HandleUpdateReportPriority.cs index 7fc54b4..6589189 100644 --- a/Hotel.Domain/Handlers/ReportHandlers/HandleUpdateReportPriority.cs +++ b/Hotel.Domain/Handlers/ReportHandlers/HandleUpdateReportPriority.cs @@ -13,8 +13,15 @@ public async Task HandleUpdatePriorityAsync(EPriority priority, Guid i report.ChangePriority(priority); - _repository.Update(report); - await _repository.SaveChangesAsync(); + try + { + _repository.Update(report); + await _repository.SaveChangesAsync(); + } + catch (Exception ex) + { + _logger.LogError($"Ocorreu um erro ao atualizar um relatório no banco de dados: {ex.Message}"); + } return new Response("Prioridade atualizada com sucesso!", new { report.Id }); } diff --git a/Hotel.Domain/Handlers/ReservationHandlers/HandleCancelReservation.cs b/Hotel.Domain/Handlers/ReservationHandlers/HandleCancelReservation.cs index f3acc95..058ccbb 100644 --- a/Hotel.Domain/Handlers/ReservationHandlers/HandleCancelReservation.cs +++ b/Hotel.Domain/Handlers/ReservationHandlers/HandleCancelReservation.cs @@ -25,8 +25,9 @@ public async Task HandleCancelReservationAsync(Guid id, Guid customerI { await _repository.SaveChangesAsync(); } - catch (DbUpdateException) + catch (DbUpdateException e) { + _logger.LogError($"Erro ao atualizar o status da reserva no banco de dados: {e.Message}"); throw new DbUpdateException("Ocorreu um erro ao atualizar a reserva no banco de dados"); } @@ -36,6 +37,7 @@ public async Task HandleCancelReservationAsync(Guid id, Guid customerI } catch (StripeException e) { + _logger.LogError($"Erro ao cancelar o PaymentIntent no stripe: {e.Message}"); throw new StripeException($"Ocorreu um erro ao lidar com o serviço de pagamento. Erro: {e.Message}"); } diff --git a/Hotel.Domain/Handlers/ReservationHandlers/HandleCreateReservation.cs b/Hotel.Domain/Handlers/ReservationHandlers/HandleCreateReservation.cs index 844c081..313f064 100644 --- a/Hotel.Domain/Handlers/ReservationHandlers/HandleCreateReservation.cs +++ b/Hotel.Domain/Handlers/ReservationHandlers/HandleCreateReservation.cs @@ -19,8 +19,9 @@ public partial class ReservationHandler : IHandler private readonly IServiceRepository _serviceRepository; private readonly InvoiceHandler _invoiceHandler; private readonly IStripeService _stripeService; + private readonly ILogger _logger; - public ReservationHandler(IReservationRepository repository, IRoomRepository roomRepository, ICustomerRepository customerRepository, IServiceRepository serviceRepository, InvoiceHandler invoiceHandler, IStripeService stripeService) + public ReservationHandler(IReservationRepository repository, IRoomRepository roomRepository, ICustomerRepository customerRepository, IServiceRepository serviceRepository, InvoiceHandler invoiceHandler, IStripeService stripeService, ILogger logger) { _repository = repository; _roomRepository = roomRepository; @@ -28,6 +29,7 @@ public ReservationHandler(IReservationRepository repository, IRoomRepository roo _serviceRepository = serviceRepository; _invoiceHandler = invoiceHandler; _stripeService = stripeService; + _logger = logger; } public async Task HandleCreateAsync(CreateReservation model, Guid customerId) @@ -49,8 +51,9 @@ public async Task HandleCreateAsync(CreateReservation model, Guid cust await _repository.CreateAsync(reservation); await _repository.SaveChangesAsync(); } - catch(DbUpdateException) + catch(DbUpdateException e) { + _logger.LogError($"Erro ao criar reserva no banco de dados: {e.Message}"); throw new DbUpdateException("Ocorreu um erro ao criar a reserva no banco de dados"); } @@ -67,6 +70,7 @@ public async Task HandleCreateAsync(CreateReservation model, Guid cust } catch (StripeException e) { + _logger.LogError($"Erro ao criar PaymentIntent no stripe: {e.Message}"); throw new StripeException($"Ocorreu um erro ao lidar com o serviço de pagamento. Erro: {e.Message}"); } diff --git a/Hotel.Domain/Handlers/ReservationHandlers/HandleDeleteReservation.cs b/Hotel.Domain/Handlers/ReservationHandlers/HandleDeleteReservation.cs index 5389ea0..08f53e9 100644 --- a/Hotel.Domain/Handlers/ReservationHandlers/HandleDeleteReservation.cs +++ b/Hotel.Domain/Handlers/ReservationHandlers/HandleDeleteReservation.cs @@ -24,8 +24,9 @@ public async Task HandleDeleteAsync(Guid id, Guid customerId) _repository.Delete(reservation); await _repository.SaveChangesAsync(); } - catch (DbUpdateException) + catch (DbUpdateException e) { + _logger.LogError($"Erro ao deletar reserva no banco de dados: {e.Message}"); throw new DbUpdateException("Ocorreu um erro ao deletar a reserva do banco de dados"); } @@ -35,6 +36,7 @@ public async Task HandleDeleteAsync(Guid id, Guid customerId) } catch (StripeException e) { + _logger.LogError($"Erro ao cancelar PaymentIntent no Stripe: {e.Message}"); throw new StripeException($"Ocorreu um erro ao lidar com o serviço de pagamento. Erro: {e.Message}"); } diff --git a/Hotel.Domain/Handlers/ReservationHandlers/HandleFinishReservation.cs b/Hotel.Domain/Handlers/ReservationHandlers/HandleFinishReservation.cs index d66355a..c1fff30 100644 --- a/Hotel.Domain/Handlers/ReservationHandlers/HandleFinishReservation.cs +++ b/Hotel.Domain/Handlers/ReservationHandlers/HandleFinishReservation.cs @@ -22,14 +22,22 @@ public async Task HandleFinishReservationAsync(Guid id, Guid customerI //Create invoice and finalize Reservation var invoice = reservation.Finish(); - await _repository.SaveChangesAsync(); - + try + { + await _repository.SaveChangesAsync(); + } + catch (Exception e) + { + _logger.LogError($"Erro ao atualizar o status da reserva no banco de dados: {e.Message}"); + } + try { await _stripeService.CapturePaymentIntentAsync(reservation.StripePaymentIntentId, reservation); } catch (StripeException e) { + _logger.LogError($"Erro ao capturar o PaymentIntent no Stripe: {e.Message}"); throw new StripeException($"Ocorreu um erro ao capturar a transação no Stripe. Erro: {e.Message}"); } diff --git a/Hotel.Domain/Handlers/ReservationHandlers/HandleReservationCheckIn.cs b/Hotel.Domain/Handlers/ReservationHandlers/HandleReservationCheckIn.cs index a02746b..c1c966a 100644 --- a/Hotel.Domain/Handlers/ReservationHandlers/HandleReservationCheckIn.cs +++ b/Hotel.Domain/Handlers/ReservationHandlers/HandleReservationCheckIn.cs @@ -17,15 +17,33 @@ public async Task HandleReservationCheckInAsync(Guid id, string tokenI reservation.ToCheckIn(); - await _repository.SaveChangesAsync(); + try + { + await _repository.SaveChangesAsync(); + } + catch (Exception e) + { + _logger.LogError($"Erro ao atualizar o status da reserva para CheckedIn no banco de dados: {e.Message}"); + } + try - { + { await _stripeService.CreatePaymentMethodAsync(tokenId, reservation.StripePaymentIntentId); + } + catch (StripeException e) + { + _logger.LogError($"Erro ao criar método de pagamento no Stripe: {e.Message}"); + throw new StripeException($"Ocorreu um erro ao lidar com o serviço de pagamento. Erro: {e.Message}"); + } + + try + { await _stripeService.ConfirmPaymentIntentAsync(reservation.StripePaymentIntentId); } catch (StripeException e) { + _logger.LogError($"Erro ao confirmar o PaymentIntent no Stripe: {e.Message}"); throw new StripeException($"Ocorreu um erro ao lidar com o serviço de pagamento. Erro: {e.Message}"); } diff --git a/Hotel.Domain/Handlers/ReservationHandlers/HandleUpdateReservationExpectedCheckIn.cs b/Hotel.Domain/Handlers/ReservationHandlers/HandleUpdateReservationExpectedCheckIn.cs index ae2735a..db4e7e4 100644 --- a/Hotel.Domain/Handlers/ReservationHandlers/HandleUpdateReservationExpectedCheckIn.cs +++ b/Hotel.Domain/Handlers/ReservationHandlers/HandleUpdateReservationExpectedCheckIn.cs @@ -22,8 +22,9 @@ public async Task HandleUpdateExpectedCheckInAsync(Guid id, DateTime e { await _repository.SaveChangesAsync(); } - catch (DbUpdateException) + catch (DbUpdateException e) { + _logger.LogError($"Erro ao atualizar ExpectedCheckIn da reserva {reservation.Id} no banco de dados. Erro: {e.Message}"); throw new DbUpdateException("Ocorreu um erro ao atualizar a reserva no banco de dados"); } @@ -33,6 +34,7 @@ public async Task HandleUpdateExpectedCheckInAsync(Guid id, DateTime e } catch (StripeException e) { + _logger.LogError($"Erro ao atualizar o PaymentIntent ao atualizar ExpectedCheckIn da reserva {reservation.Id}. Erro: {e.Message}"); throw new StripeException($"Ocorreu um erro ao lidar com o serviço de pagamento. Erro: {e.Message}"); } diff --git a/Hotel.Domain/Handlers/ReservationHandlers/HandleUpdateReservationExpectedCheckOut.cs b/Hotel.Domain/Handlers/ReservationHandlers/HandleUpdateReservationExpectedCheckOut.cs index 777c43b..8ce1bdd 100644 --- a/Hotel.Domain/Handlers/ReservationHandlers/HandleUpdateReservationExpectedCheckOut.cs +++ b/Hotel.Domain/Handlers/ReservationHandlers/HandleUpdateReservationExpectedCheckOut.cs @@ -22,8 +22,9 @@ public async Task HandleUpdateExpectedCheckOutAsync(Guid id, DateTime { await _repository.SaveChangesAsync(); } - catch (DbUpdateException) + catch (DbUpdateException e) { + _logger.LogError($"Erro ao atualizar ExpectedCheckOut da reserva {reservation.Id} no banco de dados. Erro: {e.Message}"); throw new DbUpdateException("Ocorreu um erro ao atualizar a reserva no banco de dados"); } @@ -33,6 +34,7 @@ public async Task HandleUpdateExpectedCheckOutAsync(Guid id, DateTime } catch (StripeException e) { + _logger.LogError($"Erro ao atualizar o PaymentIntent ao atualizar ExpectedCheckOut da reserva {reservation.Id}. Erro: {e.Message}"); throw new StripeException($"Ocorreu um erro ao lidar com o serviço de pagamento. Erro: {e.Message}"); } diff --git a/Hotel.Domain/Handlers/ReservationHandlers/Services/HandleAddReservationService.cs b/Hotel.Domain/Handlers/ReservationHandlers/Services/HandleAddReservationService.cs index 7bf67f9..3c7fe5b 100644 --- a/Hotel.Domain/Handlers/ReservationHandlers/Services/HandleAddReservationService.cs +++ b/Hotel.Domain/Handlers/ReservationHandlers/Services/HandleAddReservationService.cs @@ -30,13 +30,21 @@ public async Task HandleAddServiceAsync(Guid id, Guid serviceId) { await _repository.SaveChangesAsync(); } - catch (DbUpdateException) + catch (DbUpdateException e) { + _logger.LogError($"Erro ao salvar o serviço no banco de dados: {e.Message}"); throw new DbUpdateException("Ocorreu um erro ao salvar o serviço no banco de dados"); } - await _stripeService.AddPaymentIntentProduct(reservation.StripePaymentIntentId, service); - + try + { + await _stripeService.AddPaymentIntentProduct(reservation.StripePaymentIntentId, service); + }catch + { + _logger.LogError($"Erro ao adicionar produto ao PaymentIntent no stripe"); + } + + await transaction.CommitAsync(); return new Response("Serviço adicionado com sucesso!"); diff --git a/Hotel.Domain/Handlers/ReservationHandlers/Services/HandleRemoveReservationService.cs b/Hotel.Domain/Handlers/ReservationHandlers/Services/HandleRemoveReservationService.cs index 61dcd03..2bfcf74 100644 --- a/Hotel.Domain/Handlers/ReservationHandlers/Services/HandleRemoveReservationService.cs +++ b/Hotel.Domain/Handlers/ReservationHandlers/Services/HandleRemoveReservationService.cs @@ -25,12 +25,21 @@ public async Task HandleRemoveServiceAsync(Guid id, Guid serviceId) { await _repository.SaveChangesAsync(); } - catch (DbUpdateException) + catch (DbUpdateException e) { + _logger.LogError($"Erro ao remove o serviço no banco de dados: {e.Message}"); throw new DbUpdateException("Ocorreu um erro ao atualizar a reserva no banco de dados"); } - await _stripeService.RemovePaymentIntentProduct(reservation.StripePaymentIntentId, serviceId); + + try + { + await _stripeService.RemovePaymentIntentProduct(reservation.StripePaymentIntentId, serviceId); + } + catch + { + _logger.LogError($"Erro ao remover produto do PaymentIntent no stripe"); + } await transaction.CommitAsync(); diff --git a/Hotel.Domain/Handlers/ResponsibilityHandlers/HandleCreateResponsibility.cs b/Hotel.Domain/Handlers/ResponsibilityHandlers/HandleCreateResponsibility.cs index 882c774..00fe47e 100644 --- a/Hotel.Domain/Handlers/ResponsibilityHandlers/HandleCreateResponsibility.cs +++ b/Hotel.Domain/Handlers/ResponsibilityHandlers/HandleCreateResponsibility.cs @@ -9,15 +9,28 @@ namespace Hotel.Domain.Handlers.y.ResponsibilityHandlers; public partial class ResponsibilityHandler : IHandler { private readonly IResponsibilityRepository _repository; - public ResponsibilityHandler(IResponsibilityRepository repository) - => _repository = repository; + private readonly ILogger _logger; + + public ResponsibilityHandler(IResponsibilityRepository repository, ILogger logger) + { + _repository = repository; + _logger = logger; + } public async Task HandleCreateAsync(EditorResponsibility model) { var responsibility = new Responsibility(model.Name, model.Description, model.Priority); - await _repository.CreateAsync(responsibility); - await _repository.SaveChangesAsync(); + try + { + await _repository.CreateAsync(responsibility); + await _repository.SaveChangesAsync(); + } + catch (Exception e) + { + _logger.LogError($"Erro ao criar a responsabilidade no banco de dados. Erro: {e.Message}"); + throw; + } return new Response("Responsabilidade criada com sucesso!", new { responsibility.Id }); } diff --git a/Hotel.Domain/Handlers/ResponsibilityHandlers/HandleDeleteResponsibility.cs b/Hotel.Domain/Handlers/ResponsibilityHandlers/HandleDeleteResponsibility.cs index baf87fc..68feda2 100644 --- a/Hotel.Domain/Handlers/ResponsibilityHandlers/HandleDeleteResponsibility.cs +++ b/Hotel.Domain/Handlers/ResponsibilityHandlers/HandleDeleteResponsibility.cs @@ -1,4 +1,5 @@ using Hotel.Domain.DTOs; +using Hotel.Domain.Entities.ResponsibilityEntity; namespace Hotel.Domain.Handlers.y.ResponsibilityHandlers; @@ -7,7 +8,17 @@ public partial class ResponsibilityHandler public async Task HandleDeleteAsync(Guid id) { _repository.Delete(id); - await _repository.SaveChangesAsync(); - return new Response("Responsabilide deletada com sucesso!", new { id }); + + try + { + await _repository.SaveChangesAsync(); + } + catch (Exception e) + { + _logger.LogError($"Erro ao deletar a responsabilidade {id} do banco de dados. Erro: {e.Message}"); + throw; + } + + return new Response("Responsabilidade deletada com sucesso!", new { id }); } } \ No newline at end of file diff --git a/Hotel.Domain/Handlers/ResponsibilityHandlers/HandleUpdateResponsibility.cs b/Hotel.Domain/Handlers/ResponsibilityHandlers/HandleUpdateResponsibility.cs index e7d7cca..6975734 100644 --- a/Hotel.Domain/Handlers/ResponsibilityHandlers/HandleUpdateResponsibility.cs +++ b/Hotel.Domain/Handlers/ResponsibilityHandlers/HandleUpdateResponsibility.cs @@ -1,5 +1,6 @@ using Hotel.Domain.DTOs; using Hotel.Domain.DTOs.ResponsibilityDTOs; +using Hotel.Domain.Entities.ResponsibilityEntity; namespace Hotel.Domain.Handlers.y.ResponsibilityHandlers; @@ -15,9 +16,18 @@ public async Task HandleUpdateAsync(EditorResponsibility model, Guid i Responsibility.ChangeDescription(model.Description); Responsibility.ChangePriority(model.Priority); - _repository.Update(Responsibility); - await _repository.SaveChangesAsync(); + try + { + _repository.Update(Responsibility); + await _repository.SaveChangesAsync(); + } + catch (Exception e) + { + _logger.LogError($"Erro ao atualizar a responsabilidade {id} no banco de dados. Erro: {e.Message}"); + throw; + } - return new Response("Responsabilidade atualizado com sucesso!", new { Responsibility.Id }); + + return new Response("Responsabilidade atualizada com sucesso!", new { Responsibility.Id }); } } \ No newline at end of file diff --git a/Hotel.Domain/Handlers/RoomHandlers/HandleCreateRoom.cs b/Hotel.Domain/Handlers/RoomHandlers/HandleCreateRoom.cs index 780b8fa..6d994de 100644 --- a/Hotel.Domain/Handlers/RoomHandlers/HandleCreateRoom.cs +++ b/Hotel.Domain/Handlers/RoomHandlers/HandleCreateRoom.cs @@ -16,13 +16,15 @@ public partial class RoomHandler : IHandler private readonly IServiceRepository _serviceRepository; private readonly ICategoryRepository _categoryRepository; private readonly IStripeService _stripeService; + private readonly ILogger _logger; - public RoomHandler(IRoomRepository repository, IServiceRepository serviceRepository, ICategoryRepository categoryRepository, IStripeService stripeService) + public RoomHandler(IRoomRepository repository, IServiceRepository serviceRepository, ICategoryRepository categoryRepository, IStripeService stripeService, ILogger logger) { _repository = repository; _serviceRepository = serviceRepository; _categoryRepository = categoryRepository; _stripeService = stripeService; + _logger = logger; } public async Task HandleCreateAsync(EditorRoom model) @@ -45,8 +47,14 @@ public async Task HandleCreateAsync(EditorRoom model) var room = new Room(model.Name, model.Number, model.Price, model.Capacity, model.Description, category); - await _repository.CreateAsync(room); - await _repository.SaveChangesAsync(); + try + { + await _repository.CreateAsync(room); + await _repository.SaveChangesAsync(); + }catch (Exception e) + { + _logger.LogError($"Erro ao criar cômodo no banco de dados. Erro: {e.Message}"); + } try { @@ -54,8 +62,9 @@ public async Task HandleCreateAsync(EditorRoom model) room.StripeProductId = stripeProduct.Id; await _repository.SaveChangesAsync(); } - catch + catch (Exception e) { + _logger.LogError($"Erro ao criar cômodo como produto no Stripe. Erro: {e.Message}"); throw new StripeException("Um ero ocorreu ao criar o produto no Stripe."); } diff --git a/Hotel.Domain/Handlers/RoomHandlers/HandleDeleteRoom.cs b/Hotel.Domain/Handlers/RoomHandlers/HandleDeleteRoom.cs index b70c95a..20f8f9a 100644 --- a/Hotel.Domain/Handlers/RoomHandlers/HandleDeleteRoom.cs +++ b/Hotel.Domain/Handlers/RoomHandlers/HandleDeleteRoom.cs @@ -19,8 +19,16 @@ public async Task HandleDeleteAsync(Guid id) if (room.Reservations.Count > 0) throw new InvalidOperationException("Não foi possível deletar a hospedagem pois tem reservas associadas a ela. Sugiro que desative a hospedagem."); - _repository.Delete(room); - await _repository.SaveChangesAsync(); + try + { + _repository.Delete(room); + await _repository.SaveChangesAsync(); + } + catch (Exception e) + { + _logger.LogError($"Erro ao deletar cômodo {room.Id} no banco de dados. Erro: {e.Message}"); + } + try { @@ -28,9 +36,10 @@ public async Task HandleDeleteAsync(Guid id) var stripeResponse = await _stripeService.DisableProductAsync(room.StripeProductId) ?? throw new Exception(); } - catch + catch (Exception e) { - throw new StripeException("Um ero ocorreu ao desativar o produto no Stripe."); + _logger.LogError($"Erro ao desativar produto no Stripe ao deletar cômodo {room.Id}. Erro: {e.Message}"); + throw new StripeException("Um erro ocorreu ao desativar o produto no Stripe."); } await transaction.CommitAsync(); diff --git a/Hotel.Domain/Handlers/RoomHandlers/HandleDisableRoom.cs b/Hotel.Domain/Handlers/RoomHandlers/HandleDisableRoom.cs index 7ae9e3b..ca804da 100644 --- a/Hotel.Domain/Handlers/RoomHandlers/HandleDisableRoom.cs +++ b/Hotel.Domain/Handlers/RoomHandlers/HandleDisableRoom.cs @@ -1,4 +1,5 @@ using Hotel.Domain.DTOs; +using Hotel.Domain.Entities.ServiceEntity; using Hotel.Domain.Exceptions; using Stripe; @@ -21,14 +22,23 @@ public async Task HandleDisableRoom(Guid id) throw new InvalidOperationException("Não foi possível desativar a hospedagem pois tem reservas pendentes relacionadas."); room.Disable(); - await _repository.SaveChangesAsync(); + + try + { + await _repository.SaveChangesAsync(); + } + catch (Exception e) + { + _logger.LogError($"Erro ao atualizar no banco de dados ao desativar cômodo {room.Id}. Erro: {e.Message}"); + } try { await _stripeService.UpdateProductAsync(room.StripeProductId, room.Name, room.Description, room.Price, false); } - catch + catch (Exception e) { + _logger.LogError($"Erro ao desativar produto {room.StripeProductId} no Stripe. Erro: {e.Message}"); throw new StripeException("Ocorreu um erro ao atualizar o produto no Stripe."); } diff --git a/Hotel.Domain/Handlers/RoomHandlers/HandleEnableRoom.cs b/Hotel.Domain/Handlers/RoomHandlers/HandleEnableRoom.cs index 2a62689..e7f8845 100644 --- a/Hotel.Domain/Handlers/RoomHandlers/HandleEnableRoom.cs +++ b/Hotel.Domain/Handlers/RoomHandlers/HandleEnableRoom.cs @@ -1,4 +1,5 @@ using Hotel.Domain.DTOs; +using Hotel.Domain.Entities.ServiceEntity; using Hotel.Domain.Exceptions; using Stripe; @@ -17,14 +18,23 @@ public async Task HandleEnableRoom(Guid id) throw new NotFoundException("Hospedagem não encontrada."); room.Enable(); - await _repository.SaveChangesAsync(); + + try + { + await _repository.SaveChangesAsync(); + } + catch (Exception e) + { + _logger.LogError($"Erro ao atualizar no banco de dados ao ativar o cômodo {room.Id}. Erro: {e.Message}"); + } try { await _stripeService.UpdateProductAsync(room.StripeProductId, room.Name, room.Description, room.Price, true); } - catch + catch (Exception e) { + _logger.LogError($"Erro ao ativar produto {room.StripeProductId} no Stripe. Erro: {e.Message}"); throw new StripeException("Ocorreu um erro ao atualizar o produto no Stripe."); } diff --git a/Hotel.Domain/Handlers/RoomHandlers/HandleUpdateRoom.cs b/Hotel.Domain/Handlers/RoomHandlers/HandleUpdateRoom.cs index c94f71a..fa700f4 100644 --- a/Hotel.Domain/Handlers/RoomHandlers/HandleUpdateRoom.cs +++ b/Hotel.Domain/Handlers/RoomHandlers/HandleUpdateRoom.cs @@ -1,5 +1,6 @@ using Hotel.Domain.DTOs; using Hotel.Domain.DTOs.RoomDTOs; +using Hotel.Domain.Entities.ServiceEntity; using Hotel.Domain.Exceptions; using Stripe; @@ -40,14 +41,22 @@ public async Task HandleUpdateAsync(EditorRoom model, Guid id) room.ChangeDescription(model.Description); room.ChangeCategory(model.CategoryId); - await _repository.SaveChangesAsync(); + try + { + await _repository.SaveChangesAsync(); + } + catch (Exception e) + { + _logger.LogError($"Erro atualizar cômodo {room.Id} no banco de dados. Erro: {e.Message}"); + } try { await _stripeService.UpdateProductAsync(room.StripeProductId, room.Name, room.Description, room.Price, room.IsActive); } - catch + catch (Exception e) { + _logger.LogError($"Erro ao criar cômodo como produto no Stripe. Erro: {e.Message}"); throw new StripeException("Um erro ocorreu ao atualizar o produto no Stripe."); } diff --git a/Hotel.Domain/Handlers/RoomHandlers/HandleUpdateRoomCapacity.cs b/Hotel.Domain/Handlers/RoomHandlers/HandleUpdateRoomCapacity.cs index 05e2ad0..0f90705 100644 --- a/Hotel.Domain/Handlers/RoomHandlers/HandleUpdateRoomCapacity.cs +++ b/Hotel.Domain/Handlers/RoomHandlers/HandleUpdateRoomCapacity.cs @@ -13,7 +13,14 @@ public async Task HandleUpdateCapacityAsync(Guid id, int newCapacity) room.ChangeCapacity(newCapacity); - await _repository.SaveChangesAsync(); + try + { + await _repository.SaveChangesAsync(); + } + catch (Exception e) + { + _logger.LogError($"Erro ao atualizar capacidade do cômodo {room.Id} no banco de dados. Erro: {e.Message}"); + } return new Response("Capacidade atualizada com sucesso!"); } diff --git a/Hotel.Domain/Handlers/RoomHandlers/HandleUpdateRoomCategory.cs b/Hotel.Domain/Handlers/RoomHandlers/HandleUpdateRoomCategory.cs index 9fd6d5f..5d0b658 100644 --- a/Hotel.Domain/Handlers/RoomHandlers/HandleUpdateRoomCategory.cs +++ b/Hotel.Domain/Handlers/RoomHandlers/HandleUpdateRoomCategory.cs @@ -15,7 +15,14 @@ public async Task HandleUpdateCategoryAsync(Guid id, Guid categoryId) room.ChangeCategory(categoryId); - await _repository.SaveChangesAsync(); + try + { + await _repository.SaveChangesAsync(); + } + catch (Exception e) + { + _logger.LogError($"Erro ao atualizar categoria do cômodo {room.Id} no banco de dados. Erro: {e.Message}"); + } return new Response("Categoria atualizada com sucesso!"); } diff --git a/Hotel.Domain/Handlers/RoomHandlers/HandleUpdateRoomName.cs b/Hotel.Domain/Handlers/RoomHandlers/HandleUpdateRoomName.cs index 17ef600..839983c 100644 --- a/Hotel.Domain/Handlers/RoomHandlers/HandleUpdateRoomName.cs +++ b/Hotel.Domain/Handlers/RoomHandlers/HandleUpdateRoomName.cs @@ -21,14 +21,22 @@ public async Task HandleUpdateNameAsync(Guid id, string newName) room.ChangeName(newName); - await _repository.SaveChangesAsync(); + try + { + await _repository.SaveChangesAsync(); + } + catch (Exception e) + { + _logger.LogError($"Erro ao atualizar nome do cômodo {room.Id} no banco de dados. Erro: {e.Message}"); + } try { await _stripeService.UpdateProductAsync(room.StripeProductId, room.Name, room.Description, room.Price, room.IsActive); } - catch + catch (Exception e) { + _logger.LogError($"Erro ao atualizar nome do produto {room.StripeProductId} no Stripe. Erro: {e.Message}"); throw new StripeException("Um erro ocorreu ao atualizar o produto no Stripe."); } diff --git a/Hotel.Domain/Handlers/RoomHandlers/HandleUpdateRoomNumber.cs b/Hotel.Domain/Handlers/RoomHandlers/HandleUpdateRoomNumber.cs index 21b91db..12d5efc 100644 --- a/Hotel.Domain/Handlers/RoomHandlers/HandleUpdateRoomNumber.cs +++ b/Hotel.Domain/Handlers/RoomHandlers/HandleUpdateRoomNumber.cs @@ -16,7 +16,14 @@ public async Task HandleUpdateNumberAsync(Guid id, int newNumber) room.ChangeNumber(newNumber); - await _repository.SaveChangesAsync(); + try + { + await _repository.SaveChangesAsync(); + } + catch (Exception e) + { + _logger.LogError($"Erro ao atualizar número do cômodo {room.Id} no banco de dados. Erro: {e.Message}"); + } return new Response("Número atualizado com sucesso!"); } diff --git a/Hotel.Domain/Handlers/RoomHandlers/HandleUpdateRoomPrice.cs b/Hotel.Domain/Handlers/RoomHandlers/HandleUpdateRoomPrice.cs index 0664b9b..3073a91 100644 --- a/Hotel.Domain/Handlers/RoomHandlers/HandleUpdateRoomPrice.cs +++ b/Hotel.Domain/Handlers/RoomHandlers/HandleUpdateRoomPrice.cs @@ -20,15 +20,23 @@ public async Task HandleUpdatePriceAsync(Guid id, decimal price) throw new InvalidOperationException("Não foi possível atualizar o preço pois possuem reservas pendentes relacionadas a hospedagem."); room.ChangePrice(price); - await _repository.SaveChangesAsync(); + try + { + await _repository.SaveChangesAsync(); + } + catch (Exception e) + { + _logger.LogError($"Erro ao atualizar o preço do cômodo {room.Id} no banco de dados. Erro: {e.Message}"); + } try { await _stripeService.UpdateProductAsync(room.StripeProductId, room.Name, room.Description, room.Price); } - catch + catch (Exception e) { + _logger.LogError($"Erro ao atualizar o preço do produto {room.StripeProductId} no Stripe. Erro: {e.Message}"); throw new StripeException("Um erro ocorreu ao atualizar o produto no Stripe."); } diff --git a/Hotel.Domain/Handlers/RoomHandlers/HandleUpdateRoomToAvailableStatus.cs b/Hotel.Domain/Handlers/RoomHandlers/HandleUpdateRoomToAvailableStatus.cs index 1bf6dcc..0d0715d 100644 --- a/Hotel.Domain/Handlers/RoomHandlers/HandleUpdateRoomToAvailableStatus.cs +++ b/Hotel.Domain/Handlers/RoomHandlers/HandleUpdateRoomToAvailableStatus.cs @@ -13,7 +13,14 @@ public async Task HandleChangeToAvailableStatusAsync(Guid id) room.ChangeStatus(ERoomStatus.Available); - await _repository.SaveChangesAsync(); + try + { + await _repository.SaveChangesAsync(); + } + catch (Exception e) + { + _logger.LogError($"Erro ao atualizar o status do cômodo {room.Id} para disponível no banco de dados. Erro: {e.Message}"); + } return new Response("Status atualizado com sucesso!"); } diff --git a/Hotel.Domain/Handlers/RoomHandlers/Services/HandleAddRoomService.cs b/Hotel.Domain/Handlers/RoomHandlers/Services/HandleAddRoomService.cs index fdf61d7..2e6d138 100644 --- a/Hotel.Domain/Handlers/RoomHandlers/Services/HandleAddRoomService.cs +++ b/Hotel.Domain/Handlers/RoomHandlers/Services/HandleAddRoomService.cs @@ -15,7 +15,14 @@ public async Task HandleAddServiceAsync(Guid id, Guid serviceId) room.AddService(service); - await _repository.SaveChangesAsync(); + try + { + await _repository.SaveChangesAsync(); + } + catch (Exception e) + { + _logger.LogError($"Erro ao associar serviço {service.Id} ao cômodo {room.Id}. Erro: {e.Message}"); + } return new Response("Serviço adicinado com sucesso!"); } diff --git a/Hotel.Domain/Handlers/RoomHandlers/Services/HandleRemoveRoomService.cs b/Hotel.Domain/Handlers/RoomHandlers/Services/HandleRemoveRoomService.cs index 6bb74b3..50d01f8 100644 --- a/Hotel.Domain/Handlers/RoomHandlers/Services/HandleRemoveRoomService.cs +++ b/Hotel.Domain/Handlers/RoomHandlers/Services/HandleRemoveRoomService.cs @@ -15,7 +15,14 @@ public async Task HandleRemoveServiceAsync(Guid id, Guid serviceId) room.RemoveService(service); - await _repository.SaveChangesAsync(); + try + { + await _repository.SaveChangesAsync(); + } + catch (Exception e) + { + _logger.LogError($"Erro ao desassociar serviço {service.Id} do cômodo {room.Id}. Erro: {e.Message}"); + } return new Response("Serviço removido com sucesso!"); } diff --git a/Hotel.Domain/Hotel.Domain.csproj b/Hotel.Domain/Hotel.Domain.csproj index 0177f0b..4f0c127 100644 --- a/Hotel.Domain/Hotel.Domain.csproj +++ b/Hotel.Domain/Hotel.Domain.csproj @@ -25,6 +25,7 @@ + diff --git a/Hotel.Domain/Initialization/ConfigureDependencies.cs b/Hotel.Domain/Initialization/ConfigureDependencies.cs index 2da3e9b..d7e1900 100644 --- a/Hotel.Domain/Initialization/ConfigureDependencies.cs +++ b/Hotel.Domain/Initialization/ConfigureDependencies.cs @@ -27,15 +27,30 @@ using Microsoft.EntityFrameworkCore; using Hotel.Domain.Services.Interfaces; using Hotel.Domain.Middlewares; +using Serilog; namespace Hotel.Domain.Initialization; -public static class ConfigureDependencies +public static class ConfigureServices { public static void Configure(WebApplicationBuilder builder) { - builder.Services.AddExceptionHandler(); - builder.Services.AddProblemDetails(); + var services = builder.Services; + + //ExceptionHandler + services.AddExceptionHandler(); + services.AddProblemDetails(); + + //Logs + Log.Logger = new LoggerConfiguration() + .WriteTo.Console() + .CreateLogger(); + + services.AddLogging(logginBuilder => + { + logginBuilder.ClearProviders(); + logginBuilder.AddSerilog(); + }); if (builder.Environment.IsDevelopment() || builder.Environment.IsProduction()) { @@ -43,56 +58,55 @@ public static void Configure(WebApplicationBuilder builder) .UseSqlServer(Configuration.ConnectionString) .Options; - builder.Services.AddSingleton(options); + services.AddSingleton(options); - builder.Services.AddDbContext(opt => + services.AddDbContext(opt => { opt.UseSqlServer(Configuration.ConnectionString); }); } //Configurar repositórios - builder.Services.AddScoped(); - builder.Services.AddScoped(); - builder.Services.AddScoped(); - builder.Services.AddScoped(); - builder.Services.AddScoped(); - builder.Services.AddScoped(); - builder.Services.AddScoped(); - builder.Services.AddScoped(); - builder.Services.AddScoped(); - builder.Services.AddScoped(); - builder.Services.AddScoped(); - builder.Services.AddScoped(); - builder.Services.AddScoped(); - builder.Services.AddScoped(); - builder.Services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); //Services - builder.Services.AddSingleton(); - builder.Services.AddScoped(); - builder.Services.AddSingleton(); - builder.Services.AddSingleton(); - builder.Services.AddScoped(); - builder.Services.AddScoped(); - builder.Services.AddSingleton(); + services.AddScoped(); + services.AddSingleton(); + services.AddSingleton(); + services.AddScoped(); + services.AddScoped(); + services.AddSingleton(); //Configurar handlers - builder.Services.AddScoped(); - builder.Services.AddScoped(); - builder.Services.AddScoped(); - builder.Services.AddScoped(); - builder.Services.AddScoped(); - builder.Services.AddScoped(); - builder.Services.AddScoped(); - builder.Services.AddScoped(); - builder.Services.AddScoped(); - builder.Services.AddScoped(); - builder.Services.AddScoped(); - builder.Services.AddScoped(); - builder.Services.AddScoped(); - builder.Services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); } } diff --git a/Hotel.Domain/Program.cs b/Hotel.Domain/Program.cs index 5ebb25f..e91c234 100644 --- a/Hotel.Domain/Program.cs +++ b/Hotel.Domain/Program.cs @@ -1,20 +1,15 @@ -using Hotel.Domain.Extensions; using Hotel.Domain.Initialization; using System.Text; var builder = WebApplication.CreateBuilder(args); -builder.Logging.ClearProviders(); -builder.Logging.AddConsole(); -builder.Logging.AddDebug(); - Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); Console.OutputEncoding = Encoding.UTF8; builder.Configuration.AddEnvironmentVariables(); LoadConfigurationClass.Configure(builder); -ConfigureDependencies.Configure(builder); +ConfigureServices.Configure(builder); ConfigureAuthentication.Configure(builder.Services); ConfigureCors.Configure(builder.Services); diff --git a/Hotel.Domain/Services/AuthorizationServices/ConvertToPermission.cs b/Hotel.Domain/Services/AuthorizationServices/ConvertToPermission.cs index 843dc08..e3fae0c 100644 --- a/Hotel.Domain/Services/AuthorizationServices/ConvertToPermission.cs +++ b/Hotel.Domain/Services/AuthorizationServices/ConvertToPermission.cs @@ -2,7 +2,7 @@ namespace Hotel.Domain.Services.Authorization; -public partial class AuthorizationService +public static partial class AuthorizationService { /// /// Serviço para transformar uma string em uma permissão diff --git a/Hotel.Domain/Services/AuthorizationServices/GetUserPermissions.cs b/Hotel.Domain/Services/AuthorizationServices/GetUserPermissions.cs index e68ba2e..f768159 100644 --- a/Hotel.Domain/Services/AuthorizationServices/GetUserPermissions.cs +++ b/Hotel.Domain/Services/AuthorizationServices/GetUserPermissions.cs @@ -3,7 +3,7 @@ namespace Hotel.Domain.Services.Authorization; -public partial class AuthorizationService +public static partial class AuthorizationService { /// /// Serviço para buscar todas as permissões da ClaimPrincipal @@ -15,14 +15,15 @@ public static IEnumerable GetUserPermissions(ClaimsPrincipal user) var permissionsClaim = user.FindFirst("permissions"); if (permissionsClaim == null) throw new UnauthorizedAccessException("Você não tem acesso a esse serviço."); - + var stringPermissions = permissionsClaim.Value.Split(","); // separar as permissões por vírgula(',') //Convertendo as permissões de string para enumerador - Func, string, IEnumerable> aggregateFunction = (acc, name) - => acc = acc.Append(ConvertToPermission(name)); - - var permissions = stringPermissions.Aggregate([], aggregateFunction); + var permissions = new List(); + foreach (var permissionName in stringPermissions) + { + permissions.Add(ConvertToPermission(permissionName.Trim())); + } return permissions; } diff --git a/Hotel.Domain/Services/AuthorizationServices/GetUserRole.cs b/Hotel.Domain/Services/AuthorizationServices/GetUserRole.cs index 29861c6..766788a 100644 --- a/Hotel.Domain/Services/AuthorizationServices/GetUserRole.cs +++ b/Hotel.Domain/Services/AuthorizationServices/GetUserRole.cs @@ -3,7 +3,7 @@ namespace Hotel.Domain.Services.Authorization; -public partial class AuthorizationService +public static partial class AuthorizationService { /// /// Serviço para buscar a Role do usuário diff --git a/Hotel.Domain/Services/EmailServices/SendEmailAsync.cs b/Hotel.Domain/Services/EmailServices/SendEmailAsync.cs index 5ae1dfc..377fc0a 100644 --- a/Hotel.Domain/Services/EmailServices/SendEmailAsync.cs +++ b/Hotel.Domain/Services/EmailServices/SendEmailAsync.cs @@ -26,6 +26,6 @@ public async Task SendEmailAsync(SendEmailModel email) }; await smtpClient.SendMailAsync(mailMessage); - Console.WriteLine("Email enviado com sucesso!"); + _logger.LogInformation($"Email enviado com sucesso para {email.To.Address}"); } } diff --git a/Hotel.Domain/Services/EmailServices/VerifyEmailCodeAsync.cs b/Hotel.Domain/Services/EmailServices/VerifyEmailCodeAsync.cs index d326eed..dec9dbe 100644 --- a/Hotel.Domain/Services/EmailServices/VerifyEmailCodeAsync.cs +++ b/Hotel.Domain/Services/EmailServices/VerifyEmailCodeAsync.cs @@ -7,20 +7,30 @@ namespace Hotel.Domain.Services.EmailServices; public partial class EmailService { private readonly IVerificationCodeRepository _verificationCodeRepository; + private readonly ILogger _logger; - public EmailService(IVerificationCodeRepository verificationCodeRepository) - => _verificationCodeRepository = verificationCodeRepository; + public EmailService(IVerificationCodeRepository verificationCodeRepository, ILogger logger) + { + _verificationCodeRepository = verificationCodeRepository; + _logger = logger; + } public async Task VerifyEmailCodeAsync(Email email, string? codeStr) { if (string.IsNullOrEmpty(codeStr)) + { + _logger.LogWarning($"Código de validação de email é nullo ou vazio. Email: {email.Address}"); throw new ArgumentException("Código inválido."); + } var code = new VerificationCode(codeStr); var verificationCode = await _verificationCodeRepository.GetCode(code); if (verificationCode == null || verificationCode.Email == null || verificationCode?.Email.Address != email.Address) + { + _logger.LogWarning($"Código de validação de email é inválido. Email: {email.Address}"); throw new ArgumentException("Código inválido."); + } //Deletar código após ser validado _verificationCodeRepository.Delete(verificationCode); diff --git a/Hotel.Domain/Services/LoginServices/LoginService.cs b/Hotel.Domain/Services/LoginServices/LoginService.cs index 97d23c8..98f8c38 100644 --- a/Hotel.Domain/Services/LoginServices/LoginService.cs +++ b/Hotel.Domain/Services/LoginServices/LoginService.cs @@ -9,12 +9,15 @@ namespace Hotel.Domain.Services.LoginServices; public class LoginService { private readonly TokenService _tokenService; + private readonly ILogger _logger; - public LoginService(TokenService tokenService) + public LoginService(TokenService tokenService, ILogger logger) { _tokenService = tokenService; + _logger = logger; } + //Login com cliente public Response UserLogin(string password, Customer customer) { @@ -24,7 +27,10 @@ public Response UserLogin(string password, Customer customer) return new Response("Login efetuado com sucesso!", new { Token = token }); } else + { + _logger.LogError($"Cliente falhou ao tentar fazer login com o email {customer.Email.Address}"); throw new ArgumentException("Email ou senha inválidos."); + } } //Login com administrador @@ -36,7 +42,10 @@ public Response UserLogin(string password, Admin admin) return new Response("Login efetuado com sucesso!", new { Token = token }); } else + { + _logger.LogError($"Administrador falhou ao tentar fazer login com o email {admin.Email.Address}"); throw new ArgumentException("Email ou senha inválidos."); + } } //Login com funcionário @@ -48,6 +57,9 @@ public Response UserLogin(string password, Employee employee) return new Response("Login efetuado com sucesso!", new { Token = token }); } else + { + _logger.LogError($"Funcionário falhou ao tentar fazer login com o email {employee.Email.Address}"); throw new ArgumentException("Email ou senha inválidos."); + } } } diff --git a/Hotel.Domain/Services/StripeService.cs b/Hotel.Domain/Services/StripeService.cs index c6ab26a..a7cb259 100644 --- a/Hotel.Domain/Services/StripeService.cs +++ b/Hotel.Domain/Services/StripeService.cs @@ -13,14 +13,16 @@ public class StripeService : IStripeService private readonly PriceService _stripePriceService; private readonly PaymentIntentService _stripePaymentIntentService; private readonly PaymentMethodService _stripePaymentMethodService; + private readonly ILogger _logger; - public StripeService() + public StripeService(ILogger logger) { _stripeCustomerService = new CustomerService(); _stripeProductService = new ProductService(); _stripePriceService = new PriceService(); _stripePaymentIntentService = new PaymentIntentService(); _stripePaymentMethodService = new PaymentMethodService(); + _logger = logger; } //Customer @@ -38,12 +40,22 @@ public async Task CreateCustomerAsync(Name name, Email email, Phone ph Phone = phone.Number }; - return await _stripeCustomerService.CreateAsync(options); + var customer = await _stripeCustomerService.CreateAsync(options); + _logger.LogInformation($"Cliente stripe foi criado. Id: {customer.Id}"); + return customer; } public async Task DeleteCustomerAsync(string customerId) { - return await _stripeCustomerService.DeleteAsync(customerId) is null ? false : true; + var isDeleted = await _stripeCustomerService.DeleteAsync(customerId) is null ? false : true; + if (isDeleted) + { + _logger.LogInformation("Cliente stripe foi deletado"); + }else + { + _logger.LogError("Tentativa de deletar cliente stripe mal sucedida"); + } + return isDeleted; } public async Task GetCustomerAsync(string customerId) @@ -65,7 +77,9 @@ public async Task UpdateCustomerAsync(string customerId, Name name, Em Phone = phone.Number }; - return await _stripeCustomerService.UpdateAsync(customerId, options); + var customer = await _stripeCustomerService.UpdateAsync(customerId, options); + _logger.LogInformation($"Cliente stripe com o id {customer.Id} foi atualizado"); + return customer; } @@ -81,6 +95,7 @@ public async Task CreateProductAsync(string name, string description, d }; var product = await _stripeProductService.CreateAsync(productOptions); + _logger.LogInformation($"Produto criado no Stripe. Id: {product.Id}"); var priceCreateOptions = new PriceCreateOptions { @@ -89,8 +104,8 @@ public async Task CreateProductAsync(string name, string description, d Product = product.Id }; - await _stripePriceService.CreateAsync(priceCreateOptions); - + var stripePrice = await _stripePriceService.CreateAsync(priceCreateOptions); + _logger.LogInformation($"Preço criado no Stripe. Id: {stripePrice.Id}"); return product; } @@ -103,7 +118,8 @@ public async Task DisableProductAsync(string productId) Active = false, }; - return await _stripeProductService.UpdateAsync(productId, productUpdateOptions); + await _stripeProductService.UpdateAsync(productId, productUpdateOptions); + return product; } public async Task GetProductAsync(string productId) diff --git a/Hotel.Domain/Services/TokenServices/GenerateToken.cs b/Hotel.Domain/Services/TokenServices/GenerateToken.cs index 86cc6ac..e5c2007 100644 --- a/Hotel.Domain/Services/TokenServices/GenerateToken.cs +++ b/Hotel.Domain/Services/TokenServices/GenerateToken.cs @@ -16,10 +16,10 @@ public class TokenService public string GenerateToken(Admin admin) { var claims = new List() - { - new(ClaimTypes.NameIdentifier, admin.Id.ToString()), - new(ClaimTypes.Email, admin.Email.Address) - }; + { + new(ClaimTypes.NameIdentifier, admin.Id.ToString()), + new(ClaimTypes.Email, admin.Email.Address) + }; //Se for admin ou rootAdmin if (admin.IsRootAdmin) // Possui todo acesso diff --git a/Hotel.Domain/Services/VerificationServices/DeleteExpiresCode.cs b/Hotel.Domain/Services/VerificationServices/DeleteExpiresCode.cs index a5335d5..ff64f01 100644 --- a/Hotel.Domain/Services/VerificationServices/DeleteExpiresCode.cs +++ b/Hotel.Domain/Services/VerificationServices/DeleteExpiresCode.cs @@ -7,11 +7,13 @@ public partial class VerificationService { private readonly Timer _timer; private readonly DbContextOptions _dbContextOptions; + private readonly ILogger _logger; - public VerificationService(DbContextOptions options) + public VerificationService(Timer timer, DbContextOptions dbContextOptions, ILogger logger) { - _dbContextOptions = options; - _timer = new Timer(DeleteExpiredCodes, null, TimeSpan.Zero, TimeSpan.FromMinutes(20)); + _timer = timer; + _dbContextOptions = dbContextOptions; + _logger = logger; } private async void DeleteExpiredCodes(object? state) @@ -27,6 +29,7 @@ private async void DeleteExpiredCodes(object? state) { context.VerificationCodes.RemoveRange(expiredCodes); await context.SaveChangesAsync(); + _logger.LogInformation($"Foram excluidos {expiredCodes.Count} códigos de verificação expirados"); } } }