初始化專案:租屋契約 PDF 產生器

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-05-15 12:04:54 +08:00
commit e1fcf3eb77
13 changed files with 1768 additions and 0 deletions

166
public/app.js Normal file
View File

@@ -0,0 +1,166 @@
const form = document.querySelector('#contractForm');
const templateSelect = document.querySelector('#template');
const submitButton = document.querySelector('#submitButton');
const downloadButton = document.querySelector('#downloadButton');
const shareButton = document.querySelector('#shareButton');
const message = document.querySelector('#message');
const resultTitle = document.querySelector('#resultTitle');
const connectionStatus = document.querySelector('#connectionStatus');
let currentPdfBlob = null;
let currentPdfFileName = '租屋契約.pdf';
loadTemplates();
form.addEventListener('submit', async (event) => {
event.preventDefault();
setBusy(true);
resetPdf();
try {
const formData = new FormData(form);
const response = await fetch('/api/contracts/pdf', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
template: formData.get('template'),
monthlyRent: formData.get('monthlyRent'),
paymentDay: formData.get('paymentDay'),
deposit: formData.get('deposit'),
}),
});
if (!response.ok) {
const errorBody = await response.json().catch(() => ({}));
throw new Error(errorBody.error || 'PDF 產生失敗。');
}
currentPdfBlob = await response.blob();
currentPdfFileName = getFileNameFromDisposition(response.headers.get('Content-Disposition'))
|| buildDefaultFileName(formData.get('template'));
resultTitle.textContent = 'PDF 已產生';
message.textContent = currentPdfFileName;
downloadButton.disabled = false;
shareButton.disabled = !canShareCurrentPdf();
} catch (error) {
resultTitle.textContent = '產生失敗';
message.textContent = error.message;
} finally {
setBusy(false);
}
});
downloadButton.addEventListener('click', () => {
if (!currentPdfBlob) {
return;
}
downloadPdf();
});
shareButton.addEventListener('click', async () => {
if (!currentPdfBlob) {
return;
}
const file = new File([currentPdfBlob], currentPdfFileName, { type: 'application/pdf' });
if (!navigator.canShare || !navigator.canShare({ files: [file] })) {
downloadPdf();
return;
}
try {
await navigator.share({
title: '租屋契約 PDF',
files: [file],
});
} catch (error) {
if (error.name !== 'AbortError') {
message.textContent = '分享失敗,已保留下載按鈕。';
}
}
});
async function loadTemplates() {
try {
const response = await fetch('/api/templates');
if (!response.ok) {
throw new Error('無法讀取範本。');
}
const body = await response.json();
templateSelect.replaceChildren(
...body.templates.map((name) => new Option(name, name)),
);
if (body.templates.length === 0) {
templateSelect.append(new Option('templates 資料夾沒有 .doc 範本', ''));
templateSelect.disabled = true;
submitButton.disabled = true;
connectionStatus.textContent = '缺少範本';
message.textContent = '請先將 .doc 範本放進 templates 資料夾。';
return;
}
connectionStatus.textContent = '可使用';
} catch (error) {
templateSelect.append(new Option('讀取失敗', ''));
templateSelect.disabled = true;
submitButton.disabled = true;
connectionStatus.textContent = '離線';
message.textContent = error.message;
}
}
function setBusy(isBusy) {
submitButton.disabled = isBusy || templateSelect.disabled;
submitButton.textContent = isBusy ? '產生中' : '產生 PDF';
}
function resetPdf() {
currentPdfBlob = null;
downloadButton.disabled = true;
shareButton.disabled = true;
resultTitle.textContent = '產生中';
message.textContent = '正在建立 PDF。';
}
function canShareCurrentPdf() {
if (!currentPdfBlob || !navigator.canShare) {
return false;
}
const file = new File([currentPdfBlob], currentPdfFileName, { type: 'application/pdf' });
return navigator.canShare({ files: [file] });
}
function downloadPdf() {
const url = URL.createObjectURL(currentPdfBlob);
const link = document.createElement('a');
link.href = url;
link.download = currentPdfFileName;
document.body.append(link);
link.click();
link.remove();
URL.revokeObjectURL(url);
}
function getFileNameFromDisposition(disposition) {
if (!disposition) {
return '';
}
const utf8Match = disposition.match(/filename\*=UTF-8''([^;]+)/i);
if (utf8Match) {
return decodeURIComponent(utf8Match[1]);
}
const asciiMatch = disposition.match(/filename="([^"]+)"/i);
return asciiMatch ? asciiMatch[1] : '';
}
function buildDefaultFileName(templateName) {
const baseName = String(templateName || '租屋契約').replace(/\.[^.]+$/, '');
return `${baseName}.pdf`;
}

69
public/index.html Normal file
View File

@@ -0,0 +1,69 @@
<!doctype html>
<html lang="zh-Hant">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>租屋契約 PDF 產生器</title>
<link rel="stylesheet" href="/styles.css">
</head>
<body>
<main class="app-shell">
<header class="topbar">
<div>
<p class="eyebrow">Word to PDF</p>
<h1>租屋契約 PDF 產生器</h1>
</div>
<span id="connectionStatus" class="status-pill">連線中</span>
</header>
<section class="workspace" aria-label="租屋契約資料">
<form id="contractForm" class="tool-panel">
<label class="field">
<span>Word 範本</span>
<select id="template" name="template" required></select>
</label>
<div class="field-grid">
<label class="field">
<span>每月租金</span>
<input name="monthlyRent" type="number" inputmode="numeric" min="1" step="1" value="8000" required>
</label>
<label class="field">
<span>繳款日期</span>
<input name="paymentDay" type="number" inputmode="numeric" min="1" max="31" step="1" value="18" required>
</label>
<label class="field">
<span>保證金</span>
<input name="deposit" type="number" inputmode="numeric" min="1" step="1" value="16000" required>
</label>
</div>
<button id="submitButton" class="primary-button" type="submit">
產生 PDF
</button>
</form>
<section class="result-panel" aria-label="PDF 結果">
<div>
<p class="eyebrow">PDF</p>
<h2 id="resultTitle">尚未產生</h2>
<p id="message" class="message">請輸入資料後產生 PDF。</p>
</div>
<div class="result-actions">
<button id="downloadButton" class="secondary-button" type="button" disabled>
下載 PDF
</button>
<button id="shareButton" class="secondary-button" type="button" disabled>
分享 PDF
</button>
</div>
</section>
</section>
</main>
<script src="/app.js" defer></script>
</body>
</html>

214
public/styles.css Normal file
View File

@@ -0,0 +1,214 @@
:root {
color-scheme: light;
--bg: #f6f8f7;
--surface: #ffffff;
--surface-muted: #eef4f1;
--border: #cfdbd5;
--text: #18201d;
--muted: #64716b;
--accent: #0f766e;
--accent-hover: #0b5f59;
--warning: #9a5b00;
--shadow: 0 18px 45px rgba(15, 35, 30, 0.08);
}
* {
box-sizing: border-box;
}
body {
margin: 0;
min-height: 100vh;
background:
linear-gradient(180deg, #ffffff 0, var(--bg) 260px),
var(--bg);
color: var(--text);
font-family: "Noto Sans TC", "Microsoft JhengHei", system-ui, sans-serif;
}
button,
input,
select {
font: inherit;
}
.app-shell {
width: min(1080px, calc(100% - 32px));
margin: 0 auto;
padding: 32px 0;
}
.topbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
margin-bottom: 24px;
}
.eyebrow {
margin: 0 0 6px;
color: var(--accent);
font-size: 0.78rem;
font-weight: 700;
text-transform: uppercase;
}
h1,
h2 {
margin: 0;
letter-spacing: 0;
}
h1 {
font-size: clamp(1.7rem, 2.3vw, 2.45rem);
}
h2 {
font-size: 1.35rem;
}
.status-pill {
flex: 0 0 auto;
min-width: 76px;
border: 1px solid var(--border);
border-radius: 999px;
background: var(--surface-muted);
padding: 7px 12px;
color: var(--muted);
font-size: 0.9rem;
text-align: center;
}
.workspace {
display: grid;
grid-template-columns: minmax(0, 1.35fr) minmax(280px, 0.65fr);
gap: 20px;
align-items: start;
}
.tool-panel,
.result-panel {
border: 1px solid var(--border);
border-radius: 8px;
background: var(--surface);
box-shadow: var(--shadow);
}
.tool-panel {
display: grid;
gap: 18px;
padding: 22px;
}
.field-grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 14px;
}
.field {
display: grid;
gap: 8px;
color: var(--muted);
font-size: 0.92rem;
font-weight: 700;
}
.field input,
.field select {
width: 100%;
min-height: 46px;
border: 1px solid var(--border);
border-radius: 6px;
background: #ffffff;
color: var(--text);
padding: 10px 12px;
outline: none;
}
.field input:focus,
.field select:focus {
border-color: var(--accent);
box-shadow: 0 0 0 3px rgba(15, 118, 110, 0.15);
}
.primary-button,
.secondary-button {
min-height: 46px;
border: 0;
border-radius: 6px;
padding: 0 16px;
cursor: pointer;
font-weight: 800;
}
.primary-button {
justify-self: start;
min-width: 150px;
background: var(--accent);
color: #ffffff;
}
.primary-button:hover:not(:disabled) {
background: var(--accent-hover);
}
.secondary-button {
border: 1px solid var(--border);
background: #ffffff;
color: var(--text);
}
.primary-button:disabled,
.secondary-button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.result-panel {
display: grid;
gap: 24px;
min-height: 216px;
padding: 22px;
}
.message {
min-height: 46px;
margin: 10px 0 0;
color: var(--muted);
line-height: 1.6;
overflow-wrap: anywhere;
}
.result-actions {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
align-self: end;
}
@media (max-width: 760px) {
.app-shell {
width: min(100% - 24px, 560px);
padding: 20px 0;
}
.topbar,
.workspace,
.field-grid {
grid-template-columns: 1fr;
}
.topbar {
display: grid;
}
.status-pill {
justify-self: start;
}
.primary-button {
width: 100%;
}
}