Untitled

Anonymous
Plain Text
10/07/2025 11:17 AM
6.3 KB
18
Indexable
Never
function main(workbook: ExcelScript.Workbook) {
  // --- Helpers ---
  function norm(s: string): string {
    if (!s) return "";
    return s.replace(/\r|\n/g, " ").replace(/\s+/g, " ").trim();
  }
  function baseNoDigits(s: string): string {
    return norm(s).replace(/\s*\d+\s*$/g, "");
  }
  function startsWithAny(s: string, prefixes: string[]): boolean {
    const t = (s || "").trim();
    for (let i = 0; i < prefixes.length; i++) {
      if (t.startsWith(prefixes[i])) return true;
    }
    return false;
  }
  function equalsIC(a: string, b: string): boolean {
    return (a || "").toLowerCase() === (b || "").toLowerCase();
  }

  // --- Get the source table ---
  const srcTable = workbook.getTable("Responses");
  if (!srcTable) {
    throw new Error("Table 'Responses' not found.");
  }
  const headers = srcTable.getHeaderRowRange().getTexts()[0];
  const data = srcTable.getRangeBetweenHeaderAndTotal().getTexts();
  const colCount = headers.length;

  // --- Canonical middle fields ---
  const perNames = [
    "Deficiency inquiry",
    "LCM Activity Type",
    "Related CTD section",
    "Responsible Department",
    "Category",
    "Query classification",
    "Root Cause"
  ];

  // --- Detect repeating block ---
  const perPrefixes = [...perNames, "Do you want to add another point"];
  const perMask: boolean[] = [];
  for (let i = 0; i < headers.length; i++) {
    perMask.push(startsWithAny(headers[i], perPrefixes));
  }
  const firstPer = perMask.indexOf(true);
  const lastPer = perMask.lastIndexOf(true);
  if (firstPer < 0 || lastPer < 0) {
    throw new Error("Could not detect the Sections 2–24 block.");
  }

  // --- Section 1 and Section 25 columns ---
  const s1Idxs: number[] = [];
  for (let i = 0; i < firstPer; i++) s1Idxs.push(i);
  const s25Idxs: number[] = [];
  for (let c = lastPer + 1; c < colCount; c++) s25Idxs.push(c);

  // --- Map per-section columns (sequential, anchored on "Deficiency inquiry") ---
  const perFields: { name: string; idx: number; col: number }[] = [];
  let currentIdx = 0;
  let haveStarted = false;

  for (let c = firstPer; c <= lastPer; c++) {
    const raw = headers[c] || "";
    if (raw.startsWith("Do you want to add another point")) continue;

    let base = baseNoDigits(raw);
    if (/^deficiency inquirie(s)?$/i.test(base)) base = "Deficiency inquiry";

    // Keep only the fields we care about
    let keep = false;
    for (let k = 0; k < perNames.length; k++) {
      if (equalsIC(perNames[k], base)) { keep = true; break; }
    }
    if (!keep) continue;

    if (equalsIC(base, "Deficiency inquiry")) {
      // Start/advance a section when we hit a "Deficiency inquiry"
      const m = raw.match(/\d+\s*$/);
      if (m) {
        currentIdx = parseInt(m[0], 10);
      } else {
        currentIdx = currentIdx + 1; // no suffix? increment
      }
      haveStarted = true;
    } else {
      // For sibling fields, skip until we've seen the first Deficiency inquiry
      if (!haveStarted) continue;
    }

    perFields.push({ name: base, idx: currentIdx, col: c });
  }

  // --- Group perFields by section index ---
  const byIdx: { [key: string]: { name: string; idx: number; col: number }[] } = {};
  for (let i = 0; i < perFields.length; i++) {
    const f = perFields[i];
    const key = String(f.idx);
    if (!byIdx[key]) byIdx[key] = [];
    byIdx[key].push(f);
  }

  // --- Section 25 display names ---
  const s25Display: { col: number; name: string }[] = [];
  for (let i = 0; i < s25Idxs.length; i++) {
    const c = s25Idxs[i];
    const base = baseNoDigits(headers[c] || "");
    const fixed = /^deficiency inquirie(s)?$/i.test(base) ? "Deficiency inquiry" : base;
    let collide = false;
    for (let k = 0; k < perNames.length; k++) {
      if (equalsIC(perNames[k], fixed)) { collide = true; break; }
    }
    s25Display.push({ col: c, name: collide ? fixed + " (S25)" : (headers[c] || "") });
  }

  // --- Build header ---
  const outHeader: string[] = [];
  for (let i = 0; i < s1Idxs.length; i++) outHeader.push(headers[s1Idxs[i]]);
  for (let i = 0; i < perNames.length; i++) outHeader.push(perNames[i]);
  for (let i = 0; i < s25Display.length; i++) outHeader.push(s25Display[i].name);

  // --- Build rows ---
  const outRows: string[][] = [];
  const sortedKeys = Object.keys(byIdx).map(k => parseInt(k, 10)).sort((a, b) => a - b);

  for (let r = 0; r < data.length; r++) {
    const srcRow = data[r];

    for (let kk = 0; kk < sortedKeys.length; kk++) {
      const secIdx = sortedKeys[kk];
      const fields = byIdx[String(secIdx)];
      if (!fields || fields.length === 0) continue;

      const sectionValues: { [key: string]: string } = {};
      let anyFilled = false;

      for (let i = 0; i < fields.length; i++) {
        const field = fields[i];
        const val = norm(srcRow[field.col]);
        sectionValues[field.name] = val;
        if (val !== "") anyFilled = true;
      }

      if (!anyFilled) continue;

      const out: string[] = [];

      // S1 columns
      for (let i = 0; i < s1Idxs.length; i++) {
        out.push(srcRow[s1Idxs[i]]);
      }

      // Per-section canonical columns (in fixed order)
      for (let i = 0; i < perNames.length; i++) {
        const name = perNames[i];
        const val = sectionValues[name] || "";
        out.push(val);
      }

      // S25 columns
      for (let i = 0; i < s25Display.length; i++) {
        out.push(srcRow[s25Display[i].col]);
      }

      outRows.push(out);
    }
  }

  // --- Write to / create 'Entries' sheet ---
  let ws = workbook.getWorksheet("Entries");
  if (!ws) ws = workbook.addWorksheet("Entries");

  const used = ws.getUsedRange();
  if (used) used.clear(ExcelScript.ClearApplyTo.all);

  const rows = outRows.length + 1;
  const cols = outHeader.length;
  const rng = ws.getRangeByIndexes(0, 0, Math.max(rows, 1), Math.max(cols, 1));

  const values: string[][] = [outHeader, ...outRows];
  rng.getCell(0, 0).getResizedRange(values.length - 1, cols - 1).setValues(values);

  const tables = ws.getTables();
  for (let i = 0; i < tables.length; i++) {
    if (tables[i].getName() === "Entries") {
      tables[i].delete();
      break;
    }
  }
  ws.addTable(rng.getAddress(), true).setName("Entries");
}
Editor is loading...
Leave a Comment