using System.Data.Common; using System.Globalization; using System.Text.RegularExpressions; using Khaemhat.Application.Audit; using Khaemhat.Application.Instance; using Khaemhat.Application.Security; using Khaemhat.Core.Files; using Khaemhat.Data; using Khaemhat.Data.Querying; using Khaemhat.Infrastructure.Files; namespace Khaemhat.Application.Files; /// An attachment as the interface shows it. /// The identifier. /// The entity of the owning record. /// The owning record. /// Uploaded, generated, e-invoice or notification. /// The name. /// The download name, with the version suffix from v2 (fattura_v2.pdf). /// The media type. /// The size in bytes. /// The SHA-256 of the content. /// The version, from 1. /// The generator code (generated files). /// Whether it is locked (cannot be deleted). /// Whether it is the latest version of its series. /// When it was uploaded or generated (UTC). /// Who uploaded or generated it. /// When it was moved to the trash; if in use. public sealed record AttachmentView( long Id, string Entity, long EntityId, AttachmentKind Kind, string Name, string FileName, string Mime, long Size, string Sha256, int Version, string? GeneratedBy, bool Locked, bool IsLatest, DateTime CreatedAt, string? CreatedBy, DateTime? DeletedAt) { /// How the interface can preview the file. public AttachmentPreview Preview => MediaTypes.PreviewOf(Mime); /// The version label, v1, v2... public string VersionLabel => "v" + Version.ToString(CultureInfo.InvariantCulture); /// The view of a row. /// The row. /// Whether it is the latest of its series. /// The view. public static AttachmentView From(Attachment row, bool isLatest) { ArgumentNullException.ThrowIfNull(row); return new AttachmentView( row.Id, row.Entity, row.EntityId, row.Kind, row.Name, MediaTypes.VersionedFileName(row.Name, row.Version), row.Mime, row.Size, row.Sha256, row.Version, row.GeneratedBy, row.Locked, isLatest, row.CreatedAt, row.UserName ?? row.CreatedBy, row.DeletedAt); } } /// An open attachment: its description and its content. Dispose it to close the file. /// The attachment. /// The content, a read-only seekable stream. public sealed class AttachmentContent(AttachmentView attachment, Stream content) : IAsyncDisposable, IDisposable { /// The attachment. public AttachmentView Attachment { get; } = attachment; /// The content. public Stream Content { get; } = content; /// public ValueTask DisposeAsync() => Content.DisposeAsync(); /// public void Dispose() => Content.Dispose(); } /// A file to attach that is not uploaded by a user: an e-invoice, a notification, a file from a procedure. /// The kind. /// The file name. /// The media type; from the extension when . /// The procedure that produced it: the versions count per this code when set, per name otherwise. /// Whether it is locked from the start (for example the XML sent to the SDI). public sealed record AttachmentFile(AttachmentKind Kind, string FileName, string? Mime = null, string? GeneratedBy = null, bool Locked = false); /// /// The attachments of the company records (SPEC ยง9.4; wiki Allegati e file): upload, generated files with /// versions, list, download, ZIP of all, lock, trash and restore. An attachment belongs to exactly one record /// (entity + entity_id); its bytes are in the , its row in attachments, /// and every change writes the history (). /// /// /// Permissions: reading needs attachments.read, uploading, generating and locking attachments.write, /// deleting and restoring attachments.delete. The permission on the owning record is checked by the caller (the /// document service or page), which knows it. A company user works only in its own company. Deleting moves to the /// company trash; removes rows and files 30 days later. /// public sealed partial class AttachmentService { /// Permission to see and download attachments. public const string ReadPermission = "attachments.read"; /// Permission to upload and generate attachments. public const string WritePermission = "attachments.write"; /// Permission to delete and restore attachments. public const string DeletePermission = "attachments.delete"; /// The instance setting with the largest upload in MB (default 25). public const string MaxUploadSetting = "files.max-upload-mb"; /// The instance setting with the space each company may use in MB (default: no quota). public const string CompanyQuotaSetting = "files.company-quota-mb"; /// Error: no such attachment (or not in this company). public const string NotFoundError = "attachments.not_found"; /// Error: the attachment is locked. public const string LockedError = "attachments.locked"; /// Error: the file is larger than the limit. public const string TooLargeError = "attachments.file_too_large"; /// Error: the company has no space left. public const string QuotaError = "attachments.quota_exceeded"; /// Error: the scanner rejected the file. public const string RejectedError = "attachments.file_rejected"; /// Error: the entity or record is not valid. public const string InvalidOwnerError = "attachments.owner_invalid"; /// Error: the file is empty. public const string EmptyError = "attachments.file_empty"; /// How long attachments stay in the trash. public static readonly TimeSpan TrashRetention = TimeSpan.FromDays(30); private const int MaxVersionAttempts = 3; private const long Megabyte = 1024 * 1024; private readonly IUnitOfWorkFactory _factory; private readonly IFileStore _store; private readonly PermissionService _permissions; private readonly AuditTrail _audit; private readonly SystemSettingsStore _settings; private readonly FileStoreOptions _options; private readonly TimeProvider _clock; /// Creates the service. /// Opens the company databases. /// The file store. /// Checks permissions. /// Writes the history. /// Reads the limits set by the administrators. /// The default limits. /// The clock (trash dates). public AttachmentService( IUnitOfWorkFactory factory, IFileStore store, PermissionService permissions, AuditTrail audit, SystemSettingsStore settings, FileStoreOptions options, TimeProvider clock) { ArgumentNullException.ThrowIfNull(factory); ArgumentNullException.ThrowIfNull(store); ArgumentNullException.ThrowIfNull(permissions); ArgumentNullException.ThrowIfNull(audit); ArgumentNullException.ThrowIfNull(settings); ArgumentNullException.ThrowIfNull(options); ArgumentNullException.ThrowIfNull(clock); _factory = factory; _store = store; _permissions = permissions; _audit = audit; _settings = settings; _options = options; _clock = clock; } /// The limits in force: the instance settings, else the store defaults (25 MB, no quota). /// Cancellation. /// The limits for uploads. public async Task GetLimitsAsync(CancellationToken cancellationToken = default) { var max = await ReadMegabytesAsync(MaxUploadSetting, cancellationToken).ConfigureAwait(false) ?? _options.MaxFileBytes; var quota = await ReadMegabytesAsync(CompanyQuotaSetting, cancellationToken).ConfigureAwait(false) ?? _options.CompanyQuotaBytes; return new FileLimits(max, quota); } /// Uploads a file to a record (streaming; the size limit and the quota apply). /// Who uploads. /// The company. /// The entity of the record, for example sales.invoice. /// The record. /// The file name as received. /// The type declared by the client (used only when the extension is unknown). /// The content. /// Cancellation. /// The new attachment; a file with the same name as an existing one becomes its next version. /// The actor may not upload. /// The file is empty, too large, over quota or rejected. public async Task UploadAsync( Actor actor, string companyCode, string entity, long entityId, string fileName, string? declaredMime, Stream content, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(content); var company = await DemandAsync(actor, companyCode, WritePermission, cancellationToken).ConfigureAwait(false); CheckOwner(entity, entityId); var limits = await GetLimitsAsync(cancellationToken).ConfigureAwait(false); var stored = await StoreAsync(company, limits, (target, ct) => content.CopyToAsync(target, ct), cancellationToken).ConfigureAwait(false); var name = MediaTypes.CleanFileName(fileName); return await RecordAsync(actor, company, entity, entityId, new AttachmentFile(AttachmentKind.Uploaded, name, MediaTypes.Resolve(name, declaredMime)), stored, cancellationToken).ConfigureAwait(false); } /// /// Adds a file produced by Khaemhat, written by straight into the store. Each call adds /// the next version of the series of (or of the name): this is "Rigenera". /// /// Who generates. /// The company. /// The entity of the record. /// The record. /// Kind, name, type, generator, lock. /// Writes the content to the stream it receives (write-only, not seekable). /// Cancellation. /// The new attachment. /// The actor may not add attachments. /// The company has no space left, or the file is empty. public async Task AddAsync( Actor actor, string companyCode, string entity, long entityId, AttachmentFile file, Func write, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(file); ArgumentNullException.ThrowIfNull(write); var company = await DemandAsync(actor, companyCode, WritePermission, cancellationToken).ConfigureAwait(false); CheckOwner(entity, entityId); if (file.GeneratedBy is { } generator && (generator.Length is 0 or > 100)) { throw new ValidationFailedException([InvalidOwnerError]); } // Files made by Khaemhat are bounded by their generator: only the quota applies. var limits = await GetLimitsAsync(cancellationToken).ConfigureAwait(false); var stored = await StoreAsync(company, new FileLimits(0, limits.QuotaBytes), write, cancellationToken).ConfigureAwait(false); var name = MediaTypes.CleanFileName(file.FileName); var normalized = file with { FileName = name, Mime = MediaTypes.Resolve(name, file.Mime) }; return await RecordAsync(actor, company, entity, entityId, normalized, stored, cancellationToken).ConfigureAwait(false); } /// The attachments of a record, newest first (trash excluded). /// Who reads. /// The company. /// The entity. /// The record. /// Whether to list the earlier versions too (marked not ). /// Cancellation. /// The attachments. public async Task> ListAsync( Actor actor, string companyCode, string entity, long entityId, bool includeOlderVersions = false, CancellationToken cancellationToken = default) { var company = await DemandAsync(actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false); return Views(await ListRowsAsync(company, entity, entityId, cancellationToken).ConfigureAwait(false), includeOlderVersions); } /// How many attachments a record has (latest versions only): the number on the toolbar icon. /// Who reads. /// The company. /// The entity. /// The record. /// Cancellation. /// The count. public async Task CountAsync(Actor actor, string companyCode, string entity, long entityId, CancellationToken cancellationToken = default) => (await ListAsync(actor, companyCode, entity, entityId, false, cancellationToken).ConfigureAwait(false)).Count; /// One attachment, in use or in the trash. /// Who reads. /// The company. /// The attachment. /// Cancellation. /// The attachment, or . public async Task GetAsync(Actor actor, string companyCode, long attachmentId, CancellationToken cancellationToken = default) { var company = await DemandAsync(actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false); return (await LoadAsync(company, attachmentId, cancellationToken).ConfigureAwait(false))?.View; } /// Opens an attachment for download or preview. /// Who reads. /// The company. /// The attachment. /// Cancellation. /// The attachment and its content; dispose it. /// No such attachment in use, or its file is missing. public async Task OpenAsync(Actor actor, string companyCode, long attachmentId, CancellationToken cancellationToken = default) { var company = await DemandAsync(actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false); var loaded = await LoadAsync(company, attachmentId, cancellationToken).ConfigureAwait(false); if (loaded is not { } found || found.Row.DeletedAt is not null) { throw new KeyNotFoundException(NotFoundError); } var (row, view) = found; try { return new AttachmentContent(view, _store.OpenRead(company, row.StorageKey)); } catch (FileStoreException ex) when (ex.Code == FileStoreException.NotFound) { throw new KeyNotFoundException(NotFoundError, ex); } } /// /// Writes a ZIP with the latest version of every attachment of a record ("Scarica tutto"), streaming: the output /// can be the HTTP response. /// /// Who downloads. /// The company. /// The entity. /// The record. /// The stream that receives the ZIP; it is left open. /// Cancellation. /// How many files were written. public async Task WriteZipAsync(Actor actor, string companyCode, string entity, long entityId, Stream output, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(output); var company = await DemandAsync(actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false); var rows = await ListRowsAsync(company, entity, entityId, cancellationToken).ConfigureAwait(false); var keys = rows.ToDictionary(r => r.Id, r => r.StorageKey); await using var zip = await ZipStreamWriter.CreateAsync(output, leaveOpen: true, cancellationToken).ConfigureAwait(false); foreach (var attachment in Views(rows, includeOlderVersions: false)) { var key = keys[attachment.Id]; if (!_store.Exists(company, key)) { continue; } var content = _store.OpenRead(company, key); await using (content.ConfigureAwait(false)) { var level = attachment.Mime is "image/jpeg" or "image/png" or MediaTypes.Zip or MediaTypes.Xlsx ? System.IO.Compression.CompressionLevel.NoCompression : System.IO.Compression.CompressionLevel.Optimal; await zip.AddAsync(attachment.FileName, content, new DateTimeOffset(DateTime.SpecifyKind(attachment.CreatedAt, DateTimeKind.Utc)), level, cancellationToken).ConfigureAwait(false); } } return zip.Count; } /// Locks an attachment: from now on it cannot be deleted (for example the XML sent to the SDI). Locks are permanent. /// Who locks. /// The company. /// The attachment. /// Cancellation. /// A task. public Task LockAsync(Actor actor, string companyCode, long attachmentId, CancellationToken cancellationToken = default) => ChangeAsync( actor, companyCode, attachmentId, WritePermission, row => { if (row.Locked) { return false; } row.Locked = true; return true; }, cancellationToken); /// Moves one attachment to the company trash (restorable for 30 days). /// Who deletes. /// The company. /// The attachment. /// Cancellation. /// A task. /// The attachment is locked (). public Task DeleteAsync(Actor actor, string companyCode, long attachmentId, CancellationToken cancellationToken = default) { var now = _clock.GetUtcNow().UtcDateTime; return ChangeAsync( actor, companyCode, attachmentId, DeletePermission, row => { if (row.Locked) { throw new ValidationFailedException([LockedError]); } if (row.DeletedAt is not null) { return false; } row.DeletedAt = now; return true; }, cancellationToken); } /// Takes an attachment back from the trash. /// Who restores. /// The company. /// The attachment. /// Cancellation. /// A task. public Task RestoreAsync(Actor actor, string companyCode, long attachmentId, CancellationToken cancellationToken = default) => ChangeAsync( actor, companyCode, attachmentId, DeletePermission, row => { if (row.DeletedAt is null) { return false; } row.DeletedAt = null; return true; }, cancellationToken); /// /// Moves every attachment of a record to the trash: call it in the deletion of the record (the caller has checked /// that the record may be deleted). Refused when an attachment is locked: a record with a sent e-invoice cannot go. /// /// Who deletes the record. /// The company. /// The entity. /// The record. /// Cancellation. /// How many attachments were moved. /// An attachment is locked (). public Task TrashForEntityAsync(Actor actor, string companyCode, string entity, long entityId, CancellationToken cancellationToken = default) => ChangeEntityAsync(actor, companyCode, entity, entityId, toTrash: true, cancellationToken); /// Takes back from the trash every attachment of a record (the record was restored). /// Who restores. /// The company. /// The entity. /// The record. /// Cancellation. /// How many attachments were restored. public Task RestoreForEntityAsync(Actor actor, string companyCode, string entity, long entityId, CancellationToken cancellationToken = default) => ChangeEntityAsync(actor, companyCode, entity, entityId, toTrash: false, cancellationToken); /// The company trash, most recently deleted first. /// Who looks (needs attachments.delete). /// The company. /// Cancellation. /// The attachments in the trash. public async Task> ListTrashAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default) { var company = await DemandAsync(actor, companyCode, DeletePermission, cancellationToken).ConfigureAwait(false); await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); var rows = (await unitOfWork.Repository().ListAsync( Query.For().Where(a => a.DeletedAt != null).OrderByDescending(a => a.DeletedAt).Take(1000), cancellationToken).ConfigureAwait(false)).Items; return rows.Select(r => AttachmentView.From(r, isLatest: false)).ToList(); } /// The space the company uses in the file store, with the quota in force. /// Who looks. /// The company. /// Cancellation. /// The usage. public async Task GetUsageAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default) { var company = await DemandAsync(actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false); var limits = await GetLimitsAsync(cancellationToken).ConfigureAwait(false); return await _store.GetUsageAsync(company, limits.QuotaBytes, cancellationToken).ConfigureAwait(false); } /// /// Removes for good the attachments in the trash for more than 30 days, rows and files, and the partial files of /// interrupted uploads. Run by the scheduled job . /// /// The company. /// Cancellation. /// How many attachments were removed. public async Task PurgeTrashAsync(string companyCode, CancellationToken cancellationToken = default) { var company = CompanyCodes.Normalize(companyCode); var limit = _clock.GetUtcNow().UtcDateTime - TrashRetention; await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); var repository = unitOfWork.Repository(); var rows = (await repository.ListAsync(Query.For().Where(a => a.DeletedAt != null && a.DeletedAt < limit), cancellationToken).ConfigureAwait(false)).Items; var removed = 0; foreach (var row in rows) { await unitOfWork.InTransactionAsync( async ct => { await repository.DeleteAsync(row.Id, ct).ConfigureAwait(false); await _audit.RecordAsync(unitOfWork, AuditAction.Delete, row.Id, row, null, Actor.System.UserName, ct).ConfigureAwait(false); }, cancellationToken).ConfigureAwait(false); // The row is gone: the file follows (a file left behind by a crash here is only wasted space). if (!await StorageKeyInUseAsync(repository, row.StorageKey, cancellationToken).ConfigureAwait(false)) { _store.Delete(company, row.StorageKey); } removed++; } _store.DeleteAbandonedParts(company, TimeSpan.FromDays(1)); return removed; } private static List Views(IReadOnlyList rows, bool includeOlderVersions) { var latest = rows.GroupBy(r => r.VersionKey, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.Max(r => r.Version), StringComparer.Ordinal); return rows .Select(r => AttachmentView.From(r, r.Version == latest[r.VersionKey])) .Where(v => includeOlderVersions || v.IsLatest) .ToList(); } private static void CheckOwner(string entity, long entityId) { if (entity is null || entity.Length > 100 || !EntityPattern().IsMatch(entity) || entityId <= 0) { throw new ValidationFailedException([InvalidOwnerError]); } } private static string VersionKeyOf(AttachmentFile file) => file.GeneratedBy is { } generator ? "gen:" + generator : "name:" + file.FileName.ToLowerInvariant(); private static async Task IsLatestAsync(IUnitOfWork unitOfWork, Attachment row, CancellationToken cancellationToken) { var (entity, id, key, version) = (row.Entity, row.EntityId, row.VersionKey, row.Version); return await unitOfWork.Repository().CountAsync( Query.For().Where(a => a.Entity == entity && a.EntityId == id && a.VersionKey == key && a.Version > version), cancellationToken).ConfigureAwait(false) == 0; } private static async Task StorageKeyInUseAsync(IRepository repository, string key, CancellationToken cancellationToken) => await repository.CountAsync(Query.For().Where(a => a.StorageKey == key), cancellationToken).ConfigureAwait(false) > 0; [GeneratedRegex("^[a-z][a-z0-9_]*(\\.[a-z][a-z0-9_-]*)*$", RegexOptions.CultureInvariant)] private static partial Regex EntityPattern(); private async Task DemandAsync(Actor actor, string companyCode, string permission, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(actor); var company = CompanyCodes.Normalize(companyCode); if (!actor.IsInstanceAccount && !string.Equals(actor.CompanyCode, company, StringComparison.Ordinal)) { throw new AccessDeniedException(SecurityErrors.PermissionDenied, "A company user works only in its own company."); } await _permissions.DemandAsync(actor, permission, cancellationToken).ConfigureAwait(false); return company; } private async Task ReadMegabytesAsync(string key, CancellationToken cancellationToken) { var value = await _settings.GetAsync(key, cancellationToken).ConfigureAwait(false); return long.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var megabytes) && megabytes >= 0 ? megabytes * Megabyte : null; } private async Task StoreAsync(string company, FileLimits limits, Func write, CancellationToken cancellationToken) { try { await using var writer = await _store.CreateAsync(company, limits, cancellationToken).ConfigureAwait(false); await write(writer.Content, cancellationToken).ConfigureAwait(false); if (writer.Content.Length == 0) { throw new ValidationFailedException([EmptyError]); } return await writer.CommitAsync(cancellationToken).ConfigureAwait(false); } catch (FileStoreException ex) { var code = ex.Code switch { FileStoreException.TooLarge => TooLargeError, FileStoreException.QuotaExceeded => QuotaError, _ => RejectedError, }; throw new ValidationFailedException(code, ex); } } private async Task RecordAsync( Actor actor, string company, string entity, long entityId, AttachmentFile file, StoredFile stored, CancellationToken cancellationToken) { var key = VersionKeyOf(file); try { for (var attempt = 1; ; attempt++) { try { return await InsertAsync(actor, company, entity, entityId, file, key, stored, cancellationToken).ConfigureAwait(false); } catch (DbException) when (attempt < MaxVersionAttempts) { // Two versions of the same series at once: the unique index refused one; take the next number. } } } catch { _store.Delete(company, stored.Key); throw; } } private async Task InsertAsync( Actor actor, string company, string entity, long entityId, AttachmentFile file, string key, StoredFile stored, CancellationToken cancellationToken) { await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); var repository = unitOfWork.Repository(); Attachment? row = null; await unitOfWork.InTransactionAsync( async ct => { var last = await repository.FindAsync( Query.For().Where(a => a.Entity == entity && a.EntityId == entityId && a.VersionKey == key).OrderByDescending(a => a.Version).Take(1), ct).ConfigureAwait(false); row = new Attachment { Entity = entity, EntityId = entityId, Kind = file.Kind, Name = file.FileName, Mime = file.Mime ?? MediaTypes.OctetStream, Size = stored.Size, Sha256 = stored.Sha256, Version = (last?.Version ?? 0) + 1, VersionKey = key, GeneratedBy = file.GeneratedBy, StorageKey = stored.Key, UserName = actor.UserName.Length > 100 ? actor.UserName[..100] : actor.UserName, Locked = file.Locked, }; await repository.InsertAsync(row, ct).ConfigureAwait(false); await _audit.RecordAsync(unitOfWork, AuditAction.Insert, row.Id, null, row, actor.UserName, ct).ConfigureAwait(false); }, cancellationToken).ConfigureAwait(false); return AttachmentView.From(row!, isLatest: true); } private async Task ChangeAsync(Actor actor, string companyCode, long attachmentId, string permission, Func change, CancellationToken cancellationToken) { var company = await DemandAsync(actor, companyCode, permission, cancellationToken).ConfigureAwait(false); await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); var repository = unitOfWork.Repository(); await unitOfWork.InTransactionAsync( async ct => { var row = await repository.GetAsync(attachmentId, ct).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotFoundError); var before = Copy(row); if (change(row)) { await repository.UpdateAsync(row, ct).ConfigureAwait(false); await _audit.RecordAsync(unitOfWork, AuditAction.Update, row.Id, before, row, actor.UserName, ct).ConfigureAwait(false); } }, cancellationToken).ConfigureAwait(false); } private async Task ChangeEntityAsync(Actor actor, string companyCode, string entity, long entityId, bool toTrash, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(actor); var company = CompanyCodes.Normalize(companyCode); if (!actor.IsInstanceAccount && !string.Equals(actor.CompanyCode, company, StringComparison.Ordinal)) { throw new AccessDeniedException(SecurityErrors.PermissionDenied, "A company user works only in its own company."); } CheckOwner(entity, entityId); var now = _clock.GetUtcNow().UtcDateTime; var changed = 0; await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); var repository = unitOfWork.Repository(); await unitOfWork.InTransactionAsync( async ct => { var query = toTrash ? Query.For().Where(a => a.Entity == entity && a.EntityId == entityId && a.DeletedAt == null) : Query.For().Where(a => a.Entity == entity && a.EntityId == entityId && a.DeletedAt != null); var rows = (await repository.ListAsync(query, ct).ConfigureAwait(false)).Items; if (toTrash && rows.Any(r => r.Locked)) { throw new ValidationFailedException([LockedError]); } foreach (var row in rows) { var before = Copy(row); row.DeletedAt = toTrash ? now : null; await repository.UpdateAsync(row, ct).ConfigureAwait(false); await _audit.RecordAsync(unitOfWork, AuditAction.Update, row.Id, before, row, actor.UserName, ct).ConfigureAwait(false); changed++; } }, cancellationToken).ConfigureAwait(false); return changed; } private async Task> ListRowsAsync(string company, string entity, long entityId, CancellationToken cancellationToken) { await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); return (await unitOfWork.Repository().ListAsync( Query.For().Where(a => a.Entity == entity && a.EntityId == entityId && a.DeletedAt == null).OrderByDescending(a => a.Id), cancellationToken).ConfigureAwait(false)).Items; } private async Task<(Attachment Row, AttachmentView View)?> LoadAsync(string company, long attachmentId, CancellationToken cancellationToken) { await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); var row = await unitOfWork.Repository().GetAsync(attachmentId, cancellationToken).ConfigureAwait(false); return row is null ? null : (row, AttachmentView.From(row, await IsLatestAsync(unitOfWork, row, cancellationToken).ConfigureAwait(false))); } private static Attachment Copy(Attachment row) => new() { Id = row.Id, Entity = row.Entity, EntityId = row.EntityId, Kind = row.Kind, Name = row.Name, Mime = row.Mime, Size = row.Size, Sha256 = row.Sha256, Version = row.Version, VersionKey = row.VersionKey, GeneratedBy = row.GeneratedBy, StorageKey = row.StorageKey, UserName = row.UserName, Locked = row.Locked, DeletedAt = row.DeletedAt, }; }