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;
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue