การทดสอบ 6 รอบบนเครื่องจริง (Mac, Word 16.101) พิสูจน์ว่า ms-word:ofe
ถูกเมินแบบไม่ deterministic ทุกรูปแบบ (http/https/query/ไม่มี query/
file:// — Word ไม่ยิง request ถึง server เลย เด้งหน้าเลือกไฟล์แทน)
open -a Word <local file> ใช้ได้แต่เรียกจากเว็บไม่ได้ (sandbox +
backend รัน server กลางใน production) → สรุปทางเดียวที่ deterministic
คือ download-first
- Backend: OpenLinkService (HMAC อายุสั้น ValidateOnStart) +
OpenController /api/open/{t}/{e}/v/{did}/{vid}/file.docx และ /d/{objectKey}
— ทุกอย่างอยู่ใน path ไม่มี query string (Word เมิน URL มี query),
[AllowAnonymous] ด้วยลายเซ็นแทน Bearer, stream จาก MinIO + disposition
ชื่อไทยเหมือนเดิม · download-link + generate-draft ออก open-link
แทน presigned ของ MinIO (http) · ลบ dead code presigned ทิ้ง
- Web: openDocxUrl = ดาวน์โหลดทันทีทุกครั้ง + ยิง ms-word ควบคู่แบบ
best-effort + notice "ไฟล์อยู่ Downloads" — เอา heuristic สลับแอป
ออก (โดนหน้าเลือกไฟล์ของ Word หลอกจนไม่ดาวน์โหลด)
- Spec v9.2 + ตารางทดสอบเครื่องจริงใน acceptance-review + CLAUDE.md
กฎ 13 (ms-word = best-effort เท่านั้น) + ทางเลือก helper อนาคต
- backend 86 / web 58 / add-in 66 + build ครบ; QA reviewer PASS
(1 round, minors 4 แก้ครบ)
หมายเหตุ deploy: ต้องตั้ง OpenLinks__Secret (ค่าลับจริง) และ
OpenLinks__BaseUrl (https domain ของ backend) — fail ดังตั้งแต่สตาร์ทถ้าไม่ตั้ง
Co-Authored-By: Claude Code <noreply@anthropic.com>
590 lines
31 KiB
C#
590 lines
31 KiB
C#
using System.Text.Json;
|
|
using Amazon.Runtime;
|
|
using DocumentFormat.OpenXml.Packaging;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.Options;
|
|
using Npgsql;
|
|
using WordVersioning.Api.Data;
|
|
using WordVersioning.Api.Models;
|
|
using WordVersioning.Api.Services;
|
|
|
|
namespace WordVersioning.Api.Controllers;
|
|
|
|
/// <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")]
|
|
public class DocumentsController(
|
|
AppDbContext db,
|
|
IObjectStorageService storage,
|
|
IHashService hasher,
|
|
IDocxGenerationService docxGeneration,
|
|
IFieldSyncService fieldSync,
|
|
IOpenLinkService openLinks,
|
|
ICurrentUser currentUser,
|
|
IOptions<MinioOptions> minioOptions,
|
|
ILogger<DocumentsController> logger) : ControllerBase
|
|
{
|
|
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;
|
|
private const int MaxVersionMessageLength = 2048; // FR-13 — ตรงกับ HasMaxLength ใน AppDbContext
|
|
|
|
/// <summary>FR-5 — อัปโหลด version ใหม่ (auto-create Document ถ้ายังไม่มี)
|
|
/// + FR-15: optional PDF; PDF storage failure still returns 201 with HasPdf=false
|
|
/// + FR-11: แนบ `fields` (map tag→text) → sync latest values + snapshot ต่อ version</summary>
|
|
[HttpPost("{documentId:guid}/versions")]
|
|
[RequestSizeLimit(MaxUploadBytes)]
|
|
[RequestFormLimits(MultipartBodyLengthLimit = MaxUploadBytes)]
|
|
[ProducesResponseType(typeof(UploadVersionResponse), StatusCodes.Status201Created)]
|
|
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
|
[ProducesResponseType(StatusCodes.Status413PayloadTooLarge)]
|
|
[ProducesResponseType(StatusCodes.Status502BadGateway)]
|
|
public async Task<IActionResult> UploadVersion(Guid documentId, [FromForm] UploadVersionRequest request, CancellationToken ct)
|
|
{
|
|
if (request.File is null || request.File.Length == 0)
|
|
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))
|
|
return BadRequest("รองรับเฉพาะไฟล์ .docx (Word document)");
|
|
|
|
// parse fields map (FR-11) — optional, ผิด format คือ 400
|
|
if (!FieldMapJson.TryParse(request.Fields, out var fieldMap, out var fieldsError))
|
|
return BadRequest(fieldsError);
|
|
|
|
// FR-13 — commit message ทางเลือก (เช็คก่อนแตะ DB/storage กัน 500 จากข้อจำกัดความยาว)
|
|
var message = NormalizeMessage(request.Message);
|
|
if (message is { Length: > MaxVersionMessageLength })
|
|
return BadRequest($"`message` ยาวเกิน {MaxVersionMessageLength} อักขระ");
|
|
|
|
if (request.Pdf is not null)
|
|
{
|
|
if (request.Pdf.Length > MaxUploadBytes)
|
|
return StatusCode(StatusCodes.Status413PayloadTooLarge, "ไฟล์ PDF ใหญ่เกิน 100MB");
|
|
if (request.Pdf.Length == 0 || !PdfUploadValidation.IsValidPdf(request.Pdf))
|
|
return BadRequest("ต้องแนบไฟล์ .pdf ที่ไม่ว่าง (application/pdf)");
|
|
}
|
|
|
|
await using var pdfStream = new MemoryStream();
|
|
if (request.Pdf is not null)
|
|
{
|
|
await request.Pdf.CopyToAsync(pdfStream, ct);
|
|
pdfStream.Position = 0;
|
|
}
|
|
|
|
var now = DateTimeOffset.UtcNow;
|
|
var fileName = request.File.FileName;
|
|
|
|
// hash ระหว่าง stream ผ่าน (pass แรก) แล้ว rewind ส่ง MinIO (pass สอง)
|
|
await using var fileStream = request.File.OpenReadStream();
|
|
Stream uploadStream = fileStream;
|
|
if (!fileStream.CanSeek)
|
|
{
|
|
// IFormFile ปกติ seek ได้ — กันเหลือ: buffer ก่อน
|
|
var buffered = new MemoryStream();
|
|
await fileStream.CopyToAsync(buffered, ct);
|
|
uploadStream = buffered;
|
|
}
|
|
var contentHash = await hasher.ComputeSha256HexAsync(uploadStream, ct);
|
|
uploadStream.Seek(0, SeekOrigin.Begin);
|
|
|
|
// สร้าง 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)
|
|
{
|
|
doc = new Document
|
|
{
|
|
Id = documentId,
|
|
FileName = fileName,
|
|
AddInSignature = string.Empty, // ฝั่ง add-in stamp ในไฟล์เอง
|
|
TemplateId = templateIdToLink, // null = เอกสาร track เอง · มีค่า = ไฟล์ร่างจาก template (field sync ทำงานเต็มระบบที่ v1)
|
|
CreatedAt = now,
|
|
};
|
|
db.Documents.Add(doc);
|
|
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++)
|
|
{
|
|
var nextNumber = await db.DocumentVersions
|
|
.Where(v => v.DocumentId == documentId)
|
|
.Select(v => (int?)v.VersionNumber)
|
|
.MaxAsync(ct) ?? 0;
|
|
nextNumber++;
|
|
|
|
version = new DocumentVersion
|
|
{
|
|
Id = versionId, // ใช้ id เดิมทุก retry — field sync ที่ stage ไว้อ้างอิง id นี้
|
|
DocumentId = documentId,
|
|
VersionNumber = nextNumber,
|
|
ObjectKey = $"{documentId}/v{nextNumber:D4}_{request.ClientVersionId}.docx",
|
|
PdfObjectKey = request.Pdf is null ? null : $"{documentId}/v{nextNumber:D4}_{request.ClientVersionId}.pdf",
|
|
ContentHash = contentHash,
|
|
CreatedByUserId = currentUser.UserId, // จาก claim `sub` เท่านั้น
|
|
CreatedAt = now,
|
|
FieldsSnapshotJson = fieldsSnapshotJson,
|
|
Message = message, // FR-13
|
|
};
|
|
db.DocumentVersions.Add(version);
|
|
|
|
try
|
|
{
|
|
await db.SaveChangesAsync(ct);
|
|
break;
|
|
}
|
|
catch (DbUpdateException ex) when (IsUniqueViolation(ex) && attempt < MaxVersionInsertRetries)
|
|
{
|
|
logger.LogWarning(
|
|
"Version number conflict documentId={DocumentId} attempt={Attempt} userId={UserId} — retry",
|
|
documentId, attempt, currentUser.UserId);
|
|
|
|
db.Entry(version).State = EntityState.Detached;
|
|
if (createdDoc)
|
|
{
|
|
// document อาจถูกสร้างโดย request คู่แข่งไปแล้ว — ถอดออกจาก tracker แล้วอ่านใหม่
|
|
var existing = await db.Documents.AsNoTracking()
|
|
.FirstOrDefaultAsync(d => d.Id == documentId, ct);
|
|
if (existing is not null)
|
|
{
|
|
db.Entry(doc).State = EntityState.Detached;
|
|
doc = existing;
|
|
createdDoc = false;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// upload ลง MinIO หลังจองเลข version สำเร็จ (key มี versionNumber อยู่ข้างใน)
|
|
try
|
|
{
|
|
await storage.PutAsync(minioOptions.Value.VersionsBucket, version.ObjectKey, uploadStream, DocxContentType, ct);
|
|
}
|
|
catch (AmazonServiceException ex)
|
|
{
|
|
logger.LogError(ex, "MinIO upload failed documentId={DocumentId} versionId={VersionId} userId={UserId}",
|
|
documentId, version.Id, currentUser.UserId);
|
|
|
|
// ถอน record ที่เพิ่ง insert — ไม่ทิ้ง row ที่ชี้ไฟล์ที่ไม่มีจริง
|
|
db.DocumentVersions.Remove(version);
|
|
if (createdDoc)
|
|
db.Documents.Remove(doc);
|
|
RevertStagedFieldChanges(db, fieldValuesBefore);
|
|
await db.SaveChangesAsync(CancellationToken.None);
|
|
return StatusCode(StatusCodes.Status502BadGateway, "อัปโหลดไฟล์ขึ้น storage ไม่สำเร็จ");
|
|
}
|
|
|
|
// FR-15: PDF is derived; its storage failure must not undo the saved docx.
|
|
if (version.PdfObjectKey is not null)
|
|
{
|
|
try
|
|
{
|
|
await storage.PutAsync(minioOptions.Value.VersionsBucket, version.PdfObjectKey,
|
|
pdfStream, PdfUploadValidation.PdfContentType, ct);
|
|
}
|
|
catch (Exception ex) when (ex is AmazonServiceException or IOException or HttpRequestException or OperationCanceledException)
|
|
{
|
|
logger.LogWarning(ex, "PDF upload failed documentId={DocumentId} versionId={VersionId}", documentId, version.Id);
|
|
version.PdfObjectKey = null;
|
|
await db.SaveChangesAsync(CancellationToken.None);
|
|
}
|
|
}
|
|
|
|
logger.LogInformation(
|
|
"Version uploaded documentId={DocumentId} versionId={VersionId} versionNumber={VersionNumber} userId={UserId} bytes={Size} hash={Hash}",
|
|
documentId, version.Id, version.VersionNumber, currentUser.UserId, request.File.Length, contentHash);
|
|
|
|
return CreatedAtAction(nameof(GetVersions), new { documentId },
|
|
new UploadVersionResponse(version.Id, version.VersionNumber, version.PdfObjectKey is not null));
|
|
}
|
|
|
|
/// <summary>FR-10 — สร้างเอกสารจาก template: generate docx + stamp metadata + upload version 0
|
|
/// + 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}");
|
|
|
|
// FR-13 — เช็คก่อนทำ MinIO/template IO ใดๆ (กัน 500 + orphan object ใน bucket เมื่อ DB reject ทีหลัง)
|
|
var message = NormalizeMessage(request.Message);
|
|
if (message is { Length: > MaxVersionMessageLength })
|
|
return BadRequest($"`message` ยาวเกิน {MaxVersionMessageLength} อักขระ");
|
|
|
|
// 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;
|
|
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 ไม่ได้)");
|
|
}
|
|
catch (Exception ex) when (ex is not OperationCanceledException)
|
|
{
|
|
// กันหน้า: OpenXML โยนอะไรก็ตามที่เราไม่ได้เจอมาก่อน — ให้เป็น 502 ที่อ่านออกแทน 500 stack เต็มจอ
|
|
logger.LogError(ex, "Generate failed templateId={TemplateId} userId={UserId}",
|
|
template.Id, currentUser.UserId);
|
|
return StatusCode(StatusCodes.Status502BadGateway, "สร้างเอกสารไม่สำเร็จ (ไฟล์ template หรือค่าที่กรอกมีปัญหา)");
|
|
}
|
|
|
|
var now = DateTimeOffset.UtcNow;
|
|
using (var hashStream = new MemoryStream(fileBytes))
|
|
{
|
|
var contentHash = await hasher.ComputeSha256HexAsync(hashStream, ct);
|
|
|
|
var doc = new Document
|
|
{
|
|
Id = documentId,
|
|
FileName = DocxGenerationService.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 = 0,
|
|
ObjectKey = $"{documentId}/v0000_{Guid.NewGuid()}.docx", // clientVersionId generate ฝั่ง server (flow นี้ไม่มี client)
|
|
ContentHash = contentHash,
|
|
CreatedByUserId = currentUser.UserId,
|
|
CreatedAt = now,
|
|
Message = message, // FR-13
|
|
};
|
|
db.DocumentVersions.Add(version);
|
|
|
|
// snapshot + field values ของ v0 (ทุก 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-12 — detail ของเอกสาร: ข้อมูลหัวเรื่อง + template + ค่าล่าสุดของทุก field
|
|
/// (นิยามจาก TemplateField merge กับ DocumentFieldValue — รองรับ template เปลี่ยนนิยามหลังเอกสารสร้างแล้ว)</summary>
|
|
[HttpGet("{documentId:guid}")]
|
|
[ProducesResponseType(typeof(DocumentDetail), StatusCodes.Status200OK)]
|
|
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
|
public async Task<ActionResult<DocumentDetail>> GetDetail(Guid documentId, CancellationToken ct)
|
|
{
|
|
var doc = await db.Documents
|
|
.AsNoTracking()
|
|
.Where(d => d.Id == documentId)
|
|
.Select(d => new
|
|
{
|
|
d.Id,
|
|
d.FileName,
|
|
d.CreatedAt,
|
|
d.TemplateId,
|
|
TemplateName = d.Template != null ? d.Template.Name : null,
|
|
TemplateIsActive = d.Template != null && d.Template.IsActive,
|
|
})
|
|
.FirstOrDefaultAsync(ct);
|
|
if (doc is null)
|
|
return NotFound($"ไม่พบ document {documentId}");
|
|
|
|
var fields = new List<DocumentFieldItem>();
|
|
if (doc.TemplateId is not null)
|
|
{
|
|
// โหลดสองข้างแยกแล้ว merge ใน memory (แบบเดียวกับ FieldSyncService) —
|
|
// ไม่ใช้ Join เพราะ inner join จะทิ้ง orphan ทั้งสองฝั่งเงียบๆ
|
|
var defs = await db.TemplateFields
|
|
.AsNoTracking()
|
|
.Where(f => f.TemplateId == doc.TemplateId)
|
|
.OrderBy(f => f.SortOrder)
|
|
.Select(f => new { f.Key, f.Label, f.Type, f.IsRequired })
|
|
.ToListAsync(ct);
|
|
|
|
var values = await db.DocumentFieldValues
|
|
.AsNoTracking()
|
|
.Where(v => v.DocumentId == documentId)
|
|
.ToDictionaryAsync(v => v.FieldKey, ct);
|
|
|
|
foreach (var def in defs)
|
|
{
|
|
values.TryGetValue(def.Key, out var value);
|
|
fields.Add(new DocumentFieldItem(
|
|
def.Key, def.Label, def.Type, def.IsRequired,
|
|
value?.Value ?? string.Empty,
|
|
value?.SourceVersionId, value?.UpdatedByUserId, value?.UpdatedAt));
|
|
}
|
|
|
|
// ค่าที่เก็บไว้แต่ key ไม่มีในนิยามปัจจุบัน (replace ไฟล์แล้ว tag หาย) — ต่อท้ายโดยไม่มีนิยาม
|
|
foreach (var (key, value) in values.Where(kv => defs.All(d => d.Key != kv.Key)).OrderBy(kv => kv.Key))
|
|
{
|
|
fields.Add(new DocumentFieldItem(
|
|
key, null, null, null,
|
|
value.Value,
|
|
value.SourceVersionId, value.UpdatedByUserId, value.UpdatedAt));
|
|
}
|
|
}
|
|
|
|
return Ok(new DocumentDetail(
|
|
doc.Id, doc.FileName, doc.CreatedAt, doc.TemplateId, doc.TemplateName, doc.TemplateIsActive, fields));
|
|
}
|
|
|
|
/// <summary>FR-6 — version history เรียงใหม่ → เก่า (พร้อม snapshot fields ต่อ version)</summary>
|
|
[HttpGet("{documentId:guid}/versions")]
|
|
[ProducesResponseType(typeof(IReadOnlyList<VersionListItem>), StatusCodes.Status200OK)]
|
|
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
|
public async Task<ActionResult<IReadOnlyList<VersionListItem>>> GetVersions(Guid documentId, CancellationToken ct)
|
|
{
|
|
var exists = await db.Documents.AnyAsync(d => d.Id == documentId, ct);
|
|
if (!exists)
|
|
return NotFound($"ไม่พบ document {documentId}");
|
|
|
|
var rows = await db.DocumentVersions
|
|
.AsNoTracking()
|
|
.Where(v => v.DocumentId == documentId)
|
|
.OrderByDescending(v => v.VersionNumber)
|
|
.Select(v => new
|
|
{
|
|
v.Id,
|
|
v.VersionNumber,
|
|
v.CreatedAt,
|
|
v.CreatedByUserId,
|
|
v.ContentHash,
|
|
v.FieldsSnapshotJson,
|
|
v.Message,
|
|
v.PdfObjectKey,
|
|
})
|
|
.ToListAsync(ct);
|
|
|
|
return Ok(rows.Select(r => new VersionListItem(
|
|
r.Id, r.VersionNumber, r.CreatedAt, r.CreatedByUserId, r.ContentHash,
|
|
ParseSnapshot(r.FieldsSnapshotJson), r.Message, r.PdfObjectKey is not null)).ToList());
|
|
}
|
|
|
|
/// <summary>FR-7/FR-15 — proxy download; format=pdf selects PDF (404 when absent), default is docx.</summary>
|
|
[HttpGet("{documentId:guid}/versions/{versionId:guid}/download")]
|
|
[ProducesResponseType(typeof(FileContentResult), StatusCodes.Status200OK)]
|
|
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
|
public async Task<IActionResult> DownloadVersion(Guid documentId, Guid versionId, CancellationToken ct, [FromQuery] string? format = null)
|
|
{
|
|
var row = await db.DocumentVersions
|
|
.AsNoTracking()
|
|
.Where(v => v.DocumentId == documentId && v.Id == versionId)
|
|
.Join(db.Documents, v => v.DocumentId, d => d.Id, (v, d) => new { v.ObjectKey, v.PdfObjectKey, d.FileName })
|
|
.FirstOrDefaultAsync(ct);
|
|
if (row is null)
|
|
return NotFound($"ไม่พบ version {versionId} ของ document {documentId}");
|
|
|
|
var isPdf = string.Equals(format, "pdf", StringComparison.OrdinalIgnoreCase);
|
|
var objectKey = isPdf ? row.PdfObjectKey : row.ObjectKey;
|
|
if (objectKey is null)
|
|
return NotFound("version นี้ไม่มีสำเนา PDF");
|
|
|
|
Stream stream;
|
|
try
|
|
{
|
|
stream = await storage.GetStreamAsync(minioOptions.Value.VersionsBucket, objectKey, ct);
|
|
}
|
|
catch (KeyNotFoundException)
|
|
{
|
|
logger.LogError("Object missing in storage documentId={DocumentId} versionId={VersionId} key={ObjectKey}",
|
|
documentId, versionId, objectKey);
|
|
return NotFound("ไฟล์ของ version นี้ไม่พบใน storage");
|
|
}
|
|
|
|
logger.LogInformation("Version download documentId={DocumentId} versionId={VersionId} userId={UserId}",
|
|
documentId, versionId, currentUser.UserId);
|
|
|
|
var downloadName = row.FileName.EndsWith(".docx", StringComparison.OrdinalIgnoreCase)
|
|
? row.FileName
|
|
: row.FileName + ".docx";
|
|
return File(stream, isPdf ? PdfUploadValidation.PdfContentType : DocxContentType,
|
|
isPdf ? Path.ChangeExtension(downloadName, ".pdf") : downloadName);
|
|
}
|
|
|
|
/// <summary>FR-7/FR-15 — ลิงก์เปิดไฟล์อายุสั้น (HMAC) ที่วิ่งผ่าน https ของ backend; format=pdf = inline PDF (404 เมื่อไม่มี).
|
|
/// ออก URL ให้ add-in/เว็บเปิดในเบราว์เซอร์หรือ ms-word:ofe ของผู้ใช้ — webview ของ Word ทิ้ง blob download
|
|
/// เงียบๆ และ Word รุ่นใหม่เมิน URL ที่เป็น http จึงไม่ใช้ presigned ของ MinIO ตรงๆ อีก (v9.2)</summary>
|
|
[HttpGet("{documentId:guid}/versions/{versionId:guid}/download-link")]
|
|
[ProducesResponseType(typeof(VersionDownloadLinkResponse), StatusCodes.Status200OK)]
|
|
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
|
public async Task<ActionResult<VersionDownloadLinkResponse>> GetVersionDownloadLink(
|
|
Guid documentId, Guid versionId, CancellationToken ct, [FromQuery] string? format = null)
|
|
{
|
|
var row = await db.DocumentVersions
|
|
.AsNoTracking()
|
|
.Where(v => v.DocumentId == documentId && v.Id == versionId)
|
|
.Join(db.Documents, v => v.DocumentId, d => d.Id,
|
|
(v, d) => new { v.ObjectKey, v.PdfObjectKey, v.VersionNumber, d.FileName })
|
|
.FirstOrDefaultAsync(ct);
|
|
if (row is null)
|
|
return NotFound($"ไม่พบ version {versionId} ของ document {documentId}");
|
|
|
|
var isPdf = string.Equals(format, "pdf", StringComparison.OrdinalIgnoreCase);
|
|
var objectKey = isPdf ? row.PdfObjectKey : row.ObjectKey;
|
|
if (objectKey is null)
|
|
return NotFound("version นี้ไม่มีสำเนา PDF");
|
|
|
|
var url = openLinks.CreateLink($"v:{documentId}:{versionId}", isPdf ? "pdf" : "docx", out var expiresAt);
|
|
|
|
logger.LogInformation(
|
|
"Version download link issued documentId={DocumentId} versionId={VersionId} userId={UserId} expiresAt={ExpiresAt}",
|
|
documentId, versionId, currentUser.UserId, expiresAt);
|
|
|
|
return Ok(new VersionDownloadLinkResponse(url, expiresAt));
|
|
}
|
|
|
|
/// <summary>ถอนการเปลี่ยน DocumentFieldValue ที่ stage ไว้กลับเป็นค่าก่อน request
|
|
/// — ใช้ตอน MinIO fail หลัง SaveChanges แล้ว (ไม่ให้ค่าล้ำหน้า version ที่ถูกถอน)</summary>
|
|
private static void RevertStagedFieldChanges(
|
|
AppDbContext db, Dictionary<string, DocumentFieldValue>? valuesBefore)
|
|
{
|
|
if (valuesBefore is null)
|
|
return;
|
|
|
|
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 object? ParseSnapshot(string? json)
|
|
{
|
|
if (json is null)
|
|
return null;
|
|
using var doc = JsonDocument.Parse(json);
|
|
return doc.RootElement.Clone(); // clone ก่อน dispose JsonDocument เพื่อให้ serialize ต่อได้
|
|
}
|
|
|
|
private static bool IsUniqueViolation(DbUpdateException ex) =>
|
|
ex.InnerException is PostgresException { SqlState: PostgresErrorCodes.UniqueViolation };
|
|
|
|
/// <summary>FR-13 — normalize commit message: ว่าง/whitespace ล้วน → null, ไม่เช่นนั้น trim
|
|
/// (นโยบายเดียวกับ Template.Description ใน TemplatesController)</summary>
|
|
private static string? NormalizeMessage(string? message) =>
|
|
string.IsNullOrWhiteSpace(message) ? null : message.Trim();
|
|
}
|