using Leiren.Erp.Contracts; using Leiren.Erp.Domain.Entities; using Microsoft.EntityFrameworkCore; namespace Leiren.Erp.Application.Customs; /// /// Persistence and validation for versioned CI/PL template field mappings. /// A profile belongs to exactly one immutable template version /// (, the /// scanned template file version id). Every placeholder found in the template /// must map to a field from before a /// document may be generated; generation locks the profile forever. /// public sealed class DocumentTemplateMappingService(IDocumentTemplateMappingDbContext db) { public IReadOnlyList ListFields() => DocumentTemplateFields.All .Select(x => new DocumentTemplateFieldDto(x.Key, x.DisplayName, x.Scope.ToString(), x.ValueType)) .ToList(); // ---------- Profiles ---------- public async Task CreateProfileAsync( Guid templateVersionId, CreateDocumentTemplateMappingProfileRequest request, CancellationToken ct = default) { if (!await db.FileAttachments.AsNoTracking().AnyAsync(x => x.Id == templateVersionId && !x.IsDeleted, ct)) throw new CustomsNotFoundException("模板版本(扫描的模板文件)不存在。"); if (await db.DocumentTemplateMappingProfiles.AsNoTracking().AnyAsync(x => x.TemplateVersionId == templateVersionId, ct)) throw new CustomsConflictException("该模板版本已存在字段映射,请直接编辑现有映射或上传新模板版本。"); var errors = new ErrorBag(); var placeholders = NormalizePlaceholders(request.Placeholders, errors); var mappings = ValidateMappingInputs(request.Mappings, placeholders, errors); errors.ThrowIfAny(); var profile = new DocumentTemplateMappingProfile { TemplateVersionId = templateVersionId, TemplateId = request.TemplateId, TemplateReference = TrimOrNull(request.TemplateReference) ?? templateVersionId.ToString("D"), DocumentKind = TrimOrNull(request.DocumentKind), Placeholders = placeholders }; foreach (var (placeholder, businessField, numberFormat) in mappings) profile.Mappings.Add(NewMapping(profile, placeholder, businessField, numberFormat)); db.DocumentTemplateMappingProfiles.Add(profile); await db.SaveChangesAsync(ct); return ToDto(profile); } public async Task GetProfileAsync(Guid templateVersionId, CancellationToken ct = default) => ToDto(await LoadProfileAsync(templateVersionId, ct)); public Task ProfileExistsAsync(Guid templateVersionId, CancellationToken ct = default) => db.DocumentTemplateMappingProfiles.AsNoTracking().AnyAsync(x => x.TemplateVersionId == templateVersionId, ct); public async Task> ListProfilesAsync(Guid? templateId, CancellationToken ct = default) { IQueryable query = db.DocumentTemplateMappingProfiles.AsNoTracking().Include(x => x.Mappings); if (templateId is { } id) query = query.Where(x => x.TemplateId == id); var items = await query.OrderByDescending(x => x.Id).ToListAsync(ct); return items.Select(ToDto).ToList(); } public async Task UpdateProfileAsync( Guid templateVersionId, UpdateDocumentTemplateMappingProfileRequest request, CancellationToken ct = default) { var profile = await LoadProfileAsync(templateVersionId, ct); await EnsureMutableAsync(profile, ct); var errors = new ErrorBag(); var placeholders = request.Placeholders is null ? profile.Placeholders : NormalizePlaceholders(request.Placeholders, errors); if (request.Placeholders is not null) { var keys = placeholders.Select(DocumentTemplateFieldMapping.NormalizePlaceholderKey).ToHashSet(StringComparer.Ordinal); var orphaned = profile.Mappings.Where(m => !keys.Contains(m.PlaceholderKey)).Select(m => m.Placeholder).ToList(); if (orphaned.Count > 0) errors.Add("Placeholders", $"以下映射的占位符不在新占位符列表中,请先删除这些映射:{string.Join("、", orphaned)}。"); } errors.ThrowIfAny(); profile.TemplateId = request.TemplateId; profile.TemplateReference = TrimOrNull(request.TemplateReference) ?? profile.TemplateReference; profile.DocumentKind = TrimOrNull(request.DocumentKind); profile.Placeholders = placeholders; profile.Touch(); await db.SaveChangesAsync(ct); return ToDto(profile); } public async Task DeleteProfileAsync(Guid templateVersionId, CancellationToken ct = default) { var profile = await LoadProfileAsync(templateVersionId, ct); await EnsureMutableAsync(profile, ct); db.DocumentTemplateFieldMappings.RemoveRange(profile.Mappings); db.DocumentTemplateMappingProfiles.Remove(profile); await db.SaveChangesAsync(ct); } // ---------- Mapping CRUD ---------- public async Task AddMappingAsync( Guid templateVersionId, SaveDocumentTemplateFieldMappingRequest request, CancellationToken ct = default) { var profile = await LoadProfileAsync(templateVersionId, ct); await EnsureMutableAsync(profile, ct); var errors = new ErrorBag(); var input = ValidateMappingInputs([request], profile.Placeholders, errors); if (input.Count == 1 && profile.Mappings.Any(m => m.PlaceholderKey == DocumentTemplateFieldMapping.NormalizePlaceholderKey(input[0].Placeholder))) errors.Add(nameof(request.Placeholder), $"占位符 {input[0].Placeholder} 已有映射,不能重复映射。"); errors.ThrowIfAny(); var (placeholder, businessField, numberFormat) = input[0]; profile.Mappings.Add(NewMapping(profile, placeholder, businessField, numberFormat)); profile.Touch(); await db.SaveChangesAsync(ct); return ToDto(profile); } public async Task UpdateMappingAsync( Guid templateVersionId, Guid mappingId, SaveDocumentTemplateFieldMappingRequest request, CancellationToken ct = default) { var profile = await LoadProfileAsync(templateVersionId, ct); await EnsureMutableAsync(profile, ct); var mapping = profile.Mappings.SingleOrDefault(x => x.Id == mappingId) ?? throw new CustomsNotFoundException("字段映射不存在。"); var errors = new ErrorBag(); var input = ValidateMappingInputs([request], profile.Placeholders, errors); if (input.Count == 1) { var key = DocumentTemplateFieldMapping.NormalizePlaceholderKey(input[0].Placeholder); if (profile.Mappings.Any(m => m.Id != mappingId && m.PlaceholderKey == key)) errors.Add(nameof(request.Placeholder), $"占位符 {input[0].Placeholder} 已有映射,不能重复映射。"); } errors.ThrowIfAny(); var (placeholder, businessField, numberFormat) = input[0]; mapping.Placeholder = placeholder; mapping.PlaceholderKey = DocumentTemplateFieldMapping.NormalizePlaceholderKey(placeholder); mapping.BusinessField = businessField; mapping.NumberFormat = numberFormat; mapping.Touch(); profile.Touch(); await db.SaveChangesAsync(ct); return ToDto(profile); } public async Task DeleteMappingAsync( Guid templateVersionId, Guid mappingId, CancellationToken ct = default) { var profile = await LoadProfileAsync(templateVersionId, ct); await EnsureMutableAsync(profile, ct); var mapping = profile.Mappings.SingleOrDefault(x => x.Id == mappingId) ?? throw new CustomsNotFoundException("字段映射不存在。"); db.DocumentTemplateFieldMappings.Remove(mapping); profile.Mappings.Remove(mapping); profile.Touch(); await db.SaveChangesAsync(ct); return ToDto(profile); } public async Task ReplaceMappingsAsync( Guid templateVersionId, ReplaceDocumentTemplateFieldMappingsRequest request, CancellationToken ct = default) { var profile = await LoadProfileAsync(templateVersionId, ct); await EnsureMutableAsync(profile, ct); var errors = new ErrorBag(); var mappings = ValidateMappingInputs(request.Mappings, profile.Placeholders, errors); errors.ThrowIfAny(); db.DocumentTemplateFieldMappings.RemoveRange(profile.Mappings); profile.Mappings.Clear(); foreach (var (placeholder, businessField, numberFormat) in mappings) profile.Mappings.Add(NewMapping(profile, placeholder, businessField, numberFormat)); profile.Touch(); await db.SaveChangesAsync(ct); return ToDto(profile); } public async Task CopyMappingsAsync( Guid templateVersionId, CopyDocumentTemplateMappingsRequest request, CancellationToken ct = default) { var profile = await LoadProfileAsync(templateVersionId, ct); await EnsureMutableAsync(profile, ct); var source = await LoadProfileAsync(request.SourceTemplateVersionId, ct); var inputs = source.Mappings .Select(m => new SaveDocumentTemplateFieldMappingRequest(m.Placeholder, m.BusinessField, m.NumberFormat)) .ToList(); var errors = new ErrorBag(); var mappings = ValidateMappingInputs(inputs, profile.Placeholders, errors); foreach (var duplicate in mappings.Where(m => profile.Mappings.Any(x => x.PlaceholderKey == DocumentTemplateFieldMapping.NormalizePlaceholderKey(m.Placeholder)))) errors.Add(nameof(SaveDocumentTemplateFieldMappingRequest.Placeholder), $"占位符 {duplicate.Placeholder} 已有映射,不能重复映射。"); errors.ThrowIfAny(); foreach (var (placeholder, businessField, numberFormat) in mappings) profile.Mappings.Add(NewMapping(profile, placeholder, businessField, numberFormat)); profile.Touch(); await db.SaveChangesAsync(ct); return ToDto(profile); } // ---------- Generation validation / locking ---------- public async Task ValidateAsync( Guid templateVersionId, IReadOnlyCollection? scannedPlaceholders = null, CancellationToken ct = default) { var profile = await LoadProfileAsync(templateVersionId, ct); return BuildValidation(profile, scannedPlaceholders); } /// /// Throws listing every unmapped /// placeholder (and any unknown placeholder/business field) when this /// template version is not fully mapped; otherwise returns the profile. /// Callers generating XLSX must call this before rendering. /// public async Task ValidateForGenerationAsync( Guid templateVersionId, IReadOnlyCollection? scannedPlaceholders = null, CancellationToken ct = default) { var profile = await LoadProfileAsync(templateVersionId, ct); var result = BuildValidation(profile, scannedPlaceholders); ThrowIfInvalid(result); return ToDto(profile); } /// Parameterless-placeholder overload of using the stored scan snapshot. public Task EnsureGenerationAllowedAsync(Guid templateVersionId, CancellationToken ct = default) => ValidateForGenerationAsync(templateVersionId, scannedPlaceholders: null, ct); /// Locks the profile after a document package was generated from it; locked mappings are immutable. public async Task LockAfterGenerationAsync( Guid templateVersionId, Guid documentPackageId, CancellationToken ct = default) { var profile = await LoadProfileAsync(templateVersionId, ct); profile.LockAfterGeneration(documentPackageId); await db.SaveChangesAsync(ct); return ToDto(profile); } /// Alias for . public Task MarkUsedAsync(Guid templateVersionId, Guid documentPackageId, CancellationToken ct = default) => LockAfterGenerationAsync(templateVersionId, documentPackageId, ct); // ---------- Helpers ---------- private async Task LoadProfileAsync(Guid templateVersionId, CancellationToken ct) => await db.DocumentTemplateMappingProfiles .Include(x => x.Mappings) .SingleOrDefaultAsync(x => x.TemplateVersionId == templateVersionId, ct) ?? throw new CustomsNotFoundException("该模板版本尚无字段映射,请先创建映射。"); private async Task EnsureMutableAsync(DocumentTemplateMappingProfile profile, CancellationToken ct) { if (!profile.IsLocked && await db.DocumentPackages.AsNoTracking().AnyAsync(x => x.TemplateVersionId == profile.TemplateVersionId, ct)) profile.IsLocked = true; try { profile.EnsureMutable(); } catch (InvalidOperationException ex) { throw new CustomsConflictException(ex.Message); } } private static DocumentTemplateFieldMapping NewMapping( DocumentTemplateMappingProfile profile, string placeholder, string businessField, string? numberFormat) => new() { MappingProfileId = profile.Id, MappingProfile = profile, TemplateVersionId = profile.TemplateVersionId, Placeholder = placeholder, PlaceholderKey = DocumentTemplateFieldMapping.NormalizePlaceholderKey(placeholder), BusinessField = businessField, NumberFormat = numberFormat }; private static List NormalizePlaceholders(IReadOnlyList? raw, ErrorBag errors) { var result = new List(); if (raw is null) return result; var seen = new HashSet(StringComparer.Ordinal); foreach (var item in raw) { var name = NormalizePlaceholder(item); if (name is null) { errors.Add("Placeholders", $"占位符名称无效:\"{item}\"。"); continue; } if (!seen.Add(DocumentTemplateFieldMapping.NormalizePlaceholderKey(name))) errors.Add("Placeholders", $"占位符 {name} 在扫描结果中重复。"); else result.Add(name); } return result; } private static List<(string Placeholder, string BusinessField, string? NumberFormat)> ValidateMappingInputs( IReadOnlyList? inputs, IReadOnlyList knownPlaceholders, ErrorBag errors) { var result = new List<(string, string, string?)>(); if (inputs is null) return result; var knownKeys = knownPlaceholders .Select(DocumentTemplateFieldMapping.NormalizePlaceholderKey) .ToHashSet(StringComparer.Ordinal); var seen = new HashSet(StringComparer.Ordinal); foreach (var input in inputs) { var placeholder = NormalizePlaceholder(input.Placeholder); if (placeholder is null) { errors.Add(nameof(input.Placeholder), $"占位符名称无效:\"{input.Placeholder}\"(应为不含花括号的名称,如 CustomerName)。"); continue; } var key = DocumentTemplateFieldMapping.NormalizePlaceholderKey(placeholder); if (!seen.Add(key)) errors.Add(nameof(input.Placeholder), $"占位符 {placeholder} 重复映射。"); if (knownKeys.Count > 0 && !knownKeys.Contains(key)) errors.Add(nameof(input.Placeholder), $"占位符 {placeholder} 不在该模板版本的扫描结果中,不能映射。"); if (!DocumentTemplateFields.TryGet(input.BusinessField, out var field)) { errors.Add(nameof(input.BusinessField), $"业务字段 \"{input.BusinessField}\" 不在允许字段目录中。允许字段:{string.Join("、", DocumentTemplateFields.Keys)}。"); continue; } var numberFormat = TrimOrNull(input.NumberFormat); if (numberFormat is { Length: > 100 }) { errors.Add(nameof(input.NumberFormat), "数字/日期格式长度不能超过 100。"); continue; } result.Add((placeholder, field.Key, numberFormat)); } return result; } private static DocumentTemplateValidationResultDto BuildValidation( DocumentTemplateMappingProfile profile, IReadOnlyCollection? scannedPlaceholders) { var errors = new ErrorBag(); var placeholders = scannedPlaceholders is null ? profile.Placeholders : NormalizePlaceholders(scannedPlaceholders.ToList(), errors); var placeholderKeys = placeholders .Select(DocumentTemplateFieldMapping.NormalizePlaceholderKey) .ToHashSet(StringComparer.Ordinal); var unmapped = placeholders .Where(p => !profile.Mappings.Any(m => m.PlaceholderKey == DocumentTemplateFieldMapping.NormalizePlaceholderKey(p))) .ToList(); var unknownPlaceholders = profile.Mappings .Where(m => placeholderKeys.Count > 0 && !placeholderKeys.Contains(m.PlaceholderKey)) .Select(m => m.Placeholder).ToList(); var unknownFields = profile.Mappings .Where(m => !DocumentTemplateFields.TryGet(m.BusinessField, out _)) .Select(m => m.BusinessField).Distinct(StringComparer.OrdinalIgnoreCase).ToList(); return new DocumentTemplateValidationResultDto( profile.TemplateVersionId, placeholders.Count > 0 && unmapped.Count == 0 && unknownPlaceholders.Count == 0 && unknownFields.Count == 0, placeholders, unmapped, unknownPlaceholders, unknownFields, profile.Mappings.Count(m => placeholderKeys.Contains(m.PlaceholderKey))); } private static void ThrowIfInvalid(DocumentTemplateValidationResultDto result) { if (result.IsValid) return; var errors = new Dictionary(); if (result.Placeholders.Count == 0) errors["Placeholders"] = ["该模板版本没有登记任何扫描占位符,无法确认全部占位符已映射,禁止生成。"]; if (result.UnmappedPlaceholders.Count > 0) errors["UnmappedPlaceholders"] = result.UnmappedPlaceholders.Select(p => $"{{{{{p}}}}}").ToArray(); if (result.UnknownPlaceholders.Count > 0) errors["UnknownPlaceholders"] = result.UnknownPlaceholders.Select(p => $"{{{{{p}}}}}").ToArray(); if (result.UnknownBusinessFields.Count > 0) errors["BusinessField"] = result.UnknownBusinessFields .Select(f => $"业务字段 \"{f}\" 不在允许字段目录中。允许字段:{string.Join("、", DocumentTemplateFields.Keys)}。").ToArray(); throw new CustomsValidationException(errors); } private static string? NormalizePlaceholder(string? raw) { if (string.IsNullOrWhiteSpace(raw)) return null; var name = raw.Trim(); if (name.StartsWith("{{", StringComparison.Ordinal) && name.EndsWith("}}", StringComparison.Ordinal) && name.Length > 4) name = name[2..^2].Trim(); if (name.Length is 0 or > 200 || name.Contains('{') || name.Contains('}') || name.Contains('\n') || name.Contains('\r')) return null; return name; } private static string? TrimOrNull(string? v) => string.IsNullOrWhiteSpace(v) ? null : v.Trim(); private static DocumentTemplateFieldMappingDto ToDto(DocumentTemplateFieldMapping m) => new( m.Id, m.MappingProfileId, m.TemplateVersionId, m.Placeholder, m.BusinessField, DocumentTemplateFields.TryGet(m.BusinessField, out var field) ? field.Scope.ToString() : "Unknown", m.NumberFormat, m.CreatedAt, m.UpdatedAt); private static DocumentTemplateMappingProfileDto ToDto(DocumentTemplateMappingProfile p) { var mappedKeys = p.Mappings.Select(x => x.PlaceholderKey).ToHashSet(StringComparer.Ordinal); return new DocumentTemplateMappingProfileDto( p.Id, p.TemplateVersionId, p.TemplateId, p.TemplateReference, p.DocumentKind, p.Placeholders, p.IsLocked, p.LockedAt, p.LockedByDocumentPackageId, p.CreatedAt, p.UpdatedAt, p.Mappings.OrderBy(x => x.Placeholder, StringComparer.OrdinalIgnoreCase).Select(ToDto).ToList(), p.Placeholders.Where(x => !mappedKeys.Contains(DocumentTemplateFieldMapping.NormalizePlaceholderKey(x))).ToList()); } private sealed class ErrorBag { private readonly Dictionary> _errors = new(StringComparer.Ordinal); public void Add(string field, string message) { if (!_errors.TryGetValue(field, out var list)) _errors[field] = list = []; list.Add(message); } public void ThrowIfAny() { if (_errors.Count > 0) throw new CustomsValidationException(_errors.ToDictionary(x => x.Key, x => x.Value.ToArray())); } } }