Need help with vba

Lakshmi Polisetti 20 Reputation points
2025-12-17T20:52:00.9+00:00
// ===================================================
// QUEUE B – Fill AR details (FILL-ONLY, NO SUBMIT)
// Patch v2: Set via Angular scope.field.value (strongest)
// Exposes: window.fillARQueueBFromPrompt()
// ===================================================
(function () {
  const SLEEP = (ms) => new Promise((r) => setTimeout(r, ms));
  const log = (...a) => console.log("Queue B:", ...a);
  function normalize(s) {
    return String(s || "").toLowerCase().replace(/[\s\-]+/g, "");
  }
  function getAngularScope(el) {
    try {
      if (!window.angular || !el) return null;
      const sc = window.angular.element(el).scope?.();
      return sc || null;
    } catch {
      return null;
    }
  }
  function scrollFocus(el) {
    if (!el) return;
    try { el.scrollIntoView({ block: "center" }); } catch {}
    try { el.focus(); } catch {}
  }
  function domSetInput(el, value) {
    if (!el) return false;
    scrollFocus(el);
    el.value = value ?? "";
    try { el.dispatchEvent(new InputEvent("input", { bubbles: true })); } catch {}
    try { el.dispatchEvent(new Event("input", { bubbles: true })); } catch {}
    try { el.dispatchEvent(new Event("change", { bubbles: true })); } catch {}
    try { el.dispatchEvent(new Event("blur", { bubbles: true })); } catch {}
    return true;
  }
  function domSelectByText(el, wantedText) {
    if (!el) return false;
    scrollFocus(el);
    const tgt = normalize(wantedText);
    if (!tgt) return false;
    let opt = null;
    for (const o of el.options) {
      if (normalize(o.text) === tgt) { opt = o; break; }
    }
    if (!opt) {
      for (const o of el.options) {
        if (normalize(o.text).includes(tgt)) { opt = o; break; }
      }
    }
    if (!opt) return false;
    el.value = opt.value;
    try { el.dispatchEvent(new Event("change", { bubbles: true })); } catch {}
    try { el.dispatchEvent(new Event("blur", { bubbles: true })); } catch {}
    return true;
  }
  // ✅ Strong setters: scope.field.value
  function setFieldValueById(id, value) {
    const el = document.getElementById(id);
    if (!el) return false;
    scrollFocus(el);
    const sc = getAngularScope(el);
    if (sc && sc.field && Object.prototype.hasOwnProperty.call(sc.field, "value")) {
      try {
        sc.$applyAsync(() => {
          sc.field.value = value ?? "";
        });
      } catch {}
    }
    // DOM fallback
    domSetInput(el, value);
    return true;
  }
  function selectFieldOptionById(id, wantedText) {
    const el = document.getElementById(id);
    if (!el) return false;
    scrollFocus(el);
    const sc = getAngularScope(el);
    const tgt = normalize(wantedText);
    let setOk = false;
    // If this select is using ng-options="option.name for option in field.options"
    // then field.value is the option OBJECT, not a primitive.
    if (sc && sc.field && Array.isArray(sc.field.options) && Object.prototype.hasOwnProperty.call(sc.field, "value")) {
      let match = sc.field.options.find(o => normalize(o?.name) === tgt);
      if (!match) match = sc.field.options.find(o => normalize(o?.name).includes(tgt));
      if (match) {
        try {
          sc.$applyAsync(() => {
            sc.field.value = match;     // ✅ set object
          });
          setOk = true;
        } catch {}
      }
    }
    // DOM fallback (still helps UI paint)
    const domOk = domSelectByText(el, wantedText);
    return setOk || domOk;
  }
  async function retry(fn, tries = 12, delay = 250) {
    for (let t = 1; t <= tries; t++) {
      const ok = fn();
      if (ok) return true;
      await SLEEP(delay);
    }
    return false;
  }
  // ---------- Parse Excel ----------
  function parseRaw(raw) {
    return raw
      .trim()
      .split(/\r?\n/)
      .map((l) => {
        const c = l.split("\t").map((x) => x.trim());
        if (c.length < 12) return null;
        return {
          action: c[0],
          firstName: c[1],
          middleName: c[2],
          lastName: c[3],
          suffix: c[4],
          jobTitle: c[5],
          country: c[6],
          countryOther: c[7],
          phoneType: c[8],
          phoneNumber: c[9],
          email: c[10],
          role: c[11],
        };
      })
      .filter(Boolean);
  }
  // Verify helper (reads from scope.field.value)
  function readFieldValueById(id) {
    const el = document.getElementById(id);
    if (!el) return "";
    const sc = getAngularScope(el);
    if (sc && sc.field && Object.prototype.hasOwnProperty.call(sc.field, "value")) {
      const v = sc.field.value;
      // dropdown may be object
      if (v && typeof v === "object" && "name" in v) return String(v.name || "");
      return String(v ?? "");
    }
    return String(el.value ?? "");
  }
  async function runQueueBFromPrompt() {
    const raw = prompt(
      "QUEUE B\n\nPaste Excel rows (NO HEADER):\nAction | First | Middle | Last | Suffix | JobTitle | Country | CountryOther | PhoneType | Phone | Email | Role",
      window._queueBLastRaw || ""
    );
    if (!raw) return;
    window._queueBLastRaw = raw;
    const reps = parseRaw(raw);
    if (!reps.length) {
      alert("No valid rows");
      return;
    }
    log("Filling", reps.length, "person(s)");
    for (let i = 0; i < reps.length; i++) {
      const rep = reps[i];
      const idx = i + 1;
      log("Filling Person", idx, rep);
      // Action radio
      if (normalize(rep.action) === "delete") {
        document.getElementById(`activiti-action${idx}B_1`)?.click();
      } else {
        document.getElementById(`activiti-action${idx}B_0`)?.click();
      }
      // Names
      setFieldValueById(`activiti-firstname${idx}B`, rep.firstName);
      setFieldValueById(`activiti-middlename${idx}B`, rep.middleName);
      setFieldValueById(`activiti-lastname${idx}B`, rep.lastName);
      // Job title (problem field)
      await retry(() => setFieldValueById(`activiti-jobtitle${idx}B`, rep.jobTitle), 14, 250);
      // Email
      setFieldValueById(`activiti-email${idx}B`, rep.email);
      // Suffix / Role
      selectFieldOptionById(`activiti-suffix${idx}B`, rep.suffix);
      selectFieldOptionById(`activiti-role${idx}B`, rep.role);
      // Country
      selectFieldOptionById(`activiti-country${idx}B`, rep.country);
      if (normalize(rep.country) === "other") {
        setFieldValueById(`activiti-countryother${idx}B`, rep.countryOther);
      }
      // Phone type (problem field)
      await retry(() => selectFieldOptionById(`activiti-phonetype${idx}B`, rep.phoneType), 14, 250);
      // Phone number
      setFieldValueById(`activiti-phonenumber${idx}B`, rep.phoneNumber);
      // ✅ Post-verify (extra for your case)
      await SLEEP(200);
      const jt = readFieldValueById(`activiti-jobtitle${idx}B`);
      if (normalize(jt) !== normalize(rep.jobTitle)) {
        log(`Person ${idx}: JobTitle verify failed -> retrying hard`, { want: rep.jobTitle, got: jt });
        await retry(() => setFieldValueById(`activiti-jobtitle${idx}B`, rep.jobTitle), 18, 250);
      }
      const pt = readFieldValueById(`activiti-phonetype${idx}B`);
      if (normalize(pt) !== normalize(rep.phoneType)) {
        log(`Person ${idx}: PhoneType verify failed -> retrying hard`, { want: rep.phoneType, got: pt });
        await retry(() => selectFieldOptionById(`activiti-phonetype${idx}B`, rep.phoneType), 18, 250);
      }
      await SLEEP(120);
    }
    log("DONE — Review & submit manually.");
    alert("Queue B fill complete. Please review fields (no submit clicked).");
  }
  // Expose globally for bookmarklet
  window.fillARQueueBFromPrompt = runQueueBFromPrompt;
  // Auto-run when snippet executed
  runQueueBFromPrompt();
})();
Microsoft 365 and Office | Word | For home | Android
0 comments No comments
{count} votes

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.