Phase 3
This commit is contained in:
parent
9321f5a370
commit
25c2ce53cd
23 changed files with 1746 additions and 68 deletions
|
|
@ -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)
|
||||
{
|
||||
|
|
|
|||
325
backend/WordVersioning.Api/Controllers/TemplatesController.cs
Normal file
325
backend/WordVersioning.Api/Controllers/TemplatesController.cs
Normal 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();
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue