using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.CustomProperties;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.VariantTypes;
using DocumentFormat.OpenXml.Wordprocessing;
namespace WordVersioning.Api.Services;
public interface IDocxGenerationService
{
/// parse content controls (SDT tags) จากไฟล์ template — เรียงตามที่ปรากฏในไฟล์ ไม่ซ้ำ
/// (FR-9: detect fields อัตโนมัติตอน upload)
IReadOnlyList DetectFieldTags(Stream docxStream);
/// FR-10 — สร้างเอกสารจาก template: แทนที่ข้อความใน SDT แต่ละ field
/// ที่ run level (รักษา run properties/formatting ของ template) แล้ว stamp
/// Custom Properties (SavedByAddIn + DocumentTrackingId) — คืนเป็น bytes ของไฟล์ใหม่
byte[] Generate(Stream templateStream, IReadOnlyDictionary values, Guid documentTrackingId);
}
/// จัดการ docx ด้วย OpenXML SDK — ใช้ทั้งตอน detect fields และตอน generate (FR-9, FR-10)
public class DocxGenerationService : IDocxGenerationService
{
/// fmtid มาตรฐานของ user-defined custom properties (ตาม MS-ODRAW/Office convention)
private const string CustomPropertyFormatId = "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}";
public IReadOnlyList DetectFieldTags(Stream docxStream)
{
using var doc = WordprocessingDocument.Open(docxStream, false);
var tags = new List();
foreach (var root in AllContentRoots(doc))
{
foreach (var tag in root.Descendants())
{
var key = tag.Val?.Value?.Trim();
if (!string.IsNullOrEmpty(key) && !tags.Contains(key))
tags.Add(key);
}
}
return tags;
}
public byte[] Generate(Stream templateStream, IReadOnlyDictionary values, Guid documentTrackingId)
{
// ก๊อปเข้า memory ก่อน — MinIO stream ไม่ seek ได้ และ package จะเขียนกลับลง stream นี้ตอน dispose
var buffer = new MemoryStream();
templateStream.CopyTo(buffer);
buffer.Position = 0;
using (var doc = WordprocessingDocument.Open(buffer, true))
{
foreach (var root in AllContentRoots(doc))
{
foreach (var tag in root.Descendants().ToList())
{
var key = tag.Val?.Value?.Trim();
if (string.IsNullOrEmpty(key) || !values.TryGetValue(key, out var value))
continue;
ReplaceSdtContent(tag, value);
}
}
SetCustomProperty(doc, AddInMetadata.SavedByAddInPropertyName, AddInMetadata.AddInSignatureGuid);
SetCustomProperty(doc, AddInMetadata.DocumentTrackingIdPropertyName, documentTrackingId.ToString());
} // dispose เขียน package กลับลง buffer
buffer.Position = 0;
return buffer.ToArray();
}
/// แทนที่ข้อความใน SDT ที่ run level — เก็บ Run เดิมไว้ตัวแรก (formatting ตาม template)
/// แล้วลบ Text ที่เหลือ ไม่ทับทั้ง paragraph (spec ส่วน 9 เพิ่มเติม v2)
private static void ReplaceSdtContent(Tag tag, string value)
{
var sdtPr = tag.Parent; // w:sdtPr
var sdt = sdtPr?.Parent; // w:sdt (block หรือ run context — SDK แยก class แต่ localName เดียวกัน)
var content = sdt?.ChildElements.FirstOrDefault(c => c.LocalName == "sdtContent");
if (content is null)
return;
var texts = content.Descendants().ToList();
if (texts.Count == 0)
{
// SDT ไม่มีข้อความเลย (เช่น ที่ว่างมา) — สร้าง Run ใหม่ใน paragraph แรก (block) หรือใน content ตรงๆ (run)
var run = new Run(new Text(value) { Space = SpaceProcessingModeValues.Preserve });
if (content is SdtContentBlock)
{
var paragraph = content.ChildElements.OfType().FirstOrDefault();
if (paragraph is null)
{
paragraph = new Paragraph();
content.Append(paragraph);
}
paragraph.AppendChild(run);
}
else
{
content.AppendChild(run);
}
return;
}
// เขียนที่ Text แรก (อยู่ใน Run แรก — สืบทอด rPr ของ run นั้น) แล้วเก็บ space ไว้กรณีค่ามีช่องว่างหัว/ท้าย
texts[0].Text = value;
texts[0].Space = SpaceProcessingModeValues.Preserve;
// Text ที่เหลือ (จากการ split run เดิม เช่น rsid/formatting ปนกัน) ลบทิ้ง — field = ค่าเดียว
foreach (var text in texts.Skip(1))
{
var run = text.Parent;
text.Remove();
// Run ที่กลายเป็นโล่ง (ไม่มี Break/Tab/อื่นๆ) ลบทิ้งไม่ให้เหลือรอย formatting หลอนๆ
if (run is { } && run.ChildElements.Count == 0)
run.Remove();
}
}
/// แก้ custom property (มีอยู่แล้ว = แทนที่, ยังไม่มี = เพิ่ม) ผ่าน CustomFilePropertiesPart
private static void SetCustomProperty(WordprocessingDocument doc, string name, string value)
{
var part = doc.CustomFilePropertiesPart;
if (part is null)
{
part = doc.AddCustomFilePropertiesPart();
part.Properties = new Properties();
}
var props = part.Properties
?? throw new InvalidOperationException("CustomFilePropertiesPart ไม่มี root Properties");
foreach (var existing in props.Elements()
.Where(p => p.Name?.Value == name).ToList())
{
existing.Remove();
}
// pid ต้องเริ่มที่ 2 และไม่ซ้ำ — ต่อจากตัวสูงสุดที่มีอยู่
var nextPid = props.Elements()
.Select(p => p.PropertyId?.Value ?? 1)
.DefaultIfEmpty(1)
.Max() + 1;
props.Append(new CustomDocumentProperty
{
Name = name,
FormatId = CustomPropertyFormatId,
PropertyId = nextPid,
VTLPWSTR = new VTLPWSTR(value),
});
}
/// content controls อยู่ได้ทั้ง body, header, footer — เก็บครบทุกที่
private static IEnumerable AllContentRoots(WordprocessingDocument doc)
{
var main = doc.MainDocumentPart
?? throw new InvalidOperationException("ไฟล์ docx ไม่มี MainDocumentPart");
if (main.Document is { } document)
yield return document;
foreach (var header in main.HeaderParts)
{
if (header.Header is { } root)
yield return root;
}
foreach (var footer in main.FooterParts)
{
if (footer.Footer is { } root)
yield return root;
}
}
}