ツール管理へ戻るv1 のソース
<!doctype html>
<html lang="ja">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>月別 細分内訳集計</title>
<style>
:root {
color-scheme: light;
font-family: system-ui, -apple-system, "Segoe UI", sans-serif;
color: #1f2937;
background: #f3f5f8;
}
* { box-sizing: border-box; }
body { margin: 0; }
main {
width: min(1100px, calc(100% - 32px));
margin: 32px auto;
}
h1 { margin: 0 0 8px; font-size: 1.6rem; }
.intro { margin: 0 0 20px; color: #4b5563; line-height: 1.6; }
.panel {
background: #fff;
border: 1px solid #d9dee7;
border-radius: 10px;
padding: 18px;
margin: 14px 0;
box-shadow: 0 2px 8px #1f29370c;
}
label { font-weight: 650; }
input[type="file"] { display: block; margin-top: 8px; max-width: 100%; }
.controls { display: flex; flex-wrap: wrap; gap: 10px; margin-top: 14px; }
button {
border: 1px solid #b8c2d1;
border-radius: 7px;
background: #fff;
padding: 9px 14px;
font: inherit;
cursor: pointer;
}
button.primary { background: #155eef; color: #fff; border-color: #155eef; }
button:disabled { opacity: .5; cursor: not-allowed; }
.status { margin: 12px 0 0; min-height: 1.5em; color: #374151; }
.status.error { color: #b42318; }
.status.success { color: #067647; }
.note { font-size: .92rem; color: #525b6a; line-height: 1.6; }
.table-wrap { overflow-x: auto; }
table { width: 100%; border-collapse: collapse; font-size: .94rem; }
th, td { border: 1px solid #d9dee7; padding: 8px 10px; text-align: left; }
th { background: #f1f4f9; white-space: nowrap; }
td.num, th.num { text-align: right; font-variant-numeric: tabular-nums; }
.empty { color: #667085; text-align: center; padding: 24px; }
.summary { font-weight: 700; margin: 0 0 12px; }
.small { font-size: .85rem; }
@media (max-width: 600px) {
main { width: calc(100% - 20px); margin: 18px auto; }
.panel { padding: 13px; }
}
</style>
</head>
<body>
<main>
<h1>月別 細分内訳集計</h1>
<p class="intro">
月ごとに「年月・作業者名・細分・合計時間・割合の合計」を一覧にします。
小計・総合計は集計せず、PDFの明細行のみを対象にします。
</p>
<section class="panel">
<label for="pdfFiles">PDFファイルを選択(複数選択可)</label>
<input id="pdfFiles" type="file" accept="application/pdf,.pdf" multiple>
<div class="controls">
<button id="readBtn" class="primary" type="button">PDFを読み込んで集計</button>
<button id="exportBtn" type="button" disabled>CSVをダウンロード</button>
<button id="clearBtn" type="button">結果を消去</button>
</div>
<p id="status" class="status" role="status" aria-live="polite"></p>
<p class="note">
このページはファイルを外部へ送信せず、ブラウザ内で処理します。PDFから文字を取り出せない場合は読み取りに失敗します。
その場合は、文字を選択・コピーできるPDFか確認してください。
</p>
</section>
<section class="panel">
<p id="summary" class="summary">集計結果はありません。</p>
<div class="table-wrap">
<table>
<thead>
<tr>
<th>年月</th>
<th>作業者名</th>
<th>細分</th>
<th class="num">合計時間</th>
<th class="num">割合の合計</th>
</tr>
</thead>
<tbody id="results">
<tr><td class="empty" colspan="5">PDFを選択して読み込んでください。</td></tr>
</tbody>
</table>
</div>
<p class="note small">
PDFのレイアウトや文字抽出順によって、細分名と時間・割合の対応を誤認することがあります。
集計結果は原本と照合してください。
</p>
</section>
</main>
<script>
"use strict";
/*
* PDF読み取りについて:
* ブラウザ標準機能だけではPDFのテキストを安定して抽出できないため、
* この単一ファイル版ではPDF内の可読なテキスト断片を検索する簡易方式を実装しています。
* 圧縮されたPDFストリームや複雑なフォント文字コードのPDFは読み取れません。
* その場合に誤った集計を出さないよう、文字列が取り出せない場合はエラーを表示します。
*/
const fileInput = document.getElementById("pdfFiles");
const readBtn = document.getElementById("readBtn");
const exportBtn = document.getElementById("exportBtn");
const clearBtn = document.getElementById("clearBtn");
const statusEl = document.getElementById("status");
const resultsBody = document.getElementById("results");
const summaryEl = document.getElementById("summary");
let currentRows = [];
function setStatus(message, kind = "") {
statusEl.textContent = message;
statusEl.className = "status" + (kind ? " " + kind : "");
}
function normalizeText(text) {
return text
.replace(/\u0000/g, "")
.replace(/\r\n?/g, "\n")
.replace(/[0-9]/g, ch => String.fromCharCode(ch.charCodeAt(0) - 0xFEE0))
.replace(/[.。]/g, ".")
.replace(/[,、]/g, ",")
.replace(/\u3000/g, " ");
}
function decodePdfLiteral(s) {
let out = "";
for (let i = 0; i < s.length; i++) {
const c = s[i];
if (c === "\\" && i + 1 < s.length) {
const n = s[++i];
if (n === "n") out += "\n";
else if (n === "r") out += "\r";
else if (n === "t") out += "\t";
else if (n === "b") out += "\b";
else if (n === "f") out += "\f";
else if (n === "(" || n === ")" || n === "\\") out += n;
else if (/[0-7]/.test(n)) {
let oct = n;
for (let k = 0; k < 2 && i + 1 < s.length && /[0-7]/.test(s[i + 1]); k++) {
oct += s[++i];
}
out += String.fromCharCode(parseInt(oct, 8));
} else if (n === "\n") {
// PDFの行継続
} else {
out += n;
}
} else {
out += c;
}
}
return out;
}
function extractReadablePdfStrings(arrayBuffer) {
const bytes = new Uint8Array(arrayBuffer);
let binary = "";
const chunkSize = 0x8000;
for (let i = 0; i < bytes.length; i += chunkSize) {
binary += String.fromCharCode(...bytes.subarray(i, Math.min(i + chunkSize, bytes.length)));
}
const pieces = [];
// PDFのリテラル文字列を抽出する簡易処理
const literalPattern = /\(((?:\\.|[^\\)]){1,2000})\)\s*(?:Tj|'|"|TJ)/gs;
let match;
while ((match = literalPattern.exec(binary)) !== null) {
const decoded = decodePdfLiteral(match[1]);
if (decoded.trim()) pieces.push(decoded);
}
// ToUnicode等で使われる16進文字列の一部を抽出
const hexPattern = /<([0-9A-Fa-f]{4,4000})>\s*Tj/g;
while ((match = hexPattern.exec(binary)) !== null) {
const hex = match[1];
if (hex.length % 4 === 0) {
let s = "";
for (let i = 0; i < hex.length; i += 4) {
const code = parseInt(hex.slice(i, i + 4), 16);
s += String.fromCharCode(code);
}
if (s.trim()) pieces.push(s);
}
}
// PDFの中に可読なUTF-8/ASCIIテキストが直接含まれている場合の補助
if (pieces.length === 0) {
const decoded = new TextDecoder("utf-8", { fatal: false }).decode(bytes);
const visible = decoded.replace(/[^\x09\x0A\x0D\x20-\uFFFF]/g, " ");
if (/[0-9]{4}\s*年/.test(visible) || /小計/.test(visible)) pieces.push(visible);
}
return pieces.join("\n");
}
function parseMonth(text, filename) {
const patterns = [
/((?:19|20)\d{2})\s*年\s*(\d{1,2})\s*月\s*度/,
/((?:19|20)\d{2})[年/.-]\s*(\d{1,2})\s*月?/
];
for (const p of patterns) {
const m = text.match(p);
if (m) return `${m[1]}年${String(Number(m[2])).padStart(2, "0")}月`;
}
const fileMatch = filename.match(/((?:19|20)\d{2})[-_.年]?(\d{1,2})月?/);
if (fileMatch) return `${fileMatch[1]}年${String(Number(fileMatch[2])).padStart(2, "0")}月`;
return "年月不明";
}
const sectionNames = [
"技術相談 工", "販売促進費", "広告宣伝費", "アフターサービス費",
"教育訓練費", "事業管理費", "共通費"
];
const knownCodes = [
"3211 DS", "3212 検査", "3214 DI", "3215 DIB",
"3221 BC", "3228 ET", "3229 FT", "3310 開発課",
"3311 工機", "8200 総務", "8400 開発", "8500 仮勘定",
"2122 自動機", "3111 時計"
];
function cleanToken(s) {
return normalizeText(s).replace(/\s+/g, " ").trim();
}
function extractNames(text) {
const lines = normalizeText(text).split(/\n+/).map(cleanToken).filter(Boolean);
const names = [];
for (let i = 0; i < lines.length; i++) {
if (/小計|総合計|細分内訳|作業者名|^\d+\s*\/\s*\d+\s*ページ$/.test(lines[i])) continue;
if (/^\d{4}\s/.test(lines[i])) continue;
if (/^(?:技術相談|販売促進費|広告宣伝費|アフターサービス費|教育訓練費|事業管理費|共通費|MP-|SUWA-|TVL-|FT-|BC-|KO-|SE-|MITSU-|MP6)/i.test(lines[i])) continue;
if (/^[\d.,\s]+$/.test(lines[i])) continue;
if (/^(?:202\d年|202\d\/)/.test(lines[i])) continue;
if (/^(?:時間|割合|コード|細分名|テーマ)$/.test(lines[i])) continue;
if (/^[ぁ-んァ-ヶ一-龠々ー]{2,8}\s+[ぁ-んァ-ヶ一-龠々ー]{1,8}$/.test(lines[i]) ||
/^[ぁ-んァ-ヶ一-龠々ー]{2,8}$/.test(lines[i])) {
const candidate = lines[i].replace(/\s+/g, " ").trim();
if (!names.includes(candidate)) names.push(candidate);
}
}
return names;
}
function parseRecords(text, filename) {
const normalized = normalizeText(text);
const month = parseMonth(normalized, filename);
// 抽出文字列を行単位にし、明細名・数値が同一付近に現れる場合のみ採用する。
const lines = normalized.split(/\n+/).map(cleanToken).filter(Boolean);
const rows = [];
let currentWorker = "";
let pendingLabel = "";
let pendingTheme = "";
let skipRestOfWorker = false;
const namePattern = /^[ぁ-んァ-ヶ一-龠々ー]{2,8}\s+[ぁ-んァ-ヶ一-龠々ー]{1,8}$/;
const numberPattern = /^\d{1,4}(?:\.\d{1,2})?$/;
const codePattern = /^(?:MP-|SUWA-|TVL-|FT-|BC-|KO-|SE-|MITSU-|MP6|[A-Z]{2,})/i;
const categoryPattern = new RegExp("^(" + sectionNames.map(x => x.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|") + ")$");
// 抽出順の違いが大きいPDFに対して、作業者ごとの範囲と明細ラベルを追跡する。
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (/総合計/.test(line)) break;
if (/小計/.test(line)) {
pendingLabel = "";
pendingTheme = "";
skipRestOfWorker = true;
continue;
}
if (/^(?:202\d年|202\d\/)/.test(line) ||
/^(?:作業者名|細分内訳|コード|細分名|テーマ|時間|割合)$/.test(line) ||
/^\d+\s*\/\s*\d+\s*ページ$/.test(line)) {
continue;
}
if (namePattern.test(line) && !categoryPattern.test(line) && !codePattern.test(line)) {
currentWorker = line;
pendingLabel = "";
pendingTheme = "";
skipRestOfWorker = false;
continue;
}
if (skipRestOfWorker || !currentWorker) continue;
if (categoryPattern.test(line)) {
pendingLabel = line;
pendingTheme = "";
continue;
}
if (codePattern.test(line)) {
pendingTheme = line;
continue;
}
if (numberPattern.test(line) && pendingLabel) {
const time = Number(line);
// 割合が直後の独立数値として抽出される形式を優先し、見つからなければ未記入。
let ratio = null;
let j = i + 1;
while (j < lines.length && j <= i + 3) {
if (numberPattern.test(lines[j])) {
ratio = Number(lines[j]);
i = j;
break;
}
if (categoryPattern.test(lines[j]) || codePattern.test(lines[j]) ||
namePattern.test(lines[j]) || /小計|総合計/.test(lines[j])) break;
j++;
}
rows.push({
month,
worker: currentWorker,
category: pendingLabel,
theme: pendingTheme,
time,
ratio
});
pendingLabel = "";
pendingTheme = "";
}
}
// 行抽出形式で必要な情報が見つからない場合は、推測で結果を生成しない。
return rows;
}
function aggregate(records) {
const map = new Map();
for (const r of records) {
const key = [r.month, r.worker, r.category].join("\u0001");
if (!map.has(key)) {
map.set(key, {
month: r.month,
worker: r.worker,
category: r.category,
time: 0,
ratio: 0,
ratioKnown: true
});
}
const item = map.get(key);
item.time += r.time;
if (r.ratio === null || !Number.isFinite(r.ratio)) item.ratioKnown = false;
else item.ratio += r.ratio;
}
return [...map.values()].sort((a, b) =>
a.month.localeCompare(b.month, "ja") ||
a.worker.localeCompare(b.worker, "ja") ||
a.category.localeCompare(b.category, "ja")
);
}
function formatNumber(value) {
return Number(value.toFixed(2)).toString();
}
function render(rows) {
currentRows = rows;
resultsBody.replaceChildren();
if (!rows.length) {
const tr = document.createElement("tr");
const td = document.createElement("td");
td.colSpan = 5;
td.className = "empty";
td.textContent = "集計できる明細がありません。PDFの文字抽出に対応しているか確認してください。";
tr.appendChild(td);
resultsBody.appendChild(tr);
summaryEl.textContent = "集計結果はありません。";
exportBtn.disabled = true;
return;
}
for (const row of rows) {
const tr = document.createElement("tr");
const values = [
row.month,
row.worker,
row.category,
formatNumber(row.time),
row.ratioKnown ? formatNumber(row.ratio) : "確認が必要"
];
values.forEach((value, index) => {
const td = document.createElement("td");
td.textContent = value;
if (index >= 3) td.className = "num";
tr.appendChild(td);
});
resultsBody.appendChild(tr);
}
const months = new Set(rows.map(r => r.month));
summaryEl.textContent = `${rows.length}件の集計行(${months.size}か月)`;
exportBtn.disabled = false;
}
readBtn.addEventListener("click", async () => {
const files = [...fileInput.files];
if (!files.length) {
setStatus("PDFファイルを選択してください。", "error");
return;
}
readBtn.disabled = true;
setStatus("PDFをブラウザ内で読み込んでいます…");
const allRecords = [];
const warnings = [];
try {
for (const file of files) {
if (!/\.pdf$/i.test(file.name) && file.type !== "application/pdf") {
warnings.push(`${file.name}: PDFではないためスキップ`);
continue;
}
const buffer = await file.arrayBuffer();
const text = extractReadablePdfStrings(buffer);
if (!text.trim()) {
warnings.push(`${file.name}: 読み取れる文字列が見つかりません`);
continue;
}
const records = parseRecords(text, file.name);
if (!records.length) {
warnings.push(`${file.name}: 明細を認識できませんでした`);
} else {
allRecords.push(...records);
}
}
const aggregated = aggregate(allRecords);
render(aggregated);
if (warnings.length) {
setStatus(
`読み込み完了。${warnings.join(" / ")}。結果を原本と照合してください。`,
aggregated.length ? "" : "error"
);
} else if (aggregated.length) {
setStatus("読み込みと集計が完了しました。割合が「確認が必要」の行を含め、原本と照合してください。", "success");
} else {
setStatus("明細を読み取れませんでした。PDFの形式を確認してください。", "error");
}
} catch (error) {
render([]);
setStatus("PDFの読み込み中に問題が発生しました。別のPDF形式である可能性があります。", "error");
} finally {
readBtn.disabled = false;
}
});
function csvEscape(value) {
return '"' + String(value).replace(/"/g, '""') + '"';
}
exportBtn.addEventListener("click", () => {
if (!currentRows.length) return;
const header = ["年月", "作業者名", "細分", "合計時間", "割合の合計"];
const lines = [header.map(csvEscape).join(",")];
for (const row of currentRows) {
lines.push([
row.month,
row.worker,
row.category,
formatNumber(row.time),
row.ratioKnown ? formatNumber(row.ratio) : "確認が必要"
].map(csvEscape).join(","));
}
const blob = new Blob(["\uFEFF" + lines.join("\r\n")], { type: "text/csv;charset=utf-8" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = "月別細分内訳集計.csv";
document.body.appendChild(a);
a.click();
a.remove();
URL.revokeObjectURL(url);
});
clearBtn.addEventListener("click", () => {
fileInput.value = "";
currentRows = [];
render([]);
resultsBody.firstElementChild?.querySelector("td")?.replaceChildren(
document.createTextNode("PDFを選択して読み込んでください。")
);
setStatus("結果を消去しました。");
});
</script>
</body>
</html>