using NTP.Application.Common; using NTP.Domain.Grains.Registry; namespace NTP.Application.Grains.Registry; public interface IRegistryAttachmentService { Task UploadTempAsync(Stream content, string fileName, long length, CancellationToken ct = default); /// Verifies every temp id exists (so a save fails before anything is written). Returns the distinct ids. Task> EnsureTempFilesAsync(IEnumerable? tempIds, CancellationToken ct = default); /// Saves GRAINS_FILES rows and moves the temp files to the permanent folder (legacy genFileName + cffile rename). Task AttachAsync(string kind, long entityId, IReadOnlyList tempIds, CancellationToken ct = default); Task> ListAsync(string kind, long entityId, CancellationToken ct = default); Task OpenAsync(string kind, string fileName, CancellationToken ct = default); } public sealed class RegistryAttachmentService( IRegistryRepository repository, IRegistryFileStoreService store, IRegistrySettingsService settings) : IRegistryAttachmentService { public const string KindTruck = "truck"; public const string KindTrailer = "trailer"; public const string KindDriver = "driver"; private static (string Type, string Folder) Map(string kind) => kind.ToLowerInvariant() switch { KindTruck => (RegistryAttachmentTypes.TruckLicense, RegistryAttachmentTypes.TruckFolder), KindTrailer => (RegistryAttachmentTypes.TrailerLicense, RegistryAttachmentTypes.TrailerFolder), KindDriver => (RegistryAttachmentTypes.DriverLicense, RegistryAttachmentTypes.DriverFolder), _ => throw new NotFoundException("Attachment kind", kind) }; public async Task UploadTempAsync(Stream content, string fileName, long length, CancellationToken ct = default) { if (string.IsNullOrWhiteSpace(fileName) || length <= 0) throw new BusinessException(RegistryErrors.InvalidInput, RegistryMessages.RequiredFields); if (length > settings.MaxUploadBytes) throw new BusinessException(RegistryErrors.InvalidInput, "حجم الملف كبير جدا"); var ext = Path.GetExtension(fileName).TrimStart('.').ToLowerInvariant(); if (!settings.AllowedUploadExtensions.Contains(ext, StringComparer.OrdinalIgnoreCase)) throw new BusinessException(RegistryErrors.InvalidInput, "نوع الملف غير مسموح"); return await store.SaveTempAsync(content, Path.GetFileName(fileName), ct); } public async Task> EnsureTempFilesAsync(IEnumerable? tempIds, CancellationToken ct = default) { var ids = (tempIds ?? []).Where(x => !string.IsNullOrWhiteSpace(x)).Select(x => x.Trim()).Distinct().ToList(); foreach (var id in ids) if (await store.GetTempNameAsync(id, ct) is null) throw new BusinessException(RegistryErrors.AttachmentMissing, RegistryMessages.AttachmentsIncomplete); return ids; } public async Task AttachAsync(string kind, long entityId, IReadOnlyList tempIds, CancellationToken ct = default) { var (type, folder) = Map(kind); foreach (var id in tempIds) { var original = await store.GetTempNameAsync(id, ct) ?? throw new BusinessException(RegistryErrors.AttachmentMissing, RegistryMessages.AttachmentsIncomplete); var ext = Path.GetExtension(original); var stored = $"{Guid.NewGuid():N}{ext.ToLowerInvariant()}"; await repository.InsertFileAsync(type, entityId, original, stored, ct); await store.PromoteAsync(id, folder, stored, ct); } } public async Task> ListAsync(string kind, long entityId, CancellationToken ct = default) { var (type, _) = Map(kind); var files = await repository.GetFilesAsync(entityId, type, ct); return files.Select(f => new RegistryAttachmentDto { FileName = f.FileName, OriginalName = f.OriginalName, Kind = kind.ToLowerInvariant() }).ToList(); } public async Task OpenAsync(string kind, string fileName, CancellationToken ct = default) { var (type, folder) = Map(kind); // The name must be a registered file of this type (also keeps path traversal out). var row = await repository.FindFileAsync(type, fileName, ct) ?? throw new NotFoundException("Attachment", fileName); var stream = await store.OpenAsync(folder, row.FileName, ct) ?? throw new NotFoundException("Attachment", fileName); return new RegistryDownload(stream, ContentTypeOf(row.FileName), string.IsNullOrWhiteSpace(row.OriginalName) ? row.FileName : row.OriginalName); } private static string ContentTypeOf(string name) => Path.GetExtension(name).ToLowerInvariant() switch { ".pdf" => "application/pdf", ".png" => "image/png", ".jpg" or ".jpeg" => "image/jpeg", ".gif" => "image/gif", ".tif" or ".tiff" => "image/tiff", ".bmp" => "image/bmp", ".doc" => "application/msword", ".docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document", _ => "application/octet-stream" }; }