From b515f18ca93226c53d851b1f01c7be330b58da8db74cb4da93f1b66ffca026ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Garc=C3=ADa?= <93217193+Daniel-Garmig@users.noreply.github.com> Date: Sun, 11 Oct 2026 20:17:57 +0200 Subject: [PATCH] StayExport Tracking - StayEntry edit StayEntries now can be edited: - Implemented required entityService method. - Added UI for edit mode in StayEntry details page. --- .../Pages/GuestDocuments/GuestDocDetail.razor | 8 +- .../Pages/StayEntries/StayEntryDetail.razor | 149 ++++++++++++++---- .../Resources/LanguageLocale.es.resx | 12 +- .../Resources/LanguageLocale.resx | 10 +- .../Services/Entity/StayEntryEntityService.cs | 92 ++++++++++- 5 files changed, 223 insertions(+), 48 deletions(-) diff --git a/src/Somnia.GuestLog/Components/Pages/GuestDocuments/GuestDocDetail.razor b/src/Somnia.GuestLog/Components/Pages/GuestDocuments/GuestDocDetail.razor index 1d5872a..909518a 100644 --- a/src/Somnia.GuestLog/Components/Pages/GuestDocuments/GuestDocDetail.razor +++ b/src/Somnia.GuestLog/Components/Pages/GuestDocuments/GuestDocDetail.razor @@ -149,7 +149,7 @@ { Debug.Assert(_isEditMode == false); - userMessage.ShowMessage(LanguageLocale.page_GuestDocDetail_msgEditEnabled, MessageKind.Normal); + userMessage.ShowMessage(LanguageLocale.general_msgEditEnabled, MessageKind.Normal); _isEditMode = true; } @@ -158,7 +158,7 @@ Debug.Assert(_isEditMode == true); var result = await DialogService.ShowMessageBoxAsync( - LanguageLocale.general_confirmTitle, LanguageLocale.page_GuestDocDetail_msgConfirmCancelEdit, + LanguageLocale.general_confirmTitle, LanguageLocale.general_msgConfirmCancelEdit, yesText: "OK", cancelText: LanguageLocale.general_btnCancel); if (result == null || result.Value == false) @@ -179,7 +179,7 @@ Debug.Assert(_isEditMode == true && documentModel is not null); var confirmResult = await DialogService.ShowMessageBoxAsync( - LanguageLocale.general_confirmTitle, LanguageLocale.page_GuestDocDetail_msgConfirmSaveEdit, + LanguageLocale.general_confirmTitle, LanguageLocale.general_msgConfirmSaveEdit, yesText: "OK", cancelText: LanguageLocale.general_btnCancel); if (confirmResult == null || confirmResult.Value == false) @@ -195,7 +195,7 @@ Result updateResult = await guestDocService.UpdateDocumentAsync(documentModel); if (!updateResult.IsSuccess) { - string errorMsg = string.Format(LanguageLocale.page_GuestDocDetail_msgEditError, documentModel.FullDocument); + string errorMsg = string.Format(LanguageLocale.general_msgEditError, documentModel.FullDocument); userMessage.ShowResultWithMessage(updateResult, errorMsg); loadingDialog.Close(); return; diff --git a/src/Somnia.GuestLog/Components/Pages/StayEntries/StayEntryDetail.razor b/src/Somnia.GuestLog/Components/Pages/StayEntries/StayEntryDetail.razor index d676633..e00f790 100644 --- a/src/Somnia.GuestLog/Components/Pages/StayEntries/StayEntryDetail.razor +++ b/src/Somnia.GuestLog/Components/Pages/StayEntries/StayEntryDetail.razor @@ -19,40 +19,57 @@ @LanguageLocale.page_StayEntryDetail_pageTitle - "@StayId" - - @LanguageLocale.general_btnEdit - - - @LanguageLocale.general_btnReturn - + @if (_isEditMode) + { + + @LanguageLocale.general_btnCancel + + + @LanguageLocale.general_btnSave + + } + @if (!_isEditMode) + { + + @LanguageLocale.general_btnEdit + + + @LanguageLocale.general_btnReturn + + } @if (stayModel is not null) { - + - - - - - - - - - - - - - - @LanguageLocale.page_StayEntryList_btnUpdateUploadStatus - - - - + @if (!_isEditMode) + { + + + + + + + + + + + + + + @LanguageLocale.page_StayEntryList_btnUpdateUploadStatus + + + + + } } @@ -67,6 +84,10 @@ StayEntryDTO? stayModel = null; + private bool _isEditMode = false; + private FormMode _formFormMode => _isEditMode ? FormMode.Edit : FormMode.ReadOnly; + + protected override async Task OnInitializedAsync() { @* if (StayId is default) @@ -94,11 +115,77 @@ #region Event Handlers - private void BtnEdit() + private void BtnEnableEdit() { - userMessage.ShowMessage("Not implemented yet!", MessageKind.Info); + Debug.Assert(_isEditMode == false && stayModel != null); + + if (stayModel.StayUploadStatus == UploadStatus.Uploaded) + { + userMessage.ShowMessage(LanguageLocale.page_StayEntryDetail_cantEditFinalData, MessageKind.Info); + return; + } + + userMessage.ShowMessage(LanguageLocale.general_msgEditEnabled, MessageKind.Normal); + _isEditMode = true; } + private async Task BtnCancelEdit() + { + Debug.Assert(_isEditMode == true); + + var result = await DialogService.ShowMessageBoxAsync( + LanguageLocale.general_confirmTitle, LanguageLocale.general_msgConfirmCancelEdit, + yesText: "OK", cancelText: LanguageLocale.general_btnCancel); + + if (result == null || result.Value == false) + { + // Cancel cancel -> Continue with edit. + return; + } + + //Cancel edit -> Reload data from DB. + await LoadModelAsync(); + + userMessage.ShowMessage(LanguageLocale.general_msgEditCanceled, MessageKind.Normal); + _isEditMode = false; + } + + private async Task BtnSaveEdit() + { + Debug.Assert(_isEditMode == true && stayModel is not null); + + var confirmResult = await DialogService.ShowMessageBoxAsync( + LanguageLocale.general_confirmTitle, LanguageLocale.general_msgConfirmSaveEdit, + yesText: "OK", cancelText: LanguageLocale.general_btnCancel); + + if (confirmResult == null || confirmResult.Value == false) + { + // Cancel save -> Continue with edit. + return; + } + + //Show Loading dialog... + var loadingDialog = await DialogService.ShowAsync(); + + //Save edit. + Result updateResult = await stayService.UpdateEntryAsync(stayModel); + if (!updateResult.IsSuccess) + { + string errorMsg = string.Format(LanguageLocale.general_msgEditError, stayModel.Id); + userMessage.ShowResultWithMessage(updateResult, errorMsg); + loadingDialog.Close(); + return; + } + + //Reload data from DB. + await LoadModelAsync(); + loadingDialog.Close(); + userMessage.ShowMessage(LanguageLocale.general_msgEditSaved, MessageKind.Success); + + _isEditMode = false; + } + + private void BtnReturn() { string uri = ReturnUrl ?? GuestConsts.Page_StayEntry_List; diff --git a/src/Somnia.GuestLog/Resources/LanguageLocale.es.resx b/src/Somnia.GuestLog/Resources/LanguageLocale.es.resx index 5df4670..cb610c3 100644 --- a/src/Somnia.GuestLog/Resources/LanguageLocale.es.resx +++ b/src/Somnia.GuestLog/Resources/LanguageLocale.es.resx @@ -185,7 +185,7 @@ Volver Cerrar Buscar - Guaradar + Guardar Cancelar Continuar No hay resultados @@ -197,6 +197,10 @@ Cambios Guardados... ¡Edición cancelada! ¡Operación Cancelada! + Se ha entrado en modo edición + ¿Guardar los cambios? + ¿Desea cancelar y salir sin guardar?. ¡Se perderán los cambios! + Error al guardar los cambios para la entidad '{0}' Idioma Dirección @@ -249,11 +253,6 @@ ¡Ya existe un huésped con este documento! Ver huésped existente - Se ha entrado en modo edición - Guardar cambios en el documento - Cancelar edición. Se perderán los cambios - Error al guardar el documento '{0}' - Lista Estancias Lista Estancias Nueva Estancia @@ -261,6 +260,7 @@ Modificar Estado de envío Estancia + Esta estancia no se puede editar: Ya ha sido enviada Estado de envío modificado. Nuevo estado: '{0}' Nueva Estancia diff --git a/src/Somnia.GuestLog/Resources/LanguageLocale.resx b/src/Somnia.GuestLog/Resources/LanguageLocale.resx index 6a57778..4b8145d 100644 --- a/src/Somnia.GuestLog/Resources/LanguageLocale.resx +++ b/src/Somnia.GuestLog/Resources/LanguageLocale.resx @@ -197,6 +197,10 @@ Changes saved... Edit Canceled! Operation Canceled! + Entered Edit mode + Save changes + Cancel edit. Changes will be lost! + Error saving changes to db for entity '{0}' Language Address @@ -249,11 +253,6 @@ This Guest Document Already exists!! Go to existing document - Entered Edit mode - Save changes to GuestDocument - Cancel edit. Changes will be lost! - Error saving Document '{0}' - Stay Entries Entry List New Stay @@ -261,6 +260,7 @@ Update Upload Status Stay Entry + Stay can't be edited: it's already uploaded! Upload status updated. New Status: '{0}' New Stay diff --git a/src/Somnia.GuestLog/Services/Entity/StayEntryEntityService.cs b/src/Somnia.GuestLog/Services/Entity/StayEntryEntityService.cs index 50dc44a..0713c30 100644 --- a/src/Somnia.GuestLog/Services/Entity/StayEntryEntityService.cs +++ b/src/Somnia.GuestLog/Services/Entity/StayEntryEntityService.cs @@ -1,3 +1,4 @@ +using FluentStorage.Utils.Extensions; using FluentValidation; using Microsoft.EntityFrameworkCore; using Somnia.GuestLog.Enums.Models; @@ -79,9 +80,91 @@ public class StayEntryEntityService( } } - public Task UpdateEntryAsync(StayEntryDTO updatedDto) + public async Task UpdateEntryAsync(StayEntryDTO updatedDto) { - throw new NotImplementedException(); + var valResult = dtoValidator.Validate(updatedDto); + if (!valResult.IsValid) + { + logger.LogWarning("StayEntryService - UpdateEntryAsync: Dto validation failed. Fix the errors: {errorList}", valResult.Errors); + return Result.Fail(ResultCode.FailedValidation); + } + + try + { + using var dbContext = contextFactory.CreateDbContext(); + //Get current entity from DB. + StayEntry? dbItem = await dbContext.StayEntries + .Where(e => e.Id == updatedDto.Id) + .Include(e => e.GuestDocuments) + .SingleAsync(); + + if (dbItem == null) + { + logger.LogWarning("StayEntryService - UpdateEntryAsync: Error updating StayEntry (ID: '{id}'): StayEntry not found!", updatedDto.Id); + return Result.Fail(ResultCode.NotFound); + } + + if (dbItem.StayUploadStatus == UploadStatus.Uploaded) + { + logger.LogWarning("StayEntryService - UpdateEntryAsync: StayEntry (ID: '{id}') can't be updated: StayEntry is already uploaded!", updatedDto.Id); + return Result.Fail(ResultCode.DataIsFinal); + } + + DateTime updateTime = DateTime.UtcNow; + StayEntry updatedItem = new() + { + Id = dbItem.Id, + DateIn = updatedDto.DateIn!.Value.ToUniversalTime(), + DateOut = updatedDto.DateOut!.Value.ToUniversalTime(), + RoomCount = updatedDto.RoomCount!.Value, + RoomNumber = updatedDto.RoomNumber, + PaymentMethod = updatedDto.PaymentMethod!, + StayUploadStatus = dbItem.StayUploadStatus, + StayUploadStatusTime = dbItem.StayUploadStatusTime, + CreateTime = dbItem.CreateTime, + UpdateTime = updateTime, + }; + dbContext.Entry(dbItem).CurrentValues.SetValues(updatedItem); + + //Update GuestDocuments + if (updatedDto.GuestDocuments != null) + { + var updatedGuestDocIdList = updatedDto.GuestDocuments.Select(e => e.Id); + List updatedDbGuests = await dbContext.GuestDocuments + .Where(e => updatedGuestDocIdList.Contains(e.Id)) + .ToListAsync(); + + foreach (GuestDocument guest in updatedDbGuests) + { + //Skip check for guests already in the stay. + if (dbItem.GuestDocuments.Any(e => e.Id == guest.Id)) + { + continue; + } + + //Check if Guest is already in other stay during the same period. + bool isInOtherStay = await this.IsGuestInStayInPeriod(guest.Id, updatedItem.DateIn, updatedItem.DateOut); + if (isInOtherStay) + { + string period = $"{updatedItem.DateIn}-{updatedItem.DateOut}"; + return Result.FailWithContext(ResultCode.GuestCurrentlyInStay, guest.FullDocument, period); + } + } + + dbItem.GuestDocuments.Clear(); + dbItem.GuestDocuments.AddRange(updatedDbGuests); + } + + var result = await dbContext.SaveChangesAsync(); + logger.LogInformation("StayEntryService - UpdateEntryAsync: StayEntry Updated OK {id}", dbItem.GetFullKey()); + + return Result.Ok(); + } + catch (Exception ex) + { + logger.LogError(ex, "StayEntryService - UpdateEntryAsync: Error updating StayEntry: '{id}'", updatedDto.Id); + return Result.FailUnknownError(); + } } public async Task DeleteEntryAsync(StayEntryDTO dto) @@ -260,5 +343,10 @@ public class StayEntryEntityService( return EntityMapping.MapStayEntryEntityToDTO(dbItem, queryConfig.IncludeGuests); } + private static string? GetValueOrNull(string? dtoValue) + { + return string.IsNullOrWhiteSpace(dtoValue) ? null : dtoValue; + } + #endregion } \ No newline at end of file