This commit is contained in:
Suphonchai Phoonsawat 2026-08-19 12:15:20 +07:00
parent 9321f5a370
commit 25c2ce53cd
23 changed files with 1746 additions and 68 deletions

View file

@ -14,7 +14,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
Infra ทั้งหมดรันผ่าน `docker-compose.yml`: PostgreSQL + MinIO + Keycloak (OIDC, 3 public clients พร้อม PKCE: `word-addin-officejs`, `word-versioning-web`, `word-addin-vsto`) Infra ทั้งหมดรันผ่าน `docker-compose.yml`: PostgreSQL + MinIO + Keycloak (OIDC, 3 public clients พร้อม PKCE: `word-addin-officejs`, `word-versioning-web`, `word-addin-vsto`)
**สถานะปัจจุบัน: Phase 0–2 เสร็จ** (scaffold + infra + backend core FR-5–8) — งานต่อคือ implement phase 3–8 ในแผน **สถานะปัจจุบัน: Phase 0–3 เสร็จ** (scaffold + infra + backend core FR-5–8 + backend template & generation FR-9–11) — งานต่อคือ implement phase 4–8 ในแผน (4–5 add-in กับ 6 web ทำขนานกันได้)
## เอกสารหลัก (อ่านก่อนเริ่มงานใดๆ) ## เอกสารหลัก (อ่านก่อนเริ่มงานใดๆ)

View file

@ -33,12 +33,12 @@
| 0 | Scaffold 3 โปรเจกต์ (addin / backend / web) | ✅ เสร็จ | | 0 | Scaffold 3 โปรเจกต์ (addin / backend / web) | ✅ เสร็จ |
| 1 | Local dev infra — docker-compose + Keycloak (realm, 3 clients + PKCE) + MinIO (buckets) | ✅ เสร็จ | | 1 | Local dev infra — docker-compose + Keycloak (realm, 3 clients + PKCE) + MinIO (buckets) | ✅ เสร็จ |
| 2 | Backend core — version API (FR-5–7) + JWT auth (FR-8) | ✅ เสร็จ | | 2 | Backend core — version API (FR-5–7) + JWT auth (FR-8) | ✅ เสร็จ |
| 3 | Template system + docx generation + field sync (FR-9–11) | ⏳ รอ implement | | 3 | Template system + docx generation + field sync (FR-9–11) | ✅ เสร็จ |
| 4–5 | Add-in services + task pane UI (FR-1–4) | ⏳ รอ implement | | 4–5 | Add-in services + task pane UI (FR-1–4) | ⏳ รอ implement |
| 6 | Web Portal UI (FR-9–10) | ⏳ รอ implement | | 6 | Web Portal UI (FR-9–10) | ⏳ รอ implement |
| 7–8 | Tests + เอกสารฉบับเต็ม | ⏳ รอ implement | | 7–8 | Tests + เอกสารฉบับเต็ม | ⏳ รอ implement |
**ใช้ได้แล้วตอนนี้:** infra ทั้งชุด + backend API สำหรับ upload / ดู history / ดาวน์โหลด version (พร้อม JWT auth จาก Keycloak) — ลองเล่นได้ผ่าน Swagger **ใช้ได้แล้วตอนนี้:** infra ทั้งชุด + backend API ครบทั้ง version API (upload / history / download) และ template system (upload template พร้อม auto-detect fields, generate เอกสารเป็น v1, field sync ตอนสร้าง version) — ลองเล่นได้ผ่าน Swagger หรือ curl (ตัวอย่างด้านล่าง)
## เอกสาร ## เอกสาร
@ -92,13 +92,27 @@ dotnet run # Swagger ที่ http://localhost:5075/swagger
**API ที่มีตอนนี้** (ทุก endpoint ต้องแนบ `Authorization: Bearer <token>`): **API ที่มีตอนนี้** (ทุก endpoint ต้องแนบ `Authorization: Bearer <token>`):
``` ```
POST /api/documents/{documentId}/versions # อัปโหลด version ใหม่ (FR-5) # Documents / versions (FR-5–7, 11)
GET /api/documents/{documentId}/versions # version history ใหม่ → เก่า (FR-6) POST /api/documents/{documentId}/versions # อัปโหลด version ใหม่ + field sync
GET /api/documents/{documentId}/versions/{versionId}/download # ดาวน์โหลด version (FR-7) GET /api/documents/{documentId}/versions # version history ใหม่ → เก่า (พร้อม snapshot fields)
GET /api/documents/{documentId}/versions/{versionId}/download # ดาวน์โหลด version (proxy stream จาก MinIO)
# Generate จาก template (FR-10)
POST /api/documents/generate # { templateId, values } → เอกสาร v1 พร้อม metadata
# Templates (FR-9)
GET /api/templates # รายการ (?includeInactive=true สำหรับ admin)
GET /api/templates/{id} # รายละเอียด + field definitions
POST /api/templates # upload .docx → detect fields อัตโนมัติ
PUT /api/templates/{id} # แก้ metadata + field definitions (label/type/required/ลำดับ)
PUT /api/templates/{id}/file # แทนที่ไฟล์ → re-detect (บอก tag ที่เพิ่ม/หาย)
DELETE /api/templates/{id} # deactivate (soft-delete)
``` ```
- Upload เป็น multipart/form-data: `file` (.docx เท่านั้น, จำกัด 100MB) + `clientVersionId` (GUID) + `fields` (optional, JSON map tag→text สำหรับ field sync) - Upload เป็น multipart/form-data: `file` (.docx เท่านั้น, จำกัด 100MB) + `clientVersionId` (GUID) + `fields` (optional, JSON map tag→text สำหรับ field sync)
- `documentId` ยังไม่มีในระบบ = สร้างใหม่อัตโนมัติ · `versionNumber` เพิ่มอัตโนมัติต่อเอกสาร · เก็บ SHA256 ของทุก version - `documentId` ยังไม่มีในระบบ = สร้างใหม่อัตโนมัติ · `versionNumber` เพิ่มอัตโนมัติต่อเอกสาร · เก็บ SHA256 ของทุก version
- Field sync policy (FR-11): field ที่ส่งมาขาด (ผู้ใช้ลบ content control ใน Word) → เก็บค่าเดิม + mark missing ใน snapshot **ไม่ fail request** · ส่งเกินนิยาม → ignore
- Generate (FR-10): backend เปิด template ด้วย OpenXML → แทนที่ค่าใน SDT ที่ **run level** (รักษา formatting) → stamp custom properties (`SavedByAddIn`, `DocumentTrackingId`) → upload เป็น v1 → response `{ documentId, versionId, versionNumber, downloadUrl }` — เปิดไฟล์ใน Word แล้ว add-in (Phase 4–5) จะรู้จักทันที
### ขอ token ทดสอบ (dev) ### ขอ token ทดสอบ (dev)
@ -121,6 +135,56 @@ curl -X POST http://localhost:5075/api/documents/$DOC_ID/versions \
# → { "versionId": "...", "versionNumber": 1 } # → { "versionId": "...", "versionNumber": 1 }
``` ```
### ลองเล่น template → generate → field sync (Phase 3)
**0) เตรียมไฟล์ template** — เขียน .docx ใน Word แล้วแทรก content controls ในจุดที่จะเป็น field (Developer tab → Rich Text Content Control → Properties ตั้ง **Tag** ให้ unique ต่อไฟล์ เช่น `employee_name`, `salary`)
**1) Upload template → ระบบ detect fields อัตโนมัติ:**
```bash
curl -X POST http://localhost:5075/api/templates \
-H "Authorization: Bearer $TOKEN" \
-F "name=สัญญาจ้างงาน" \
-F "file=@template.docx;type=application/vnd.openxmlformats-officedocument.wordprocessingml.document"
# → { "id": "...", "fields": [ { "key": "employee_name", ... }, ... ] }
```
**2) ตั้งค่า field definitions** (label ที่แสดงในฟอร์ม / ชนิด `text|number|date` / required / ลำดับ):
```bash
curl -X PUT http://localhost:5075/api/templates/$TPL_ID \
-H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
-d '{"fields": [
{ "key": "employee_name", "label": "ชื่อ-นามสกุล", "type": "text", "isRequired": true, "sortOrder": 0 },
{ "key": "salary", "label": "เงินเดือน", "type": "number", "isRequired": true, "sortOrder": 1 } ]}'
```
**3) Generate เอกสาร — ได้ .docx ที่เป็น version 1 พร้อม metadata:**
```bash
curl -X POST http://localhost:5075/api/documents/generate \
-H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
-d "{\"templateId\":\"$TPL_ID\",\"values\":{\"employee_name\":\"สมชาย ใจดี\",\"salary\":\"50000\"}}"
# → { "documentId": "...", "versionId": "...", "versionNumber": 1, "downloadUrl": "/api/documents/.../download" }
curl -H "Authorization: Bearer $TOKEN" -o ไฟล์ที่สร้าง.docx \
"http://localhost:5075$DOWNLOAD_URL"
```
เปิดไฟล์ที่ได้ตรวจได้ว่า: ค่าถูกทุก field (formatting ของ template คงเดิม) และมี custom properties `SavedByAddIn` / `DocumentTrackingId` (unzip ดู `docProps/custom.xml` หรือ Word → File → Info → Properties → Advanced Properties)
**4) Field sync ตอนสร้าง version ถัดไป** — upload v2 พร้อมแนบ `fields` (map tag→text ที่ extract จาก content controls — ในอนาคตฝั่ง add-in ทำให้อัตโนมัติ):
```bash
curl -X POST http://localhost:5075/api/documents/$DOC_ID/versions \
-H "Authorization: Bearer $TOKEN" \
-F "file=@ไฟล์แก้แล้ว.docx;type=application/vnd.openxmlformats-officedocument.wordprocessingml.document" \
-F "clientVersionId=$(uuidgen)" \
-F 'fields={"employee_name":"สมชาย ใจดี มากกว่าเดิม","salary":"60000"}'
```
แล้วดู `GET /api/documents/$DOC_ID/versions` — แต่ละ version มี snapshot fields ของตัวเอง หากลบ content control ออกจาก Word ก่อน upload field นั้นจะเห็น `"missing": true` โดยค่าเดิมยังคงอยู่ (ไม่ error)
### 3) Add-in และ Web Portal (ยังเป็น scaffold) ### 3) Add-in และ Web Portal (ยังเป็น scaffold)
```bash ```bash

View file

@ -1,5 +1,7 @@
using System.Globalization;
using System.Text.Json; using System.Text.Json;
using Amazon.Runtime; using Amazon.Runtime;
using DocumentFormat.OpenXml.Packaging;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
@ -11,7 +13,8 @@ using WordVersioning.Api.Services;
namespace WordVersioning.Api.Controllers; namespace WordVersioning.Api.Controllers;
/// <summary>FR-5 (upload version), FR-6 (history), FR-7 (download) + รับ fields สำหรับ FR-11</summary> /// <summary>FR-5 (upload version), FR-6 (history), FR-7 (download),
/// FR-10 (generate จาก template), FR-11 (field sync ตอน upload)</summary>
[ApiController] [ApiController]
[Authorize] // FR-8: ทุก endpoint ต้องแนบ token [Authorize] // FR-8: ทุก endpoint ต้องแนบ token
[Route("api/documents")] [Route("api/documents")]
@ -19,17 +22,21 @@ public class DocumentsController(
AppDbContext db, AppDbContext db,
IObjectStorageService storage, IObjectStorageService storage,
IHashService hasher, IHashService hasher,
IDocxGenerationService docxGeneration,
IFieldSyncService fieldSync,
ICurrentUser currentUser, ICurrentUser currentUser,
IOptions<MinioOptions> minioOptions, IOptions<MinioOptions> minioOptions,
ILogger<DocumentsController> logger) : ControllerBase ILogger<DocumentsController> logger) : ControllerBase
{ {
public const string DocxContentType = public const string DocxContentType = DocxUploadValidation.DocxContentType;
"application/vnd.openxmlformats-officedocument.wordprocessingml.document";
private static readonly JsonSerializerOptions SnapshotJsonOptions = new(JsonSerializerDefaults.Web);
private const long MaxUploadBytes = 100L * 1024 * 1024; // 100MB ตาม spec private const long MaxUploadBytes = 100L * 1024 * 1024; // 100MB ตาม spec
private const int MaxVersionInsertRetries = 5; private const int MaxVersionInsertRetries = 5;
/// <summary>FR-5 — อัปโหลด version ใหม่ (auto-create Document ถ้ายังไม่มี)</summary> /// <summary>FR-5 — อัปโหลด version ใหม่ (auto-create Document ถ้ายังไม่มี)
/// + FR-11: แนบ `fields` (map tag→text) → sync latest values + snapshot ต่อ version</summary>
[HttpPost("{documentId:guid}/versions")] [HttpPost("{documentId:guid}/versions")]
[RequestSizeLimit(MaxUploadBytes)] [RequestSizeLimit(MaxUploadBytes)]
[RequestFormLimits(MultipartBodyLengthLimit = MaxUploadBytes)] [RequestFormLimits(MultipartBodyLengthLimit = MaxUploadBytes)]
@ -45,30 +52,12 @@ public class DocumentsController(
return BadRequest("`clientVersionId` ต้องเป็น GUID"); return BadRequest("`clientVersionId` ต้องเป็น GUID");
if (request.File.Length > MaxUploadBytes) if (request.File.Length > MaxUploadBytes)
return StatusCode(StatusCodes.Status413PayloadTooLarge, $"ไฟล์ใหญ่เกิน {MaxUploadBytes / (1024 * 1024)}MB"); return StatusCode(StatusCodes.Status413PayloadTooLarge, $"ไฟล์ใหญ่เกิน {MaxUploadBytes / (1024 * 1024)}MB");
if (!IsValidDocx(request.File)) if (!DocxUploadValidation.IsValidDocx(request.File))
return BadRequest("รองรับเฉพาะไฟล์ .docx (Word document)"); return BadRequest("รองรับเฉพาะไฟล์ .docx (Word document)");
// parse fields map (FR-11) — optional, ผิด format คือ 400 // parse fields map (FR-11) — optional, ผิด format คือ 400
string? fieldsSnapshotJson = null; if (!FieldMapJson.TryParse(request.Fields, out var fieldMap, out var fieldsError))
if (!string.IsNullOrWhiteSpace(request.Fields)) return BadRequest(fieldsError);
{
try
{
using var fieldsDoc = JsonDocument.Parse(request.Fields);
if (fieldsDoc.RootElement.ValueKind != JsonValueKind.Object)
return BadRequest("`fields` ต้องเป็น JSON object รูป { tag: text }");
foreach (var prop in fieldsDoc.RootElement.EnumerateObject())
{
if (!IsScalar(prop.Value.ValueKind))
return BadRequest($"`fields.{prop.Name}` ต้องเป็นค่า scalar (string/number/bool/null)");
}
fieldsSnapshotJson = fieldsDoc.RootElement.GetRawText();
}
catch (JsonException)
{
return BadRequest("`fields` ไม่ใช่ JSON ที่ถูกต้อง");
}
}
var now = DateTimeOffset.UtcNow; var now = DateTimeOffset.UtcNow;
var fileName = request.File.FileName; var fileName = request.File.FileName;
@ -102,6 +91,26 @@ public class DocumentsController(
createdDoc = true; createdDoc = true;
} }
// FR-11 — stage การ sync field values ก่อน insert version (ค่าเดิมเก็บไว้เผื่อต้องถอนกลับ)
var versionId = Guid.NewGuid();
Dictionary<string, DocumentFieldValue>? fieldValuesBefore = null;
string? fieldsSnapshotJson;
if (doc.TemplateId is not null)
{
fieldValuesBefore = await db.DocumentFieldValues.AsNoTracking()
.Where(v => v.DocumentId == documentId)
.ToDictionaryAsync(v => v.FieldKey, ct);
var sync = await fieldSync.StageFieldSyncAsync(doc, versionId, fieldMap, now, ct);
fieldsSnapshotJson = sync.SnapshotJson;
}
else
{
// เอกสารไม่ผูก template (track เองจาก add-in) — ไม่มีนิยามให้ sync เก็บ map ดิบใน snapshot
fieldsSnapshotJson = fieldMap.Count == 0
? null
: JsonSerializer.Serialize(fieldMap, SnapshotJsonOptions);
}
// จอง versionNumber = max+1 — ถ้าชน unique index แปลว่ามี request คู่แข่ง ให้คำนวณใหม่ // จอง versionNumber = max+1 — ถ้าชน unique index แปลว่ามี request คู่แข่ง ให้คำนวณใหม่
DocumentVersion version = null!; DocumentVersion version = null!;
for (var attempt = 1; ; attempt++) for (var attempt = 1; ; attempt++)
@ -114,7 +123,7 @@ public class DocumentsController(
version = new DocumentVersion version = new DocumentVersion
{ {
Id = Guid.NewGuid(), Id = versionId, // ใช้ id เดิมทุก retry — field sync ที่ stage ไว้อ้างอิง id นี้
DocumentId = documentId, DocumentId = documentId,
VersionNumber = nextNumber, VersionNumber = nextNumber,
ObjectKey = $"{documentId}/v{nextNumber:D4}_{request.ClientVersionId}.docx", ObjectKey = $"{documentId}/v{nextNumber:D4}_{request.ClientVersionId}.docx",
@ -166,6 +175,7 @@ public class DocumentsController(
db.DocumentVersions.Remove(version); db.DocumentVersions.Remove(version);
if (createdDoc) if (createdDoc)
db.Documents.Remove(doc); db.Documents.Remove(doc);
RevertStagedFieldChanges(db, fieldValuesBefore);
await db.SaveChangesAsync(CancellationToken.None); await db.SaveChangesAsync(CancellationToken.None);
return StatusCode(StatusCodes.Status502BadGateway, "อัปโหลดไฟล์ขึ้น storage ไม่สำเร็จ"); return StatusCode(StatusCodes.Status502BadGateway, "อัปโหลดไฟล์ขึ้น storage ไม่สำเร็จ");
} }
@ -178,6 +188,153 @@ public class DocumentsController(
new UploadVersionResponse(version.Id, version.VersionNumber)); new UploadVersionResponse(version.Id, version.VersionNumber));
} }
/// <summary>FR-10 — สร้างเอกสารจาก template: generate docx + stamp metadata + upload version 1
/// + field values ทั้งหมดใน flow เดียว — เปิดใน Word แล้ว add-in ตรวจพบ tracked document ทันที (AC-12)</summary>
[HttpPost("generate")]
[ProducesResponseType(typeof(GenerateDocumentResponse), StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status502BadGateway)]
public async Task<IActionResult> Generate([FromBody] GenerateDocumentRequest request, CancellationToken ct)
{
var template = await db.Templates.AsNoTracking()
.FirstOrDefaultAsync(t => t.Id == request.TemplateId, ct);
if (template is null)
return NotFound($"ไม่พบ template {request.TemplateId}");
if (!template.IsActive)
return BadRequest("template นี้ถูก deactivate แล้ว — สร้างเอกสารใหม่ไม่ได้ (เอกสารที่สร้างไว้แล้วยังใช้ได้)");
var fieldDefs = await db.TemplateFields.AsNoTracking()
.Where(f => f.TemplateId == template.Id)
.OrderBy(f => f.SortOrder)
.ToListAsync(ct);
if (!FieldMapJson.TryNormalize(request.Values, out var values, out var valuesError))
return BadRequest($"`values` ผิด format: {valuesError}");
// validate required + type (FR-10) — field ที่ส่งเกินนิยาม ignore ตาม policy เดียวกับ FR-11
var missingRequired = fieldDefs
.Where(f => f.IsRequired && (!values.TryGetValue(f.Key, out var v) || string.IsNullOrWhiteSpace(v ?? string.Empty)))
.Select(f => f.Key)
.ToList();
if (missingRequired.Count > 0)
return BadRequest($"กรอก required fields ให้ครบ: {string.Join(", ", missingRequired)}");
var typeErrors = new List<string>();
foreach (var def in fieldDefs)
{
if (!values.TryGetValue(def.Key, out var v) || string.IsNullOrWhiteSpace(v))
continue;
var valid = def.Type switch
{
"number" => decimal.TryParse(v, NumberStyles.Number, CultureInfo.InvariantCulture, out _),
"date" => DateTimeOffset.TryParse(v, CultureInfo.InvariantCulture, DateTimeStyles.None, out _),
_ => true,
};
if (!valid)
typeErrors.Add(def.Type == "number"
? $"`{def.Key}` ต้องเป็นตัวเลข"
: $"`{def.Key}` ต้องเป็นวันที่ที่ parse ได้ (ISO-8601 เช่น 2026-08-19)");
}
if (typeErrors.Count > 0)
return BadRequest(string.Join("; ", typeErrors));
// โหลด template จาก MinIO → generate ไฟล์ + stamp custom properties (FR-10)
Stream templateStream;
try
{
templateStream = await storage.GetStreamAsync(minioOptions.Value.TemplatesBucket, template.ObjectKey, ct);
}
catch (KeyNotFoundException)
{
logger.LogError("Template object missing in storage templateId={TemplateId} key={ObjectKey}",
template.Id, template.ObjectKey);
return StatusCode(StatusCodes.Status502BadGateway, "ไฟล์ template ไม่พบใน storage");
}
// documentId = DocumentTrackingId ที่ stamp ลงไฟล์ — add-in ใช้ค่านี้เรียก history ต่อ
var documentId = Guid.NewGuid();
byte[] fileBytes;
try
{
await using (templateStream)
{
// null (JSON null) มองเป็นค่าว่าง — field "หาย" คือไม่มี key ใน map เท่านั้น
fileBytes = docxGeneration.Generate(
templateStream,
values.ToDictionary(kv => kv.Key, kv => kv.Value ?? string.Empty),
documentId);
}
}
catch (OpenXmlPackageException ex)
{
logger.LogError(ex, "Template file corrupt templateId={TemplateId} key={ObjectKey}",
template.Id, template.ObjectKey);
return StatusCode(StatusCodes.Status502BadGateway, "ไฟล์ template เสียหาย (เปิดด้วย OpenXML ไม่ได้)");
}
var now = DateTimeOffset.UtcNow;
using (var hashStream = new MemoryStream(fileBytes))
{
var contentHash = await hasher.ComputeSha256HexAsync(hashStream, ct);
var doc = new Document
{
Id = documentId,
FileName = BuildGeneratedFileName(template.Name, now),
AddInSignature = AddInMetadata.AddInSignatureGuid,
TemplateId = template.Id,
CreatedAt = now,
};
db.Documents.Add(doc);
var version = new DocumentVersion
{
Id = Guid.NewGuid(),
DocumentId = documentId,
VersionNumber = 1,
ObjectKey = $"{documentId}/v0001_{Guid.NewGuid()}.docx", // clientVersionId generate ฝั่ง server (flow นี้ไม่มี client)
ContentHash = contentHash,
CreatedByUserId = currentUser.UserId,
CreatedAt = now,
};
db.DocumentVersions.Add(version);
// snapshot + field values ของ v1 (ทุก field มีค่า = missing=false ทั้งหมด)
var sync = await fieldSync.StageFieldSyncAsync(doc, version.Id, values, now, ct);
version.FieldsSnapshotJson = sync.SnapshotJson;
try
{
await storage.PutAsync(minioOptions.Value.VersionsBucket, version.ObjectKey,
new MemoryStream(fileBytes), DocxContentType, ct);
}
catch (AmazonServiceException ex)
{
logger.LogError(ex, "MinIO upload failed on generate documentId={DocumentId} templateId={TemplateId} userId={UserId}",
documentId, template.Id, currentUser.UserId);
// ถอนทั้งชุด — document ที่สร้างใหม่ยังไม่ถูกใครเห็น ลบได้สะอาด (field values ตาม FK cascade)
db.Entry(version).State = EntityState.Detached;
db.Entry(doc).State = EntityState.Detached;
foreach (var entry in db.ChangeTracker.Entries<DocumentFieldValue>().ToList())
entry.State = EntityState.Detached;
return StatusCode(StatusCodes.Status502BadGateway, "อัปโหลดไฟล์ขึ้น storage ไม่สำเร็จ");
}
await db.SaveChangesAsync(ct);
logger.LogInformation(
"Document generated documentId={DocumentId} templateId={TemplateId} versionId={VersionId} userId={UserId} bytes={Size} hash={Hash}",
documentId, template.Id, version.Id, currentUser.UserId, fileBytes.Length, contentHash);
return CreatedAtAction(nameof(GetVersions), new { documentId },
new GenerateDocumentResponse(
documentId, version.Id, version.VersionNumber,
$"/api/documents/{documentId}/versions/{version.Id}/download"));
}
}
/// <summary>FR-6 — version history เรียงใหม่ → เก่า (พร้อม snapshot fields ต่อ version)</summary> /// <summary>FR-6 — version history เรียงใหม่ → เก่า (พร้อม snapshot fields ต่อ version)</summary>
[HttpGet("{documentId:guid}/versions")] [HttpGet("{documentId:guid}/versions")]
[ProducesResponseType(typeof(IReadOnlyList<VersionListItem>), StatusCodes.Status200OK)] [ProducesResponseType(typeof(IReadOnlyList<VersionListItem>), StatusCodes.Status200OK)]
@ -243,20 +400,40 @@ public class DocumentsController(
return File(stream, DocxContentType, downloadName); return File(stream, DocxContentType, downloadName);
} }
private static bool IsValidDocx(IFormFile file) => /// <summary>ถอนการเปลี่ยน DocumentFieldValue ที่ stage ไว้กลับเป็นค่าก่อน request
file.FileName.EndsWith(".docx", StringComparison.OrdinalIgnoreCase) /// — ใช้ตอน MinIO fail หลัง SaveChanges แล้ว (ไม่ให้ค่าล้ำหน้า version ที่ถูกถอน)</summary>
&& IsAcceptableContentType(file.ContentType); private static void RevertStagedFieldChanges(
AppDbContext db, Dictionary<string, DocumentFieldValue>? valuesBefore)
{
if (valuesBefore is null)
return;
// spec: reject content-type ที่ไม่ใช่ docx — ยอมรับ octet-stream/zip ด้วยเพราะ client บางตัว foreach (var entry in db.ChangeTracker.Entries<DocumentFieldValue>().ToList())
// (เช่น curl -F) ไม่ set ชนิดไฟล์ให้ ส่วนชื่อไฟล์ต้องลง .docx เสมอ (เช็คข้างบน) {
private static bool IsAcceptableContentType(string contentType) => if (entry.State == EntityState.Added)
string.IsNullOrWhiteSpace(contentType) {
|| contentType.Equals(DocxContentType, StringComparison.OrdinalIgnoreCase) entry.State = EntityState.Detached;
|| contentType.Equals("application/octet-stream", StringComparison.OrdinalIgnoreCase) }
|| contentType.Equals("application/zip", StringComparison.OrdinalIgnoreCase); else if (entry.State == EntityState.Modified && valuesBefore.TryGetValue(entry.Entity.FieldKey, out var before))
{
entry.Entity.Value = before.Value;
entry.Entity.SourceVersionId = before.SourceVersionId;
entry.Entity.UpdatedByUserId = before.UpdatedByUserId;
entry.Entity.UpdatedAt = before.UpdatedAt;
entry.State = EntityState.Unchanged;
}
}
}
private static bool IsScalar(JsonValueKind kind) => /// <summary>ชื่อไฟล์ของเอกสารที่ generate: ชื่อ template + timestamp — ตัดอักขระที่ filename ใช้ไม่ได้ออก</summary>
kind is JsonValueKind.String or JsonValueKind.Number or JsonValueKind.True or JsonValueKind.False or JsonValueKind.Null; private static string BuildGeneratedFileName(string templateName, DateTimeOffset now)
{
var invalid = Path.GetInvalidFileNameChars();
var clean = new string(templateName.Select(c => invalid.Contains(c) ? '_' : c).ToArray()).Trim();
if (clean.Length == 0)
clean = "document";
return $"{clean}_{now:yyyyMMdd-HHmmss}.docx";
}
private static object? ParseSnapshot(string? json) private static object? ParseSnapshot(string? json)
{ {

View file

@ -0,0 +1,325 @@
using Amazon.Runtime;
using DocumentFormat.OpenXml.Packaging;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using WordVersioning.Api.Data;
using WordVersioning.Api.Models;
using WordVersioning.Api.Services;
namespace WordVersioning.Api.Controllers;
/// <summary>FR-9 — template CRUD + auto-detect fields (SDT tags) ตอน upload/replace ไฟล์</summary>
[ApiController]
[Authorize]
[Route("api/templates")]
public class TemplatesController(
AppDbContext db,
IObjectStorageService storage,
IDocxGenerationService docxGeneration,
ICurrentUser currentUser,
IOptions<MinioOptions> minioOptions,
ILogger<TemplatesController> logger) : ControllerBase
{
private const long MaxUploadBytes = 100L * 1024 * 1024; // 100MB ตาม spec
/// <summary>รายการ template — default เฉพาะ active (หน้าเลือกสร้างเอกสาร), ส่ง includeInactive=true สำหรับหน้า admin</summary>
[HttpGet]
[ProducesResponseType(typeof(IReadOnlyList<TemplateListItem>), StatusCodes.Status200OK)]
public async Task<ActionResult<IReadOnlyList<TemplateListItem>>> List(
[FromQuery] bool includeInactive = false, CancellationToken ct = default)
{
var query = db.Templates.AsNoTracking().AsQueryable();
if (!includeInactive)
query = query.Where(t => t.IsActive);
var rows = await query
.OrderBy(t => t.Name)
.Select(t => new
{
t.Id,
t.Name,
t.Description,
t.IsActive,
FieldCount = t.Fields.Count,
t.CreatedAt,
t.UpdatedAt,
})
.ToListAsync(ct);
return Ok(rows.Select(r => new TemplateListItem(
r.Id, r.Name, r.Description, r.IsActive, r.FieldCount, r.CreatedAt, r.UpdatedAt)).ToList());
}
/// <summary>รายละเอียด template พร้อม field definitions (สำหรับหน้า edit)</summary>
[HttpGet("{id:guid}")]
[ProducesResponseType(typeof(TemplateDetail), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<ActionResult<TemplateDetail>> Get(Guid id, CancellationToken ct)
{
var template = await db.Templates.AsNoTracking()
.Include(t => t.Fields)
.FirstOrDefaultAsync(t => t.Id == id, ct);
if (template is null)
return NotFound($"ไม่พบ template {id}");
return Ok(ToDetail(template));
}
/// <summary>upload template ใหม่ — parse SDT tags ออกมาเป็น field list อัตโนมัติ
/// (สร้าง TemplateField พร้อมค่า default ทันที: label = tag, type = text, required = false)</summary>
[HttpPost]
[RequestSizeLimit(MaxUploadBytes)]
[RequestFormLimits(MultipartBodyLengthLimit = MaxUploadBytes)]
[ProducesResponseType(typeof(CreateTemplateResponse), StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status413PayloadTooLarge)]
[ProducesResponseType(StatusCodes.Status502BadGateway)]
public async Task<IActionResult> Create([FromForm] CreateTemplateRequest request, CancellationToken ct)
{
if (string.IsNullOrWhiteSpace(request.Name))
return BadRequest("ต้องระบุ `name`");
if (request.File is null || request.File.Length == 0)
return BadRequest("ต้องแนบไฟล์ `file` (docx)");
if (request.File.Length > MaxUploadBytes)
return StatusCode(StatusCodes.Status413PayloadTooLarge, $"ไฟล์ใหญ่เกิน {MaxUploadBytes / (1024 * 1024)}MB");
if (!DocxUploadValidation.IsValidDocx(request.File))
return BadRequest("รองรับเฉพาะไฟล์ .docx (Word document)");
// detect fields จากไฟล์ที่อัปโหลด (IFormFile spool ลง disk แล้ว — stream seek ได้)
List<string> tags;
try
{
await using var detectStream = request.File.OpenReadStream();
tags = docxGeneration.DetectFieldTags(detectStream).ToList();
}
catch (OpenXmlPackageException ex)
{
logger.LogWarning(ex, "Template upload: ไฟล์เปิดไม่ได้ userId={UserId} fileName={FileName}",
currentUser.UserId, request.File.FileName);
return BadRequest("ไฟล์ .docx ไม่ถูกต้อง (เปิดด้วย OpenXML ไม่ได้)");
}
var now = DateTimeOffset.UtcNow;
var template = new Template
{
Id = Guid.NewGuid(),
Name = request.Name.Trim(),
Description = string.IsNullOrWhiteSpace(request.Description) ? null : request.Description.Trim(),
ObjectKey = string.Empty, // จะเติมหลัง upload สำเร็จ — ไม่บันทึก row ที่ชี้ไฟล์ที่ไม่มีจริง
IsActive = true,
CreatedAt = now,
UpdatedAt = now,
};
var sortOrder = 0;
foreach (var tag in tags)
{
template.Fields.Add(new TemplateField
{
TemplateId = template.Id,
Key = tag,
Label = tag, // default — admin ไปตั้งต่อผ่าน PUT
Type = "text",
IsRequired = false,
SortOrder = sortOrder++,
});
}
// upload ไฟล์ก่อน insert row — ถ้า DB fail ทีหลังจะเหลือ object กำพร้าใน bucket (log ไว้ ไม่กระทบกระเสีย)
var objectKey = $"{template.Id}/{now:yyyyMMddHHmmss}.docx";
try
{
await using var uploadStream = request.File.OpenReadStream();
uploadStream.Seek(0, SeekOrigin.Begin);
await storage.PutAsync(minioOptions.Value.TemplatesBucket, objectKey, uploadStream,
DocxUploadValidation.DocxContentType, ct);
}
catch (AmazonServiceException ex)
{
logger.LogError(ex, "Template file upload failed templateId={TemplateId} userId={UserId}",
template.Id, currentUser.UserId);
return StatusCode(StatusCodes.Status502BadGateway, "อัปโหลดไฟล์ขึ้น storage ไม่สำเร็จ");
}
template.ObjectKey = objectKey;
db.Templates.Add(template);
await db.SaveChangesAsync(ct);
logger.LogInformation(
"Template created templateId={TemplateId} name={TemplateName} fields={FieldCount} userId={UserId}",
template.Id, template.Name, template.Fields.Count, currentUser.UserId);
return CreatedAtAction(nameof(Get), new { id = template.Id },
new CreateTemplateResponse(template.Id, FieldDtos(template)));
}
/// <summary>แก้ metadata + บันทึก field definitions (label/type/required/sortOrder)
/// — key ต้องเป็นชุดที่ detect ไว้เท่านั้น จะเพิ่ม/ลบ key ต้องผ่านการ replace ไฟล์</summary>
[HttpPut("{id:guid}")]
[ProducesResponseType(typeof(TemplateDetail), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> Update(Guid id, [FromBody] UpdateTemplateRequest request, CancellationToken ct)
{
var template = await db.Templates
.Include(t => t.Fields)
.FirstOrDefaultAsync(t => t.Id == id, ct);
if (template is null)
return NotFound($"ไม่พบ template {id}");
if (request.Name is not null)
{
if (string.IsNullOrWhiteSpace(request.Name))
return BadRequest("`name` ห้ามว่าง");
template.Name = request.Name.Trim();
}
if (request.Description is not null)
template.Description = string.IsNullOrWhiteSpace(request.Description) ? null : request.Description.Trim();
if (request.IsActive.HasValue)
template.IsActive = request.IsActive.Value;
if (request.Fields is not null)
{
var unknown = request.Fields
.Select(f => f.Key)
.Distinct()
.Except(template.Fields.Select(f => f.Key))
.ToList();
if (unknown.Count > 0)
return BadRequest($"ไม่รู้จัก field key: {string.Join(", ", unknown)} (key มาจากไฟล์ — เพิ่ม/ลบต้อง replace ไฟล์)");
foreach (var def in request.Fields)
{
if (!TemplateField.ValidTypes.Contains(def.Type))
return BadRequest($"type ของ `{def.Key}` ต้องเป็น text/number/date (ได้ `{def.Type}`)");
if (string.IsNullOrWhiteSpace(def.Label))
return BadRequest($"label ของ `{def.Key}` ห้ามว่าง");
var row = template.Fields.First(f => f.Key == def.Key);
row.Label = def.Label.Trim();
row.Type = def.Type;
row.IsRequired = def.IsRequired;
row.SortOrder = def.SortOrder;
}
}
template.UpdatedAt = DateTimeOffset.UtcNow;
await db.SaveChangesAsync(ct);
logger.LogInformation("Template updated templateId={TemplateId} userId={UserId}", template.Id, currentUser.UserId);
return Ok(ToDetail(template));
}
/// <summary>แทนที่ไฟล์ template — re-detect fields: tag ใหม่เพิ่มเป็น default, tag ที่หายไปลบนิยามทิ้ง
/// (document เก่าที่สร้างไปแล้วไม่กระทบ — field values เก็บแยกที่ตัว document)</summary>
[HttpPut("{id:guid}/file")]
[RequestSizeLimit(MaxUploadBytes)]
[RequestFormLimits(MultipartBodyLengthLimit = MaxUploadBytes)]
[ProducesResponseType(typeof(ReplaceTemplateFileResponse), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status502BadGateway)]
public async Task<IActionResult> ReplaceFile(Guid id, [FromForm] ReplaceTemplateFileRequest request, CancellationToken ct)
{
var template = await db.Templates
.Include(t => t.Fields)
.FirstOrDefaultAsync(t => t.Id == id, ct);
if (template is null)
return NotFound($"ไม่พบ template {id}");
if (request.File is null || request.File.Length == 0)
return BadRequest("ต้องแนบไฟล์ `file` (docx)");
if (request.File.Length > MaxUploadBytes)
return StatusCode(StatusCodes.Status413PayloadTooLarge, $"ไฟล์ใหญ่เกิน {MaxUploadBytes / (1024 * 1024)}MB");
if (!DocxUploadValidation.IsValidDocx(request.File))
return BadRequest("รองรับเฉพาะไฟล์ .docx (Word document)");
List<string> newTags;
try
{
await using var detectStream = request.File.OpenReadStream();
newTags = docxGeneration.DetectFieldTags(detectStream).ToList();
}
catch (OpenXmlPackageException ex)
{
logger.LogWarning(ex, "Template replace: ไฟล์เปิดไม่ได้ templateId={TemplateId} userId={UserId}",
template.Id, currentUser.UserId);
return BadRequest("ไฟล์ .docx ไม่ถูกต้อง (เปิดด้วย OpenXML ไม่ได้)");
}
var existingKeys = template.Fields.Select(f => f.Key).ToList();
var addedTags = newTags.Except(existingKeys).ToList();
var removedTags = existingKeys.Except(newTags).ToList();
var now = DateTimeOffset.UtcNow;
var objectKey = $"{template.Id}/{now:yyyyMMddHHmmss}.docx";
try
{
await using var uploadStream = request.File.OpenReadStream();
uploadStream.Seek(0, SeekOrigin.Begin);
await storage.PutAsync(minioOptions.Value.TemplatesBucket, objectKey, uploadStream,
DocxUploadValidation.DocxContentType, ct);
}
catch (AmazonServiceException ex)
{
logger.LogError(ex, "Template file upload failed templateId={TemplateId} userId={UserId}",
template.Id, currentUser.UserId);
return StatusCode(StatusCodes.Status502BadGateway, "อัปโหลดไฟล์ขึ้น storage ไม่สำเร็จ");
}
template.ObjectKey = objectKey;
template.UpdatedAt = now;
foreach (var removed in template.Fields.Where(f => removedTags.Contains(f.Key)).ToList())
template.Fields.Remove(removed);
var nextSort = template.Fields.Count == 0 ? 0 : template.Fields.Max(f => f.SortOrder) + 1;
foreach (var tag in addedTags)
{
// ห้าม set Id เอง — Guid PK ที่มีค่าทำให้ EF ตีเป็น Modified (update แถวที่ไม่มี) แทน Added
template.Fields.Add(new TemplateField
{
TemplateId = template.Id,
Key = tag,
Label = tag,
Type = "text",
IsRequired = false,
SortOrder = nextSort++,
});
}
await db.SaveChangesAsync(ct);
logger.LogInformation(
"Template file replaced templateId={TemplateId} userId={UserId} added={AddedTags} removed={RemovedTags}",
template.Id, currentUser.UserId, string.Join(",", addedTags), string.Join(",", removedTags));
return Ok(new ReplaceTemplateFileResponse(template.Id, FieldDtos(template), addedTags, removedTags));
}
/// <summary>deactivate (soft-delete) — document เก่าที่อ้างอยู่ยังใช้ได้ต่อ แต่สร้างเอกสารใหม่ไม่ได้</summary>
[HttpDelete("{id:guid}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> Deactivate(Guid id, CancellationToken ct)
{
var template = await db.Templates.FirstOrDefaultAsync(t => t.Id == id, ct);
if (template is null)
return NotFound($"ไม่พบ template {id}");
template.IsActive = false;
template.UpdatedAt = DateTimeOffset.UtcNow;
await db.SaveChangesAsync(ct);
logger.LogInformation("Template deactivated templateId={TemplateId} userId={UserId}", template.Id, currentUser.UserId);
return NoContent();
}
private static TemplateDetail ToDetail(Template template) => new(
template.Id, template.Name, template.Description, template.IsActive,
template.CreatedAt, template.UpdatedAt, FieldDtos(template));
private static List<TemplateFieldDto> FieldDtos(Template template) => template.Fields
.OrderBy(f => f.SortOrder)
.Select(f => new TemplateFieldDto(f.Id, f.Key, f.Label, f.Type, f.IsRequired, f.SortOrder))
.ToList();
}

View file

@ -9,6 +9,12 @@ public class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(op
public DbSet<DocumentVersion> DocumentVersions => Set<DocumentVersion>(); public DbSet<DocumentVersion> DocumentVersions => Set<DocumentVersion>();
public DbSet<Template> Templates => Set<Template>();
public DbSet<TemplateField> TemplateFields => Set<TemplateField>();
public DbSet<DocumentFieldValue> DocumentFieldValues => Set<DocumentFieldValue>();
protected override void OnModelCreating(ModelBuilder modelBuilder) protected override void OnModelCreating(ModelBuilder modelBuilder)
{ {
modelBuilder.Entity<Document>(entity => modelBuilder.Entity<Document>(entity =>
@ -16,6 +22,13 @@ public class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(op
entity.HasKey(x => x.Id); entity.HasKey(x => x.Id);
entity.Property(x => x.FileName).HasMaxLength(512); entity.Property(x => x.FileName).HasMaxLength(512);
entity.Property(x => x.AddInSignature).HasMaxLength(64); entity.Property(x => x.AddInSignature).HasMaxLength(64);
// FR-10: เอกสารผูกกับ template — Restrict เพราะ template ต้อง soft-delete เท่านั้น
// (แถว Template ไม่ควรถูกลบจริงตรงๆ แต่กันไว้เผื่อมือสั่น)
entity.HasOne(x => x.Template)
.WithMany(t => t.Documents)
.HasForeignKey(x => x.TemplateId)
.OnDelete(DeleteBehavior.Restrict);
}); });
modelBuilder.Entity<DocumentVersion>(entity => modelBuilder.Entity<DocumentVersion>(entity =>
@ -32,5 +45,47 @@ public class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(op
.WithMany(d => d.Versions) .WithMany(d => d.Versions)
.HasForeignKey(x => x.DocumentId); .HasForeignKey(x => x.DocumentId);
}); });
modelBuilder.Entity<Template>(entity =>
{
entity.HasKey(x => x.Id);
entity.Property(x => x.Name).HasMaxLength(256);
entity.Property(x => x.Description).HasMaxLength(2048);
entity.Property(x => x.ObjectKey).HasMaxLength(1024);
entity.HasMany(x => x.Documents)
.WithOne(d => d.Template)
.HasForeignKey(d => d.TemplateId);
});
modelBuilder.Entity<TemplateField>(entity =>
{
entity.HasKey(x => x.Id);
// Key = SDT tag ต้อง unique ต่อ template (spec ส่วน 9 เพิ่มเติม v2)
entity.HasIndex(x => new { x.TemplateId, x.Key }).IsUnique();
entity.Property(x => x.Key).HasMaxLength(256);
entity.Property(x => x.Label).HasMaxLength(512);
entity.Property(x => x.Type).HasMaxLength(16);
entity.HasOne(x => x.Template)
.WithMany(t => t.Fields)
.HasForeignKey(x => x.TemplateId)
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity<DocumentFieldValue>(entity =>
{
// latest value ต่อ (document, field) — ตาม spec ส่วน 7 ไม่มี Id แยก
entity.HasKey(x => new { x.DocumentId, x.FieldKey });
entity.Property(x => x.FieldKey).HasMaxLength(256);
entity.HasOne<Document>()
.WithMany()
.HasForeignKey(x => x.DocumentId)
.OnDelete(DeleteBehavior.Cascade);
});
} }
} }

View file

@ -0,0 +1,252 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using WordVersioning.Api.Data;
#nullable disable
namespace WordVersioning.Api.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20260819045552_TemplatesAndFieldSync")]
partial class TemplatesAndFieldSync
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "8.0.11")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("WordVersioning.Api.Models.Document", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("AddInSignature")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("character varying(64)");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("FileName")
.IsRequired()
.HasMaxLength(512)
.HasColumnType("character varying(512)");
b.Property<Guid?>("TemplateId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("TemplateId");
b.ToTable("Documents");
});
modelBuilder.Entity("WordVersioning.Api.Models.DocumentFieldValue", b =>
{
b.Property<Guid>("DocumentId")
.HasColumnType("uuid");
b.Property<string>("FieldKey")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<Guid>("SourceVersionId")
.HasColumnType("uuid");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("UpdatedByUserId")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Value")
.IsRequired()
.HasColumnType("text");
b.HasKey("DocumentId", "FieldKey");
b.ToTable("DocumentFieldValues");
});
modelBuilder.Entity("WordVersioning.Api.Models.DocumentVersion", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("ContentHash")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("character varying(64)");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("CreatedByUserId")
.IsRequired()
.HasColumnType("text");
b.Property<Guid>("DocumentId")
.HasColumnType("uuid");
b.Property<string>("FieldsSnapshotJson")
.HasColumnType("text");
b.Property<string>("ObjectKey")
.IsRequired()
.HasMaxLength(1024)
.HasColumnType("character varying(1024)");
b.Property<int>("VersionNumber")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("DocumentId", "VersionNumber")
.IsUnique();
b.ToTable("DocumentVersions");
});
modelBuilder.Entity("WordVersioning.Api.Models.Template", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Description")
.HasMaxLength(2048)
.HasColumnType("character varying(2048)");
b.Property<bool>("IsActive")
.HasColumnType("boolean");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("ObjectKey")
.IsRequired()
.HasMaxLength(1024)
.HasColumnType("character varying(1024)");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.ToTable("Templates");
});
modelBuilder.Entity("WordVersioning.Api.Models.TemplateField", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<bool>("IsRequired")
.HasColumnType("boolean");
b.Property<string>("Key")
.IsRequired()
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("Label")
.IsRequired()
.HasMaxLength(512)
.HasColumnType("character varying(512)");
b.Property<int>("SortOrder")
.HasColumnType("integer");
b.Property<Guid>("TemplateId")
.HasColumnType("uuid");
b.Property<string>("Type")
.IsRequired()
.HasMaxLength(16)
.HasColumnType("character varying(16)");
b.HasKey("Id");
b.HasIndex("TemplateId", "Key")
.IsUnique();
b.ToTable("TemplateFields");
});
modelBuilder.Entity("WordVersioning.Api.Models.Document", b =>
{
b.HasOne("WordVersioning.Api.Models.Template", "Template")
.WithMany("Documents")
.HasForeignKey("TemplateId")
.OnDelete(DeleteBehavior.Restrict);
b.Navigation("Template");
});
modelBuilder.Entity("WordVersioning.Api.Models.DocumentFieldValue", b =>
{
b.HasOne("WordVersioning.Api.Models.Document", null)
.WithMany()
.HasForeignKey("DocumentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("WordVersioning.Api.Models.DocumentVersion", b =>
{
b.HasOne("WordVersioning.Api.Models.Document", "Document")
.WithMany("Versions")
.HasForeignKey("DocumentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Document");
});
modelBuilder.Entity("WordVersioning.Api.Models.TemplateField", b =>
{
b.HasOne("WordVersioning.Api.Models.Template", "Template")
.WithMany("Fields")
.HasForeignKey("TemplateId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Template");
});
modelBuilder.Entity("WordVersioning.Api.Models.Document", b =>
{
b.Navigation("Versions");
});
modelBuilder.Entity("WordVersioning.Api.Models.Template", b =>
{
b.Navigation("Documents");
b.Navigation("Fields");
});
#pragma warning restore 612, 618
}
}
}

View file

@ -0,0 +1,117 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace WordVersioning.Api.Migrations
{
/// <inheritdoc />
public partial class TemplatesAndFieldSync : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "DocumentFieldValues",
columns: table => new
{
DocumentId = table.Column<Guid>(type: "uuid", nullable: false),
FieldKey = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: false),
Value = table.Column<string>(type: "text", nullable: false),
SourceVersionId = table.Column<Guid>(type: "uuid", nullable: false),
UpdatedByUserId = table.Column<string>(type: "text", nullable: false),
UpdatedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_DocumentFieldValues", x => new { x.DocumentId, x.FieldKey });
table.ForeignKey(
name: "FK_DocumentFieldValues_Documents_DocumentId",
column: x => x.DocumentId,
principalTable: "Documents",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Templates",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
Name = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: false),
Description = table.Column<string>(type: "character varying(2048)", maxLength: 2048, nullable: true),
ObjectKey = table.Column<string>(type: "character varying(1024)", maxLength: 1024, nullable: false),
IsActive = table.Column<bool>(type: "boolean", nullable: false),
CreatedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
UpdatedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Templates", x => x.Id);
});
migrationBuilder.CreateTable(
name: "TemplateFields",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
TemplateId = table.Column<Guid>(type: "uuid", nullable: false),
Key = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: false),
Label = table.Column<string>(type: "character varying(512)", maxLength: 512, nullable: false),
Type = table.Column<string>(type: "character varying(16)", maxLength: 16, nullable: false),
IsRequired = table.Column<bool>(type: "boolean", nullable: false),
SortOrder = table.Column<int>(type: "integer", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_TemplateFields", x => x.Id);
table.ForeignKey(
name: "FK_TemplateFields_Templates_TemplateId",
column: x => x.TemplateId,
principalTable: "Templates",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_Documents_TemplateId",
table: "Documents",
column: "TemplateId");
migrationBuilder.CreateIndex(
name: "IX_TemplateFields_TemplateId_Key",
table: "TemplateFields",
columns: new[] { "TemplateId", "Key" },
unique: true);
migrationBuilder.AddForeignKey(
name: "FK_Documents_Templates_TemplateId",
table: "Documents",
column: "TemplateId",
principalTable: "Templates",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Documents_Templates_TemplateId",
table: "Documents");
migrationBuilder.DropTable(
name: "DocumentFieldValues");
migrationBuilder.DropTable(
name: "TemplateFields");
migrationBuilder.DropTable(
name: "Templates");
migrationBuilder.DropIndex(
name: "IX_Documents_TemplateId",
table: "Documents");
}
}
}

View file

@ -46,9 +46,39 @@ namespace WordVersioning.Api.Migrations
b.HasKey("Id"); b.HasKey("Id");
b.HasIndex("TemplateId");
b.ToTable("Documents"); b.ToTable("Documents");
}); });
modelBuilder.Entity("WordVersioning.Api.Models.DocumentFieldValue", b =>
{
b.Property<Guid>("DocumentId")
.HasColumnType("uuid");
b.Property<string>("FieldKey")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<Guid>("SourceVersionId")
.HasColumnType("uuid");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("UpdatedByUserId")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Value")
.IsRequired()
.HasColumnType("text");
b.HasKey("DocumentId", "FieldKey");
b.ToTable("DocumentFieldValues");
});
modelBuilder.Entity("WordVersioning.Api.Models.DocumentVersion", b => modelBuilder.Entity("WordVersioning.Api.Models.DocumentVersion", b =>
{ {
b.Property<Guid>("Id") b.Property<Guid>("Id")
@ -89,6 +119,97 @@ namespace WordVersioning.Api.Migrations
b.ToTable("DocumentVersions"); b.ToTable("DocumentVersions");
}); });
modelBuilder.Entity("WordVersioning.Api.Models.Template", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Description")
.HasMaxLength(2048)
.HasColumnType("character varying(2048)");
b.Property<bool>("IsActive")
.HasColumnType("boolean");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("ObjectKey")
.IsRequired()
.HasMaxLength(1024)
.HasColumnType("character varying(1024)");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.ToTable("Templates");
});
modelBuilder.Entity("WordVersioning.Api.Models.TemplateField", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<bool>("IsRequired")
.HasColumnType("boolean");
b.Property<string>("Key")
.IsRequired()
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("Label")
.IsRequired()
.HasMaxLength(512)
.HasColumnType("character varying(512)");
b.Property<int>("SortOrder")
.HasColumnType("integer");
b.Property<Guid>("TemplateId")
.HasColumnType("uuid");
b.Property<string>("Type")
.IsRequired()
.HasMaxLength(16)
.HasColumnType("character varying(16)");
b.HasKey("Id");
b.HasIndex("TemplateId", "Key")
.IsUnique();
b.ToTable("TemplateFields");
});
modelBuilder.Entity("WordVersioning.Api.Models.Document", b =>
{
b.HasOne("WordVersioning.Api.Models.Template", "Template")
.WithMany("Documents")
.HasForeignKey("TemplateId")
.OnDelete(DeleteBehavior.Restrict);
b.Navigation("Template");
});
modelBuilder.Entity("WordVersioning.Api.Models.DocumentFieldValue", b =>
{
b.HasOne("WordVersioning.Api.Models.Document", null)
.WithMany()
.HasForeignKey("DocumentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("WordVersioning.Api.Models.DocumentVersion", b => modelBuilder.Entity("WordVersioning.Api.Models.DocumentVersion", b =>
{ {
b.HasOne("WordVersioning.Api.Models.Document", "Document") b.HasOne("WordVersioning.Api.Models.Document", "Document")
@ -100,10 +221,28 @@ namespace WordVersioning.Api.Migrations
b.Navigation("Document"); b.Navigation("Document");
}); });
modelBuilder.Entity("WordVersioning.Api.Models.TemplateField", b =>
{
b.HasOne("WordVersioning.Api.Models.Template", "Template")
.WithMany("Fields")
.HasForeignKey("TemplateId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Template");
});
modelBuilder.Entity("WordVersioning.Api.Models.Document", b => modelBuilder.Entity("WordVersioning.Api.Models.Document", b =>
{ {
b.Navigation("Versions"); b.Navigation("Versions");
}); });
modelBuilder.Entity("WordVersioning.Api.Models.Template", b =>
{
b.Navigation("Documents");
b.Navigation("Fields");
});
#pragma warning restore 612, 618 #pragma warning restore 612, 618
} }
} }

View file

@ -10,10 +10,11 @@ public class Document
/// <summary>ค่า custom property `SavedByAddIn` ที่ stamp ไว้ในไฟล์ (FR-1)</summary> /// <summary>ค่า custom property `SavedByAddIn` ที่ stamp ไว้ในไฟล์ (FR-1)</summary>
public string AddInSignature { get; set; } = string.Empty; public string AddInSignature { get; set; } = string.Empty;
/// <summary>เอกสารที่สร้างจาก template (FR-10) — null ถ้า track เอกสารเปล่า /// <summary>เอกสารที่สร้างจาก template (FR-10) — null ถ้า track เอกสารเปล่า</summary>
/// (Phase 3 จะเติม FK ไป Template เมื่อมี entity)</summary>
public Guid? TemplateId { get; set; } public Guid? TemplateId { get; set; }
public Template? Template { get; set; }
public DateTimeOffset CreatedAt { get; set; } public DateTimeOffset CreatedAt { get; set; }
public List<DocumentVersion> Versions { get; set; } = new(); public List<DocumentVersion> Versions { get; set; } = new();

View file

@ -0,0 +1,20 @@
namespace WordVersioning.Api.Models;
/// <summary>ค่าล่าสุดต่อ field ของ document (FR-11) — PK คือ (DocumentId, FieldKey)</summary>
public class DocumentFieldValue
{
public Guid DocumentId { get; set; }
public string FieldKey { get; set; } = string.Empty;
/// <summary>เก็บเป็น string ทุก type (number/date ก็ตามที่ผู้ใช้กรอก/extract มา)</summary>
public string Value { get; set; } = string.Empty;
/// <summary>version ล่าสุดที่อัปเดตค่านี้</summary>
public Guid SourceVersionId { get; set; }
/// <summary>จาก claim `sub` ของผู้กด Save & Version / ผู้ generate</summary>
public string UpdatedByUserId { get; set; } = string.Empty;
public DateTimeOffset UpdatedAt { get; set; }
}

View file

@ -0,0 +1,25 @@
namespace WordVersioning.Api.Models;
/// <summary>Template เอกสาร .docx ที่มี content controls (FR-9) — ไฟล์เก็บใน MinIO bucket docx-templates</summary>
public class Template
{
public Guid Id { get; set; }
public string Name { get; set; } = string.Empty;
public string? Description { get; set; }
/// <summary>MinIO object key ใน bucket docx-templates (เปลี่ยนทุกครั้งที่ replace ไฟล์)</summary>
public string ObjectKey { get; set; } = string.Empty;
/// <summary>soft-delete flag — ห้ามลบแถวจริงเพราะ document เก่ายังอ้าง TemplateId อยู่</summary>
public bool IsActive { get; set; } = true;
public DateTimeOffset CreatedAt { get; set; }
public DateTimeOffset UpdatedAt { get; set; }
public List<TemplateField> Fields { get; set; } = new();
public List<Document> Documents { get; set; } = new();
}

View file

@ -0,0 +1,81 @@
using System.ComponentModel.DataAnnotations;
namespace WordVersioning.Api.Models;
/// <summary>body ของ POST /api/templates (multipart/form-data)</summary>
public class CreateTemplateRequest
{
[Required]
public string Name { get; set; } = string.Empty;
public string? Description { get; set; }
[Required]
public IFormFile File { get; set; } = null!;
}
/// <summary>body ของ PUT /api/templates/{id} — Fields เป็น optional (ไม่ส่ง = แก้ metadata อย่างเดียว)</summary>
public class UpdateTemplateRequest
{
public string? Name { get; set; }
public string? Description { get; set; }
public bool? IsActive { get; set; }
public List<TemplateFieldDefinition>? Fields { get; set; }
}
/// <summary>นิยาม field หนึ่งตัวที่ admin ตั้ง — Key ต้องตรงกับที่ detect จากไฟล์ (เพิ่ม/ลบ key ต้องผ่าน replace ไฟล์)</summary>
public class TemplateFieldDefinition
{
[Required]
public string Key { get; set; } = string.Empty;
public string Label { get; set; } = string.Empty;
/// <summary>text | number | date</summary>
public string Type { get; set; } = "text";
public bool IsRequired { get; set; }
public int SortOrder { get; set; }
}
/// <summary>body ของ PUT /api/templates/{id}/file (multipart/form-data)</summary>
public class ReplaceTemplateFileRequest
{
[Required]
public IFormFile File { get; set; } = null!;
}
public record TemplateFieldDto(Guid Id, string Key, string Label, string Type, bool IsRequired, int SortOrder);
public record TemplateListItem(
Guid Id,
string Name,
string? Description,
bool IsActive,
int FieldCount,
DateTimeOffset CreatedAt,
DateTimeOffset UpdatedAt);
public record TemplateDetail(
Guid Id,
string Name,
string? Description,
bool IsActive,
DateTimeOffset CreatedAt,
DateTimeOffset UpdatedAt,
IReadOnlyList<TemplateFieldDto> Fields);
/// <summary>response ของ POST /api/templates — fields ที่ detect อัตโนมัติพร้อมค่า default
/// ให้ admin ไปตั้ง label/type/required ต่อผ่าน PUT (FR-9)</summary>
public record CreateTemplateResponse(Guid Id, IReadOnlyList<TemplateFieldDto> Fields);
/// <summary>response ของ PUT /api/templates/{id}/file — เตือน tag ที่หายไป/เพิ่มมาหลัง replace ไฟล์</summary>
public record ReplaceTemplateFileResponse(
Guid Id,
IReadOnlyList<TemplateFieldDto> Fields,
IReadOnlyList<string> AddedTags,
IReadOnlyList<string> RemovedTags);

View file

@ -0,0 +1,27 @@
namespace WordVersioning.Api.Models;
/// <summary>นิยาม field หนึ่งตัวของ template (FR-9) — Key = content control (SDT) tag ที่ detect ตอน upload</summary>
public class TemplateField
{
public Guid Id { get; set; }
public Guid TemplateId { get; set; }
public Template? Template { get; set; }
/// <summary>= SDT tag — unique ต่อ template ใช้ค่าเดียวกันทั้ง generate/extract/sync</summary>
public string Key { get; set; } = string.Empty;
/// <summary>ชื่อที่แสดงในฟอร์ม (default = Key จนกว่า admin จะตั้ง)</summary>
public string Label { get; set; } = string.Empty;
/// <summary>text | number | date</summary>
public string Type { get; set; } = "text";
public bool IsRequired { get; set; }
/// <summary>ลำดับตอนแสดงฟอร์ม (default = ลำดับที่ปรากฏในไฟล์ตอน detect)</summary>
public int SortOrder { get; set; }
public static readonly string[] ValidTypes = ["text", "number", "date"];
}

View file

@ -1,4 +1,5 @@
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.Text.Json;
namespace WordVersioning.Api.Models; namespace WordVersioning.Api.Models;
@ -12,12 +13,24 @@ public class UploadVersionRequest
[Required] [Required]
public string ClientVersionId { get; set; } = string.Empty; public string ClientVersionId { get; set; } = string.Empty;
/// <summary>JSON object map tag→text จาก content controls (FR-11 — Phase 3 จะใช้ sync เต็มรูปแบบ)</summary> /// <summary>JSON object map tag→text จาก content controls (FR-11)</summary>
public string? Fields { get; set; } public string? Fields { get; set; }
} }
public record UploadVersionResponse(Guid VersionId, int VersionNumber); public record UploadVersionResponse(Guid VersionId, int VersionNumber);
/// <summary>body ของ POST /api/documents/generate (FR-10)</summary>
public class GenerateDocumentRequest
{
[Required]
public Guid TemplateId { get; set; }
/// <summary>map fieldKey → value (ค่า scalar ทั้งหมด)</summary>
public JsonElement Values { get; set; }
}
public record GenerateDocumentResponse(Guid DocumentId, Guid VersionId, int VersionNumber, string DownloadUrl);
/// <summary>item ของ version history — fields คือ snapshot ที่ parse แล้ว (ถ้ามี)</summary> /// <summary>item ของ version history — fields คือ snapshot ที่ parse แล้ว (ถ้ามี)</summary>
public record VersionListItem( public record VersionListItem(
Guid VersionId, Guid VersionId,

View file

@ -35,10 +35,12 @@ builder.Services.AddSwaggerGen(options =>
builder.Services.AddDbContext<AppDbContext>(options => builder.Services.AddDbContext<AppDbContext>(options =>
options.UseNpgsql(builder.Configuration.GetConnectionString("Default"))); options.UseNpgsql(builder.Configuration.GetConnectionString("Default")));
// MinIO / hash / current user // MinIO / hash / docx generation / field sync / current user
builder.Services.Configure<MinioOptions>(builder.Configuration.GetSection(MinioOptions.SectionName)); builder.Services.Configure<MinioOptions>(builder.Configuration.GetSection(MinioOptions.SectionName));
builder.Services.AddSingleton<IObjectStorageService, ObjectStorageService>(); builder.Services.AddSingleton<IObjectStorageService, ObjectStorageService>();
builder.Services.AddSingleton<IHashService, HashService>(); builder.Services.AddSingleton<IHashService, HashService>();
builder.Services.AddSingleton<IDocxGenerationService, DocxGenerationService>();
builder.Services.AddScoped<IFieldSyncService, FieldSyncService>();
builder.Services.AddHttpContextAccessor(); builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped<ICurrentUser, CurrentUser>(); builder.Services.AddScoped<ICurrentUser, CurrentUser>();

View file

@ -0,0 +1,12 @@
namespace WordVersioning.Api.Services;
/// <summary>ค่าคงที่ metadata ที่ฝังในไฟล์ .docx (spec ส่วน 8) — ต้องเป็นค่าเดียวกับที่ add-in ใช้</summary>
public static class AddInMetadata
{
/// <summary>GUID คงที่ของ add-in — ฝั่ง add-in ใช้ชื่อ ADDIN_SIGNATURE_GUID ค่าเดียวกันนี้ (Phase 4)</summary>
public const string AddInSignatureGuid = "9B7A3C51-4E6F-4D2A-8B5C-1E0F2A3B4C5D";
public const string SavedByAddInPropertyName = "SavedByAddIn";
public const string DocumentTrackingIdPropertyName = "DocumentTrackingId";
}

View file

@ -0,0 +1,170 @@
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
{
/// <summary>parse content controls (SDT tags) จากไฟล์ template — เรียงตามที่ปรากฏในไฟล์ ไม่ซ้ำ
/// (FR-9: detect fields อัตโนมัติตอน upload)</summary>
IReadOnlyList<string> DetectFieldTags(Stream docxStream);
/// <summary>FR-10 — สร้างเอกสารจาก template: แทนที่ข้อความใน SDT แต่ละ field
/// <b>ที่ run level</b> (รักษา run properties/formatting ของ template) แล้ว stamp
/// Custom Properties (SavedByAddIn + DocumentTrackingId) — คืนเป็น bytes ของไฟล์ใหม่</summary>
byte[] Generate(Stream templateStream, IReadOnlyDictionary<string, string> values, Guid documentTrackingId);
}
/// <summary>จัดการ docx ด้วย OpenXML SDK — ใช้ทั้งตอน detect fields และตอน generate (FR-9, FR-10)</summary>
public class DocxGenerationService : IDocxGenerationService
{
/// <summary>fmtid มาตรฐานของ user-defined custom properties (ตาม MS-ODRAW/Office convention)</summary>
private const string CustomPropertyFormatId = "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}";
public IReadOnlyList<string> DetectFieldTags(Stream docxStream)
{
using var doc = WordprocessingDocument.Open(docxStream, false);
var tags = new List<string>();
foreach (var root in AllContentRoots(doc))
{
foreach (var tag in root.Descendants<Tag>())
{
var key = tag.Val?.Value?.Trim();
if (!string.IsNullOrEmpty(key) && !tags.Contains(key))
tags.Add(key);
}
}
return tags;
}
public byte[] Generate(Stream templateStream, IReadOnlyDictionary<string, string> 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<Tag>().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();
}
/// <summary>แทนที่ข้อความใน SDT ที่ <b>run level</b> — เก็บ Run เดิมไว้ตัวแรก (formatting ตาม template)
/// แล้วลบ Text ที่เหลือ ไม่ทับทั้ง paragraph (spec ส่วน 9 เพิ่มเติม v2)</summary>
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<Text>().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<Paragraph>().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();
}
}
/// <summary>แก้ custom property (มีอยู่แล้ว = แทนที่, ยังไม่มี = เพิ่ม) ผ่าน CustomFilePropertiesPart</summary>
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<CustomDocumentProperty>()
.Where(p => p.Name?.Value == name).ToList())
{
existing.Remove();
}
// pid ต้องเริ่มที่ 2 และไม่ซ้ำ — ต่อจากตัวสูงสุดที่มีอยู่
var nextPid = props.Elements<CustomDocumentProperty>()
.Select(p => p.PropertyId?.Value ?? 1)
.DefaultIfEmpty(1)
.Max() + 1;
props.Append(new CustomDocumentProperty
{
Name = name,
FormatId = CustomPropertyFormatId,
PropertyId = nextPid,
VTLPWSTR = new VTLPWSTR(value),
});
}
/// <summary>content controls อยู่ได้ทั้ง body, header, footer — เก็บครบทุกที่</summary>
private static IEnumerable<OpenXmlPartRootElement> 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;
}
}
}

View file

@ -0,0 +1,20 @@
namespace WordVersioning.Api.Services;
/// <summary>ตรวจไฟล์ .docx ที่รับเข้ามาทาง multipart — ใช้ร่วมทั้ง upload version และ template</summary>
public static class DocxUploadValidation
{
public const string DocxContentType =
"application/vnd.openxmlformats-officedocument.wordprocessingml.document";
public static bool IsValidDocx(IFormFile file) =>
file.FileName.EndsWith(".docx", StringComparison.OrdinalIgnoreCase)
&& IsAcceptableContentType(file.ContentType);
// spec: reject content-type ที่ไม่ใช่ docx — ยอมรับ octet-stream/zip ด้วยเพราะ client บางตัว
// (เช่น curl -F) ไม่ set ชนิดไฟล์ให้ ส่วนชื่อไฟล์ต้องลง .docx เสมอ (เช็คข้างบน)
public static bool IsAcceptableContentType(string contentType) =>
string.IsNullOrWhiteSpace(contentType)
|| contentType.Equals(DocxContentType, StringComparison.OrdinalIgnoreCase)
|| contentType.Equals("application/octet-stream", StringComparison.OrdinalIgnoreCase)
|| contentType.Equals("application/zip", StringComparison.OrdinalIgnoreCase);
}

View file

@ -0,0 +1,64 @@
using System.Text.Json;
namespace WordVersioning.Api.Services;
/// <summary>แปลง/ตรวจ map ของ fields (JSON object รูป { tag: value }) ที่ client ส่งมา —
/// ใช้ทั้ง form field `fields` ของ upload (FR-11) และ body `values` ของ generate (FR-10)</summary>
public static class FieldMapJson
{
/// <summary>parse จาก string — คืน false พร้อมข้อความ error เมื่อ JSON ไม่ถูกต้อง</summary>
public static bool TryParse(string? json, out Dictionary<string, string?> map, out string? error)
{
map = [];
error = null;
if (string.IsNullOrWhiteSpace(json))
return true;
try
{
using var doc = JsonDocument.Parse(json);
return TryNormalize(doc.RootElement, out map, out error);
}
catch (JsonException)
{
error = "`fields` ไม่ใช่ JSON ที่ถูกต้อง";
return false;
}
}
/// <summary>normalize จาก JsonElement — ค่า scalar (string/number/bool/null) เท่านั้น
/// null กลายเป็น null ใน map (จะถูกมองเป็นค่าว่าง ไม่ใช่ field หาย)</summary>
public static bool TryNormalize(JsonElement element, out Dictionary<string, string?> map, out string? error)
{
map = [];
error = null;
if (element.ValueKind is JsonValueKind.Null or JsonValueKind.Undefined)
return true;
if (element.ValueKind != JsonValueKind.Object)
{
error = "ต้องเป็น JSON object รูป { tag: value }";
return false;
}
foreach (var prop in element.EnumerateObject())
{
string? value = prop.Value.ValueKind switch
{
JsonValueKind.String => prop.Value.GetString(),
JsonValueKind.Number => prop.Value.GetRawText(),
JsonValueKind.True => "true",
JsonValueKind.False => "false",
JsonValueKind.Null => null,
_ => null,
};
if (prop.Value.ValueKind is not (JsonValueKind.String or JsonValueKind.Number
or JsonValueKind.True or JsonValueKind.False or JsonValueKind.Null))
{
error = $"ค่าของ `{prop.Name}` ต้องเป็น scalar (string/number/bool/null)";
return false;
}
map[prop.Name] = value;
}
return true;
}
}

View file

@ -0,0 +1,99 @@
using System.Text.Json;
using Microsoft.EntityFrameworkCore;
using WordVersioning.Api.Data;
using WordVersioning.Api.Models;
namespace WordVersioning.Api.Services;
/// <summary>entry หนึ่ง field ใน `DocumentVersion.FieldsSnapshotJson` (เอกสารที่ผูก template)</summary>
public record FieldSnapshotEntry(string Value, bool Missing);
public record FieldSyncResult(string? SnapshotJson);
public interface IFieldSyncService
{
/// <summary>FR-11 — เทียบ fields ที่ส่งมากับ TemplateField ของ template ที่ document ผูกอยู่:
/// stage การ upsert `DocumentFieldValue` (latest value) ลง change tracker (**caller เป็นคน SaveChanges**)
/// แล้วคืน snapshot JSON ของ version นี้ไปเก็บใน `DocumentVersion.FieldsSnapshotJson`
///
/// policy ตาม spec: field ขาด (ผู้ใช้ลบ content control) → เก็บค่าเดิม + mark missing **ไม่ fail**;
/// field เกินนิยาม → ignore; `UpdatedByUserId` จาก JWT เสมอ</summary>
Task<FieldSyncResult> StageFieldSyncAsync(
Document document,
Guid sourceVersionId,
IReadOnlyDictionary<string, string?> sentFields,
DateTimeOffset now,
CancellationToken ct);
}
public class FieldSyncService(AppDbContext db, ICurrentUser currentUser) : IFieldSyncService
{
// camelCase ให้ตรงกับ JSON ที่ API คืนทั้งระบบ
private static readonly JsonSerializerOptions SnapshotJsonOptions = new(JsonSerializerDefaults.Web);
public async Task<FieldSyncResult> StageFieldSyncAsync(
Document document,
Guid sourceVersionId,
IReadOnlyDictionary<string, string?> sentFields,
DateTimeOffset now,
CancellationToken ct)
{
if (document.TemplateId is null)
{
// เอกสารไม่ผูก template (track เองจาก add-in) — ไม่มีนิยามให้เทียบ
// เก็บ map ดิบตามที่ส่งมาใน snapshot ไว้ดู history ได้ (Phase 2 behavior)
return sentFields.Count == 0
? new FieldSyncResult(null)
: new FieldSyncResult(JsonSerializer.Serialize(sentFields, SnapshotJsonOptions));
}
var fieldDefs = await db.TemplateFields.AsNoTracking()
.Where(f => f.TemplateId == document.TemplateId)
.OrderBy(f => f.SortOrder)
.ToListAsync(ct);
if (fieldDefs.Count == 0)
return new FieldSyncResult(null);
// tracked — update ทีหลังให้เข้า SaveChanges เดียวกับ version insert
var existingValues = await db.DocumentFieldValues
.Where(v => v.DocumentId == document.Id)
.ToDictionaryAsync(v => v.FieldKey, ct);
var snapshot = new Dictionary<string, FieldSnapshotEntry>(fieldDefs.Count);
foreach (var def in fieldDefs)
{
if (sentFields.TryGetValue(def.Key, out var sentValue))
{
sentValue ??= string.Empty;
if (existingValues.TryGetValue(def.Key, out var row))
{
row.Value = sentValue;
row.SourceVersionId = sourceVersionId;
row.UpdatedByUserId = currentUser.UserId;
row.UpdatedAt = now;
}
else
{
db.DocumentFieldValues.Add(new DocumentFieldValue
{
DocumentId = document.Id,
FieldKey = def.Key,
Value = sentValue,
SourceVersionId = sourceVersionId,
UpdatedByUserId = currentUser.UserId,
UpdatedAt = now,
});
}
snapshot[def.Key] = new FieldSnapshotEntry(sentValue, Missing: false);
}
else
{
// field หายจากเอกสาร (ผู้ใช้ลบ content control) — เก็บค่าเดิม + mark missing ไม่ fail (AC-14)
var oldValue = existingValues.TryGetValue(def.Key, out var row) ? row.Value : string.Empty;
snapshot[def.Key] = new FieldSnapshotEntry(oldValue, Missing: true);
}
}
return new FieldSyncResult(JsonSerializer.Serialize(snapshot, SnapshotJsonOptions));
}
}

View file

@ -34,6 +34,9 @@ public class ObjectStorageService : IObjectStorageService
public async Task PutAsync(string bucket, string key, Stream content, string contentType, CancellationToken ct = default) public async Task PutAsync(string bucket, string key, Stream content, string contentType, CancellationToken ct = default)
{ {
// จับความยาวไว้ก่อน — AWSSDK 4.x dispose input stream ให้หลัง upload เสร็จ อ่าน .Length ตอนหลังไม่ได้
long? length = content.CanSeek ? content.Length : null;
var request = new PutObjectRequest var request = new PutObjectRequest
{ {
BucketName = bucket, BucketName = bucket,
@ -41,14 +44,14 @@ public class ObjectStorageService : IObjectStorageService
InputStream = content, InputStream = content,
ContentType = contentType, ContentType = contentType,
}; };
if (content.CanSeek) if (length.HasValue)
{ {
// ระบุความยาวชัดๆ ไม่ต้องให้ SDK ไป buffer ทั้ง stream // ระบุความยาวชัดๆ ไม่ต้องให้ SDK ไป buffer ทั้ง stream
request.Headers.ContentLength = content.Length; request.Headers.ContentLength = length.Value;
} }
await _s3.PutObjectAsync(request, ct); await _s3.PutObjectAsync(request, ct);
_logger.LogInformation("Uploaded object {Bucket}/{Key} ({Length} bytes)", bucket, key, content.Length); _logger.LogInformation("Uploaded object {Bucket}/{Key} ({Length} bytes)", bucket, key, length);
} }
public async Task<Stream> GetStreamAsync(string bucket, string key, CancellationToken ct = default) public async Task<Stream> GetStreamAsync(string bucket, string key, CancellationToken ct = default)

View file

@ -1,7 +1,7 @@
# Implementation Plan: Word Versioning Add-in (Office.js + .NET 8) # Implementation Plan: Word Versioning Add-in (Office.js + .NET 8)
> แผนงานสร้างระบบจาก spec: [`specs/spec-officejs.md`](../../specs/spec-officejs.md) > แผนงานสร้างระบบจาก spec: [`specs/spec-officejs.md`](../../specs/spec-officejs.md)
> สถานะ: รอเริ่ม implement (repo ยังไม่มีโค้ด) > สถานะ: Phase 0–3 เสร็จ (scaffold + infra + backend core + backend template & generation) — ต่อไป: phase 4–5 (add-in) หรือ phase 6 (web) ทำขนานกันได้
> วันที่แผน: 2026-08-18 (ฉบับแก้ไข v2: เพิ่ม FR-9 ถึง FR-11 — ระบบ template, สร้างเอกสาร v1 ผ่านเว็บ และ field sync) > วันที่แผน: 2026-08-18 (ฉบับแก้ไข v2: เพิ่ม FR-9 ถึง FR-11 — ระบบ template, สร้างเอกสาร v1 ผ่านเว็บ และ field sync)
--- ---
@ -245,23 +245,23 @@ POST /api/documents/generate { templateId, values: { <fieldKey>: <value> } }
**เป้า:** ระบบ template ครบวงจร — upload พร้อม auto-detect fields + generate เอกสาร v1 พร้อม metadata **เป้า:** ระบบ template ครบวงจร — upload พร้อม auto-detect fields + generate เอกสาร v1 พร้อม metadata
### 3.1 Entities + migrations ### 3.1 Entities + migrations
- [ ] `Template` — Id (Guid), Name, Description, ObjectKey (ใน bucket `docx-templates`), IsActive (soft-delete), CreatedAt/UpdatedAt - [x] `Template` — Id (Guid), Name, Description, ObjectKey (ใน bucket `docx-templates`), IsActive (soft-delete), CreatedAt/UpdatedAt
- [ ] `TemplateField` — Id, TemplateId, Key (= SDT tag), Label, Type (`text|number|date`), IsRequired, SortOrder; unique `(TemplateId, Key)` - [x] `TemplateField` — Id, TemplateId, Key (= SDT tag), Label, Type (`text|number|date`), IsRequired, SortOrder; unique `(TemplateId, Key)`
- [ ] `DocumentFieldValue` — DocumentId, FieldKey, Value (string), UpdatedAt, UpdatedByUserId, SourceVersionId; unique `(DocumentId, FieldKey)` = latest value ต่อ field - [x] `DocumentFieldValue` — DocumentId, FieldKey, Value (string), UpdatedAt, UpdatedByUserId, SourceVersionId; unique `(DocumentId, FieldKey)` = latest value ต่อ field (ทำเป็น composite PK)
- [ ] `Document` เพิ่ม `TemplateId?` + migration - [x] `Document` เพิ่ม `TemplateId?` + migration (`TemplatesAndFieldSync`)
### 3.2 TemplatesController (FR-9) ### 3.2 TemplatesController (FR-9)
- [ ] `GET /api/templates` — list (filter active/all) - [x] `GET /api/templates` — list (filter active/all) + `GET /api/templates/{id}` (สำหรับหน้า edit เพิ่มเติมจากแผน)
- [ ] `POST /api/templates` — multipart: ไฟล์ .docx + name/description → upload ลง MinIO + **parse SDT tags คืนเป็น field list ที่ detect ได้** (response ให้ admin ไปตั้ง label/type/required ต่อ) - [x] `POST /api/templates` — multipart: ไฟล์ .docx + name/description → upload ลง MinIO + **parse SDT tags คืนเป็น field list ที่ detect ได้** (สร้าง TemplateField defaults ทันที: label=tag, type=text — admin ไปตั้งต่อผ่าน PUT)
- [ ] `PUT /api/templates/{id}` — แก้ metadata + บันทึก field definitions - [x] `PUT /api/templates/{id}` — แก้ metadata (name/description/isActive) + บันทึก field definitions (key ต้องเป็นชุดที่ detect ไว้ — เพิ่ม/ลบ key ต้องผ่าน replace ไฟล์)
- [ ] `PUT /api/templates/{id}/file` — แทนที่ไฟล์ (re-parse fields, เตือนถ้า tag หายไป) - [x] `PUT /api/templates/{id}/file` — แทนที่ไฟล์ (re-parse fields, response บอก `addedTags`/`removedTags`)
- [ ] `DELETE /api/templates/{id}` = deactivate (soft-delete) - [x] `DELETE /api/templates/{id}` = deactivate (soft-delete)
### 3.3 DocxGenerationService (FR-10) ### 3.3 DocxGenerationService (FR-10)
- [ ] โหลด template จาก MinIO → เปิดด้วย `DocumentFormat.OpenXml` - [x] โหลด template จาก MinIO → เปิดด้วย `DocumentFormat.OpenXml`
- [ ] แทนที่ข้อความใน SDT แต่ละ field **ที่ run level** (รักษา run properties/formatting ของ template — ไม่ทับทั้ง paragraph) - [x] แทนที่ข้อความใน SDT แต่ละ field **ที่ run level** (รักษา run properties/formatting ของ template — ไม่ทับทั้ง paragraph)
- [ ] Stamp Custom Properties ผ่าน `CustomFilePropertiesPart`: `SavedByAddIn` = `ADDIN_SIGNATURE_GUID` (ค่าคงที่เดียวกับที่ add-in ใช้ตรวจ), `DocumentTrackingId` = Guid ใหม่ - [x] Stamp Custom Properties ผ่าน `CustomFilePropertiesPart`: `SavedByAddIn` = `ADDIN_SIGNATURE_GUID` (ค่าคงที่เดียวกับที่ add-in ใช้ตรวจ), `DocumentTrackingId` = Guid ใหม่
- [ ] `POST /api/documents/generate { templateId, values }`: - [x] `POST /api/documents/generate { templateId, values }`:
1. Validate required + type 1. Validate required + type
2. Generate ไฟล์จาก template 2. Generate ไฟล์จาก template
3. คำนวณ SHA256 + upload เป็น **version 1** (`ObjectStorageService`) 3. คำนวณ SHA256 + upload เป็น **version 1** (`ObjectStorageService`)
@ -269,11 +269,23 @@ POST /api/documents/generate { templateId, values: { <fieldKey>: <value> } }
5. Response `{ documentId, versionId, versionNumber, downloadUrl }` 5. Response `{ documentId, versionId, versionNumber, downloadUrl }`
### 3.4 Field sync บน upload endpoint (FR-11 ฝั่ง backend) ### 3.4 Field sync บน upload endpoint (FR-11 ฝั่ง backend)
- [ ] ขยาย `POST /api/documents/{documentId}/versions`: รับ `fields` (map tag→text) → เทียบกับ `TemplateField` ของ template ที่ document ผูกอยู่ → update `DocumentFieldValue` (latest value) + เขียน `DocumentVersion.FieldsSnapshotJson` ของ version นั้น - [x] ขยาย `POST /api/documents/{documentId}/versions`: รับ `fields` (map tag→text) → เทียบกับ `TemplateField` ของ template ที่ document ผูกอยู่ → update `DocumentFieldValue` (latest value) + เขียน `DocumentVersion.FieldsSnapshotJson` ของ version นั้น
- [ ] field ที่ส่งมาขาด (ผู้ใช้ลบ content control) → เก็บค่าเดิม + mark missing ใน snapshot **ไม่ fail request**; field ที่ส่งมาเกินนิยาม → ignore - [x] field ที่ส่งมาขาด (ผู้ใช้ลบ content control) → เก็บค่าเดิม + mark missing ใน snapshot **ไม่ fail request**; field ที่ส่งมาเกินนิยาม → ignore
หมายเหตุจากการทำจริง (2026-08-19):
- **ค่า `ADDIN_SIGNATURE_GUID` = `9B7A3C51-4E6F-4D2A-8B5C-1E0F2A3B4C5D`** — ปักหมุดไว้ที่ `Services/AddInMetadata.cs` และ spec ส่วน 8 แล้ว — Phase 4 (add-in `metadataService`) ต้องใช้ค่านี้เป๊ะ
- OpenXML SDK 3.5.1: root ของ custom properties = `DocumentFormat.OpenXml.CustomProperties.Properties` + `CustomDocumentProperty` (property `Name`/`FormatId`/`PropertyId` + child `VTLPWSTR`); block SDT = `SdtBlock`/`SdtProperties` (ไม่ใช่ `Sdt`/`SdtPr`) — service ที่เขียนใช้ `Tag` + LocalName matching จึงไม่ผูกกับชื่อ class เหล่านี้ (กัน SDT ทั้ง block/run/cell)
- **ห้าม set `TemplateField.Id` เองตอน add เข้า `template.Fields` ของ tracked parent** — Guid ที่มีค่าทำให้ EF relationship-fixup ตีเป็น Modified (UPDATE แถวที่ไม่มี → `DbUpdateConcurrencyException`) ทิ้ง Id ว่างไว้ให้ EF generate ตาม convention
- **AWSSDK.S3 4.x dispose input stream ให้หลัง `PutObjectAsync`** — `ObjectStorageService.PutAsync` จับ `content.Length` ไว้ก่อนเรียก SDK แล้วใช้ค่านั้นทั้งตอน set ContentLength และ log
- snapshot ของเอกสารที่ผูก template เก็บแบบ structured `{ key: { value, missing } }` (camelCase) เพื่อรองรับ mark-missing; เอกสารไม่ผูก template ยังเก็บ map ดิบตาม Phase 2 — UI (Phase 5/6) ต้อง handle ทั้งสองรูป
- sync logic แชร์ผ่าน `FieldSyncService.StageFieldSyncAsync` (stage ลง tracker, caller เป็นคน SaveChanges) ใช้ทั้งตอน generate v1 และ upload version — UploadVersion ถอน staged field changes กลับด้วยตอน MinIO fail (ไม่ให้ค่าล้ำ version ที่ถูกถอน)
- generate endpoint upload MinIO **ก่อน** SaveChanges (ได้เลข v1 ล่วงหน้า ไม่ต้องจองเลข) — ตรงข้ามกับ UploadVersion ที่ insert ก่อนเพื่อจองเลข; template create/replace ก็ upload ก่อนเช่นกัน (ถ้า DB fail ทีหลังเหลือ orphan object ใน bucket — ยอมรับได้ เพราะทิศตรงข้าม (row ชี้ไฟล์ที่ไม่มี) คืออันที่อันตราย)
- ตรวจ DoD ผ่านจริง (2026-08-19): upload template (5 SDT: inline/run เดียว, multi-run คนละ formatting, block-level) → detect ครบ 5 + บันทึก defs ผ่าน PUT; validation ทำงาน (required ขาด / salary ไม่ใช่เลข / start_date ไม่ใช่วันที่ → 400 คนละข้อความ); generate → 201 + docx ค่าครบทุก field + multi-run ถูกรวมเป็น run เดียว (formatting ตัวแรก) + `docProps/custom.xml` มี `SavedByAddIn`/`DocumentTrackingId` ตรงกับ documentId + DB มี Document/v1/field values 5 แถว; upload v2 (แก้ 2 fields + ลบ position + ส่งเกิน 1 field) → 201, latest values อัปเดตเฉพาะ field ที่มี, position คงค่าเดิม + snapshot v2 `missing:true`, field เกินถูก ignore; replace-file → addedTags/removedTags ถูก; deactivate 204 → generate 400 แต่ history/download ของ document เก่ายัง 200
**DoD:** upload template จริง (เช่น สัญญาจ้างงานที่มี content controls) → detect fields ครบ → เรียก generate ผ่าน Swagger → ได้ docx ที่ (1) เปิดใน Word แล้วค่าถูกทุก field formatting ไม่พัง (2) Word บอก custom properties มี `SavedByAddIn`/`DocumentTrackingId` (ตรวจใน Advanced Properties หรือเปิดไฟล์ด้วย unzip) (3) DB มี Document + v1 + field values (AC-11, 12 ส่วน backend ผ่าน) และ (4) เรียก upload version ถัดไปพร้อม `fields` ที่เปลี่ยนค่า → latest values + snapshot อัปเดตถูก / ขาด field → ค่าเดิมคงอยู่ไม่ error (AC-13, 14 ส่วน backend ผ่าน) **DoD:** upload template จริง (เช่น สัญญาจ้างงานที่มี content controls) → detect fields ครบ → เรียก generate ผ่าน Swagger → ได้ docx ที่ (1) เปิดใน Word แล้วค่าถูกทุก field formatting ไม่พัง (2) Word บอก custom properties มี `SavedByAddIn`/`DocumentTrackingId` (ตรวจใน Advanced Properties หรือเปิดไฟล์ด้วย unzip) (3) DB มี Document + v1 + field values (AC-11, 12 ส่วน backend ผ่าน) และ (4) เรียก upload version ถัดไปพร้อม `fields` ที่เปลี่ยนค่า → latest values + snapshot อัปเดตถูก / ขาด field → ค่าเดิมคงอยู่ไม่ error (AC-13, 14 ส่วน backend ผ่าน)
> ✅ ตรวจผ่านจริง (2026-08-19): ครบทั้ง 4 ข้อตามรายละเอียดในหมายเหตุข้างบน (ตรวจ formatting/custom properties ด้วย OpenXML + unzip `docProps/custom.xml` ตามทางเลือกที่ DoD ยอมรับ — ส่วน "เปิดใน Word จริง" จะเกิดเต็มรูปแบบตอน AC-12 ใน Phase 6)
--- ---
## Phase 4: Add-in services layer — FR-8 (ฝั่ง client), FR-11 (extraction), โครง FR-1/2 ## Phase 4: Add-in services layer — FR-8 (ฝั่ง client), FR-11 (extraction), โครง FR-1/2

View file

@ -300,7 +300,7 @@ public class DocumentFieldValue // latest value ต่อ fie
Custom Document Properties: Custom Document Properties:
| Key | Value | | Key | Value |
|---|---| |---|---|
| `SavedByAddIn` | GUID คงที่ของ add-in | | `SavedByAddIn` | GUID คงที่ของ add-in — ค่าที่ปักหมุด: `9B7A3C51-4E6F-4D2A-8B5C-1E0F2A3B4C5D` (backend: `Services/AddInMetadata.AddInSignatureGuid`, add-in: `ADDIN_SIGNATURE_GUID` ต้องเป็นค่านี้เป๊ะ) |
| `DocumentTrackingId` | GUID เฉพาะของเอกสาร (ผูกกับ `documentId` ฝั่ง backend) | | `DocumentTrackingId` | GUID เฉพาะของเอกสาร (ผูกกับ `documentId` ฝั่ง backend) |
| `LastVersionId` | GUID ของ version ล่าสุด | | `LastVersionId` | GUID ของ version ล่าสุด |
| `LastVersionTimestamp` | ISO-8601 UTC timestamp | | `LastVersionTimestamp` | ISO-8601 UTC timestamp |