using System.Globalization;
using System.Text.RegularExpressions;
using ClosedXML.Excel;
using Leiren.Erp.Domain.Entities;
using Leiren.Erp.Domain.Enums;
namespace Leiren.Erp.Application.Customs;
/// One resolved placeholder mapping used by the renderer (placeholder key is the normalized name).
public sealed record CiPlMappedField(string Placeholder, string BusinessField, TemplateFieldScope Scope, string? NumberFormat);
///
/// Renders a customer CI/PL workbook from a real XLSX template and the
/// confirmed shipping-batch snapshot. Placeholders are discovered by scanning
/// every worksheet's used range (never fixed cell coordinates); the row
/// carrying line-scope placeholders is copied once per shipment line, and all
/// totals are computed in code from the shipment-line snapshots — template
/// formulas are never evaluated or relied upon.
///
public static partial class CiPlTemplateRenderer
{
[GeneratedRegex(@"\{\{\s*([^{}]+?)\s*\}\}", RegexOptions.CultureInvariant)]
private static partial Regex TokenRegex();
public static byte[] Render(
byte[] templateBytes,
ShippingBatch batch,
IReadOnlyList lines,
DocumentKind kind,
DocumentRenderSource source,
IReadOnlyDictionary mappingsByPlaceholderKey,
DateTimeOffset generatedAt,
bool allowUnmapped = false)
{
ArgumentNullException.ThrowIfNull(templateBytes);
ArgumentNullException.ThrowIfNull(batch);
ArgumentNullException.ThrowIfNull(lines);
ArgumentNullException.ThrowIfNull(source);
ArgumentNullException.ThrowIfNull(mappingsByPlaceholderKey);
// Customs documents print the declared quantity / price / HS code;
// every customs-only field (报关品名, 申报要素 ...) is read from the
// declaration line of the same shipment line whenever one exists.
var declaredByShipmentLine = source.Declaration?.Lines.ToDictionary(x => x.ShipmentLineId)
?? new Dictionary();
var useDeclared = DocumentRenderSource.IsCustomsKind(kind) && source.Declaration is not null;
var docLines = lines
.Select(l => new DocLine(l, declaredByShipmentLine.GetValueOrDefault(l.Id), useDeclared))
.ToList();
var totals = ComputeTotals(docLines);
var context = new RenderContext(batch, docLines, kind, source, totals, generatedAt);
XLWorkbook workbook;
try
{
workbook = new XLWorkbook(new MemoryStream(templateBytes, writable: false));
}
catch (Exception ex)
{
throw new CustomsValidationException("TemplateVersionId", $"模板 Excel 文件无法解析(不是有效的 .xlsx 文件):{ex.Message}");
}
using (workbook)
{
if (workbook.Worksheets.Count == 0)
throw new CustomsValidationException("TemplateVersionId", "模板工作簿中没有任何工作表。");
// Pre-pass: every placeholder in the workbook must be mapped to a
// known business field, otherwise generation is refused with the
// full list of missing placeholders. Previews (allowUnmapped) keep
// unmapped tokens as written so an incomplete mapping can be tested.
var unmapped = new SortedSet(StringComparer.OrdinalIgnoreCase);
foreach (var sheet in workbook.Worksheets)
foreach (var name in ScanPlaceholderNames(sheet))
if (!mappingsByPlaceholderKey.TryGetValue(NormalizeKey(name), out var field)
|| !DocumentTemplateFields.TryGet(field.BusinessField, out _))
unmapped.Add(name);
if (unmapped.Count > 0 && !allowUnmapped)
{
throw new CustomsValidationException(new Dictionary
{
["UnmappedPlaceholders"] = unmapped.Select(p => $"{{{{{p}}}}}").ToArray()
});
}
var usable = mappingsByPlaceholderKey
.Where(x => DocumentTemplateFields.TryGet(x.Value.BusinessField, out _))
.ToDictionary(x => x.Key, x => x.Value, StringComparer.Ordinal);
foreach (var sheet in workbook.Worksheets)
RenderSheet(sheet, context, usable);
using var output = new MemoryStream();
workbook.SaveAs(output);
return output.ToArray();
}
}
// ---------- Sheet rendering ----------
private static void RenderSheet(
IXLWorksheet sheet, RenderContext context, IReadOnlyDictionary mappings)
{
var range = sheet.RangeUsed();
if (range is null) return;
var firstColumn = range.FirstColumn().ColumnNumber();
var lastColumn = range.LastColumn().ColumnNumber();
// Detail rows carry at least one line-scope placeholder; the template
// block spans from the first to the last such row.
var detailRows = new SortedSet();
foreach (var cell in range.Cells())
{
var text = CellTokenText(cell);
if (text is null) continue;
foreach (Match match in TokenRegex().Matches(text))
{
if (mappings.TryGetValue(NormalizeKey(match.Groups[1].Value.Trim()), out var field)
&& field.Scope == TemplateFieldScope.Line)
detailRows.Add(cell.Address.RowNumber);
}
}
var lineIndexByRow = new Dictionary();
if (detailRows.Count > 0)
{
var blockStart = detailRows.Min;
var blockEnd = detailRows.Max;
var height = blockEnd - blockStart + 1;
var lineCount = context.Lines.Count;
var mergedInsideBlock = sheet.MergedRanges
.Select(r => (FirstRow: r.FirstRow().RowNumber(), FirstCol: r.FirstColumn().ColumnNumber(),
LastRow: r.LastRow().RowNumber(), LastCol: r.LastColumn().ColumnNumber()))
.Where(m => m.FirstRow >= blockStart && m.LastRow <= blockEnd)
.ToList();
var templateHeights = Enumerable.Range(blockStart, height).Select(r => sheet.Row(r).Height).ToList();
if (lineCount > 1)
{
var extraRows = (lineCount - 1) * height;
sheet.Row(blockEnd + 1).InsertRowsAbove(extraRows);
var templateRange = sheet.Range(blockStart, firstColumn, blockEnd, lastColumn);
for (var copy = 1; copy < lineCount; copy++)
{
var targetStart = blockStart + copy * height;
templateRange.CopyTo(sheet.Cell(targetStart, firstColumn));
for (var r = 0; r < height; r++)
sheet.Row(targetStart + r).Height = templateHeights[r];
foreach (var m in mergedInsideBlock)
{
var offset = copy * height;
try { sheet.Range(m.FirstRow + offset, m.FirstCol, m.LastRow + offset, m.LastCol).Merge(); }
catch (InvalidOperationException) { /* already merged by the copy */ }
}
}
}
for (var i = 0; i < lineCount; i++)
for (var r = 0; r < height; r++)
lineIndexByRow[blockStart + i * height + r] = i;
}
// Replacement pass over the (now expanded) used range.
var expanded = sheet.RangeUsed();
if (expanded is null) return;
foreach (var cell in expanded.Cells())
{
var text = CellTokenText(cell);
if (text is null) continue;
int? lineIndex = lineIndexByRow.TryGetValue(cell.Address.RowNumber, out var idx) ? idx : null;
ReplaceCell(cell, text, context, mappings, lineIndex);
}
}
private static void ReplaceCell(
IXLCell cell, string text, RenderContext context,
IReadOnlyDictionary mappings, int? lineIndex)
{
var matches = TokenRegex().Matches(text);
if (matches.Count == 0) return;
// A cell holding exactly one placeholder takes the typed value so
// numbers and dates stay real Excel values.
if (matches.Count == 1 && string.Equals(text.Trim(), matches[0].Value, StringComparison.Ordinal))
{
// Unmapped tokens (preview only) stay as written.
if (!mappings.TryGetValue(NormalizeKey(matches[0].Groups[1].Value.Trim()), out var field)) return;
var value = ResolveValue(field, context, lineIndex);
SetTypedValue(cell, value, field.NumberFormat);
return;
}
var replaced = TokenRegex().Replace(text, match =>
{
if (!mappings.TryGetValue(NormalizeKey(match.Groups[1].Value.Trim()), out var field)) return match.Value;
var value = ResolveValue(field, context, lineIndex);
return FormatAsText(value);
});
cell.Value = replaced;
}
private static object? ResolveValue(CiPlMappedField field, RenderContext context, int? lineIndex)
{
if (!DocumentTemplateFields.TryGet(field.BusinessField, out var definition))
throw new CustomsValidationException("BusinessField", $"业务字段 \"{field.BusinessField}\" 不在允许字段目录中。");
return definition.Scope switch
{
TemplateFieldScope.Line => lineIndex is { } i
? LineValue(definition.Key, context.Lines[i], i + 1, context)
: throw new CustomsValidationException("TemplateVersionId",
$"明细字段 {definition.Key} 的占位符没有放在明细行中,无法生成。"),
TemplateFieldScope.Total => TotalValue(definition.Key, context.Totals),
_ => HeaderValue(definition.Key, context)
};
}
// ---------- Field values (shipment snapshot only) ----------
private static object? HeaderValue(string key, RenderContext c) => key switch
{
"BatchNo" => c.Batch.BatchNo,
"SalesOrderNo" => c.Batch.SalesOrderNo,
"CustomerName" => c.Batch.CustomerName,
"CustomerPoNo" => c.Batch.CustomerPoNo,
"Currency" => c.Batch.Currency,
"ShipmentDate" => c.Batch.ShipmentDate,
"CutoffDate" => c.Batch.CutoffDate,
"Etd" => c.Batch.Etd,
"Eta" => c.Batch.Eta,
"VesselName" => c.Batch.VesselName,
"VoyageNo" => c.Batch.VoyageNo,
"BillOfLadingNo" => c.Batch.BillOfLadingNo,
"LoadingPort" => c.Batch.LoadingPort,
"DestinationPort" => c.Batch.DestinationPort,
"DestinationCountry" => c.Batch.DestinationCountry,
"TransportMode" => c.Batch.TransportMode,
"TradeTerm" => c.Batch.TradeTerm,
"FreightForwarder" => c.Batch.FreightForwarder,
"ContainerNumbers" => c.Batch.Containers.Count == 0
? null
: string.Join(", ", c.Batch.Containers.Select(x => x.ContainerNo)),
"DeclarationNo" => c.Source.Declaration?.DeclarationNo,
"DocumentKind" => c.Kind.ToString(),
"GeneratedDate" => DateOnly.FromDateTime(c.GeneratedAt.UtcDateTime),
"InvoiceNo" => c.Source.Declaration?.InvoiceNo ?? c.Batch.BatchNo,
"CustomerAddress" => c.Source.Customer?.Address,
"OrderDate" => c.Source.OrderDate,
"ExportDate" => c.Source.Declaration?.ExportDate ?? c.Batch.Etd ?? c.Batch.ShipmentDate,
"DeclarationDate" => c.Source.Declaration?.DeclarationDate,
"TradeMode" => c.Source.Declaration?.TradeMode,
"ExemptionNature" => c.Source.Declaration?.ExemptionNature,
"CurrencyNameZh" => CurrencyNameZh(c.Batch.Currency),
_ => throw UnknownField(key)
};
private static object? LineValue(string key, DocLine d, int lineNumber, RenderContext c)
{
var l = d.Shipment;
var declared = d.Declared;
return key switch
{
"LineNumber" => lineNumber,
"InternalSku" => l.InternalSku,
"ProductNameZh" => l.ProductNameZh,
"ProductNameEn" => l.ProductNameEn,
"CustomerSku" => l.CustomerSku,
"CustomerProductName" => l.CustomerProductName,
"HsCode" => d.UseDeclared ? declared!.HsCode : declared?.HsCode ?? l.HsCode,
"Quantity" => d.Quantity,
"Unit" => d.UseDeclared ? declared!.Unit : l.Unit,
"UnitPrice" => d.UseDeclared ? declared!.UnitPrice : l.UnitPrice,
"Amount" => d.Amount,
"PackingRate" => l.PackingRate,
"CartonCount" => l.CartonCount,
"CartonLength" => l.CartonLength,
"CartonWidth" => l.CartonWidth,
"CartonHeight" => l.CartonHeight,
"CartonGrossWeight" => l.CartonGrossWeight,
"CartonNetWeight" => l.CartonNetWeight,
"LineTotalGrossWeight" => l.TotalGrossWeight,
"LineTotalNetWeight" => l.TotalNetWeight,
"LineTotalCbm" => l.TotalCbm,
"Remark" => l.Remark,
"CustomsNameZh" => declared?.CustomsNameZh ?? l.ProductNameZh,
"CustomsNameEn" => declared?.CustomsNameEn ?? l.ProductNameEn,
"DeclarationElements" => declared?.DeclarationElements,
"OriginCountry" => declared?.OriginCountry,
"DomesticSourcePlace" => declared?.DomesticSourcePlace,
"ExemptionInfo" => declared?.ExemptionInfo,
"LineCurrencyZh" => CurrencyNameZh(c.Batch.Currency),
_ => throw UnknownField(key)
};
}
private static object? TotalValue(string key, Totals t) => key switch
{
"LineCount" => t.LineCount,
"TotalQuantity" => t.TotalQuantity,
"TotalAmount" => t.TotalAmount,
"TotalCartonCount" => t.TotalCartonCount,
"TotalGrossWeight" => t.TotalGrossWeight,
"TotalNetWeight" => t.TotalNetWeight,
"TotalCbm" => t.TotalCbm,
_ => throw UnknownField(key)
};
private static Totals ComputeTotals(IReadOnlyList lines) => new(
lines.Count,
lines.Sum(x => x.Quantity),
lines.Sum(x => x.Amount),
lines.Sum(x => x.Shipment.CartonCount ?? 0),
lines.Sum(x => x.Shipment.TotalGrossWeight ?? 0),
lines.Sum(x => x.Shipment.TotalNetWeight ?? 0),
lines.Sum(x => x.Shipment.TotalCbm ?? 0));
/// Chinese currency name used by the customs declaration (币制).
private static string CurrencyNameZh(string currency) => currency.ToUpperInvariant() switch
{
"USD" => "美元",
"CNY" or "RMB" => "人民币",
"EUR" => "欧元",
"GBP" => "英镑",
"JPY" => "日元",
"HKD" => "港币",
"AUD" => "澳大利亚元",
"CAD" => "加拿大元",
_ => currency,
};
// ---------- Cell helpers ----------
/// Token-bearing text of a cell, or null. Formula cells are skipped: their values are never a data source.
private static string? CellTokenText(IXLCell cell)
{
if (cell.HasFormula) return null;
string text;
try { text = cell.GetString(); }
catch (InvalidOperationException) { return null; }
return text.Contains("{{", StringComparison.Ordinal) ? text : null;
}
private static IEnumerable ScanPlaceholderNames(IXLWorksheet sheet)
{
var range = sheet.RangeUsed();
if (range is null) yield break;
foreach (var cell in range.Cells())
{
var text = CellTokenText(cell);
if (text is null) continue;
foreach (Match match in TokenRegex().Matches(text))
yield return match.Groups[1].Value.Trim();
}
}
private static void SetTypedValue(IXLCell cell, object? value, string? numberFormat)
{
switch (value)
{
case null: cell.Value = string.Empty; break;
case string s: cell.Value = s; break;
case decimal d: cell.Value = d; break;
case int i: cell.Value = i; break;
case DateOnly d:
cell.Value = d.ToDateTime(TimeOnly.MinValue);
if (string.IsNullOrWhiteSpace(numberFormat)) cell.Style.DateFormat.Format = "yyyy-mm-dd";
break;
case DateTime dt: cell.Value = dt; break;
default: cell.Value = value.ToString(); break;
}
if (!string.IsNullOrWhiteSpace(numberFormat) && value is not string)
{
try { cell.Style.NumberFormat.Format = numberFormat.Trim(); }
catch (ArgumentException) { /* keep the template cell's own format */ }
}
}
private static string FormatAsText(object? value) => value switch
{
null => string.Empty,
decimal d => d.ToString(CultureInfo.InvariantCulture),
int i => i.ToString(CultureInfo.InvariantCulture),
DateOnly d => d.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture),
DateTime dt => dt.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture),
_ => value.ToString() ?? string.Empty
};
private static string NormalizeKey(string placeholder)
=> DocumentTemplateFieldMapping.NormalizePlaceholderKey(placeholder);
private static CustomsValidationException UnknownField(string key)
=> new("BusinessField", $"业务字段 \"{key}\" 不在允许字段目录中。");
private sealed record Totals(
int LineCount, decimal TotalQuantity, decimal TotalAmount, int TotalCartonCount,
decimal TotalGrossWeight, decimal TotalNetWeight, decimal TotalCbm);
/// One document line: the shipment line plus its customs-declaration line, if any.
private sealed record DocLine(ShipmentLine Shipment, CustomsDeclarationLine? Declared, bool UseDeclaredValues)
{
public bool UseDeclared => UseDeclaredValues && Declared is not null;
public decimal Quantity => UseDeclared ? Declared!.Quantity : Shipment.Quantity;
public decimal Amount => UseDeclared ? Declared!.Amount : Shipment.Amount;
}
private sealed record RenderContext(
ShippingBatch Batch, IReadOnlyList Lines, DocumentKind Kind,
DocumentRenderSource Source, Totals Totals, DateTimeOffset GeneratedAt);
}