using System.Text; using Microsoft.EntityFrameworkCore; /// /// Ensures demo/seeded batches have ScannedDocument rows and placeholder PDF /// objects in MinIO so workstation document viewing does not 500. /// Idempotent — safe to run on every bootstrap. /// public static class SeedDocumentStorage { /// Minimal valid single-page PDF used as a seed placeholder. public static readonly byte[] MinimalPdf = Encoding.ASCII.GetBytes( "%PDF-1.4\n" + "1 0 obj<>endobj\n" + "2 0 obj<>endobj\n" + "3 0 obj<>endobj\n" + "xref\n0 4\n0000000000 65535 f \n0000000009 00000 n \n0000000052 00000 n \n0000000101 00000 n \n" + "trailer<>\nstartxref\n178\n%%EOF\n"); public static async Task EnsureAsync( AppDbContext db, IDocumentStorageService storage, ILogger logger, CancellationToken ct = default) { var batches = await db.DigitizationBatches .AsNoTracking() .Where(b => b.DocumentRef != "live-capture" && b.DocumentRef != "") .Select(b => new { b.Id, b.DocumentRef, b.DocumentSha256 }) .ToListAsync(ct); if (batches.Count == 0) return; var batchIds = batches.Select(b => b.Id).ToList(); var existingDocBatchIds = await db.ScannedDocuments .AsNoTracking() .Where(d => batchIds.Contains(d.BatchId)) .Select(d => d.BatchId) .ToListAsync(ct); var existingSet = existingDocBatchIds.ToHashSet(); var missingDocs = batches .Where(b => !existingSet.Contains(b.Id)) .Select(b => new ScannedDocument { Id = Guid.NewGuid(), BatchId = b.Id, ObjectKey = b.DocumentRef, Sha256 = NormalizeSha(b.DocumentSha256), ContentType = "application/pdf", FileSizeBytes = MinimalPdf.Length, UploadedAt = DateTimeOffset.UtcNow, }) .ToList(); if (missingDocs.Count > 0) { db.ScannedDocuments.AddRange(missingDocs); await db.SaveChangesAsync(ct); logger.LogInformation("Seeded {Count} missing ScannedDocument rows", missingDocs.Count); } var uploaded = 0; foreach (var batch in batches) { ct.ThrowIfCancellationRequested(); if (!await storage.ObjectExistsAsync(batch.DocumentRef)) { await storage.EnsureObjectAsync(batch.DocumentRef, MinimalPdf, "application/pdf"); uploaded++; } } if (uploaded > 0) logger.LogInformation("Uploaded {Count} placeholder scan PDFs to object storage", uploaded); } private static string NormalizeSha(string? sha) { if (string.IsNullOrWhiteSpace(sha)) return new string('0', 64); return sha.Length >= 64 ? sha[..64] : sha.PadRight(64, '0'); } }