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
|
|
@ -1,4 +1,3 @@
|
|||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using Amazon.Runtime;
|
||||
using DocumentFormat.OpenXml.Packaging;
|
||||
|
|
@ -52,6 +51,18 @@ public class DocumentsController(
|
|||
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))
|
||||
|
|
@ -97,7 +108,7 @@ public class DocumentsController(
|
|||
var contentHash = await hasher.ComputeSha256HexAsync(uploadStream, ct);
|
||||
uploadStream.Seek(0, SeekOrigin.Begin);
|
||||
|
||||
// สร้าง Document ถ้ายังไม่มี (FR-5)
|
||||
// สร้าง 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)
|
||||
|
|
@ -107,6 +118,7 @@ public class DocumentsController(
|
|||
Id = documentId,
|
||||
FileName = fileName,
|
||||
AddInSignature = string.Empty, // ฝั่ง add-in stamp ในไฟล์เอง
|
||||
TemplateId = templateIdToLink, // null = เอกสาร track เอง · มีค่า = ไฟล์ร่างจาก template (field sync ทำงานเต็มระบบที่ v1)
|
||||
CreatedAt = now,
|
||||
};
|
||||
db.Documents.Add(doc);
|
||||
|
|
@ -257,32 +269,10 @@ public class DocumentsController(
|
|||
if (message is { Length: > MaxVersionMessageLength })
|
||||
return BadRequest($"`message` ยาวเกิน {MaxVersionMessageLength} อักขระ");
|
||||
|
||||
// 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));
|
||||
// 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;
|
||||
|
|
@ -326,7 +316,7 @@ public class DocumentsController(
|
|||
var doc = new Document
|
||||
{
|
||||
Id = documentId,
|
||||
FileName = BuildGeneratedFileName(template.Name, now),
|
||||
FileName = DocxGenerationService.BuildGeneratedFileName(template.Name, now),
|
||||
AddInSignature = AddInMetadata.AddInSignatureGuid,
|
||||
TemplateId = template.Id,
|
||||
CreatedAt = now,
|
||||
|
|
@ -578,16 +568,6 @@ public class DocumentsController(
|
|||
}
|
||||
}
|
||||
|
||||
/// <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)
|
||||
{
|
||||
if (json is null)
|
||||
|
|
|
|||
|
|
@ -305,6 +305,74 @@ public class TemplatesController(
|
|||
return Ok(new ReplaceTemplateFileResponse(template.Id, FieldDtos(template), addedTags, removedTags));
|
||||
}
|
||||
|
||||
/// <summary>FR-16 — ไฟล์ร่าง (draft): generate docx จาก template แบบ stateless — ไม่สร้าง
|
||||
/// Document/DocumentVersion/DocumentFieldValue และไม่เขียน MinIO; คืนไฟล์ทันที
|
||||
/// (ผู้ใช้เปิดใน Word แล้วกด Start Versioning เพื่อเริ่ม track เป็น v1 พร้อมผูกกลับมาที่ template นี้)</summary>
|
||||
[HttpPost("{id:guid}/generate-draft")]
|
||||
[ProducesResponseType(typeof(FileContentResult), StatusCodes.Status200OK)]
|
||||
[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 ไม่ได้)");
|
||||
}
|
||||
|
||||
logger.LogInformation("Draft generated templateId={TemplateId} userId={UserId} bytes={Size}",
|
||||
template.Id, currentUser.UserId, fileBytes.Length);
|
||||
|
||||
return File(fileBytes, DocxUploadValidation.DocxContentType,
|
||||
DocxGenerationService.BuildGeneratedFileName(template.Name, DateTimeOffset.UtcNow));
|
||||
}
|
||||
|
||||
/// <summary>deactivate (soft-delete) — document เก่าที่อ้างอยู่ยังใช้ได้ต่อ แต่สร้างเอกสารใหม่ไม่ได้</summary>
|
||||
[HttpDelete("{id:guid}")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
using System.ComponentModel.DataAnnotations;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace WordVersioning.Api.Models;
|
||||
|
||||
|
|
@ -52,6 +53,14 @@ public class ReplaceTemplateFileRequest
|
|||
public IFormFile File { get; set; } = null!;
|
||||
}
|
||||
|
||||
/// <summary>body ของ POST /api/templates/{id}/generate-draft (FR-16) — ไม่มี message เพราะไฟล์ร่างยังไม่เกิด version</summary>
|
||||
public class GenerateDraftRequest
|
||||
{
|
||||
/// <summary>map fieldKey → value (ค่า scalar ทั้งหมด) — pattern เดียวกับ GenerateDocumentRequest</summary>
|
||||
[Required]
|
||||
public JsonElement Values { get; set; }
|
||||
}
|
||||
|
||||
public record TemplateFieldDto(Guid Id, string Key, string Label, string Type, string Editor, bool IsRequired, int SortOrder);
|
||||
|
||||
public record TemplateListItem(
|
||||
|
|
|
|||
|
|
@ -20,6 +20,10 @@ public class UploadVersionRequest
|
|||
|
||||
/// <summary>คำอธิบาย version แบบ commit message (FR-13) — optional</summary>
|
||||
public string? Message { get; set; }
|
||||
|
||||
/// <summary>GUID ของ template ต้นทาง (FR-16 ไฟล์ร่าง) — ใช้เฉพาะตอน auto-create Document;
|
||||
/// ไม่ส่ง = เอกสาร track เอง · ส่งมาตอน document มีอยู่แล้ว = เฉย (validate ทุกครั้งที่ส่ง)</summary>
|
||||
public string? TemplateId { get; set; }
|
||||
}
|
||||
|
||||
public record UploadVersionResponse(Guid VersionId, int VersionNumber, bool HasPdf);
|
||||
|
|
|
|||
|
|
@ -65,11 +65,14 @@ builder.Services
|
|||
builder.Services.AddAuthorization();
|
||||
|
||||
// CORS — add-in task pane (https://localhost:3000) + web portal (http://localhost:5173) เท่านั้น
|
||||
// expose Content-Disposition ให้ fetch ฝั่งเว็บอ่านชื่อไฟล์ (ไทย) ของไฟล์ร่างที่ดาวน์โหลดได้ (FR-16)
|
||||
// — ไม่ expose แล้ว header จะเป็น null บน cross-origin และชื่อไฟล์หายเงียบๆ
|
||||
const string corsPolicy = "frontends";
|
||||
builder.Services.AddCors(options => options.AddPolicy(corsPolicy, policy => policy
|
||||
.WithOrigins(builder.Configuration.GetSection("Cors:AllowedOrigins").Get<string[]>() ?? [])
|
||||
.AllowAnyHeader()
|
||||
.AllowAnyMethod()));
|
||||
.AllowAnyMethod()
|
||||
.WithExposedHeaders("Content-Disposition")));
|
||||
|
||||
// --- dev HTTPS -------------------------------------------------------------
|
||||
// Word webview (WKWebView บน Mac) บล็อก fetch จากหน้า https ไป http แบบเงียบๆ ("Load failed")
|
||||
|
|
|
|||
|
|
@ -9,4 +9,9 @@ public static class AddInMetadata
|
|||
public const string SavedByAddInPropertyName = "SavedByAddIn";
|
||||
|
||||
public const string DocumentTrackingIdPropertyName = "DocumentTrackingId";
|
||||
|
||||
/// <summary>FR-16 — stamp ลงไฟล์ร่าง (draft) เท่านั้น: template ต้นทาง · ไม่ stamp
|
||||
/// SavedByAddIn/DocumentTrackingId เพื่อให้ add-in มองไฟล์ร่างเป็น untracked
|
||||
/// (ฝั่ง add-in ใช้ชื่อ TEMPLATE_ID_PROPERTY ค่าเดียวกันนี้ ส่งต่อเป็น form field ตอน Start Versioning)</summary>
|
||||
public const string TemplateIdPropertyName = "TemplateId";
|
||||
}
|
||||
|
|
|
|||
|
|
@ -16,6 +16,11 @@ public interface IDocxGenerationService
|
|||
/// <b>ที่ run level</b> (รักษา run properties/formatting ของ template) แล้ว stamp
|
||||
/// Custom Properties (SavedByAddIn + DocumentTrackingId) — คืนเป็น bytes ของไฟล์ใหม่</summary>
|
||||
byte[] Generate(Stream templateStream, IReadOnlyDictionary<string, string> values, Guid documentTrackingId);
|
||||
|
||||
/// <summary>FR-16 — ไฟล์ร่าง (draft): แทนที่ SDT เหมือน Generate แต่ stamp custom property
|
||||
/// <b>เฉพาะ `TemplateId`</b> (GUID ของ template ต้นทาง) — ไม่ stamp SavedByAddIn/DocumentTrackingId
|
||||
/// เพื่อให้ add-in มองไฟล์ร่างเป็น untracked จนกว่าผู้ใช้จะกด Start Versioning</summary>
|
||||
byte[] GenerateDraft(Stream templateStream, IReadOnlyDictionary<string, string> values, Guid templateId);
|
||||
}
|
||||
|
||||
/// <summary>จัดการ docx ด้วย OpenXML SDK — ใช้ทั้งตอน detect fields และตอน generate (FR-9, FR-10)</summary>
|
||||
|
|
@ -42,32 +47,67 @@ public class DocxGenerationService : IDocxGenerationService
|
|||
|
||||
public byte[] Generate(Stream templateStream, IReadOnlyDictionary<string, string> values, Guid documentTrackingId)
|
||||
{
|
||||
// ก๊อปเข้า memory ก่อน — MinIO stream ไม่ seek ได้ และ package จะเขียนกลับลง stream นี้ตอน dispose
|
||||
var buffer = new MemoryStream();
|
||||
templateStream.CopyTo(buffer);
|
||||
buffer.Position = 0;
|
||||
|
||||
var buffer = CopyToMemory(templateStream);
|
||||
using (var doc = WordprocessingDocument.Open(buffer, true))
|
||||
{
|
||||
foreach (var root in AllContentRoots(doc))
|
||||
{
|
||||
foreach (var tag in root.Descendants<Tag>().ToList())
|
||||
{
|
||||
var key = tag.Val?.Value?.Trim();
|
||||
if (string.IsNullOrEmpty(key) || !values.TryGetValue(key, out var value))
|
||||
continue;
|
||||
ReplaceSdtContent(tag, value);
|
||||
}
|
||||
}
|
||||
ReplaceSdtValues(doc, values);
|
||||
|
||||
SetCustomProperty(doc, AddInMetadata.SavedByAddInPropertyName, AddInMetadata.AddInSignatureGuid);
|
||||
SetCustomProperty(doc, AddInMetadata.DocumentTrackingIdPropertyName, documentTrackingId.ToString());
|
||||
} // dispose เขียน package กลับลง buffer
|
||||
|
||||
buffer.Position = 0;
|
||||
return buffer.ToArray();
|
||||
}
|
||||
|
||||
public byte[] GenerateDraft(Stream templateStream, IReadOnlyDictionary<string, string> values, Guid templateId)
|
||||
{
|
||||
var buffer = CopyToMemory(templateStream);
|
||||
using (var doc = WordprocessingDocument.Open(buffer, true))
|
||||
{
|
||||
ReplaceSdtValues(doc, values);
|
||||
|
||||
// stamp ตัวเดียว (FR-16) — ไฟล์ร่างต้องเป็น untracked ในสายตา add-in
|
||||
SetCustomProperty(doc, AddInMetadata.TemplateIdPropertyName, templateId.ToString());
|
||||
}
|
||||
|
||||
return buffer.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>ก๊อปเข้า memory ก่อน — MinIO stream ไม่ seek ได้ และ package จะเขียนกลับลง stream นี้ตอน dispose</summary>
|
||||
private static MemoryStream CopyToMemory(Stream stream)
|
||||
{
|
||||
var buffer = new MemoryStream();
|
||||
stream.CopyTo(buffer);
|
||||
buffer.Position = 0;
|
||||
return buffer;
|
||||
}
|
||||
|
||||
/// <summary>ชื่อไฟล์ของเอกสาร/ไฟล์ร่างที่ generate จาก template: ชื่อ template + timestamp
|
||||
/// — ตัดอักขระที่ filename ใช้ไม่ได้ออก (ใช้ร่วมทั้ง generate และ generate-draft)</summary>
|
||||
public 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";
|
||||
}
|
||||
|
||||
/// <summary>แทนที่ค่าใน SDT ทุกตัวที่ tag ตรง key ใน values (ใช้ร่วมทั้ง Generate และ GenerateDraft)</summary>
|
||||
private static void ReplaceSdtValues(WordprocessingDocument doc, IReadOnlyDictionary<string, string> values)
|
||||
{
|
||||
foreach (var root in AllContentRoots(doc))
|
||||
{
|
||||
foreach (var tag in root.Descendants<Tag>().ToList())
|
||||
{
|
||||
var key = tag.Val?.Value?.Trim();
|
||||
if (string.IsNullOrEmpty(key) || !values.TryGetValue(key, out var value))
|
||||
continue;
|
||||
ReplaceSdtContent(tag, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>แทนที่ข้อความใน SDT ที่ <b>run level</b> — เก็บ Run เดิมไว้ตัวแรก (formatting ตาม template)
|
||||
/// แล้วลบ Text ที่เหลือ ไม่ทับทั้ง paragraph (spec ส่วน 9 เพิ่มเติม v2)</summary>
|
||||
private static void ReplaceSdtContent(Tag tag, string value)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,38 @@
|
|||
using System.Globalization;
|
||||
using WordVersioning.Api.Models;
|
||||
|
||||
namespace WordVersioning.Api.Services;
|
||||
|
||||
/// <summary>FR-10/FR-16 — validate required + type ของค่าที่กรอก (ใช้ร่วมทั้ง generate และ generate-draft)
|
||||
/// field ที่ส่งเกินนิยาม ignore ตาม policy เดียวกับ FR-11</summary>
|
||||
public static class TemplateFieldValidation
|
||||
{
|
||||
/// <summary>null = ผ่าน; ไม่ null = ข้อความ error สำหรับ BadRequest (รูปแบบเดียวกับที่เคยอยู่ใน Generate)</summary>
|
||||
public static string? Validate(IEnumerable<TemplateField> fieldDefs, IReadOnlyDictionary<string, string?> values)
|
||||
{
|
||||
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 $"กรอก 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)");
|
||||
}
|
||||
return typeErrors.Count > 0 ? string.Join("; ", typeErrors) : null;
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue