2026-08-19 12:15:20 +07:00
|
|
|
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}` ห้ามว่าง");
|
|
|
|
|
|
2026-08-22 09:17:15 +07:00
|
|
|
// editor (FR-14) — ไม่ส่ง/ว่าง = default ของ type · ค่าที่เท่ากับ default เก็บเป็น null (normalize-on-write)
|
|
|
|
|
var editor = string.IsNullOrWhiteSpace(def.Editor)
|
|
|
|
|
? TemplateField.DefaultEditor(def.Type)
|
|
|
|
|
: def.Editor.Trim();
|
|
|
|
|
if (!TemplateField.EditorsByType[def.Type].Contains(editor))
|
|
|
|
|
return BadRequest(
|
|
|
|
|
$"editor ของ `{def.Key}` ต้องเป็น {string.Join("/", TemplateField.EditorsByType[def.Type])} สำหรับ type {def.Type} (ได้ `{editor}`)");
|
|
|
|
|
|
2026-08-19 12:15:20 +07:00
|
|
|
var row = template.Fields.First(f => f.Key == def.Key);
|
|
|
|
|
row.Label = def.Label.Trim();
|
|
|
|
|
row.Type = def.Type;
|
2026-08-22 09:17:15 +07:00
|
|
|
row.Editor = editor == TemplateField.DefaultEditor(def.Type) ? null : editor;
|
2026-08-19 12:15:20 +07:00
|
|
|
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));
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-10 11:49:16 +07:00
|
|
|
/// <summary>FR-16 — ไฟล์ร่าง (draft): generate docx จาก template โดยไม่สร้าง
|
|
|
|
|
/// Document/DocumentVersion/DocumentFieldValue ใน DB — เก็บไฟล์ชั่วคราวใน bucket versions ใต้ prefix
|
|
|
|
|
/// `drafts/` (หมดอายุรายวันตาม lifecycle) แล้วคืน presigned URL อายุสั้นให้เว็บเปิดใน Word
|
|
|
|
|
/// ผ่าน ms-word:ofe พร้อมลิงก์ดาวน์โหลดสำรอง (v9 — ตอนแรกคืนไฟล์ตรงๆ แต่ผู้ใช้ต้องเปิด Word เอง)</summary>
|
2026-09-10 10:51:13 +07:00
|
|
|
[HttpPost("{id:guid}/generate-draft")]
|
2026-09-10 11:49:16 +07:00
|
|
|
[ProducesResponseType(typeof(GenerateDraftResponse), StatusCodes.Status200OK)]
|
2026-09-10 10:51:13 +07:00
|
|
|
[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 ไม่ได้)");
|
|
|
|
|
}
|
2026-09-10 12:07:50 +07:00
|
|
|
catch (Exception ex) when (ex is not OperationCanceledException)
|
|
|
|
|
{
|
|
|
|
|
// กันหน้า: OpenXML โยนอะไรก็ตามที่เราไม่ได้เจอมาก่อน (เช่น ArgumentException จากอักขระที่ XML ใช้ไม่ได้
|
|
|
|
|
// ตอน v9 แรกๆ หลุดเป็น 500 stack เต็มจอ) — ให้เป็น 502 ที่อ่านออกแทน
|
|
|
|
|
logger.LogError(ex, "Draft generation failed templateId={TemplateId} userId={UserId}",
|
|
|
|
|
template.Id, currentUser.UserId);
|
|
|
|
|
return StatusCode(StatusCodes.Status502BadGateway, "สร้างไฟล์ร่างไม่สำเร็จ (ไฟล์ template หรือค่าที่กรอกมีปัญหา)");
|
|
|
|
|
}
|
2026-09-10 10:51:13 +07:00
|
|
|
|
2026-09-10 11:49:16 +07:00
|
|
|
// เก็บชั่วคราวใต้ drafts/ — lifecycle ลบให้เอง (Program.cs ตั้ง rule ตอน startup)
|
|
|
|
|
var now = DateTimeOffset.UtcNow;
|
|
|
|
|
var objectKey = $"drafts/{template.Id}/{now:yyyyMMddHHmmss}_{Guid.NewGuid():N}.docx";
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
await storage.PutAsync(minioOptions.Value.VersionsBucket, objectKey,
|
|
|
|
|
new MemoryStream(fileBytes), DocxUploadValidation.DocxContentType, ct);
|
|
|
|
|
}
|
|
|
|
|
catch (AmazonServiceException ex)
|
|
|
|
|
{
|
|
|
|
|
logger.LogError(ex, "Draft upload failed templateId={TemplateId} userId={UserId}",
|
|
|
|
|
template.Id, currentUser.UserId);
|
|
|
|
|
return StatusCode(StatusCodes.Status502BadGateway, "อัปโหลดไฟล์ขึ้น storage ไม่สำเร็จ");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// presigned อายุสั้น + ชื่อไฟล์ไทยตาม RFC 5987 (นโยบายเดียวกับ download-link ของ version)
|
|
|
|
|
var expirySeconds = Math.Clamp(minioOptions.Value.PresignedExpirySeconds, 30, 600);
|
|
|
|
|
var fileName = DocxGenerationService.BuildGeneratedFileName(template.Name, now);
|
|
|
|
|
var url = storage.GetPresignedGetUrl(
|
|
|
|
|
minioOptions.Value.VersionsBucket, objectKey, TimeSpan.FromSeconds(expirySeconds),
|
|
|
|
|
$"attachment; filename*=UTF-8''{Uri.EscapeDataString(fileName)}");
|
|
|
|
|
|
|
|
|
|
logger.LogInformation("Draft generated templateId={TemplateId} userId={UserId} bytes={Size} key={ObjectKey}",
|
|
|
|
|
template.Id, currentUser.UserId, fileBytes.Length, objectKey);
|
2026-09-10 10:51:13 +07:00
|
|
|
|
2026-09-10 11:49:16 +07:00
|
|
|
return Ok(new GenerateDraftResponse(url, now.AddSeconds(expirySeconds)));
|
2026-09-10 10:51:13 +07:00
|
|
|
}
|
|
|
|
|
|
2026-08-19 12:15:20 +07:00
|
|
|
/// <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();
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-20 11:15:04 +07:00
|
|
|
/// <summary>FR-12 — รายการเอกสารที่สร้างจาก template นี้ (เรียงตามกิจกรรมล่าสุด)
|
|
|
|
|
/// ใช้ได้แม้ template ถูก deactivate (เอกสารเก่ายังต้องเข้าถึงได้ตาม policy FR-9)</summary>
|
|
|
|
|
[HttpGet("{id:guid}/documents")]
|
|
|
|
|
[ProducesResponseType(typeof(IReadOnlyList<TemplateDocumentListItem>), StatusCodes.Status200OK)]
|
|
|
|
|
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
|
|
|
|
public async Task<ActionResult<IReadOnlyList<TemplateDocumentListItem>>> ListDocuments(Guid id, CancellationToken ct)
|
|
|
|
|
{
|
|
|
|
|
if (!await db.Templates.AnyAsync(t => t.Id == id, ct))
|
|
|
|
|
return NotFound($"ไม่พบ template {id}");
|
|
|
|
|
|
|
|
|
|
// cast (int?) ใน Max จำเป็น — ทำให้ SQL MAX คืน NULL บนชุดว่างได้ (pattern เดียวกับ UploadVersion)
|
|
|
|
|
// LatestActivity ต้อง compute ใน projection — EF จะยกเข้า SQL ORDER BY ให้
|
|
|
|
|
var rows = await db.Documents
|
|
|
|
|
.AsNoTracking()
|
|
|
|
|
.Where(d => d.TemplateId == id)
|
|
|
|
|
.Select(d => new
|
|
|
|
|
{
|
|
|
|
|
d.Id,
|
|
|
|
|
d.FileName,
|
|
|
|
|
d.CreatedAt,
|
|
|
|
|
VersionCount = d.Versions.Count,
|
|
|
|
|
LatestVersionNumber = d.Versions.Max(v => (int?)v.VersionNumber) ?? 0,
|
|
|
|
|
LatestVersionAt = d.Versions.Max(v => (DateTimeOffset?)v.CreatedAt),
|
|
|
|
|
LatestActivity = d.Versions.Max(v => (DateTimeOffset?)v.CreatedAt) ?? d.CreatedAt,
|
|
|
|
|
})
|
|
|
|
|
.OrderByDescending(x => x.LatestActivity)
|
|
|
|
|
.ThenBy(x => x.FileName)
|
|
|
|
|
.ToListAsync(ct);
|
|
|
|
|
|
|
|
|
|
return Ok(rows.Select(r =>
|
|
|
|
|
new TemplateDocumentListItem(r.Id, r.FileName, r.CreatedAt, r.VersionCount, r.LatestVersionNumber, r.LatestVersionAt)).ToList());
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-19 12:15:20 +07:00
|
|
|
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)
|
2026-08-22 09:17:15 +07:00
|
|
|
.Select(f => new TemplateFieldDto(f.Id, f.Key, f.Label, f.Type,
|
|
|
|
|
f.Editor ?? TemplateField.DefaultEditor(f.Type), f.IsRequired, f.SortOrder))
|
2026-08-19 12:15:20 +07:00
|
|
|
.ToList();
|
|
|
|
|
}
|