// Import wizard: upload old sheet -> confirm structure -> answer questions about unclear records -> save. import { $, $$, esc, api, toast, guard, table } from "./ui.js"; import { show } from "./gate.js"; import * as S from "./store.js"; import * as I from "./importer.js"; const FIELDS = [["date", "Date"], ["workType", "Type (Ticket/POC)"], ["product", "Product (WAF/WAS)"], ["ticketId", "Ticket ID"], ["pocId", "POC ID"], ["itemId", "Other ID column"], ["title", "Title / issue"], ["description", "Description / notes"]]; const STEPS = ["1 · Upload", "2 · Check structure", "3 · Review", "4 · Done"]; const steps = n => `
${STEPS.map((s, i) => `${s}`).join("")}
`; const colName = (an, i) => (an.headers[i] || "").trim() || "Column " + (i + 1); export function openWizard({ onDone, onCancel, ai = false }) { const W = { sheets: [], an: [], use: [], recs: [], useAI: ai, ai, showGuessed: false, page: 0, flagged: [] }; upload(); // ------------------------------------------------------------ step 1 function upload() { const c = show(`

Import past records

${steps(0)}

Choose your old sheet(s): .xlsx or .csv. It can be a neat table, loose notes, or a mix. The file is read in your browser.

`, true); $("#cancel", c).onclick = () => onCancel(); $("#file", c).onchange = guard(async e => { W.sheets = []; for (const f of e.target.files) for (const sh of await I.readSheets(f)) W.sheets.push(sh); W.an = W.sheets.map(I.analyze); W.use = W.sheets.map(() => true); $("#found", c).innerHTML = W.sheets.length ? `

${W.sheets.length} sheet(s) found:

` + W.sheets.map((s, i) => ``).join("") : '
No data found in that file.
'; $("#next", c).disabled = !W.sheets.length; }); $("#found", c).onchange = e => { if (e.target.dataset.i) W.use[+e.target.dataset.i] = e.target.checked; }; $("#next", c).onclick = () => { if (!W.use.some(Boolean)) return toast("Select at least one sheet", true); structure(); }; } // ------------------------------------------------------------ step 2 function structure() { const blocks = W.sheets.map((sh, i) => W.use[i] ? block(sh, W.an[i], i) : "").join(""); const c = show(`

Check how I read your sheet

${steps(1)}

I guessed which column is which. Fix anything that's wrong – you'll be asked about unclear records in the next step.

${blocks}
`, true); $("#cancel", c).onclick = () => onCancel(); $("#back", c).onclick = upload; c.onchange = e => { const i = +e.target.dataset.i, an = W.an[i]; if (isNaN(i)) return; if (e.target.dataset.map) { const v = e.target.value; if (v === "") delete an.mapping[e.target.dataset.map]; else an.mapping[e.target.dataset.map] = +v; } if (e.target.dataset.order) { an.dateOrder = e.target.value; an.dateOrderCertain = true; } if (e.target.dataset.hdr) { const r = +e.target.value; if (r < 0) Object.assign(an, { structured: false, headerRow: -1, mapping: {}, headers: [] }); else { const row = W.sheets[i].rows[r] || [], m = I.mapHeaders(row); Object.assign(an, { structured: true, headerRow: r, mapping: m.mapping, headers: row.map(x => String(x ?? "").trim()) }); } structure(); } }; $("#go", c).onclick = guard(read); } function block(sh, an, i) { const hdrOpts = `` + sh.rows.slice(0, 15).map((r, k) => ``).join(""); let body = ``; if (an.structured) { const first = sh.rows.slice(an.headerRow + 1).find(r => (r || []).some(x => x !== null && String(x).trim() !== "")) || []; const opts = sel => `` + an.headers.map((h, k) => ``).join(""); body += `` + FIELDS.map(([f, label]) => ``).join("") + `
FieldColumn in your sheetExample
${label}${esc(String(an.mapping[f] !== undefined ? (first[an.mapping[f]] instanceof Date ? first[an.mapping[f]].toISOString().slice(0, 10) : first[an.mapping[f]] ?? "") : "").slice(0, 40))}
`; } else body += `
I'll read each non-empty row as a free-text note and pull out the date, ID, type and product. Lines that are only a date (like “5 Oct 2026”) set the date for the lines below.
`; body += ``; return `

${esc(sh.name)}

${body}
`; } // ------------------------------------------------------------ step 3 async function read() { const c = show(`

Reading your records…

${steps(2)}

Working…

`, true); W.recs = []; W.sheets.forEach((sh, i) => { if (W.use[i]) W.recs.push(...I.extract(sh, W.an[i], { today: new Date() })); }); if (!W.recs.length) { show(`

Nothing to import

I couldn't find any records with those settings.
`).querySelector("#b").onclick = structure; return; } const need = W.recs.filter(r => r.issues.length); if (W.ai && need.length) { const c2 = show(`

Some rows need a closer look

${steps(2)}

${need.length} of ${W.recs.length} records have missing details. The AI can try to understand them from their text.

If you use AI, the text of those ${need.length} rows only is sent through the company server to the AI service. Nothing else from your file leaves this device. Choose “No” to answer everything yourself.
`, true); await new Promise(res => { $("#y", c2).onclick = async () => { W.useAI = true; await runAI(need, c2); res(); }; $("#n", c2).onclick = () => { W.useAI = false; res(); }; }); } review(); } async function runAI(need, c) { c.innerHTML = `

Asking the AI…

0 / ${need.length}

`; for (let k = 0; k < need.length; k += 25) { const batch = need.slice(k, k + 25); try { const res = (await api("/api/ai/import-extract", "POST", { items: batch.map((r, j) => ({ i: k + j, text: r.src.text })) })).result || []; for (const a of res) { const r = need[a.i]; if (r) I.mergeAI(r, a); } } catch (e) { toast("AI couldn't read a batch – you'll be asked about those rows instead.", true); } $("#p", c).textContent = `${Math.min(k + 25, need.length)} / ${need.length}`; } } // ------------------------------------------------------------ step 3b: review & questions function review() { W.flagged = W.recs.map((r, i) => i).filter(i => W.recs[i].issues.length || (W.showGuessed && Object.keys(W.recs[i].assumed).length)); const ok = W.recs.filter(r => !r.issues.length).length, guessed = W.recs.filter(r => !r.issues.length && Object.keys(r.assumed).length).length; const pages = Math.max(1, Math.ceil(W.flagged.length / 20)); W.page = Math.min(W.page, pages - 1); const slice = W.flagged.slice(W.page * 20, W.page * 20 + 20); const c = show(`

Review your records

${steps(2)}

${W.recs.length} records read · ${ok} complete · ${W.recs.length - ok} need your answer · ${guessed} complete but with a guessed value

Highlighted fields are what I need. Dashed fields are my guesses. Records you skip are not imported.
${slice.map(i => card(i)).join("") || '

Nothing needs your attention 🎉

'}
${pages > 1 ? `
Page ${W.page + 1} of ${pages}
` : ""}
See all ${W.recs.length} records${table(["Sheet/row", "Date", "Type", "Product", "ID", "Title", "Status"], W.recs.map(r => [`${r.src.sheet} #${r.src.row}`, r.date || "—", r.workType || "—", r.product || "—", r.itemId || "—", r.title || "—", r.skip ? "skipped" : r.issues.length ? "needs: " + r.issues.join(", ") : Object.keys(r.assumed).length ? "guessed" : "ok"]), { scroll: true })}
`, true); $("#cancel", c).onclick = () => onCancel(); $("#back", c).onclick = structure; $("#sg", c).onchange = e => { W.showGuessed = e.target.checked; W.page = 0; review(); }; if ($("#prev", c)) { $("#prev", c).onclick = () => { W.page--; review(); }; $("#nextp", c).onclick = () => { W.page++; review(); }; } const upd = () => { const bad = W.recs.filter(r => r.issues.length && !r.skip).length; $("#needc", c).textContent = W.recs.filter(r => r.issues.length).length; $("#okc", c).textContent = W.recs.filter(r => !r.issues.length).length; $("#save", c).textContent = `Add ${W.recs.filter(r => !r.issues.length && !r.skip).length} records to my Excel file` + (bad ? ` (${bad} incomplete will be left out)` : ""); }; upd(); c.oninput = c.onchange = e => { const el = e.target.closest("[data-f]"); if (!el) return; const box = el.closest(".rev"), r = W.recs[+box.dataset.ri], f = el.dataset.f; if (f === "skip") r.skip = el.checked; else { r[f] = el.value.trim() || (f === "description" ? "" : null); delete r.assumed[f]; } I.finishIssues(r); paint(box, r); upd(); }; c.onclick = e => { const b = e.target.closest("[data-bulk]"); if (!b) return; const f = b.dataset.bulk, src = W.recs[+b.closest(".rev").dataset.ri]; if (!src[f]) return toast("Fill this field on this record first, then I can apply it to the others.", true); const targets = W.recs.filter(r => !r[f] && !r.skip); if (!targets.length || !confirm(`Set ${f === "workType" ? "Type" : f} = “${src[f]}” on ${targets.length} other record(s) that are missing it?`)) return; targets.forEach(r => { r[f] = src[f]; I.finishIssues(r); }); review(); }; $("#save", c).onclick = guard(save); } const L = { date: "Date", workType: "Type", product: "Product", itemId: "ID", title: "Title" }; function cls(r, f) { return !r[f] ? "miss" : r.assumed[f] ? "guess" : ""; } function card(i) { const r = W.recs[i], opt = (v, list) => `` + list.map(x => ``).join(""); return `
${esc(r.src.sheet)} · row ${r.src.row}: ${esc(r.src.text.slice(0, 300))}
${hint(r)}
${["workType", "product", "date"].map(f => ``).join("")}
`; } function hint(r) { const need = r.issues.map(f => L[f]), g = Object.entries(r.assumed).map(([f, why]) => `${L[f] || f} (${why})`); return (need.length ? `Please tell me: ${need.join(", ")}. ` : "") + (r.aiQuestions.length ? "AI asks: " + esc(r.aiQuestions.join(" ")) + " " : "") + (g.length ? `Guessed: ${esc(g.join("; "))}` : ""); } function paint(box, r) { box.classList.toggle("ok", !!r.skip || (!r.issues.length && !Object.keys(r.assumed).length)); const set = { date: 0, workType: 1, product: 2, itemId: 3 }; const labels = $$("label", box); for (const f of ["date", "workType", "product", "itemId", "title"]) { const l = box.querySelector(`[data-f="${f}"]`).closest("label"); l.classList.remove("miss", "guess"); const k = cls(r, f); if (k) l.classList.add(k); } box.querySelector("[data-q]").innerHTML = hint(r); } // ------------------------------------------------------------ step 4 async function save() { const bad = W.recs.filter(r => r.issues.length && !r.skip).length; if (bad && !confirm(`${bad} record(s) are still incomplete and will be left out. Continue?`)) return; let result; await S.commit(st => { const next = Math.max(0, ...st.entries.map(e => e.entryNo)) + 1; result = I.finalize(W.recs, st.entries, next); st.entries.push(...result.entries); st.entries.sort((a, b) => a.date < b.date ? -1 : a.date > b.date ? 1 : a.entryNo - b.entryNo); }); const months = [...new Set(result.entries.map(e => e.date.slice(0, 7)))].sort(); const c = show(`

Import finished ✔

${steps(3)}

${result.entries.length} records were added to your Excel file, across ${months.length} monthly sheet(s)${months.length ? ": " + months.join(", ") : ""}. The Summary and Weekly sheets now include them.

${result.skipped.length ? `
${result.skipped.length} record(s) not imported${table(["Source", "Text", "Reason"], result.skipped.map(s => [`${s.rec.src.sheet} #${s.rec.src.row}`, s.rec.src.text.slice(0, 80), s.why]), { scroll: true })}
` : ""}
`, true); $("#done", c).onclick = () => onDone(); } }