eCourt-Doc-Edit/web/app/pages/documents/create/[templateId].vue
Suphonchai Phoonsawat 7b20f12ede Phase 9: version message (FR-13)
- ใส่คำอธิบายแบบ commit message ได้ทุก flow ที่สร้าง version (Save & Version / Start Versioning / generate จากเว็บ) + แสดงใน version history ทุกหน้า
- backend: DocumentVersion.Message (varchar 2048) + migration AddVersionMessage + BadRequest ตรวจความยาวก่อนแตะ MinIO (กัน 500 + orphan object)
- add-in: ConfirmVersionDialog เพิ่ม textarea (Start Versioning ใช้ dialog ด้วย) + แสดง message ใน VersionHistoryPanel
- web: ฟอร์มสร้างเอกสาร + หน้า detail แสดง message (desktop truncate + tooltip, mobile เต็มบรรทัด)
- sync เอกสารทั้งหมด: spec v5 (FR-13/AC-16) + plan Phase 9 + acceptance-review 1–16 + README + CLAUDE.md + web/README
- tests: backend 52 / addin 50 / web 36 — เขียวทั้งชุด

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-20 22:05:49 +07:00

258 lines
11 KiB
Vue

<script setup lang="ts">
/** FR-10 UI — dynamic form สร้างเอกสารจาก field definitions ของ template → generate เป็น v1 + ดาวน์โหลด
* FR-12 — รองรับ re-generate: ?from={documentId} → prefill ค่าล่าสุดของเอกสารนั้นให้แก้ก่อนสร้าง */
import type { DocumentDetail, GenerateDocumentResponse, TemplateDetail } from '~/types/api'
const route = useRoute()
const { apiJson, downloadFile } = useApi()
const templateId = computed(() => String(route.params.templateId))
const detail = ref<TemplateDetail | null>(null)
const values = ref<Record<string, string>>({})
const issues = ref<Record<string, string>>({})
/** คำอธิบาย version แบบ commit message (FR-13) — ทางเลือก · re-generate ไม่ prefill เพราะเป็นเอกสารใหม่ */
const message = ref('')
/** เอกสารต้นทางของ re-generate (จาก ?from=) — ใช้ทั้ง prefill และ banner บอกบริบท */
const fromDoc = ref<{ id: string; fileName: string } | null>(null)
const prefill = ref<Record<string, string>>({})
const loading = ref(true)
const loadError = ref<string | null>(null)
const submitting = ref(false)
const submitError = ref<string | null>(null)
const result = ref<GenerateDocumentResponse | null>(null)
const downloading = ref(false)
const downloadError = ref<string | null>(null)
const sortedFields = computed(() => [...(detail.value?.fields ?? [])].sort((a, b) => a.sortOrder - b.sortOrder))
useHead({
title: computed(() =>
detail.value
? `สร้างเอกสาร: ${detail.value.name} — e-Court Documents Versioning`
: 'สร้างเอกสาร — e-Court Documents Versioning',
),
})
function blankValues(): Record<string, string> {
return Object.fromEntries((detail.value?.fields ?? []).map((f) => [f.key, '']))
}
async function load() {
loading.value = true
loadError.value = null
try {
detail.value = (await apiJson<TemplateDetail>(`/api/templates/${templateId.value}`))!
const from = typeof route.query.from === 'string' ? route.query.from : null
if (from) {
try {
const src = await apiJson<DocumentDetail>(`/api/documents/${from}`)
if (src?.templateId) {
fromDoc.value = { id: src.id, fileName: src.fileName }
// prefill เฉพาะ key ที่มีใน defs ปัจจุบัน — key ที่หายไปหลัง replace ไฟล์โชว์ไม่ได้ (generate ก็ ignore)
prefill.value = Object.fromEntries(
detail.value.fields.map((f) => [f.key, src.fields.find((s) => s.key === f.key)?.value ?? '']),
)
}
} catch {
// ไม่พบเอกสารต้นทาง — ปล่อยให้เป็นฟอร์มว่างตามปกติ
}
}
values.value = { ...blankValues(), ...prefill.value }
} catch (err) {
loadError.value = err instanceof Error ? err.message : 'โหลด template ไม่สำเร็จ'
} finally {
loading.value = false
}
}
/** validate ฝั่ง client (required/type) ก่อนยิง backend — backend ตรวจซ้ำอีกชั้นเสมอ */
async function submit() {
submitError.value = null
downloadError.value = null
issues.value = Object.fromEntries(
validateFieldValues(sortedFields.value, values.value).map((i) => [i.key, i.message]),
)
if (Object.keys(issues.value).length > 0) return
submitting.value = true
try {
result.value = await apiJson<GenerateDocumentResponse>('/api/documents/generate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ templateId: templateId.value, values: values.value, message: message.value.trim() || null }),
})
window.scrollTo({ top: 0 })
} catch (err) {
submitError.value = err instanceof Error ? err.message : 'สร้างเอกสารไม่สำเร็จ'
} finally {
submitting.value = false
}
}
async function download() {
if (!result.value) return
downloading.value = true
downloadError.value = null
try {
const name = detail.value ? `${detail.value.name}_v${result.value.versionNumber}.docx` : 'document_v1.docx'
await downloadFile(result.value.downloadUrl, name)
} catch (err) {
downloadError.value = err instanceof Error ? err.message : 'ดาวน์โหลดไม่สำเร็จ'
} finally {
downloading.value = false
}
}
/** กลับไปกรอกฟอร์มใหม่เพื่อสร้างอีกฉบับจาก template เดิม (ถ้าเป็น re-generate → คืนค่า prefill ไม่ใช่ฟอร์มว่าง) */
function resetForm() {
result.value = null
submitError.value = null
downloadError.value = null
issues.value = {}
values.value = { ...blankValues(), ...prefill.value }
message.value = ''
}
onMounted(load)
</script>
<template>
<AuthGate>
<section class="mx-auto max-w-2xl space-y-6">
<div v-if="loading" class="flex items-center gap-3 py-10 text-sm text-muted">
<span class="spinner" />
กำลังโหลด template…
</div>
<AlertBox v-else-if="loadError" type="error">
{{ loadError }}
<NuxtLink to="/" class="ml-1 font-medium underline">กลับหน้าหลัก</NuxtLink>
</AlertBox>
<template v-else-if="detail">
<!-- ผลลัพธ์: สร้างสำเร็จเป็น v1 แล้ว -->
<template v-if="result">
<AlertBox type="success">
สร้างเอกสารสำเร็จ — บันทึกเป็น <strong>version {{ result.versionNumber }}</strong> แล้ว
</AlertBox>
<div class="card p-6">
<h1 class="text-page-title">{{ detail.name }}</h1>
<dl class="mt-4 space-y-2 text-sm">
<div class="flex gap-2">
<dt class="w-32 shrink-0 text-muted">document id</dt>
<dd class="break-all font-mono text-xs leading-6">{{ result.documentId }}</dd>
</div>
<div class="flex gap-2">
<dt class="w-32 shrink-0 text-muted">version</dt>
<dd>{{ result.versionNumber }} (ต้นทางของ version history)</dd>
</div>
</dl>
<div class="mt-6 flex flex-col-reverse gap-2 sm:flex-row sm:flex-wrap">
<NuxtLink to="/" class="btn btn-secondary w-full sm:w-auto">กลับหน้าหลัก</NuxtLink>
<button type="button" class="btn btn-secondary w-full sm:w-auto" @click="resetForm">
สร้างอีกฉบับ
</button>
<button
type="button"
:disabled="downloading"
class="btn btn-primary w-full sm:w-auto"
@click="download"
>
{{ downloading ? 'กำลังเตรียมไฟล์…' : '⬇ ดาวน์โหลด .docx' }}
</button>
</div>
<AlertBox v-if="downloadError" type="error" class="mt-4">{{ downloadError }}</AlertBox>
</div>
<div class="panel-info">
<p class="font-medium text-primary">ขั้นต่อไป</p>
<ol class="mt-2 list-decimal space-y-1 pl-5">
<li>เปิดไฟล์ที่ดาวน์โหลดใน Word (Desktop หรือ Online)</li>
<li>
เปิด task pane ของ add-in <strong>e-Court Documents Versioning</strong> — ระบบจะตรวจพบว่าเป็น
tracked document และแสดง <strong>version 1</strong> ทันที โดยไม่ต้องกด Start Versioning
</li>
<li>แก้ไขเอกสารต่อแล้วกด <strong>Save &amp; Version</strong> เพื่อบันทึก version ถัดไป</li>
</ol>
</div>
</template>
<!-- ฟอร์มกรอกค่า -->
<form v-else class="space-y-5" @submit.prevent="submit" novalidate>
<div>
<h1 class="text-page-title">{{ detail.name }}</h1>
<p v-if="detail.description" class="mt-1 text-sm text-muted">
{{ detail.description }}
</p>
</div>
<AlertBox v-if="fromDoc">
กำลังสร้างเอกสารใหม่จากค่าปัจจุบันของ <strong class="break-all">{{ fromDoc.fileName }}</strong>
— แก้ค่าได้ก่อนกดสร้าง และเอกสารต้นทางจะไม่ถูกแตะ (ไม่เกิด version ใหม่)
</AlertBox>
<AlertBox v-if="!detail.isActive">
template นี้ถูก deactivate แล้ว — สร้างเอกสารใหม่ไม่ได้ (เอกสารที่สร้างไว้แล้วยังใช้ได้)
</AlertBox>
<div
v-for="f in sortedFields"
:key="f.key"
>
<label :for="`field-${f.key}`" class="label">
{{ f.label }}
<span v-if="f.isRequired" class="text-error-strong">*</span>
<span class="ml-1 font-mono text-xs font-normal text-muted">{{ f.key }}</span>
</label>
<input
:id="`field-${f.key}`"
v-model="values[f.key]"
:type="f.type === 'number' ? 'number' : f.type === 'date' ? 'date' : 'text'"
:step="f.type === 'number' ? 'any' : undefined"
class="input"
:class="issues[f.key] ? 'border-error' : ''"
/>
<p v-if="issues[f.key]" class="mt-1 text-xs text-error-strong">{{ issues[f.key] }}</p>
</div>
<div>
<label for="doc-message" class="label">คำอธิบาย version (ไม่บังคับ)</label>
<textarea
id="doc-message"
v-model="message"
class="input"
rows="2"
maxlength="2048"
placeholder="เช่น ฉบับเสนอลงนามครั้งแรก"
/>
</div>
<div v-if="sortedFields.length === 0" class="empty-state">
template นี้ไม่มี field definitions —
<NuxtLink :to="`/templates/${detail.id}/edit`" class="link">ตรวจสอบที่หน้าจัดการ template</NuxtLink>
</div>
<AlertBox v-if="submitError" type="error">{{ submitError }}</AlertBox>
<div class="flex flex-col-reverse gap-2 pt-2 sm:flex-row sm:justify-end">
<button
type="submit"
:disabled="submitting || sortedFields.length === 0 || !detail.isActive"
class="btn btn-primary w-full sm:w-auto"
>
{{ submitting ? 'กำลังสร้างเอกสาร…' : 'สร้างเอกสาร (version 1)' }}
</button>
</div>
</form>
</template>
</section>
</AuthGate>
</template>