using Leiren.Erp.Application.Files; using Leiren.Erp.Contracts; namespace Leiren.Erp.Application.Documents; /// Optional metadata supplied alongside an uploaded CI/PL template. public sealed record DocumentTemplateUploadOptions( string? Name, string? DocumentKind, Guid? CustomerId, string? UploadedBy, Guid? UploadedByUserId = null); /// /// Stores customer CI/PL .xlsx templates through /// (content on the server filesystem, metadata in the database) and scans /// them for placeholders. Scanning happens before storage, so an unreadable /// workbook or a template without any placeholder never leaves an orphan /// file behind. No template entity is kept here: the stored file group is /// the logical template and each file version is one immutable template /// version, referenced by its file id. /// public sealed class DocumentTemplateService(FileService files, FileStorageOptions storageOptions) { public const string TemplateOwnerType = "DocumentTemplate"; public async Task UploadAsync( Stream content, string? originalFileName, string? contentType, DocumentTemplateUploadOptions options, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(content); ArgumentNullException.ThrowIfNull(options); var bytes = await ReadTemplateBytesAsync(content, originalFileName, ct); var scan = ScanBytes(bytes); await using var stored = new MemoryStream(bytes, writable: false); var file = await files.UploadAsync(new UploadFileCommand( OwnerType: TemplateOwnerType, OwnerId: options.CustomerId ?? Guid.NewGuid(), Category: RequireKind(options.DocumentKind), Description: NormalizeOptional(options.Name, 1000, nameof(options.Name)), OriginalFileName: originalFileName, ContentType: contentType, Content: stored, UploadedByUserId: options.UploadedByUserId, UploadedBy: options.UploadedBy), ct); return ToResult(file, options.Name, options.DocumentKind, options.CustomerId, scan); } /// Stores a new immutable version of the template the given file version belongs to. public async Task UploadNewVersionAsync( Guid fileId, Stream content, string? originalFileName, string? contentType, DocumentTemplateUploadOptions options, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(content); ArgumentNullException.ThrowIfNull(options); var existing = await files.GetAsync(fileId, ct); EnsureTemplateFile(existing); var bytes = await ReadTemplateBytesAsync(content, originalFileName, ct); var scan = ScanBytes(bytes); await using var stored = new MemoryStream(bytes, writable: false); var file = await files.UploadNewVersionAsync( fileId, stored, originalFileName, contentType, options.DocumentKind is null ? existing.Category : RequireKind(options.DocumentKind), NormalizeOptional(options.Name, 1000, nameof(options.Name)) ?? existing.Description, options.UploadedByUserId, options.UploadedBy, ct); return ToResult(file, options.Name ?? existing.Description, options.DocumentKind ?? existing.Category, options.CustomerId, scan); } /// Re-scans an already stored template file version. public async Task ScanStoredAsync(Guid fileId, CancellationToken ct = default) { var file = await files.GetAsync(fileId, ct); EnsureTemplateFile(file); var download = await files.OpenDownloadAsync(fileId, ct); await using var content = download.Content; var bytes = await ReadTemplateBytesAsync(content, file.OriginalFileName, ct); var scan = ScanBytes(bytes); return ToResult(file, file.Description, file.Category, null, scan); } private static TemplateScanResult ScanBytes(byte[] bytes) { var scan = TemplatePlaceholderScanner.Scan(bytes); if (scan.Placeholders.Count == 0) { var detail = scan.Warnings.Count > 0 ? string.Join(" ", scan.Warnings) : null; throw new DocumentTemplateValidationException( "file", "模板中未找到任何 {{...}} 占位符,无法导入。" + (detail is null ? string.Empty : $" {detail}")); } return scan; } private async Task ReadTemplateBytesAsync(Stream content, string? originalFileName, CancellationToken ct) { var extension = Path.GetExtension(FileService.SanitizeFileName(originalFileName)).ToLowerInvariant(); if (extension != ".xlsx") { throw new DocumentTemplateValidationException( "file", "模板必须是 .xlsx 文件。"); } var maxBytes = storageOptions.MaxFileSizeBytes > 0 ? storageOptions.MaxFileSizeBytes : 50L * 1024 * 1024; using var buffer = new MemoryStream(); var chunk = new byte[81920]; int read; while ((read = await content.ReadAsync(chunk.AsMemory(), ct)) > 0) { if (buffer.Length + read > maxBytes) { throw new DocumentTemplateValidationException( "file", $"模板文件大小超过上限 {maxBytes} 字节。"); } buffer.Write(chunk, 0, read); } if (buffer.Length == 0) { throw new DocumentTemplateValidationException("file", "模板文件内容为空。"); } return buffer.ToArray(); } private static void EnsureTemplateFile(FileAttachmentDto file) { if (!string.Equals(file.Extension, ".xlsx", StringComparison.OrdinalIgnoreCase)) { throw new DocumentTemplateValidationException( "file", "只能扫描 .xlsx 模板文件。"); } } private static DocumentTemplateUploadResultDto ToResult( FileAttachmentDto file, string? name, string? documentKind, Guid? customerId, TemplateScanResult scan) => new( TemplateId: file.FileGroupId, TemplateVersionId: file.Id, TemplateReference: file.Id.ToString("D"), SourceFileId: file.Id, Name: string.IsNullOrWhiteSpace(name) ? Path.GetFileNameWithoutExtension(file.OriginalFileName) : name.Trim(), DocumentKind: string.IsNullOrWhiteSpace(documentKind) ? file.Category : documentKind.Trim(), CustomerId: customerId, File: file, Worksheets: scan.Worksheets, Placeholders: scan.Placeholders, LineRows: scan.LineRows, Warnings: scan.Warnings); private static string RequireKind(string? documentKind) => DocumentTemplateKinds.Find(documentKind)?.Key ?? throw new DocumentTemplateValidationException(nameof(documentKind), $"模板类型无效,可选:{string.Join("、", DocumentTemplateKinds.All.Select(x => $"{x.DisplayName}({x.Key})"))}。"); private static string? NormalizeOptional(string? value, int maxLength, string field) { if (string.IsNullOrWhiteSpace(value)) return null; var trimmed = value.Trim(); if (trimmed.Length > maxLength) throw new DocumentTemplateValidationException(field, $"长度不能超过 {maxLength} 个字符。"); if (trimmed.Any(char.IsControl)) throw new DocumentTemplateValidationException(field, "不能包含控制字符。"); return trimmed; } }