using System.Diagnostics; using FluentStorage; using FluentStorage.Storage; using Microsoft.Extensions.Options; using Somnia.GuestLog.Enums.Models; using Somnia.GuestLog.Enums.Services; using Somnia.GuestLog.Models.Configuration; using Somnia.GuestLog.Models.DTOs; using Somnia.GuestLog.Models.QueryConfigs; using Somnia.GuestLog.Services.Entity; namespace Somnia.GuestLog.Services.StayExport; public class StayExportService( ILogger logger, IOptions exportConfig, IStayExportFileEntityService stayExportEntityService, IStayEntryEntityService stayEntityService, IStayExportFormatProviderFactory providerFactory ) : IStayExportService { private static readonly StayEntryQueryConfig queryConfig = new(IncludeGuests: true, UseSplitQueries: true, DisableTracking: true); private readonly StayExportConfig config = exportConfig.Value; public async Task> ExportStaysByParamsAsync(StayExportFormat format, StayExportParamsDTO exportParams) { //Get data to export. IEnumerable? stayList; try { stayList = await GetStaysToExportByParamsAsync(exportParams); } catch (Exception ex) { logger.LogError(ex, "JsonStayExportService - ExportStaysByParams: Error retriving stays to export!"); return Result.Fail(ResultCode.UnknownError); } //Create initial StayExportFile DateTime exportTime = DateTime.UtcNow; StayExportFileDTO stayExport = new() { ExportFormat = format, ExportParams = exportParams, ExportTime = exportTime, }; //Export data. using Stream exportedDataStream = new MemoryStream(); //Generate data to export. StayExportFileResult exportResult; string? exportFilename = null; try { //Create Format provider and export data to stream. var provider = providerFactory.GetProvider(format); (exportResult, List entriesDetails) = await provider.ExportDataAsync(stayList, exportedDataStream); stayExport.ExportDetails = new() { ExportedStayCount = entriesDetails.Count, StayErrorCount = entriesDetails.Count(e => e.ExportResult == StayExportDetailsStayEntryResult.Error), StayEntries = entriesDetails }; // "Rewind" stream so it can be read from the begining when uploading. exportedDataStream.Seek(0, SeekOrigin.Begin); exportFilename = provider.GetFilename(exportTime); } catch (Exception ex) { logger.LogError(ex, "JsonStayExportService - ExportStaysByParams: Error exporting data!"); exportResult = StayExportFileResult.ExportError; } //If data exported OK, save to file. if (exportResult == StayExportFileResult.OK) { try { Debug.Assert(exportFilename != null); string exportPathSubdir = ""; if (config.UseSubdirectoryByFormat) { exportPathSubdir = Enum.GetName(format) ?? ""; } string exportPath = Path.Combine(exportPathSubdir, exportFilename); //Store data. using IStore exportStore = GetExportStore(); await exportStore.SetObject(objectPath: exportPath, dataStream: exportedDataStream); //Update path in item. stayExport.ExportedPath = exportPath; } catch (Exception ex) { logger.LogError(ex, "JsonStayExportService - ExportStaysByParams: Error Uploading exported data!"); exportResult = StayExportFileResult.UploadError; } } //Store StayExport in DB. stayExport.ExportResult = exportResult; Result? createResult = null; try { createResult = await stayExportEntityService.CreateStayExportAsync(stayExport); } catch (Exception ex) { logger.LogError(ex, "JsonStayExportService - ExportStaysByParams: Error storing StayExportFile entity to DB: {stayExport}", stayExport); } //If everything is OK, return OK. if (createResult != null && createResult.ResultCode == ResultCode.Ok) { return Result.Ok(stayExport); } //Saving export to DB failed. Delete exported file (if exported) if (!string.IsNullOrEmpty(stayExport.ExportedPath)) { try { using IStore exportStore = GetExportStore(); await exportStore.DeleteObject(objectPath: stayExport.ExportedPath); } catch (Exception ex) { logger.LogError(ex, "JsonStayExportService - ExportStaysByParams: Error deleting exported file after db saving error: {exportedPath}", stayExport.ExportedPath); } } logger.LogError( "JsonStayExportService - ExportStaysByDateIn: Error (code '{code}') storing StayExportFile entity to DB: {stayExport}", createResult?.ResultCode, stayExport); return Result.Fail(ResultCode.UnknownError); } public async Task GetExportedFileAsync(StayExportFileDTO item, Stream dataStream) { if (string.IsNullOrEmpty(item.ExportedPath)) { logger.LogWarning("Trying to get exported file without path!! Exported file can't be loaded!"); return Result.Fail(ResultCode.NotFound); } try { IStore store = GetExportStore(); await store.GetObject(item.ExportedPath, dataStream); } catch (Exception ex) { logger.LogError(ex, "Error getting exported file '{id}' from path '{path}'", item.Id, item.ExportedPath); return Result.FailUnknownError(); } return Result.Ok(); } public async Task DeleteExportedFileAsync(StayExportFileDTO item) { //Try to delete existing file. if (!string.IsNullOrEmpty(item.ExportedPath)) { bool fileDeletedFromStore = await DeleteExportFileFromStoreAsync(item); if (!fileDeletedFromStore) { return Result.Fail(ResultCode.FileStorageError); } } //Delete entry from DB. Result deleteResult = await stayExportEntityService.DeleteStayExportAsync(item); if (!deleteResult.IsSuccess) { return Result.Fail(deleteResult.ResultCode); } return Result.Ok(); } #region Internal Methods private async Task> GetStaysToExportByParamsAsync(StayExportParamsDTO exportParams) { //Todo - Improve type selection (when there are more types). if (exportParams.ExportType == StayExportParamType.PeriodDateIn) { if (exportParams.ExportPeriodStart == null || exportParams.ExportPeriodEnd == null) { throw new InvalidOperationException($"StayExportFile - ExportType {exportParams.ExportType} require date start/end. Null dates found"); } //Get Stays in period -> Local time should be used so it match with entities local-time. StayEntryFilterDTO filter = new() { DateInStart = exportParams.ExportPeriodStart, DateInEnd = exportParams.ExportPeriodEnd }; return await stayEntityService.GetDtoListByFilterAsync(filter, limit: 0, queryConfig: queryConfig); } throw new InvalidOperationException($"StayExportFile - Error getting stays using params: export type invalid: {exportParams.ExportType}"); } private async Task DeleteExportFileFromStoreAsync(StayExportFileDTO item) { Debug.Assert(!string.IsNullOrEmpty(item.ExportedPath)); try { IStore store = GetExportStore(); bool objectExist = await store.ObjectExists(item.ExportedPath); if (!objectExist) { logger.LogWarning("StayExportService - File for item {id} not found in store! Skip delete!", item.Id); return true; } await store.DeleteObject(item.ExportedPath); logger.LogInformation("StayExportService - File for item {id} deleted from path {path}", item.Id, item.ExportedPath); return true; } catch (Exception ex) { logger.LogError(ex, "StayExportService - Error deleting export file of item {id}", item.Id); return false; } } private IStore GetExportStore() { string? storageConnString = config.ExportStorageConnectionString; if (string.IsNullOrEmpty(storageConnString)) { throw new InvalidOperationException("No Stay Export Storage configured. Stays can't be exported"); } return StorageFactory.FromConnectionString(storageConnString); } #endregion }