Phase 12: draft generation (FR-16)
ไฟล์ร่าง (draft) — generate docx จาก template แบบ stateless ไม่สร้าง
Document/version; stamp เฉพาะ custom property TemplateId เพื่อให้ add-in
เห็นเป็น untracked; Start Versioning ส่ง form field templateId ให้ backend
ผูก template ตอน auto-create — เอกสารเริ่มที่ v1 (ไม่มี v0) + field sync เต็มระบบ
- Backend: POST /api/templates/{id}/generate-draft (200 คืนไฟล์) +
DocxGenerationService.GenerateDraft + แยก TemplateFieldValidation ใช้ร่วมกับ
generate + UploadVersion รับ templateId (non-GUID/unknown → 400,
deactivated → ผูกได้, document เดิม → เฉย) + CORS expose Content-Disposition
- Add-in: readTrackedProperties อ่าน TemplateId + ส่ง templateId เฉพาะ
startVersioning + hint ไฟล์ร่างใน task pane
- Web: ปุ่ม "สร้างไฟล์ร่าง" บนฟอร์มเดิม + downloadFile รับ init (POST → blob)
- Docs: spec v8 (FR-16, AC-19) + Phase 12 + CONTEXT.md + ADR 0002 +
acceptance-review AC-19
- Tests: backend 82 / add-in 66 / web 59 + build ครบ; QA reviewer PASS
(2 rounds); ค้าง manual บน Word จริง
Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
parent
0edb70fd38
commit
b3c1c667f7
30 changed files with 879 additions and 93 deletions
|
|
@ -10,6 +10,7 @@ public sealed class AuthTests(IntegrationTestFixture fixture)
|
|||
[InlineData("GET", "api/templates")]
|
||||
[InlineData("POST", "api/templates")]
|
||||
[InlineData("GET", "api/templates/{0}/documents")]
|
||||
[InlineData("POST", "api/templates/{0}/generate-draft")]
|
||||
[InlineData("POST", "api/documents/generate")]
|
||||
[InlineData("GET", "api/documents/{0}/versions")]
|
||||
[InlineData("POST", "api/documents/{0}/versions")]
|
||||
|
|
|
|||
129
backend/WordVersioning.Api.IntegrationTests/DraftTests.cs
Normal file
129
backend/WordVersioning.Api.IntegrationTests/DraftTests.cs
Normal file
|
|
@ -0,0 +1,129 @@
|
|||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using WordVersioning.Api.Services;
|
||||
|
||||
namespace WordVersioning.Api.IntegrationTests;
|
||||
|
||||
/// <summary>FR-16 — ไฟล์ร่าง (draft): generate docx จาก template แบบ stateless
|
||||
/// (ค่าครบ + stamp เฉพาะ TemplateId + ไม่เกิด Document/version ใดๆ ในระบบ)</summary>
|
||||
[Collection(IntegrationTestCollection.Name)]
|
||||
public sealed class DraftTests(IntegrationTestFixture fixture)
|
||||
{
|
||||
[Fact]
|
||||
public async Task Draft_FillsAllFields_PreservesFormatting_StampsOnlyTemplateId_CreatesNothing()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var (templateId, _) = await TestFlow.CreateConfiguredTemplateAsync(client, "draft หลัก");
|
||||
|
||||
using var response = await client.PostAsJsonAsync(
|
||||
$"api/templates/{templateId}/generate-draft",
|
||||
new { values = TestFlow.DefaultValues }, IntegrationTestFixture.Json);
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode); // ไม่ใช่ 201 — ไม่มีอะไรถูกสร้าง
|
||||
|
||||
// คืนไฟล์ docx พร้อมชื่อไฟล์จากชื่อ template (Content-Disposition attachment)
|
||||
Assert.Equal(TestDocx.DocxContentType, response.Content.Headers.ContentType?.MediaType);
|
||||
Assert.NotNull(response.Content.Headers.ContentDisposition?.FileNameStar);
|
||||
|
||||
var fileBytes = await response.Content.ReadAsByteArrayAsync();
|
||||
|
||||
// (1) ค่าทุก field ถูกแทนที่ใน SDT — เหมือน generate ปกติ
|
||||
Assert.Equal("สมหญิง รักงาน", TestDocx.ReadSdtText(fileBytes, "employee_name"));
|
||||
Assert.Equal("วิศวกรซอฟต์แวร์", TestDocx.ReadSdtText(fileBytes, "position"));
|
||||
Assert.Equal("75000", TestDocx.ReadSdtText(fileBytes, "salary"));
|
||||
Assert.Equal("2026-08-01", TestDocx.ReadSdtText(fileBytes, "start_date"));
|
||||
|
||||
// (2) multi-run SDT ยังรักษา formatting ของ run แรก (bold)
|
||||
var positionRuns = TestDocx.ReadSdtRuns(fileBytes, "position");
|
||||
var runWithText = Assert.Single(positionRuns.Where(r => r.Text.Length > 0));
|
||||
Assert.True(runWithText.Bold);
|
||||
|
||||
// (3) stamp เฉพาะ TemplateId — ไม่มี SavedByAddIn/DocumentTrackingId เพื่อให้ add-in เห็นเป็น untracked (FR-16)
|
||||
Assert.Equal(templateId.ToString(), TestDocx.ReadCustomProperty(fileBytes, AddInMetadata.TemplateIdPropertyName));
|
||||
Assert.Null(TestDocx.ReadCustomProperty(fileBytes, "SavedByAddIn"));
|
||||
Assert.Null(TestDocx.ReadCustomProperty(fileBytes, "DocumentTrackingId"));
|
||||
|
||||
// (4) stateless จริง: ไม่เกิด Document/version ใดๆ จาก template นี้
|
||||
await using var db = fixture.CreateDb();
|
||||
Assert.False(await db.Documents.AsNoTracking().AnyAsync(d => d.TemplateId == templateId));
|
||||
Assert.False(await db.DocumentVersions.AsNoTracking()
|
||||
.AnyAsync(v => db.Documents.Any(d => d.Id == v.DocumentId && d.TemplateId == templateId)));
|
||||
Assert.False(await db.DocumentFieldValues.AsNoTracking()
|
||||
.AnyAsync(v => db.Documents.Any(d => d.Id == v.DocumentId && d.TemplateId == templateId)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Draft_MissingRequiredField_Returns400()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var (templateId, _) = await TestFlow.CreateConfiguredTemplateAsync(client, "draft required ขาด");
|
||||
|
||||
var values = new Dictionary<string, string>(TestFlow.DefaultValues);
|
||||
values.Remove("employee_name"); // required field หาย
|
||||
|
||||
using var response = await client.PostAsJsonAsync(
|
||||
$"api/templates/{templateId}/generate-draft", new { values }, IntegrationTestFixture.Json);
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
var error = await response.Content.ReadAsStringAsync();
|
||||
Assert.Contains("employee_name", error);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("salary", "ไม่ใช่เลข")]
|
||||
[InlineData("start_date", "ไม่ใช่วันที่")]
|
||||
public async Task Draft_WrongFieldType_Returns400(string key, string badValue)
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var (templateId, _) = await TestFlow.CreateConfiguredTemplateAsync(client, $"draft type ผิด {key}");
|
||||
|
||||
var values = new Dictionary<string, string>(TestFlow.DefaultValues) { [key] = badValue };
|
||||
|
||||
using var response = await client.PostAsJsonAsync(
|
||||
$"api/templates/{templateId}/generate-draft", new { values }, IntegrationTestFixture.Json);
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Draft_UnknownTemplate_Returns404()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
|
||||
using var response = await client.PostAsJsonAsync(
|
||||
$"api/templates/{Guid.NewGuid()}/generate-draft",
|
||||
new { values = TestFlow.DefaultValues }, IntegrationTestFixture.Json);
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Draft_DeactivatedTemplate_Returns400()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var (templateId, _) = await TestFlow.CreateConfiguredTemplateAsync(client, "draft deactivate");
|
||||
|
||||
using var deactivate = await client.DeleteAsync($"api/templates/{templateId}");
|
||||
Assert.Equal(HttpStatusCode.NoContent, deactivate.StatusCode);
|
||||
|
||||
using var response = await client.PostAsJsonAsync(
|
||||
$"api/templates/{templateId}/generate-draft",
|
||||
new { values = TestFlow.DefaultValues }, IntegrationTestFixture.Json);
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Draft_IgnoresUndefinedValues()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var (templateId, _) = await TestFlow.CreateConfiguredTemplateAsync(client, "draft ค่าเกินนิยาม");
|
||||
|
||||
var values = new Dictionary<string, string>(TestFlow.DefaultValues)
|
||||
{
|
||||
["field_ที่ไม่มีใน_template"] = "ส่งเกินมา", // policy FR-11: ignore
|
||||
};
|
||||
|
||||
using var response = await client.PostAsJsonAsync(
|
||||
$"api/templates/{templateId}/generate-draft", new { values }, IntegrationTestFixture.Json);
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
var fileBytes = await response.Content.ReadAsByteArrayAsync();
|
||||
Assert.Equal(templateId.ToString(), TestDocx.ReadCustomProperty(fileBytes, AddInMetadata.TemplateIdPropertyName));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,168 @@
|
|||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace WordVersioning.Api.IntegrationTests;
|
||||
|
||||
/// <summary>FR-16 — ผูก template ตอน Start Versioning: form field `templateId` ทางเลือกของ upload
|
||||
/// ใช้เฉพาะตอน auto-create Document · upload แรกของ Document ใหม่ = version 1 เสมอ + field sync เต็มระบบ</summary>
|
||||
[Collection(IntegrationTestCollection.Name)]
|
||||
public sealed class TemplateLinkingTests(IntegrationTestFixture fixture)
|
||||
{
|
||||
private static string DefaultFieldsJson() => JsonSerializer.Serialize(TestFlow.DefaultValues);
|
||||
|
||||
[Fact]
|
||||
public async Task Upload_WithTemplateId_OnNewDocument_CreatesLinkedDocV1WithFieldSync()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var (templateId, _) = await TestFlow.CreateConfiguredTemplateAsync(client, "linking หลัก");
|
||||
|
||||
// Start Versioning ของไฟล์ร่าง: upload แรกพร้อม templateId + fields ที่ extract จาก content controls
|
||||
var documentId = Guid.NewGuid();
|
||||
using var upload = await client.PostAsync(
|
||||
$"api/documents/{documentId}/versions",
|
||||
ApiExtensions.VersionForm(
|
||||
TestDocx.BuildTemplateDocx(), "ไฟล์ร่างทดสอบ.docx", Guid.NewGuid().ToString(),
|
||||
fieldsJson: DefaultFieldsJson(), templateId: templateId.ToString()));
|
||||
Assert.Equal(HttpStatusCode.Created, upload.StatusCode);
|
||||
var v1 = (await upload.Content.ReadFromJsonAsync<UploadVersionResult>(IntegrationTestFixture.Json))!;
|
||||
|
||||
// upload แรกของ Document ใหม่ = version 1 เสมอ (ไม่มี v0 ใน flow ไฟล์ร่าง)
|
||||
Assert.Equal(1, v1.VersionNumber);
|
||||
|
||||
await using var db = fixture.CreateDb();
|
||||
var document = await db.Documents.AsNoTracking()
|
||||
.Include(d => d.Versions)
|
||||
.SingleAsync(d => d.Id == documentId);
|
||||
Assert.Equal(templateId, document.TemplateId); // ผูก template ต้นทาง
|
||||
Assert.Equal(string.Empty, document.AddInSignature); // ฝั่ง add-in stamp ในไฟล์เอง — ค่าเดิมของ auto-create
|
||||
|
||||
var version = Assert.Single(document.Versions);
|
||||
Assert.Equal(1, version.VersionNumber);
|
||||
Assert.NotNull(version.FieldsSnapshotJson); // snapshot แบบมีนิยาม (ไม่ใช่ raw map)
|
||||
|
||||
// field sync เต็มระบบ (FR-11): DocumentFieldValue ครบทุก field ของ template
|
||||
var fieldValues = await db.DocumentFieldValues.AsNoTracking()
|
||||
.Where(v => v.DocumentId == documentId)
|
||||
.ToDictionaryAsync(v => v.FieldKey);
|
||||
Assert.Equal(4, fieldValues.Count);
|
||||
Assert.Equal("สมหญิง รักงาน", fieldValues["employee_name"].Value);
|
||||
Assert.Equal("75000", fieldValues["salary"].Value);
|
||||
Assert.All(fieldValues.Values, v => Assert.Equal(v1.VersionId, v.SourceVersionId));
|
||||
Assert.All(fieldValues.Values, v => Assert.Equal(fixture.TestUserId, v.UpdatedByUserId));
|
||||
|
||||
// Save & Version ครั้งถัดไป (ไม่ส่ง templateId) = v2 และ TemplateId คงเดิม
|
||||
using var second = await client.PostAsync(
|
||||
$"api/documents/{documentId}/versions",
|
||||
ApiExtensions.VersionForm(
|
||||
TestDocx.BuildTemplateDocx(), "ไฟล์ร่างทดสอบ.docx", Guid.NewGuid().ToString(),
|
||||
fieldsJson: DefaultFieldsJson(), message: "แก้ไขรอบสอง"));
|
||||
Assert.Equal(HttpStatusCode.Created, second.StatusCode);
|
||||
var v2 = (await second.Content.ReadFromJsonAsync<UploadVersionResult>(IntegrationTestFixture.Json))!;
|
||||
Assert.Equal(2, v2.VersionNumber);
|
||||
|
||||
await using var db2 = fixture.CreateDb();
|
||||
var docAfter = await db2.Documents.AsNoTracking().SingleAsync(d => d.Id == documentId);
|
||||
Assert.Equal(templateId, docAfter.TemplateId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Upload_TemplateIdNotGuid_Returns400()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var (templateId, _) = await TestFlow.CreateConfiguredTemplateAsync(client, "linking ไม่ใช่ GUID");
|
||||
|
||||
using var response = await client.PostAsync(
|
||||
$"api/documents/{Guid.NewGuid()}/versions",
|
||||
ApiExtensions.VersionForm(
|
||||
TestDocx.BuildPlainDocx(), "a.docx", Guid.NewGuid().ToString(), templateId: "not-a-guid"));
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
var error = await response.Content.ReadAsStringAsync();
|
||||
Assert.Contains("templateId", error);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Upload_TemplateIdUnknown_Returns400()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
_ = await TestFlow.CreateConfiguredTemplateAsync(client, "linking unknown"); // ตั้ง field defs ไว้ก่อน (ชุดเดียวกับที่ใช้จริง)
|
||||
|
||||
using var response = await client.PostAsync(
|
||||
$"api/documents/{Guid.NewGuid()}/versions",
|
||||
ApiExtensions.VersionForm(
|
||||
TestDocx.BuildPlainDocx(), "a.docx", Guid.NewGuid().ToString(),
|
||||
templateId: Guid.NewGuid().ToString()));
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Upload_TemplateIdDeactivated_StillLinks()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var (templateId, _) = await TestFlow.CreateConfiguredTemplateAsync(client, "linking deactivate");
|
||||
|
||||
using var deactivate = await client.DeleteAsync($"api/templates/{templateId}");
|
||||
Assert.Equal(HttpStatusCode.NoContent, deactivate.StatusCode);
|
||||
|
||||
// ไฟล์ร่างถูกสร้างตอน template ยัง active — deactivate หลังจากนั้นต้องไม่ขวางการเริ่ม track (นโยบาย FR-9/FR-12)
|
||||
var documentId = Guid.NewGuid();
|
||||
using var upload = await client.PostAsync(
|
||||
$"api/documents/{documentId}/versions",
|
||||
ApiExtensions.VersionForm(
|
||||
TestDocx.BuildTemplateDocx(), "ไฟล์ร่าง.docx", Guid.NewGuid().ToString(),
|
||||
fieldsJson: DefaultFieldsJson(), templateId: templateId.ToString()));
|
||||
Assert.Equal(HttpStatusCode.Created, upload.StatusCode);
|
||||
|
||||
await using var db = fixture.CreateDb();
|
||||
var document = await db.Documents.AsNoTracking().SingleAsync(d => d.Id == documentId);
|
||||
Assert.Equal(templateId, document.TemplateId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Upload_ExistingDocument_IgnoresTemplateId()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var (templateId, _) = await TestFlow.CreateConfiguredTemplateAsync(client, "linking เฉย");
|
||||
|
||||
// upload แรกแบบ standalone (ไม่มี templateId) → Document ไม่ผูก template
|
||||
var documentId = Guid.NewGuid();
|
||||
using var first = await client.PostAsync(
|
||||
$"api/documents/{documentId}/versions",
|
||||
ApiExtensions.VersionForm(TestDocx.BuildPlainDocx(), "plain.docx", Guid.NewGuid().ToString()));
|
||||
Assert.Equal(HttpStatusCode.Created, first.StatusCode);
|
||||
|
||||
// upload ที่สองส่ง templateId มาด้วย — document มีอยู่แล้วจึงเฉย (TemplateId คง null)
|
||||
using var second = await client.PostAsync(
|
||||
$"api/documents/{documentId}/versions",
|
||||
ApiExtensions.VersionForm(
|
||||
TestDocx.BuildPlainDocx(), "plain.docx", Guid.NewGuid().ToString(), templateId: templateId.ToString()));
|
||||
Assert.Equal(HttpStatusCode.Created, second.StatusCode);
|
||||
var v2 = (await second.Content.ReadFromJsonAsync<UploadVersionResult>(IntegrationTestFixture.Json))!;
|
||||
Assert.Equal(2, v2.VersionNumber);
|
||||
|
||||
await using var db = fixture.CreateDb();
|
||||
var document = await db.Documents.AsNoTracking().SingleAsync(d => d.Id == documentId);
|
||||
Assert.Null(document.TemplateId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Upload_ExistingDocument_BadTemplateId_Returns400()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
_ = await TestFlow.CreateConfiguredTemplateAsync(client, "linking เฉย bad id");
|
||||
|
||||
var documentId = Guid.NewGuid();
|
||||
using var first = await client.PostAsync(
|
||||
$"api/documents/{documentId}/versions",
|
||||
ApiExtensions.VersionForm(TestDocx.BuildPlainDocx(), "plain.docx", Guid.NewGuid().ToString()));
|
||||
Assert.Equal(HttpStatusCode.Created, first.StatusCode);
|
||||
|
||||
// validate ทุกครั้งที่ส่งมา — แม้ document มีอยู่แล้วและค่าจะไม่ถูกใช้ก็ตาม
|
||||
using var second = await client.PostAsync(
|
||||
$"api/documents/{documentId}/versions",
|
||||
ApiExtensions.VersionForm(
|
||||
TestDocx.BuildPlainDocx(), "plain.docx", Guid.NewGuid().ToString(), templateId: "not-a-guid"));
|
||||
Assert.Equal(HttpStatusCode.BadRequest, second.StatusCode);
|
||||
}
|
||||
}
|
||||
|
|
@ -31,9 +31,11 @@ public record DocDetail(Guid Id, string FileName, DateTimeOffset CreatedAt, Guid
|
|||
|
||||
public static class ApiExtensions
|
||||
{
|
||||
/// <summary>multipart form ของ POST versions: file + clientVersionId + fields (option) + message (option)</summary>
|
||||
/// <summary>multipart form ของ POST versions: file + clientVersionId + fields (option) + message (option)
|
||||
/// + templateId (option — FR-16 ไฟล์ร่าง: ส่งเฉพาะตอน Start Versioning)</summary>
|
||||
public static MultipartFormDataContent VersionForm(
|
||||
byte[] docx, string fileName, string clientVersionId, string? fieldsJson = null, string? message = null, byte[]? pdf = null)
|
||||
byte[] docx, string fileName, string clientVersionId, string? fieldsJson = null, string? message = null,
|
||||
byte[]? pdf = null, string? templateId = null)
|
||||
{
|
||||
var form = new MultipartFormDataContent();
|
||||
var file = new ByteArrayContent(docx);
|
||||
|
|
@ -50,6 +52,8 @@ public static class ApiExtensions
|
|||
part.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
|
||||
form.Add(part, "pdf", "document.pdf");
|
||||
}
|
||||
if (templateId is not null)
|
||||
form.Add(new StringContent(templateId), "templateId");
|
||||
return form;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,4 +1,3 @@
|
|||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using Amazon.Runtime;
|
||||
using DocumentFormat.OpenXml.Packaging;
|
||||
|
|
@ -52,6 +51,18 @@ public class DocumentsController(
|
|||
return BadRequest("ต้องแนบไฟล์ `file` (docx)");
|
||||
if (!Guid.TryParse(request.ClientVersionId, out _))
|
||||
return BadRequest("`clientVersionId` ต้องเป็น GUID");
|
||||
|
||||
// FR-16 — templateId ทางเลือก (ส่งจาก Start Versioning ของไฟล์ร่าง): validate ทุกครั้งที่ส่งมา
|
||||
// (ใช้จริงเฉพาะตอน auto-create Document ด้านล่าง — document มีอยู่แล้วจะถูกเฉย)
|
||||
Guid? templateIdToLink = null;
|
||||
if (!string.IsNullOrWhiteSpace(request.TemplateId))
|
||||
{
|
||||
if (!Guid.TryParse(request.TemplateId, out var parsedTemplateId))
|
||||
return BadRequest("`templateId` ต้องเป็น GUID");
|
||||
if (!await db.Templates.AsNoTracking().AnyAsync(t => t.Id == parsedTemplateId, ct))
|
||||
return BadRequest($"ไม่พบ template {parsedTemplateId}");
|
||||
templateIdToLink = parsedTemplateId; // template ที่ deactivate ผูกได้ — ไฟล์ร่างถูกสร้างตอน template ยัง active (นโยบายเดียวกับ FR-9/FR-12)
|
||||
}
|
||||
if (request.File.Length > MaxUploadBytes)
|
||||
return StatusCode(StatusCodes.Status413PayloadTooLarge, $"ไฟล์ใหญ่เกิน {MaxUploadBytes / (1024 * 1024)}MB");
|
||||
if (!DocxUploadValidation.IsValidDocx(request.File))
|
||||
|
|
@ -97,7 +108,7 @@ public class DocumentsController(
|
|||
var contentHash = await hasher.ComputeSha256HexAsync(uploadStream, ct);
|
||||
uploadStream.Seek(0, SeekOrigin.Begin);
|
||||
|
||||
// สร้าง Document ถ้ายังไม่มี (FR-5)
|
||||
// สร้าง Document ถ้ายังไม่มี (FR-5) — ไฟล์ร่าง (FR-16) ผูก template ต้นทางจาก templateId ที่ส่งมา
|
||||
var doc = await db.Documents.FirstOrDefaultAsync(d => d.Id == documentId, ct);
|
||||
var createdDoc = false;
|
||||
if (doc is null)
|
||||
|
|
@ -107,6 +118,7 @@ public class DocumentsController(
|
|||
Id = documentId,
|
||||
FileName = fileName,
|
||||
AddInSignature = string.Empty, // ฝั่ง add-in stamp ในไฟล์เอง
|
||||
TemplateId = templateIdToLink, // null = เอกสาร track เอง · มีค่า = ไฟล์ร่างจาก template (field sync ทำงานเต็มระบบที่ v1)
|
||||
CreatedAt = now,
|
||||
};
|
||||
db.Documents.Add(doc);
|
||||
|
|
@ -257,32 +269,10 @@ public class DocumentsController(
|
|||
if (message is { Length: > MaxVersionMessageLength })
|
||||
return BadRequest($"`message` ยาวเกิน {MaxVersionMessageLength} อักขระ");
|
||||
|
||||
// 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));
|
||||
// validate required + type (FR-10) — ชุดเดียวกับ generate-draft (FR-16)
|
||||
var validationError = TemplateFieldValidation.Validate(fieldDefs, values);
|
||||
if (validationError is not null)
|
||||
return BadRequest(validationError);
|
||||
|
||||
// โหลด template จาก MinIO → generate ไฟล์ + stamp custom properties (FR-10)
|
||||
Stream templateStream;
|
||||
|
|
@ -326,7 +316,7 @@ public class DocumentsController(
|
|||
var doc = new Document
|
||||
{
|
||||
Id = documentId,
|
||||
FileName = BuildGeneratedFileName(template.Name, now),
|
||||
FileName = DocxGenerationService.BuildGeneratedFileName(template.Name, now),
|
||||
AddInSignature = AddInMetadata.AddInSignatureGuid,
|
||||
TemplateId = template.Id,
|
||||
CreatedAt = now,
|
||||
|
|
@ -578,16 +568,6 @@ public class DocumentsController(
|
|||
}
|
||||
}
|
||||
|
||||
/// <summary>ชื่อไฟล์ของเอกสารที่ generate: ชื่อ template + timestamp — ตัดอักขระที่ filename ใช้ไม่ได้ออก</summary>
|
||||
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)
|
||||
{
|
||||
if (json is null)
|
||||
|
|
|
|||
|
|
@ -305,6 +305,74 @@ public class TemplatesController(
|
|||
return Ok(new ReplaceTemplateFileResponse(template.Id, FieldDtos(template), addedTags, removedTags));
|
||||
}
|
||||
|
||||
/// <summary>FR-16 — ไฟล์ร่าง (draft): generate docx จาก template แบบ stateless — ไม่สร้าง
|
||||
/// Document/DocumentVersion/DocumentFieldValue และไม่เขียน MinIO; คืนไฟล์ทันที
|
||||
/// (ผู้ใช้เปิดใน Word แล้วกด Start Versioning เพื่อเริ่ม track เป็น v1 พร้อมผูกกลับมาที่ template นี้)</summary>
|
||||
[HttpPost("{id:guid}/generate-draft")]
|
||||
[ProducesResponseType(typeof(FileContentResult), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
[ProducesResponseType(StatusCodes.Status502BadGateway)]
|
||||
public async Task<IActionResult> GenerateDraft(Guid id, [FromBody] GenerateDraftRequest request, CancellationToken ct)
|
||||
{
|
||||
var template = await db.Templates.AsNoTracking()
|
||||
.FirstOrDefaultAsync(t => t.Id == id, ct);
|
||||
if (template is null)
|
||||
return NotFound($"ไม่พบ template {id}");
|
||||
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 ชุดเดียวกับ generate (FR-10) — ไฟล์ร่างไม่มี message เพราะไม่เกิด version
|
||||
var validationError = TemplateFieldValidation.Validate(fieldDefs, values);
|
||||
if (validationError is not null)
|
||||
return BadRequest(validationError);
|
||||
|
||||
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");
|
||||
}
|
||||
|
||||
byte[] fileBytes;
|
||||
try
|
||||
{
|
||||
await using (templateStream)
|
||||
{
|
||||
// null (JSON null) มองเป็นค่าว่าง — field "หาย" คือไม่มี key ใน map เท่านั้น (เหมือน Generate)
|
||||
fileBytes = docxGeneration.GenerateDraft(
|
||||
templateStream,
|
||||
values.ToDictionary(kv => kv.Key, kv => kv.Value ?? string.Empty),
|
||||
template.Id);
|
||||
}
|
||||
}
|
||||
catch (OpenXmlPackageException ex)
|
||||
{
|
||||
logger.LogError(ex, "Template file corrupt templateId={TemplateId} key={ObjectKey}",
|
||||
template.Id, template.ObjectKey);
|
||||
return StatusCode(StatusCodes.Status502BadGateway, "ไฟล์ template เสียหาย (เปิดด้วย OpenXML ไม่ได้)");
|
||||
}
|
||||
|
||||
logger.LogInformation("Draft generated templateId={TemplateId} userId={UserId} bytes={Size}",
|
||||
template.Id, currentUser.UserId, fileBytes.Length);
|
||||
|
||||
return File(fileBytes, DocxUploadValidation.DocxContentType,
|
||||
DocxGenerationService.BuildGeneratedFileName(template.Name, DateTimeOffset.UtcNow));
|
||||
}
|
||||
|
||||
/// <summary>deactivate (soft-delete) — document เก่าที่อ้างอยู่ยังใช้ได้ต่อ แต่สร้างเอกสารใหม่ไม่ได้</summary>
|
||||
[HttpDelete("{id:guid}")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
using System.ComponentModel.DataAnnotations;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace WordVersioning.Api.Models;
|
||||
|
||||
|
|
@ -52,6 +53,14 @@ public class ReplaceTemplateFileRequest
|
|||
public IFormFile File { get; set; } = null!;
|
||||
}
|
||||
|
||||
/// <summary>body ของ POST /api/templates/{id}/generate-draft (FR-16) — ไม่มี message เพราะไฟล์ร่างยังไม่เกิด version</summary>
|
||||
public class GenerateDraftRequest
|
||||
{
|
||||
/// <summary>map fieldKey → value (ค่า scalar ทั้งหมด) — pattern เดียวกับ GenerateDocumentRequest</summary>
|
||||
[Required]
|
||||
public JsonElement Values { get; set; }
|
||||
}
|
||||
|
||||
public record TemplateFieldDto(Guid Id, string Key, string Label, string Type, string Editor, bool IsRequired, int SortOrder);
|
||||
|
||||
public record TemplateListItem(
|
||||
|
|
|
|||
|
|
@ -20,6 +20,10 @@ public class UploadVersionRequest
|
|||
|
||||
/// <summary>คำอธิบาย version แบบ commit message (FR-13) — optional</summary>
|
||||
public string? Message { get; set; }
|
||||
|
||||
/// <summary>GUID ของ template ต้นทาง (FR-16 ไฟล์ร่าง) — ใช้เฉพาะตอน auto-create Document;
|
||||
/// ไม่ส่ง = เอกสาร track เอง · ส่งมาตอน document มีอยู่แล้ว = เฉย (validate ทุกครั้งที่ส่ง)</summary>
|
||||
public string? TemplateId { get; set; }
|
||||
}
|
||||
|
||||
public record UploadVersionResponse(Guid VersionId, int VersionNumber, bool HasPdf);
|
||||
|
|
|
|||
|
|
@ -65,11 +65,14 @@ builder.Services
|
|||
builder.Services.AddAuthorization();
|
||||
|
||||
// CORS — add-in task pane (https://localhost:3000) + web portal (http://localhost:5173) เท่านั้น
|
||||
// expose Content-Disposition ให้ fetch ฝั่งเว็บอ่านชื่อไฟล์ (ไทย) ของไฟล์ร่างที่ดาวน์โหลดได้ (FR-16)
|
||||
// — ไม่ expose แล้ว header จะเป็น null บน cross-origin และชื่อไฟล์หายเงียบๆ
|
||||
const string corsPolicy = "frontends";
|
||||
builder.Services.AddCors(options => options.AddPolicy(corsPolicy, policy => policy
|
||||
.WithOrigins(builder.Configuration.GetSection("Cors:AllowedOrigins").Get<string[]>() ?? [])
|
||||
.AllowAnyHeader()
|
||||
.AllowAnyMethod()));
|
||||
.AllowAnyMethod()
|
||||
.WithExposedHeaders("Content-Disposition")));
|
||||
|
||||
// --- dev HTTPS -------------------------------------------------------------
|
||||
// Word webview (WKWebView บน Mac) บล็อก fetch จากหน้า https ไป http แบบเงียบๆ ("Load failed")
|
||||
|
|
|
|||
|
|
@ -9,4 +9,9 @@ public static class AddInMetadata
|
|||
public const string SavedByAddInPropertyName = "SavedByAddIn";
|
||||
|
||||
public const string DocumentTrackingIdPropertyName = "DocumentTrackingId";
|
||||
|
||||
/// <summary>FR-16 — stamp ลงไฟล์ร่าง (draft) เท่านั้น: template ต้นทาง · ไม่ stamp
|
||||
/// SavedByAddIn/DocumentTrackingId เพื่อให้ add-in มองไฟล์ร่างเป็น untracked
|
||||
/// (ฝั่ง add-in ใช้ชื่อ TEMPLATE_ID_PROPERTY ค่าเดียวกันนี้ ส่งต่อเป็น form field ตอน Start Versioning)</summary>
|
||||
public const string TemplateIdPropertyName = "TemplateId";
|
||||
}
|
||||
|
|
|
|||
|
|
@ -16,6 +16,11 @@ public interface IDocxGenerationService
|
|||
/// <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>FR-16 — ไฟล์ร่าง (draft): แทนที่ SDT เหมือน Generate แต่ stamp custom property
|
||||
/// <b>เฉพาะ `TemplateId`</b> (GUID ของ template ต้นทาง) — ไม่ stamp SavedByAddIn/DocumentTrackingId
|
||||
/// เพื่อให้ add-in มองไฟล์ร่างเป็น untracked จนกว่าผู้ใช้จะกด Start Versioning</summary>
|
||||
byte[] GenerateDraft(Stream templateStream, IReadOnlyDictionary<string, string> values, Guid templateId);
|
||||
}
|
||||
|
||||
/// <summary>จัดการ docx ด้วย OpenXML SDK — ใช้ทั้งตอน detect fields และตอน generate (FR-9, FR-10)</summary>
|
||||
|
|
@ -42,32 +47,67 @@ public class DocxGenerationService : IDocxGenerationService
|
|||
|
||||
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;
|
||||
|
||||
var buffer = CopyToMemory(templateStream);
|
||||
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);
|
||||
}
|
||||
}
|
||||
ReplaceSdtValues(doc, values);
|
||||
|
||||
SetCustomProperty(doc, AddInMetadata.SavedByAddInPropertyName, AddInMetadata.AddInSignatureGuid);
|
||||
SetCustomProperty(doc, AddInMetadata.DocumentTrackingIdPropertyName, documentTrackingId.ToString());
|
||||
} // dispose เขียน package กลับลง buffer
|
||||
|
||||
buffer.Position = 0;
|
||||
return buffer.ToArray();
|
||||
}
|
||||
|
||||
public byte[] GenerateDraft(Stream templateStream, IReadOnlyDictionary<string, string> values, Guid templateId)
|
||||
{
|
||||
var buffer = CopyToMemory(templateStream);
|
||||
using (var doc = WordprocessingDocument.Open(buffer, true))
|
||||
{
|
||||
ReplaceSdtValues(doc, values);
|
||||
|
||||
// stamp ตัวเดียว (FR-16) — ไฟล์ร่างต้องเป็น untracked ในสายตา add-in
|
||||
SetCustomProperty(doc, AddInMetadata.TemplateIdPropertyName, templateId.ToString());
|
||||
}
|
||||
|
||||
return buffer.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>ก๊อปเข้า memory ก่อน — MinIO stream ไม่ seek ได้ และ package จะเขียนกลับลง stream นี้ตอน dispose</summary>
|
||||
private static MemoryStream CopyToMemory(Stream stream)
|
||||
{
|
||||
var buffer = new MemoryStream();
|
||||
stream.CopyTo(buffer);
|
||||
buffer.Position = 0;
|
||||
return buffer;
|
||||
}
|
||||
|
||||
/// <summary>ชื่อไฟล์ของเอกสาร/ไฟล์ร่างที่ generate จาก template: ชื่อ template + timestamp
|
||||
/// — ตัดอักขระที่ filename ใช้ไม่ได้ออก (ใช้ร่วมทั้ง generate และ generate-draft)</summary>
|
||||
public 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";
|
||||
}
|
||||
|
||||
/// <summary>แทนที่ค่าใน SDT ทุกตัวที่ tag ตรง key ใน values (ใช้ร่วมทั้ง Generate และ GenerateDraft)</summary>
|
||||
private static void ReplaceSdtValues(WordprocessingDocument doc, IReadOnlyDictionary<string, string> values)
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>แทนที่ข้อความใน SDT ที่ <b>run level</b> — เก็บ Run เดิมไว้ตัวแรก (formatting ตาม template)
|
||||
/// แล้วลบ Text ที่เหลือ ไม่ทับทั้ง paragraph (spec ส่วน 9 เพิ่มเติม v2)</summary>
|
||||
private static void ReplaceSdtContent(Tag tag, string value)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,38 @@
|
|||
using System.Globalization;
|
||||
using WordVersioning.Api.Models;
|
||||
|
||||
namespace WordVersioning.Api.Services;
|
||||
|
||||
/// <summary>FR-10/FR-16 — validate required + type ของค่าที่กรอก (ใช้ร่วมทั้ง generate และ generate-draft)
|
||||
/// field ที่ส่งเกินนิยาม ignore ตาม policy เดียวกับ FR-11</summary>
|
||||
public static class TemplateFieldValidation
|
||||
{
|
||||
/// <summary>null = ผ่าน; ไม่ null = ข้อความ error สำหรับ BadRequest (รูปแบบเดียวกับที่เคยอยู่ใน Generate)</summary>
|
||||
public static string? Validate(IEnumerable<TemplateField> fieldDefs, IReadOnlyDictionary<string, string?> values)
|
||||
{
|
||||
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 $"กรอก 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)");
|
||||
}
|
||||
return typeErrors.Count > 0 ? string.Join("; ", typeErrors) : null;
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue