ツール管理へ戻る

v1 → v2 の差分

--- v1
+++ v2
@@ -1,553 +1,762 @@
-<!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;
-      --ink: #1f2937;
-      --muted: #5b6573;
-      --line: #cbd2da;
-      --panel: #f4f6f8;
-      --accent: #145da0;
-      --accent-hover: #0e477b;
-      --danger: #a32626;
-      --success: #176b3a;
-    }
-
-    * { box-sizing: border-box; }
-
-    body {
-      margin: 0;
-      background: #eef1f4;
-      color: var(--ink);
-      font-family: system-ui, -apple-system, "Segoe UI", sans-serif;
-      line-height: 1.55;
-    }
-
-    main {
-      width: min(100% - 32px, 980px);
-      margin: 28px auto;
-      padding: 24px;
-      background: #fff;
-      border: 1px solid var(--line);
-      border-radius: 10px;
-      box-shadow: 0 3px 14px rgba(20, 35, 50, .07);
-    }
-
-    h1 {
-      margin: 0 0 8px;
-      font-size: 1.65rem;
-    }
-
-    h2 {
-      margin: 0 0 12px;
-      font-size: 1.15rem;
-    }
-
-    p { margin: 8px 0; }
-
-    .intro, .help, .status {
-      color: var(--muted);
-      font-size: .94rem;
-    }
-
-    fieldset {
-      margin: 18px 0;
-      padding: 16px;
-      border: 1px solid var(--line);
-      border-radius: 8px;
-    }
-
-    legend {
-      padding: 0 6px;
-      font-weight: 700;
-    }
-
-    .grid {
-      display: grid;
-      grid-template-columns: repeat(2, minmax(0, 1fr));
-      gap: 12px 18px;
-    }
-
-    .field label.title {
-      display: block;
-      margin-bottom: 5px;
-      font-weight: 650;
-    }
-
-    input[type="date"],
-    input[type="text"],
-    input[type="file"],
-    select {
-      max-width: 100%;
-      padding: 9px 10px;
-      border: 1px solid #9ba6b2;
-      border-radius: 5px;
-      background: #fff;
-      color: var(--ink);
-      font: inherit;
-    }
-
-    input[type="text"] { width: 100%; }
-    input[type="date"] { width: 100%; }
-
-    .checks {
-      display: flex;
-      flex-wrap: wrap;
-      gap: 8px 18px;
-      margin-top: 5px;
-    }
-
-    .checks label, .radio-group label {
-      display: inline-flex;
-      align-items: center;
-      gap: 7px;
-    }
-
-    .radio-group {
-      display: flex;
-      flex-wrap: wrap;
-      gap: 10px 18px;
-      margin: 8px 0;
-    }
-
-    .scope-grid {
-      display: grid;
-      grid-template-columns: repeat(2, minmax(0, 1fr));
-      gap: 6px 16px;
-      margin-top: 8px;
-    }
-
-    .buttons {
-      display: flex;
-      flex-wrap: wrap;
-      gap: 10px;
-      margin: 16px 0;
-    }
-
-    button {
-      padding: 10px 16px;
-      border: 0;
-      border-radius: 5px;
-      background: var(--accent);
-      color: #fff;
-      font: inherit;
-      font-weight: 650;
-      cursor: pointer;
-    }
-
-    button:hover { background: var(--accent-hover); }
-
-    button.secondary {
-      border: 1px solid #8d98a4;
-      background: #fff;
-      color: var(--ink);
-    }
-
-    button.secondary:hover { background: #f0f2f4; }
-
-    button:disabled {
-      opacity: .55;
-      cursor: not-allowed;
-    }
-
-    #status {
-      min-height: 1.6em;
-      margin: 12px 0;
-      padding: 10px 12px;
-      border-radius: 5px;
-      background: var(--panel);
-    }
-
-    #status.error {
-      color: var(--danger);
-      background: #fff0f0;
-    }
-
-    #status.success {
-      color: var(--success);
-      background: #edf8f0;
-    }
-
-    #results {
-      margin-top: 18px;
-    }
-
-    .summary {
-      margin: 10px 0;
-      padding: 12px;
-      border: 1px solid var(--line);
-      border-radius: 6px;
-      background: var(--panel);
-    }
-
-    .result-card {
-      margin: 12px 0;
-      padding: 14px;
-      border: 1px solid var(--line);
-      border-radius: 7px;
-      overflow-wrap: anywhere;
-    }
-
-    .result-card h3 {
-      margin: 0 0 8px;
-      font-size: 1rem;
-    }
-
-    .result-meta {
-      margin: 0 0 10px;
-      color: var(--muted);
-      font-size: .9rem;
-    }
-
-    .match-field {
-      margin: 8px 0;
-      padding: 9px 10px;
-      border-left: 3px solid var(--accent);
-      background: #f6f8fa;
-      white-space: pre-wrap;
-      overflow-wrap: anywhere;
-    }
-
-    mark {
-      padding: 0 2px;
-      background: #fff1a8;
-    }
-
-    .no-results {
-      padding: 14px;
-      border: 1px dashed #aab3bd;
-      border-radius: 6px;
-      color: var(--muted);
-    }
-
-    .hidden { display: none !important; }
-
-    @media (max-width: 640px) {
-      main {
-        width: min(100% - 18px, 980px);
-        margin: 9px auto;
-        padding: 16px;
-      }
-
-      .grid, .scope-grid { grid-template-columns: 1fr; }
-    }
-  </style>
-</head>
-<body>
-  <main>
-    <h1>是正処置記録検索</h1>
-    <p class="intro">
-      Excelファイルを選択し、期間・部門・キーワードで検索します。
-      処理はこのブラウザ内で行い、選択したファイルや検索内容を外部へ送信・保存しません。
-    </p>
-
-    <form id="searchForm">
-      <fieldset>
-        <legend>検索対象ファイル</legend>
-        <div class="field">
-          <label class="title" for="files">是正処置記録のExcelファイル</label>
-          <input id="files" type="file" accept=".xlsx,.xlsm,.xls" multiple>
-          <p class="help">
-            複数ファイルを選択できます。ファイル名に部門名を含めてください。
-            Excelの読み取りはブラウザ標準機能のみでは行えないため、このページでは
-            .xlsx/.xlsm/.xls の内容を解析せず、ファイル名検索を行います。
-          </p>
-        </div>
-      </fieldset>
-
-      <fieldset>
-        <legend>対象期間・部門</legend>
-        <div class="grid">
-          <div class="field">
-            <label class="title" for="startDate">開始日</label>
-            <input id="startDate" type="date">
-          </div>
-          <div class="field">
-            <label class="title" for="endDate">終了日</label>
-            <input id="endDate" type="date">
-          </div>
-        </div>
-        <div class="field" style="margin-top: 12px">
-          <span class="title"><strong>対象部門</strong></span>
-          <div class="checks">
-            <label><input type="checkbox" name="department" value="NC加工部門" checked> NC加工部門</label>
-            <label><input type="checkbox" name="department" value="時計製造部門" checked> 時計製造部門</label>
-          </div>
-        </div>
-        <p class="help">
-          期間指定時はファイル名に含まれる YYYY-MM-DD、YYYY/MM/DD、YYYY年M月D日 形式の日付を使用します。
-          該当する日付がファイル名にない記録は、期間指定時の結果に含まれません。
-        </p>
-      </fieldset>
-
-      <fieldset>
-        <legend>キーワード検索</legend>
-        <div class="field">
-          <label class="title" for="keywords">検索語(複数語は空白区切り)</label>
-          <input id="keywords" type="text" placeholder="例:異音 軸受">
-        </div>
-
-        <div style="margin-top: 12px">
-          <strong>検索方式</strong>
-          <div class="radio-group">
-            <label><input type="radio" name="matchMode" value="AND" checked> AND(すべての語を含む)</label>
-            <label><input type="radio" name="matchMode" value="OR"> OR(いずれかの語を含む)</label>
-          </div>
-        </div>
-
-        <div style="margin-top: 12px">
-          <strong>検索範囲(ファイル名のみ)</strong>
-          <div class="scope-grid">
-            <label><input type="checkbox" name="scope" value="filename" checked> ファイル名</label>
-          </div>
-          <p class="help">
-            原因・対策・効果欄を含むExcel内部の検索および該当Excelの抽出は、
-            外部ライブラリやExcel読み取り機能を使わない条件では実行できません。
-          </p>
-        </div>
-      </fieldset>
-
-      <div class="buttons">
-        <button id="searchButton" type="submit">検索</button>
-        <button id="clearButton" class="secondary" type="button">条件をクリア</button>
-      </div>
-    </form>
-
-    <div id="status" class="status" role="status" aria-live="polite">
-      Excelファイルを選択して検索してください。
-    </div>
-
-    <section id="results" aria-live="polite">
-      <h2>検索結果</h2>
-      <p class="no-results">まだ検索していません。</p>
-    </section>
-  </main>
-
-  <script>
-    "use strict";
-
-    const form = document.getElementById("searchForm");
-    const filesInput = document.getElementById("files");
-    const statusBox = document.getElementById("status");
-    const resultsBox = document.getElementById("results");
-    const searchButton = document.getElementById("searchButton");
-    const clearButton = document.getElementById("clearButton");
-
-    function setStatus(message, type) {
-      statusBox.textContent = message;
-      statusBox.className = "status" + (type ? " " + type : "");
-    }
-
-    function escapeHtml(value) {
-      return String(value).replace(/[&<>"']/g, function (character) {
-        return {
-          "&": "&amp;",
-          "<": "&lt;",
-          ">": "&gt;",
-          '"': "&quot;",
-          "'": "&#39;"
-        }[character];
-      });
-    }
-
-    function getSelectedValues(name) {
-      return Array.from(document.querySelectorAll('input[name="' + name + '"]:checked'))
-        .map(function (input) { return input.value; });
-    }
-
-    function parseFilenameDate(filename) {
-      const patterns = [
-        /(\d{4})[-.\/](\d{1,2})[-.\/](\d{1,2})/,
-        /(\d{4})年(\d{1,2})月(\d{1,2})日/
-      ];
-
-      for (const pattern of patterns) {
-        const match = filename.match(pattern);
-        if (match) {
-          const year = Number(match[1]);
-          const month = Number(match[2]);
-          const day = Number(match[3]);
-          const date = new Date(year, month - 1, day);
-
-          if (
-            date.getFullYear() === year &&
-            date.getMonth() === month - 1 &&
-            date.getDate() === day
-          ) {
-            return year + "-" + String(month).padStart(2, "0") + "-" +
-              String(day).padStart(2, "0");
-          }
-        }
-      }
-
-      return null;
-    }
-
-    function matchesDateRange(filename, startDate, endDate) {
-      if (!startDate && !endDate) return true;
-
-      const fileDate = parseFilenameDate(filename);
-      if (!fileDate) return false;
-
-      if (startDate && fileDate < startDate) return false;
-      if (endDate && fileDate > endDate) return false;
-      return true;
-    }
-
-    function matchesKeywords(filename, keywords, mode) {
-      if (keywords.length === 0) return true;
-
-      const normalizedFilename = filename.toLocaleLowerCase("ja");
-      const checks = keywords.map(function (word) {
-        return normalizedFilename.includes(word.toLocaleLowerCase("ja"));
-      });
-
-      return mode === "OR"
-        ? checks.some(Boolean)
-        : checks.every(Boolean);
-    }
-
-    function extractDepartment(filename) {
-      const departments = ["NC加工部門", "時計製造部門"];
-      return departments.find(function (department) {
-        return filename.includes(department);
-      }) || "部門不明";
-    }
-
-    function highlightText(text, keywords) {
-      if (keywords.length === 0) return escapeHtml(text);
-
-      const ordered = keywords.slice().sort(function (a, b) {
-        return b.length - a.length;
-      });
-      const escapedKeywords = ordered.map(function (word) {
-        return word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
-      });
-      const pattern = new RegExp("(" + escapedKeywords.join("|") + ")", "giu");
-      const parts = String(text).split(pattern);
-
-      return parts.map(function (part) {
-        const matched = ordered.some(function (word) {
-          return part.toLocaleLowerCase("ja") === word.toLocaleLowerCase("ja");
-        });
-        return matched ? "<mark>" + escapeHtml(part) + "</mark>" : escapeHtml(part);
-      }).join("");
-    }
-
-    function renderResults(records, keywords) {
-      resultsBox.innerHTML = "<h2>検索結果</h2>";
-
-      if (records.length === 0) {
-        const empty = document.createElement("p");
-        empty.className = "no-results";
-        empty.textContent = "条件に一致するファイルはありません。";
-        resultsBox.appendChild(empty);
-        return;
-      }
-
-      const summary = document.createElement("div");
-      summary.className = "summary";
-      summary.textContent = "該当件数:" + records.length + " 件";
-      resultsBox.appendChild(summary);
-
-      records.forEach(function (record) {
-        const card = document.createElement("article");
-        card.className = "result-card";
-
-        const title = document.createElement("h3");
-        title.innerHTML = highlightText(record.name, keywords);
-        card.appendChild(title);
-
-        const meta = document.createElement("p");
-        meta.className = "result-meta";
-        meta.textContent =
-          "部門:" + record.department +
-          " / ファイル名中の日付:" + (record.date || "見つかりません");
-        card.appendChild(meta);
-
-        const note = document.createElement("p");
-        note.className = "help";
-        note.textContent =
-          "ファイル名に対する一致です。原因・対策・効果欄の内容は検索していません。";
-        card.appendChild(note);
-
-        resultsBox.appendChild(card);
-      });
-    }
-
-    form.addEventListener("submit", function (event) {
-      event.preventDefault();
-
-      const selectedFiles = Array.from(filesInput.files || []);
-      if (selectedFiles.length === 0) {
-        setStatus("検索するExcelファイルを選択してください。", "error");
-        resultsBox.innerHTML =
-          "<h2>検索結果</h2><p class=\"no-results\">対象ファイルが選択されていません。</p>";
-        return;
-      }
-
-      const startDate = document.getElementById("startDate").value;
-      const endDate = document.getElementById("endDate").value;
-
-      if (startDate && endDate && startDate > endDate) {
-        setStatus("開始日は終了日以前の日付を指定してください。", "error");
-        return;
-      }
-
-      const departments = getSelectedValues("department");
-      const keywords = document.getElementById("keywords").value
-        .trim()
-        .split(/\s+/)
-        .filter(Boolean);
-      const mode = document.querySelector('input[name="matchMode"]:checked').value;
-
-      if (departments.length === 0) {
-        setStatus("対象部門を1つ以上選択してください。", "error");
-        return;
-      }
-
-      const matchingRecords = selectedFiles
-        .filter(function (file) {
-          const department = extractDepartment(file.name);
-          return departments.includes(department);
-        })
-        .filter(function (file) {
-          return matchesDateRange(file.name, startDate, endDate);
-        })
-        .filter(function (file) {
-          return matchesKeywords(file.name, keywords, mode);
-        })
-        .map(function (file) {
-          return {
-            name: file.name,
-            department: extractDepartment(file.name),
-            date: parseFilenameDate(file.name)
-          };
-        });
-
-      renderResults(matchingRecords, keywords);
-
-      const dateNote = (startDate || endDate)
-        ? "期間はファイル名の日付で判定しました。"
-        : "期間指定なし。";
-      setStatus(
-        "検索完了:該当 " + matchingRecords.length + " 件。 " +
-        dateNote +
-        " このページではファイル名のみ検索し、Excel内部の原因・対策・効果欄は解析していません。",
-        "success"
-      );
-    });
-
-    clearButton.addEventListener("click", function () {
-      form.reset();
-      resultsBox.innerHTML =
-        "<h2>検索結果</h2><p class=\"no-results\">まだ検索していません。</p>";
-      setStatus("条件をクリアしました。選択ファイルも解除されています。", "");
-    });
-  </script>
-</body>
+<!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;
+      --ink: #1f2937;
+      --muted: #5b6573;
+      --line: #cbd2da;
+      --panel: #f4f6f8;
+      --accent: #145da0;
+      --accent-hover: #0e477b;
+      --danger: #a32626;
+      --success: #176b3a;
+    }
+
+    * { box-sizing: border-box; }
+
+    body {
+      margin: 0;
+      background: #eef1f4;
+      color: var(--ink);
+      font-family: system-ui, -apple-system, "Segoe UI", sans-serif;
+      line-height: 1.55;
+    }
+
+    main {
+      width: min(100% - 32px, 980px);
+      margin: 28px auto;
+      padding: 24px;
+      background: #fff;
+      border: 1px solid var(--line);
+      border-radius: 10px;
+      box-shadow: 0 3px 14px rgba(20, 35, 50, .07);
+    }
+
+    h1 {
+      margin: 0 0 8px;
+      font-size: 1.65rem;
+    }
+
+    h2 {
+      margin: 0 0 12px;
+      font-size: 1.15rem;
+    }
+
+    h3 {
+      margin: 0 0 8px;
+      font-size: 1rem;
+    }
+
+    p { margin: 8px 0; }
+
+    .intro, .help, .status {
+      color: var(--muted);
+      font-size: .94rem;
+    }
+
+    fieldset {
+      margin: 18px 0;
+      padding: 16px;
+      border: 1px solid var(--line);
+      border-radius: 8px;
+    }
+
+    legend {
+      padding: 0 6px;
+      font-weight: 700;
+    }
+
+    .grid {
+      display: grid;
+      grid-template-columns: repeat(2, minmax(0, 1fr));
+      gap: 12px 18px;
+    }
+
+    .field label.title {
+      display: block;
+      margin-bottom: 5px;
+      font-weight: 650;
+    }
+
+    input[type="date"],
+    input[type="text"],
+    input[type="file"],
+    select {
+      max-width: 100%;
+      padding: 9px 10px;
+      border: 1px solid #9ba6b2;
+      border-radius: 5px;
+      background: #fff;
+      color: var(--ink);
+      font: inherit;
+    }
+
+    input[type="text"] { width: 100%; }
+    input[type="date"] { width: 100%; }
+
+    .checks {
+      display: flex;
+      flex-wrap: wrap;
+      gap: 8px 18px;
+      margin-top: 5px;
+    }
+
+    .checks label, .radio-group label {
+      display: inline-flex;
+      align-items: center;
+      gap: 7px;
+    }
+
+    .radio-group {
+      display: flex;
+      flex-wrap: wrap;
+      gap: 10px 18px;
+      margin: 8px 0;
+    }
+
+    .scope-grid {
+      display: grid;
+      grid-template-columns: repeat(2, minmax(0, 1fr));
+      gap: 6px 16px;
+      margin-top: 8px;
+    }
+
+    .buttons {
+      display: flex;
+      flex-wrap: wrap;
+      gap: 10px;
+      margin: 16px 0;
+    }
+
+    button {
+      padding: 10px 16px;
+      border: 0;
+      border-radius: 5px;
+      background: var(--accent);
+      color: #fff;
+      font: inherit;
+      font-weight: 650;
+      cursor: pointer;
+    }
+
+    button:hover { background: var(--accent-hover); }
+
+    button.secondary {
+      border: 1px solid #8d98a4;
+      background: #fff;
+      color: var(--ink);
+    }
+
+    button.secondary:hover { background: #f0f2f4; }
+
+    #status {
+      min-height: 1.6em;
+      margin: 12px 0;
+      padding: 10px 12px;
+      border-radius: 5px;
+      background: var(--panel);
+    }
+
+    #status.error {
+      color: var(--danger);
+      background: #fff0f0;
+    }
+
+    #status.success {
+      color: var(--success);
+      background: #edf8f0;
+    }
+
+    #results { margin-top: 18px; }
+
+    .summary {
+      margin: 10px 0;
+      padding: 12px;
+      border: 1px solid var(--line);
+      border-radius: 6px;
+      background: var(--panel);
+    }
+
+    .result-card {
+      margin: 12px 0;
+      padding: 14px;
+      border: 1px solid var(--line);
+      border-radius: 7px;
+      overflow-wrap: anywhere;
+    }
+
+    .result-meta {
+      margin: 0 0 10px;
+      color: var(--muted);
+      font-size: .9rem;
+    }
+
+    .excerpt {
+      margin: 10px 0;
+      padding: 10px 12px;
+      border-left: 3px solid var(--accent);
+      background: #f6f8fa;
+      white-space: pre-wrap;
+      overflow-wrap: anywhere;
+    }
+
+    .excerpt-label {
+      display: block;
+      margin-bottom: 4px;
+      font-weight: 700;
+    }
+
+    mark {
+      padding: 0 2px;
+      background: #fff1a8;
+    }
+
+    .no-results {
+      padding: 14px;
+      border: 1px dashed #aab3bd;
+      border-radius: 6px;
+      color: var(--muted);
+    }
+
+    @media (max-width: 640px) {
+      main {
+        width: min(100% - 18px, 980px);
+        margin: 9px auto;
+        padding: 16px;
+      }
+
+      .grid, .scope-grid { grid-template-columns: 1fr; }
+    }
+  </style>
+</head>
+<body>
+  <main>
+    <h1>是正処置記録検索</h1>
+    <p class="intro">
+      選択したファイルをブラウザ内で検索します。ファイルや検索内容を外部へ送信・自動保存しません。
+      外部AIサービスへの接続も行いません。
+    </p>
+
+    <form id="searchForm">
+      <fieldset>
+        <legend>検索対象ファイル</legend>
+        <div class="field">
+          <label class="title" for="files">記録ファイル(複数選択可)</label>
+          <input id="files" type="file" accept=".csv,.txt,.xlsx,.xlsm,.xls" multiple>
+          <p class="help">
+            このページで内容を読み取れるのはCSV・TXTです。Excel形式(.xlsx/.xlsm/.xls)は
+            ブラウザ標準機能だけではセル内容を解析できないため、ファイル名のみ検索します。
+            Excel内部の「原因」「対策」欄も検索するには、オフライン対応のExcel解析機能が別途必要です。
+          </p>
+        </div>
+      </fieldset>
+
+      <fieldset>
+        <legend>対象期間・部門</legend>
+        <div class="grid">
+          <div class="field">
+            <label class="title" for="startDate">開始日</label>
+            <input id="startDate" type="date">
+          </div>
+          <div class="field">
+            <label class="title" for="endDate">終了日</label>
+            <input id="endDate" type="date">
+          </div>
+        </div>
+        <div class="field" style="margin-top: 12px">
+          <span class="title"><strong>対象部門</strong></span>
+          <div class="checks">
+            <label><input type="checkbox" name="department" value="NC加工部門" checked> NC加工部門</label>
+            <label><input type="checkbox" name="department" value="時計製造部門" checked> 時計製造部門</label>
+          </div>
+        </div>
+        <p class="help">
+          期間指定時はファイル名またはCSV・TXT内の日付から判定します。
+          対応する日付表記は YYYY-MM-DD、YYYY/MM/DD、YYYY年M月D日 です。
+        </p>
+      </fieldset>
+
+      <fieldset>
+        <legend>検索条件</legend>
+        <div class="field">
+          <label class="title" for="incident">検索したい不具合事象</label>
+          <input id="incident" type="text" placeholder="例:加工面に傷が発生">
+        </div>
+
+        <div class="field" style="margin-top: 12px">
+          <label class="title" for="keywords">追加キーワード(複数語は空白区切り)</label>
+          <input id="keywords" type="text" placeholder="例:異音 軸受">
+        </div>
+
+        <div style="margin-top: 12px">
+          <strong>複数キーワードの検索方式</strong>
+          <div class="radio-group">
+            <label><input type="radio" name="matchMode" value="AND" checked> AND(すべての語を含む)</label>
+            <label><input type="radio" name="matchMode" value="OR"> OR(いずれかの語を含む)</label>
+          </div>
+        </div>
+      </fieldset>
+
+      <div class="buttons">
+        <button type="submit">検索</button>
+        <button id="clearButton" class="secondary" type="button">条件をクリア</button>
+      </div>
+    </form>
+
+    <div id="status" class="status" role="status" aria-live="polite">
+      検索対象ファイルを選択してください。
+    </div>
+
+    <section id="results" aria-live="polite">
+      <h2>検索結果</h2>
+      <p class="no-results">まだ検索していません。</p>
+    </section>
+  </main>
+
+  <script>
+    "use strict";
+
+    const form = document.getElementById("searchForm");
+    const filesInput = document.getElementById("files");
+    const statusBox = document.getElementById("status");
+    const resultsBox = document.getElementById("results");
+    const clearButton = document.getElementById("clearButton");
+
+    function setStatus(message, type) {
+      statusBox.textContent = message;
+      statusBox.className = "status" + (type ? " " + type : "");
+    }
+
+    function escapeHtml(value) {
+      return String(value).replace(/[&<>"']/g, function (character) {
+        return {
+          "&": "&amp;",
+          "<": "&lt;",
+          ">": "&gt;",
+          '"': "&quot;",
+          "'": "&#39;"
+        }[character];
+      });
+    }
+
+    function selectedDepartments() {
+      return Array.from(document.querySelectorAll('input[name="department"]:checked'))
+        .map(function (input) { return input.value; });
+    }
+
+    function parseDate(value) {
+      const patterns = [
+        /(\d{4})[-.\/](\d{1,2})[-.\/](\d{1,2})/,
+        /(\d{4})年(\d{1,2})月(\d{1,2})日/
+      ];
+
+      for (const pattern of patterns) {
+        const match = String(value).match(pattern);
+        if (!match) continue;
+
+        const year = Number(match[1]);
+        const month = Number(match[2]);
+        const day = Number(match[3]);
+        const date = new Date(year, month - 1, day);
+
+        if (
+          date.getFullYear() === year &&
+          date.getMonth() === month - 1 &&
+          date.getDate() === day
+        ) {
+          return year + "-" + String(month).padStart(2, "0") + "-" +
+            String(day).padStart(2, "0");
+        }
+      }
+
+      return null;
+    }
+
+    function findDate(text) {
+      const matches = String(text).match(
+        /\d{4}[-.\/]\d{1,2}[-.\/]\d{1,2}|\d{4}年\d{1,2}月\d{1,2}日/g
+      ) || [];
+
+      for (const value of matches) {
+        const date = parseDate(value);
+        if (date) return date;
+      }
+      return null;
+    }
+
+    function getDepartment(filename) {
+      const departments = ["NC加工部門", "時計製造部門"];
+      return departments.find(function (name) {
+        return filename.includes(name);
+      }) || "部門不明";
+    }
+
+    function normalize(text) {
+      return String(text || "").toLocaleLowerCase("ja");
+    }
+
+    function wordMatch(text, keywords, mode) {
+      if (keywords.length === 0) return true;
+      const target = normalize(text);
+      const found = keywords.map(function (word) {
+        return target.includes(normalize(word));
+      });
+      return mode === "OR" ? found.some(Boolean) : found.every(Boolean);
+    }
+
+    function splitSentences(text) {
+      return String(text || "")
+        .replace(/\r/g, "\n")
+        .split(/[\n。!?!?;;]+/)
+        .map(function (part) { return part.trim(); })
+        .filter(Boolean);
+    }
+
+    function findHeaderColumn(headers, patterns) {
+      return headers.findIndex(function (header) {
+        return patterns.some(function (pattern) {
+          return pattern.test(String(header || "").trim());
+        });
+      });
+    }
+
+    function parseCsvLine(line) {
+      const cells = [];
+      let cell = "";
+      let quoted = false;
+
+      for (let i = 0; i < line.length; i++) {
+        const character = line[i];
+
+        if (character === '"') {
+          if (quoted && line[i + 1] === '"') {
+            cell += '"';
+            i++;
+          } else {
+            quoted = !quoted;
+          }
+        } else if (character === "," && !quoted) {
+          cells.push(cell);
+          cell = "";
+        } else {
+          cell += character;
+        }
+      }
+
+      cells.push(cell);
+      return cells;
+    }
+
+    function parseCsv(text) {
+      const lines = String(text).replace(/^\uFEFF/, "").split(/\r?\n/);
+      const nonEmptyLines = lines.filter(function (line) {
+        return line.trim() !== "";
+      });
+
+      if (nonEmptyLines.length === 0) {
+        return { headers: [], rows: [] };
+      }
+
+      const headers = parseCsvLine(nonEmptyLines[0]);
+      const rows = nonEmptyLines.slice(1).map(parseCsvLine);
+      return { headers: headers, rows: rows };
+    }
+
+    function getRecordFields(file, text) {
+      const extension = file.name.toLowerCase().split(".").pop();
+      const result = {
+        readable: false,
+        cause: "",
+        action: "",
+        allText: file.name,
+        date: findDate(file.name) || null
+      };
+
+      if (extension === "txt") {
+        result.readable = true;
+        result.allText = file.name + "\n" + text;
+        result.date = result.date || findDate(text);
+
+        const causeLines = [];
+        const actionLines = [];
+        let current = "";
+
+        text.split(/\r?\n/).forEach(function (line) {
+          const trimmed = line.trim();
+          if (/原因|発生要因|真因/.test(trimmed)) {
+            current = "cause";
+            causeLines.push(trimmed.replace(/^(不具合の)?原因[::\s]*/, ""));
+          } else if (/対策|処置|再発防止/.test(trimmed)) {
+            current = "action";
+            actionLines.push(trimmed.replace(/^(不具合に対する)?対策[::\s]*/, ""));
+          } else if (current === "cause" && trimmed) {
+            causeLines.push(trimmed);
+          } else if (current === "action" && trimmed) {
+            actionLines.push(trimmed);
+          }
+        });
+
+        result.cause = causeLines.join("\n");
+        result.action = actionLines.join("\n");
+        return result;
+      }
+
+      if (extension === "csv") {
+        result.readable = true;
+        const parsed = parseCsv(text);
+        const headers = parsed.headers;
+        const causeIndex = findHeaderColumn(headers, [/原因/, /発生要因/, /真因/]);
+        const actionIndex = findHeaderColumn(headers, [/対策/, /処置/, /再発防止/]);
+        const dateIndex = findHeaderColumn(headers, [/日付/, /発生日/, /処置日/, /記録日/]);
+
+        const causeValues = [];
+        const actionValues = [];
+        const allValues = [file.name];
+
+        parsed.rows.forEach(function (row) {
+          allValues.push(row.join(" "));
+          if (causeIndex >= 0 && row[causeIndex]) causeValues.push(row[causeIndex]);
+          if (actionIndex >= 0 && row[actionIndex]) actionValues.push(row[actionIndex]);
+          if (!result.date && dateIndex >= 0 && row[dateIndex]) {
+            result.date = findDate(row[dateIndex]);
+          }
+        });
+
+        result.cause = causeValues.join("\n");
+        result.action = actionValues.join("\n");
+        result.allText = allValues.join("\n");
+        return result;
+      }
+
+      return result;
+    }
+
+    function highlight(text, terms) {
+      const value = String(text || "");
+      if (!terms.length) return escapeHtml(value);
+
+      const sorted = terms.slice().sort(function (a, b) {
+        return b.length - a.length;
+      });
+      const escaped = sorted.map(function (term) {
+        return term.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+      });
+      const pattern = new RegExp("(" + escaped.join("|") + ")", "giu");
+
+      return value.split(pattern).map(function (part) {
+        const matched = sorted.some(function (term) {
+          return normalize(part) === normalize(term);
+        });
+        return matched ? "<mark>" + escapeHtml(part) + "</mark>" : escapeHtml(part);
+      }).join("");
+    }
+
+    function relevantExcerpts(text, terms) {
+      const sentences = splitSentences(text);
+      if (!sentences.length) return [];
+
+      if (!terms.length) return sentences.slice(0, 3);
+
+      return sentences.filter(function (sentence) {
+        return terms.some(function (term) {
+          return normalize(sentence).includes(normalize(term));
+        });
+      }).slice(0, 5);
+    }
+
+    function renderResults(records, terms) {
+      resultsBox.innerHTML = "<h2>検索結果</h2>";
+
+      const summary = document.createElement("div");
+      summary.className = "summary";
+      summary.textContent = "該当件数:" + records.length + " 件";
+      resultsBox.appendChild(summary);
+
+      if (!records.length) {
+        const empty = document.createElement("p");
+        empty.className = "no-results";
+        empty.textContent = "条件に一致する記録はありません。";
+        resultsBox.appendChild(empty);
+        return;
+      }
+
+      records.forEach(function (record) {
+        const card = document.createElement("article");
+        card.className = "result-card";
+
+        const title = document.createElement("h3");
+        title.innerHTML = highlight(record.name, terms);
+        card.appendChild(title);
+
+        const meta = document.createElement("p");
+        meta.className = "result-meta";
+        meta.textContent =
+          "部門:" + record.department +
+          " / 日付:" + (record.date || "見つかりません") +
+          " / 内容を読める形式:" + (record.readable ? "はい" : "いいえ");
+        card.appendChild(meta);
+
+        const causeBox = document.createElement("div");
+        causeBox.className = "excerpt";
+        const causeLabel = document.createElement("span");
+        causeLabel.className = "excerpt-label";
+        causeLabel.textContent = "不具合の原因";
+        causeBox.appendChild(causeLabel);
+
+        const causeExcerpts = relevantExcerpts(record.cause, terms);
+        if (causeExcerpts.length) {
+          causeBox.insertAdjacentHTML(
+            "beforeend",
+            causeExcerpts.map(function (item) {
+              return "<div>" + highlight(item, terms) + "</div>";
+            }).join("")
+          );
+        } else {
+          const noCause = document.createElement("span");
+          noCause.textContent = record.readable
+            ? "キーワードに一致する原因の文章は見つかりませんでした。"
+            : "ファイル内容を読み取れないため抽出できません。";
+          causeBox.appendChild(noCause);
+        }
+        card.appendChild(causeBox);
+
+        const actionBox = document.createElement("div");
+        actionBox.className = "excerpt";
+        const actionLabel = document.createElement("span");
+        actionLabel.className = "excerpt-label";
+        actionLabel.textContent = "不具合に対する対策";
+        actionBox.appendChild(actionLabel);
+
+        const actionExcerpts = relevantExcerpts(record.action, terms);
+        if (actionExcerpts.length) {
+          actionBox.insertAdjacentHTML(
+            "beforeend",
+            actionExcerpts.map(function (item) {
+              return "<div>" + highlight(item, terms) + "</div>";
+            }).join("")
+          );
+        } else {
+          const noAction = document.createElement("span");
+          noAction.textContent = record.readable
+            ? "キーワードに一致する対策の文章は見つかりませんでした。"
+            : "ファイル内容を読み取れないため抽出できません。";
+          actionBox.appendChild(noAction);
+        }
+        card.appendChild(actionBox);
+
+        const note = document.createElement("p");
+        note.className = "help";
+        note.textContent =
+          "表示内容はキーワードに一致した文章の抜粋です。AIによる分析・要約は行っていません。";
+        card.appendChild(note);
+
+        resultsBox.appendChild(card);
+      });
+    }
+
+    form.addEventListener("submit", async function (event) {
+      event.preventDefault();
+
+      const files = Array.from(filesInput.files || []);
+      if (!files.length) {
+        setStatus("検索対象のファイルを選択してください。", "error");
+        return;
+      }
+
+      const startDate = document.getElementById("startDate").value;
+      const endDate = document.getElementById("endDate").value;
+      if (startDate && endDate && startDate > endDate) {
+        setStatus("開始日は終了日以前の日付を指定してください。", "error");
+        return;
+      }
+
+      const departments = selectedDepartments();
+      if (!departments.length) {
+        setStatus("対象部門を1つ以上選択してください。", "error");
+        return;
+      }
+
+      const incident = document.getElementById("incident").value.trim();
+      const extraKeywords = document.getElementById("keywords").value
+        .trim().split(/\s+/).filter(Boolean);
+      const terms = [];
+      if (incident) terms.push(incident);
+      extraKeywords.forEach(function (word) {
+        if (!terms.some(function (existing) {
+          return normalize(existing) === normalize(word);
+        })) {
+          terms.push(word);
+        }
+      });
+
+      const mode = document.querySelector('input[name="matchMode"]:checked').value;
+      const records = [];
+
+      setStatus("選択したファイルをブラウザ内で確認しています。", "");
+      clearButton.disabled = true;
+
+      try {
+        for (const file of files) {
+          const department = getDepartment(file.name);
+          if (!departments.includes(department)) continue;
+
+          let text = "";
+          const extension = file.name.toLowerCase().split(".").pop();
+          if (extension === "csv" || extension === "txt") {
+            text = await file.text();
+          }
+
+          const record = getRecordFields(file, text);
+          const fileDate = record.date || findDate(file.name);
+
+          if ((startDate || endDate) && !fileDate) continue;
+          if (startDate && fileDate < startDate) continue;
+          if (endDate && fileDate > endDate) continue;
+
+          const searchableText = record.readable
+            ? record.allText + "\n" + record.cause + "\n" + record.action
+            : file.name;
+
+          if (!wordMatch(searchableText, terms, mode)) continue;
+
+          records.push({
+            name: file.name,
+            department: department,
+            date: fileDate,
+            readable: record.readable,
+            cause: record.cause,
+            action: record.action
+          });
+        }
+
+        renderResults(records, terms);
+        setStatus(
+          "検索完了:" + records.length +
+          " 件。CSV・TXTは原因・対策欄の文章をキーワードで抽出しました。" +
+          " Excel形式の内部内容およびAI分析は対象外です。",
+          "success"
+        );
+      } catch (error) {
+        setStatus(
+          "ファイルを読み取れませんでした。CSV/TXTの文字コードや内容を確認してください。",
+          "error"
+        );
+      } finally {
+        clearButton.disabled = false;
+      }
+    });
+
+    clearButton.addEventListener("click", function () {
+      form.reset();
+      resultsBox.innerHTML =
+        "<h2>検索結果</h2><p class=\"no-results\">まだ検索していません。</p>";
+      setStatus("検索条件をクリアしました。", "");
+    });
+  </script>
+</body>
 </html>