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

@ -1,5 +1,7 @@
using System.Globalization;
using System.Text.Json;
using Amazon.Runtime;
using DocumentFormat.OpenXml.Packaging;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
@ -11,7 +13,8 @@ using WordVersioning.Api.Services;
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]
[Authorize] // FR-8: ทุก endpoint ต้องแนบ token
[Route("api/documents")]
@ -19,17 +22,21 @@ public class DocumentsController(
AppDbContext db,
IObjectStorageService storage,
IHashService hasher,
IDocxGenerationService docxGeneration,
IFieldSyncService fieldSync,
ICurrentUser currentUser,
IOptions<MinioOptions> minioOptions,
ILogger<DocumentsController> logger) : ControllerBase
{
public const string DocxContentType =
"application/vnd.openxmlformats-officedocument.wordprocessingml.document";
public const string DocxContentType = DocxUploadValidation.DocxContentType;
private static readonly JsonSerializerOptions SnapshotJsonOptions = new(JsonSerializerDefaults.Web);
private const long MaxUploadBytes = 100L * 1024 * 1024; // 100MB ตาม spec
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")]
[RequestSizeLimit(MaxUploadBytes)]
[RequestFormLimits(MultipartBodyLengthLimit = MaxUploadBytes)]
@ -45,30 +52,12 @@ public class DocumentsController(
return BadRequest("`clientVersionId` ต้องเป็น GUID");
if (request.File.Length > MaxUploadBytes)
return StatusCode(StatusCodes.Status413PayloadTooLarge, $"ไฟล์ใหญ่เกิน {MaxUploadBytes / (1024 * 1024)}MB");
if (!IsValidDocx(request.File))
if (!DocxUploadValidation.IsValidDocx(request.File))
return BadRequest("รองรับเฉพาะไฟล์ .docx (Word document)");
// parse fields map (FR-11) — optional, ผิด format คือ 400
string? fieldsSnapshotJson = null;
if (!string.IsNullOrWhiteSpace(request.Fields))
{
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 ที่ถูกต้อง");
}
}
if (!FieldMapJson.TryParse(request.Fields, out var fieldMap, out var fieldsError))
return BadRequest(fieldsError);
var now = DateTimeOffset.UtcNow;
var fileName = request.File.FileName;
@ -102,6 +91,26 @@ public class DocumentsController(
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 คู่แข่ง ให้คำนวณใหม่
DocumentVersion version = null!;
for (var attempt = 1; ; attempt++)
@ -114,7 +123,7 @@ public class DocumentsController(
version = new DocumentVersion
{
Id = Guid.NewGuid(),
Id = versionId, // ใช้ id เดิมทุก retry — field sync ที่ stage ไว้อ้างอิง id นี้
DocumentId = documentId,
VersionNumber = nextNumber,
ObjectKey = $"{documentId}/v{nextNumber:D4}_{request.ClientVersionId}.docx",
@ -166,6 +175,7 @@ public class DocumentsController(
db.DocumentVersions.Remove(version);
if (createdDoc)
db.Documents.Remove(doc);
RevertStagedFieldChanges(db, fieldValuesBefore);
await db.SaveChangesAsync(CancellationToken.None);
return StatusCode(StatusCodes.Status502BadGateway, "อัปโหลดไฟล์ขึ้น storage ไม่สำเร็จ");
}
@ -178,6 +188,153 @@ public class DocumentsController(
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>
[HttpGet("{documentId:guid}/versions")]
[ProducesResponseType(typeof(IReadOnlyList<VersionListItem>), StatusCodes.Status200OK)]
@ -243,20 +400,40 @@ public class DocumentsController(
return File(stream, DocxContentType, downloadName);
}
private static bool IsValidDocx(IFormFile file) =>
file.FileName.EndsWith(".docx", StringComparison.OrdinalIgnoreCase)
&& IsAcceptableContentType(file.ContentType);
/// <summary>ถอนการเปลี่ยน DocumentFieldValue ที่ stage ไว้กลับเป็นค่าก่อน request
/// — ใช้ตอน MinIO fail หลัง SaveChanges แล้ว (ไม่ให้ค่าล้ำหน้า version ที่ถูกถอน)</summary>
private static void RevertStagedFieldChanges(
AppDbContext db, Dictionary<string, DocumentFieldValue>? valuesBefore)
{
if (valuesBefore is null)
return;
// spec: reject content-type ที่ไม่ใช่ docx — ยอมรับ octet-stream/zip ด้วยเพราะ client บางตัว
// (เช่น curl -F) ไม่ set ชนิดไฟล์ให้ ส่วนชื่อไฟล์ต้องลง .docx เสมอ (เช็คข้างบน)
private 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);
foreach (var entry in db.ChangeTracker.Entries<DocumentFieldValue>().ToList())
{
if (entry.State == EntityState.Added)
{
entry.State = EntityState.Detached;
}
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) =>
kind is JsonValueKind.String or JsonValueKind.Number or JsonValueKind.True or JsonValueKind.False or JsonValueKind.Null;
/// <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)
{