← back to Mfr Review Viewer
server.js
541 lines
/**
* MFR Review Viewer — port 9870
* Helps Steve assign reactivation decisions per vendor (and per product) before bulk action.
*
* Decisions persist to /tmp/mfr_review_decisions.json
* { "<vendor>": { decision: "all"|"wallpaper"|"fabric"|"trim"|"skip", notes: "..." },
* "_per_product": { "<gid>": { decision: "...", notes: "..." } } }
*/
const express = require('express');
const helmet = require('helmet');
const fs = require('fs');
const path = require('path');
const PORT = 9871;
const USER = 'admin';
const PASS = 'DWSecure2024!';
const DECISIONS_FILE = '/tmp/mfr_review_decisions.json';
const auditPath = '/tmp/mfr_audit_state.ndjson';
const eligiblePath = '/tmp/e_eligible.json';
const e3Path = '/tmp/e3_cause_state.ndjson';
const typeMapPath = '/tmp/archived_type_map.json';
function load() {
const audit = fs.readFileSync(auditPath, 'utf8').trim().split('\n').map(l => JSON.parse(l));
const e3 = fs.existsSync(e3Path) ? fs.readFileSync(e3Path, 'utf8').trim().split('\n').map(l => JSON.parse(l)) : [];
const e3Map = new Map(e3.map(r => [r.id, r.actor]));
const typeMap = fs.existsSync(typeMapPath) ? JSON.parse(fs.readFileSync(typeMapPath, 'utf8')) : {};
// Merge
const enriched = audit.map(r => ({
...r,
actor: e3Map.get(r.id) || 'unknown',
productType: typeMap[r.id]?.type || '',
tags: typeMap[r.id]?.tags || [],
title: '',
}));
// Backfill titles from eligible
if (fs.existsSync(eligiblePath)) {
const titleMap = new Map(JSON.parse(fs.readFileSync(eligiblePath, 'utf8')).map(p => [p.id, p.title]));
enriched.forEach(r => { r.title = titleMap.get(r.id) || ''; });
}
return enriched;
}
function loadDecisions() {
if (!fs.existsSync(DECISIONS_FILE)) return { _per_product: {} };
return JSON.parse(fs.readFileSync(DECISIONS_FILE, 'utf8'));
}
function saveDecisions(d) {
fs.writeFileSync(DECISIONS_FILE, JSON.stringify(d, null, 2));
}
const app = express();
// Security headers via helmet (added 2026-05-04 overnight YOLO loop)
app.use(helmet({ contentSecurityPolicy: false }));
app.use(express.json());
// 404-guard: never serve snapshot/backup files even if accidentally dropped in tree
app.use((req, res, next) => {
if (/\.(bak|bak\.[^/]+)$|(^|\/)\.pre-|\/\.pre-/.test(req.path)) {
return res.status(404).send('Not found');
}
next();
});
// Basic Auth
app.use((req, res, next) => {
const h = req.headers.authorization || '';
if (!h.startsWith('Basic ')) {
res.set('WWW-Authenticate', 'Basic realm="MFR Review"');
return res.status(401).send('Auth required');
}
const decoded = Buffer.from(h.slice(6), 'base64').toString();
const [u, p] = decoded.split(':');
if (u !== USER || p !== PASS) {
res.set('WWW-Authenticate', 'Basic realm="MFR Review"');
return res.status(401).send('Bad credentials');
}
next();
});
app.get('/api/vendors', (req, res) => {
const all = load();
const decisions = loadDecisions();
const byVendor = {};
for (const r of all) {
const v = r.vendor || '(no vendor)';
if (!byVendor[v]) byVendor[v] = { vendor: v, total: 0, real: 0, polluted: 0, empty: 0, fmproFixable: 0, unfixable: 0, types: {}, actors: {} };
const b = byVendor[v];
b.total++;
if (r.bucket === 'real') b.real++;
else if (r.bucket === 'polluted') b.polluted++;
else if (r.bucket === 'empty') b.empty++;
if (r.bucket !== 'real' && r.fmproMfr) b.fmproFixable++;
if (r.bucket !== 'real' && !r.fmproMfr) b.unfixable++;
const t = r.productType || '(unknown)';
b.types[t] = (b.types[t] || 0) + 1;
b.actors[r.actor] = (b.actors[r.actor] || 0) + 1;
}
// Attach decisions
for (const v of Object.values(byVendor)) {
v.decision = decisions[v.vendor]?.decision || null;
v.notes = decisions[v.vendor]?.notes || '';
}
const list = Object.values(byVendor).sort((a, b) => b.total - a.total);
res.json({ vendors: list, totalProducts: all.length });
});
app.get('/api/vendors/:vendor', (req, res) => {
const vendor = decodeURIComponent(req.params.vendor);
const all = load();
const decisions = loadDecisions();
const products = all.filter(r => (r.vendor || '(no vendor)') === vendor)
.map(r => ({
id: r.id, title: r.title, sku: r.sku, mfr: r.mfr, bucket: r.bucket, fmproMfr: r.fmproMfr,
productType: r.productType, actor: r.actor,
decision: decisions._per_product[r.id]?.decision || null,
notes: decisions._per_product[r.id]?.notes || '',
}))
.sort((a, b) => (a.productType || '').localeCompare(b.productType || '') || (a.title || '').localeCompare(b.title || ''));
res.json({ vendor, products, count: products.length, vendorDecision: decisions[vendor] || null });
});
app.post('/api/vendors/:vendor/decision', (req, res) => {
const vendor = decodeURIComponent(req.params.vendor);
const { decision, notes } = req.body;
const d = loadDecisions();
d[vendor] = { decision, notes: notes || '', ts: new Date().toISOString() };
saveDecisions(d);
res.json({ ok: true });
});
app.post('/api/products/:id/decision', (req, res) => {
const id = req.params.id;
const { decision, notes } = req.body;
const d = loadDecisions();
if (!d._per_product) d._per_product = {};
d._per_product[id] = { decision, notes: notes || '', ts: new Date().toISOString() };
saveDecisions(d);
res.json({ ok: true });
});
app.get('/api/decisions/recent', (req, res) => {
const d = loadDecisions();
const all = load();
const titleMap = new Map(all.map(r => [r.id, { title: r.title, sku: r.sku, vendor: r.vendor, type: r.productType }]));
const items = [];
// Vendor decisions
for (const [v, info] of Object.entries(d)) {
if (v === '_per_product' || !info.ts) continue;
items.push({ scope: 'vendor', vendor: v, decision: info.decision, ts: info.ts, notes: info.notes || '' });
}
// Per-product decisions
for (const [id, info] of Object.entries(d._per_product || {})) {
if (!info.ts) continue;
const meta = titleMap.get(id) || {};
items.push({ scope: 'product', id, title: meta.title, sku: meta.sku, vendor: meta.vendor, type: meta.type, decision: info.decision, ts: info.ts, notes: info.notes || '' });
}
items.sort((a, b) => b.ts.localeCompare(a.ts));
res.json({ items: items.slice(0, 30), total: items.length });
});
app.get('/api/decisions', (req, res) => res.json(loadDecisions()));
app.get('/api/decisions/export', (req, res) => {
// Compute the final per-product action based on vendor + per-product decisions
const all = load();
const d = loadDecisions();
const reactivate = [], deleteIds = [], skip = [], pending = [];
for (const r of all) {
const vDecision = d[r.vendor]?.decision || 'pending';
const pDecision = d._per_product?.[r.id]?.decision || null;
let final;
if (pDecision === 'reactivate') final = 'reactivate';
else if (pDecision === 'delete') final = 'delete';
else if (pDecision === 'skip') final = 'skip';
else if (vDecision === 'all') final = 'reactivate';
else if (vDecision === 'delete') final = 'delete';
else if (vDecision === 'skip') final = 'skip';
else if (vDecision === 'wallpaper' && /wallcovering|wallpaper/i.test(r.productType || '')) final = 'reactivate';
else if (vDecision === 'fabric' && /fabric/i.test(r.productType || '')) final = 'reactivate';
else if (vDecision === 'trim' && /trim/i.test(r.productType || '')) final = 'reactivate';
else final = 'pending';
if (final === 'reactivate') reactivate.push(r.id);
else if (final === 'delete') deleteIds.push(r.id);
else if (final === 'skip') skip.push(r.id);
else pending.push(r.id);
}
res.json({
counts: { reactivate: reactivate.length, delete: deleteIds.length, skip: skip.length, pending: pending.length },
reactivate, delete: deleteIds, skip, pending,
});
});
// ===== APPLY pipeline =====
const TOKEN = (process.env.SHOPIFY_ADMIN_TOKEN || '');
const SHOP = 'designer-laboratory-sandbox.myshopify.com';
const SHOPIFY_API = `https://${SHOP}/admin/api/2024-10/graphql.json`;
const APPLY_LOG = '/tmp/mfr_apply_log.ndjson';
let applyState = { running: false, ok: 0, fail: 0, total: 0, phase: 'idle', startedAt: null, lastError: null };
async function gqlMut(q, vars) {
for (let i = 0; i < 4; i++) {
try {
const r = await fetch(SHOPIFY_API, { method: 'POST', headers: { 'X-Shopify-Access-Token': TOKEN, 'Content-Type': 'application/json' }, body: JSON.stringify({ query: q, variables: vars }) });
const t = await r.text();
if (!t.startsWith('{')) { await new Promise(res => setTimeout(res, 1500 * (i + 1))); continue; }
const j = JSON.parse(t);
if (j.errors && j.errors.some(e => /THROTTLED/i.test(JSON.stringify(e)))) { await new Promise(res => setTimeout(res, 1500 * (i + 1))); continue; }
return j;
} catch { await new Promise(res => setTimeout(res, 1000 * (i + 1))); }
}
return { errors: [{ message: 'gql_exhausted' }] };
}
app.get('/api/apply/status', (req, res) => res.json(applyState));
app.post('/api/apply', async (req, res) => {
if (applyState.running) return res.json({ error: 'already running', state: applyState });
applyState = { running: true, ok: 0, fail: 0, total: 0, phase: 'starting', startedAt: new Date().toISOString(), lastError: null };
res.json({ started: true });
try {
// Phase 1: fix metafield for fixable rows
const audit = fs.readFileSync('/tmp/mfr_audit_state.ndjson', 'utf8').trim().split('\n').map(l => JSON.parse(l));
const exp = await (await fetch(`http://localhost:${PORT}/api/decisions/export`, { headers: { 'Authorization': req.headers.authorization } })).json();
const reactSet = new Set(exp.reactivate);
const deleteSet = new Set(exp.delete);
// Only fix the ones we plan to reactivate (the others stay archived, no point)
const toFix = audit.filter(r => reactSet.has(r.id) && r.bucket !== 'real' && r.fmproMfr && r.fmproMfr !== r.mfr);
const toReactivate = exp.reactivate;
const toDelete = exp.delete;
applyState.total = toFix.length + toReactivate.length + toDelete.length;
applyState.phase = `fix mfr (${toFix.length})`;
const out = fs.createWriteStream(APPLY_LOG, { flags: 'a' });
out.write(JSON.stringify({ ts: new Date().toISOString(), phase: 'start', toFix: toFix.length, toReactivate: toReactivate.length, toDelete: toDelete.length }) + '\n');
// Phase 1: metafieldsSet in batches of 25
for (let i = 0; i < toFix.length; i += 25) {
const chunk = toFix.slice(i, i + 25);
const mfs = chunk.map(c => ({ ownerId: c.id, namespace: 'custom', key: 'manufacturer_sku', type: 'single_line_text_field', value: c.fmproMfr }));
const j = await gqlMut(`mutation set($mfs:[MetafieldsSetInput!]!){metafieldsSet(metafields:$mfs){metafields{id} userErrors{field message}}}`, { mfs });
if (j.data?.metafieldsSet?.userErrors?.length || j.errors) { applyState.fail += chunk.length; applyState.lastError = JSON.stringify(j).slice(0, 200); }
else applyState.ok += chunk.length;
out.write(JSON.stringify({ ts: new Date().toISOString(), phase: 'fix', batch: i / 25, ok: !j.errors }) + '\n');
}
// Phase 2: reactivate
applyState.phase = `reactivate (${toReactivate.length})`;
for (const id of toReactivate) {
const j = await gqlMut(`mutation($id:ID!){productChangeStatus(productId:$id,status:ACTIVE){product{id status} userErrors{field message}}}`, { id });
if (j.data?.productChangeStatus?.userErrors?.length || j.errors) { applyState.fail++; applyState.lastError = JSON.stringify(j).slice(0, 200); }
else applyState.ok++;
if ((applyState.ok + applyState.fail) % 100 === 0) {
out.write(JSON.stringify({ ts: new Date().toISOString(), phase: 'reactivate', ok: applyState.ok, fail: applyState.fail }) + '\n');
}
}
// Phase 3: delete
applyState.phase = `delete (${toDelete.length})`;
for (const id of toDelete) {
const j = await gqlMut(`mutation($id:ID!){productDelete(input:{id:$id}){deletedProductId userErrors{field message}}}`, { id });
if (j.data?.productDelete?.userErrors?.length || j.errors) { applyState.fail++; applyState.lastError = JSON.stringify(j).slice(0, 200); }
else applyState.ok++;
if ((applyState.ok + applyState.fail) % 100 === 0) {
out.write(JSON.stringify({ ts: new Date().toISOString(), phase: 'delete', ok: applyState.ok, fail: applyState.fail }) + '\n');
}
}
applyState.phase = 'done';
applyState.running = false;
out.write(JSON.stringify({ ts: new Date().toISOString(), phase: 'done', ok: applyState.ok, fail: applyState.fail }) + '\n');
out.end();
} catch (e) {
applyState.running = false;
applyState.phase = 'error';
applyState.lastError = e.message;
}
});
app.get('/', (_req, res) => {
res.set('Content-Type', 'text/html').send(html());
});
function html() {
return `<!doctype html>
<html lang="en"><head><meta charset="utf-8">
<title>MFR Review — DW Bulk Reactivation</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<style>
:root{color-scheme:dark}
*{box-sizing:border-box}
body{margin:0;background:#0a0c12;color:#e5e7eb;font-family:-apple-system,system-ui,sans-serif}
header{padding:14px 24px;background:#111827;border-bottom:1px solid #1f2937;display:flex;justify-content:space-between;align-items:center}
h1{margin:0;font-size:18px;font-weight:700}
.stat{font-size:12px;color:#9ca3af}
main{display:grid;grid-template-columns:380px 1fr;gap:0;height:calc(100vh - 56px)}
.pane{padding:14px;overflow-y:auto;height:100%}
.pane:first-child{border-right:1px solid #1f2937;background:#0f1115}
table{width:100%;border-collapse:collapse;font-size:12px}
th{text-align:left;padding:6px;color:#9ca3af;font-weight:500;border-bottom:1px solid #1f2937;position:sticky;top:0;background:#0f1115}
td{padding:6px;border-bottom:1px solid #1a1d27}
tr:hover{background:#1a1d27;cursor:pointer}
tr.active{background:#1e293b}
.decision{padding:2px 6px;border-radius:3px;font-size:10px;font-weight:600}
.d-all{background:#22c55e30;color:#86efac}
.d-skip{background:#ef444430;color:#fca5a5}
.d-wallpaper,.d-fabric,.d-trim{background:#3b82f630;color:#93c5fd}
.d-pending{background:#6b728030;color:#9ca3af}
.pill{display:inline-block;padding:2px 6px;border-radius:3px;font-size:10px;background:#1f2937}
.types{display:flex;gap:4px;flex-wrap:wrap}
.controls{display:flex;gap:8px;margin:10px 0;flex-wrap:wrap;align-items:center}
button{background:#1f2937;color:#e5e7eb;border:1px solid #374151;padding:6px 12px;border-radius:4px;cursor:pointer;font-size:12px}
button.primary{background:#2563eb;border-color:#3b82f6}
button.danger{background:#dc2626;border-color:#ef4444}
textarea{width:100%;background:#0f1115;border:1px solid #374151;color:#e5e7eb;padding:8px;border-radius:4px;font-family:inherit;min-height:60px}
select{background:#0f1115;border:1px solid #374151;color:#e5e7eb;padding:6px 10px;border-radius:4px;font-size:12px}
input[type=search]{background:#0f1115;border:1px solid #374151;color:#e5e7eb;padding:6px 10px;border-radius:4px;font-size:12px;min-width:200px}
.vendor-row .types-mini{font-size:10px;color:#6b7280;margin-top:2px}
.small{font-size:11px;color:#6b7280}
.product-list{margin-top:14px}
.product-row{display:grid;grid-template-columns:1fr 100px 100px 80px 60px 110px;gap:8px;padding:6px 0;border-bottom:1px solid #1a1d27;font-size:12px;align-items:center}
.product-row:hover{background:#1a1d27}
.product-row .title{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.product-row .mfr{font-family:monospace;font-size:11px;color:#9ca3af}
</style></head>
<body>
<header>
<div><h1>MFR Review — Bulk Reactivation Decisions</h1>
<div class="stat" id="header-stat">Loading...</div></div>
<div style="display:flex;gap:14px;align-items:center">
<div class="stat" id="totals-stat" style="text-align:right">—</div>
<button class="primary" id="apply-btn" onclick="confirmApply()" style="padding:8px 16px;font-size:13px;font-weight:600">⚡ APPLY ALL</button>
</div>
</header>
<div id="progress-strip" style="display:none;background:#1e293b;border-bottom:1px solid #334155;padding:8px 24px;font-size:12px"></div>
<div id="recent-strip" style="background:#0f1115;border-bottom:1px solid #1f2937;padding:8px 24px;font-size:12px;max-height:140px;overflow-y:auto">
<div style="color:#9ca3af;font-weight:600;margin-bottom:4px">Recent decisions</div>
<div id="recent-content" style="color:#6b7280">No decisions yet — start clicking vendors below.</div>
</div>
<main>
<div class="pane">
<input type="search" id="vendor-search" placeholder="Filter vendors..." style="width:100%;margin-bottom:10px">
<table id="vendor-table">
<thead><tr><th>Vendor</th><th>Total</th><th>Decision</th></tr></thead>
<tbody id="vendor-tbody"></tbody>
</table>
</div>
<div class="pane" id="detail">
<div style="color:#6b7280;text-align:center;padding-top:80px">Click a vendor to view details</div>
</div>
</main>
<script>
let vendors = [];
let selectedVendor = null;
async function loadVendors() {
const r = await fetch('/api/vendors').then(r=>r.json());
vendors = r.vendors;
document.getElementById('header-stat').textContent = r.totalProducts.toLocaleString() + ' archived-eligible products | ' + vendors.length + ' vendors';
renderVendorList();
updateTotals();
}
async function updateTotals() {
const t = await fetch('/api/decisions/export').then(r=>r.json());
const c = t.counts;
document.getElementById('totals-stat').innerHTML =
'<span style="color:#86efac">↻ ' + c.reactivate + ' reactivate</span> · ' +
'<span style="color:#fca5a5">✕ ' + c.delete + ' DELETE</span> · ' +
'<span style="color:#9ca3af">— ' + c.skip + ' skip</span> · ' +
'<span style="color:#fbbf24">? ' + c.pending + ' pending</span>';
updateRecent();
}
function decColor(d){
if (d==='all'||d==='reactivate') return '#86efac';
if (d==='delete') return '#fca5a5';
if (d==='skip') return '#9ca3af';
if (d==='wallpaper'||d==='fabric'||d==='trim') return '#93c5fd';
return '#fbbf24';
}
function fmtTime(iso){
const ms=Date.now()-new Date(iso).getTime();
const s=Math.round(ms/1000);
if(s<60)return s+'s ago';
const m=Math.round(s/60); if(m<60)return m+'m ago';
const h=Math.round(m/60); if(h<24)return h+'h ago';
return Math.round(h/24)+'d ago';
}
async function updateRecent() {
const r = await fetch('/api/decisions/recent').then(r=>r.json());
const el = document.getElementById('recent-content');
if (!r.items.length) { el.innerHTML = '<span style="color:#6b7280">No decisions yet</span>'; return; }
el.innerHTML = r.items.slice(0, 12).map(it => {
const c = decColor(it.decision);
if (it.scope === 'vendor') {
return '<div style="padding:2px 0">' +
'<span style="color:'+c+';font-weight:600">'+it.decision+'</span> ' +
'<b>'+it.vendor+'</b> ' +
'<span style="color:#6b7280">'+fmtTime(it.ts)+'</span>' +
(it.notes ? '<span style="color:#9ca3af"> — '+it.notes.slice(0,80)+'</span>' : '') +
'</div>';
} else {
return '<div style="padding:2px 0">' +
'<span style="color:'+c+';font-weight:600">'+(it.decision||'cleared')+'</span> ' +
'<span style="font-family:monospace;color:#9ca3af">'+(it.sku||'')+'</span> ' +
'<span style="color:#e5e7eb">'+(it.title||'').slice(0,50)+'</span> ' +
'<span style="color:#6b7280">['+(it.type||'?')+'] '+fmtTime(it.ts)+'</span>' +
'</div>';
}
}).join('') + (r.total > 12 ? '<div style="color:#6b7280;margin-top:4px">+ ' + (r.total - 12) + ' more</div>' : '');
}
function renderVendorList() {
const filter = document.getElementById('vendor-search').value.toLowerCase();
const tbody = document.getElementById('vendor-tbody');
tbody.innerHTML = vendors.filter(v => v.vendor.toLowerCase().includes(filter)).map(v => {
const dec = v.decision || 'pending';
const types = Object.entries(v.types || {}).sort((a,b)=>b[1]-a[1]).slice(0,3).map(([t,n])=>t+':'+n).join(', ');
return '<tr class="vendor-row ' + (selectedVendor===v.vendor?'active':'') + '" onclick="selectVendor(\\''+ encodeURIComponent(v.vendor) +'\\')">'
+ '<td><b>' + v.vendor + '</b><div class="types-mini">' + types + '</div></td>'
+ '<td>' + v.total.toLocaleString() + '<div class="small">' + v.fmproFixable + ' fix · ' + v.unfixable + ' un</div></td>'
+ '<td><span class="decision d-' + dec + '">' + dec + '</span></td></tr>';
}).join('');
}
document.getElementById('vendor-search').addEventListener('input', renderVendorList);
async function selectVendor(encVendor) {
const vendor = decodeURIComponent(encVendor);
selectedVendor = vendor;
renderVendorList();
const r = await fetch('/api/vendors/' + encVendor).then(r=>r.json());
const v = vendors.find(x => x.vendor === vendor);
const types = Object.entries(v.types || {}).sort((a,b)=>b[1]-a[1]);
const actors = Object.entries(v.actors || {}).sort((a,b)=>b[1]-a[1]);
const dec = r.vendorDecision?.decision || 'pending';
const notes = r.vendorDecision?.notes || '';
document.getElementById('detail').innerHTML = \`
<h2 style="margin:0 0 8px">\${vendor} <span class="small">(\${r.count.toLocaleString()} products)</span></h2>
<div style="display:grid;grid-template-columns:1fr 1fr;gap:14px;margin-bottom:14px">
<div>
<div class="small" style="margin-bottom:4px">Product types</div>
<div class="types">\${types.map(([t,n])=>'<span class="pill">'+t+': '+n+'</span>').join('')}</div>
</div>
<div>
<div class="small" style="margin-bottom:4px">Archived by</div>
<div class="types">\${actors.map(([a,n])=>'<span class="pill">'+a+': '+n+'</span>').join('')}</div>
</div>
</div>
<div class="controls">
<span class="small">Decision:</span>
<select id="vd">
<option value="pending"\${dec==='pending'?' selected':''}>Pending</option>
<option value="all"\${dec==='all'?' selected':''}>Reactivate ALL</option>
<option value="wallpaper"\${dec==='wallpaper'?' selected':''}>Wallpaper/Wallcovering only</option>
<option value="fabric"\${dec==='fabric'?' selected':''}>Fabric only</option>
<option value="trim"\${dec==='trim'?' selected':''}>Trim only</option>
<option value="skip"\${dec==='skip'?' selected':''}>Skip (leave archived)</option>
<option value="delete"\${dec==='delete'?' selected':''}>DELETE ALL (permanent)</option>
</select>
<button class="primary" onclick="saveVendor('\${encVendor}')">Save</button>
</div>
<textarea id="vn" placeholder="Notes for Claude (e.g. 'discontinued', 'settlement', 'only sample-only items', 'review by hand')...">\${notes}</textarea>
<div class="product-list">
<h3>Products (\${r.count})</h3>
<div class="small" style="display:grid;grid-template-columns:1fr 100px 100px 80px 60px 110px;gap:8px;padding:6px 0;border-bottom:1px solid #374151">
<div>Title</div><div>Type</div><div>SKU</div><div>MFR</div><div>Bkt</div><div>Override</div>
</div>
\${r.products.map(p=>\`
<div class="product-row">
<div class="title" title="\${p.title}">\${p.title || '(untitled)'}</div>
<div class="mfr">\${p.productType || '-'}</div>
<div class="mfr">\${p.sku}</div>
<div class="mfr">\${p.mfr || (p.fmproMfr ? '<span style="color:#86efac">'+p.fmproMfr+' (fix)</span>' : '<span style="color:#fca5a5">missing</span>')}</div>
<div><span class="decision d-\${p.bucket==='real'?'all':'pending'}">\${p.bucket}</span></div>
<div><select onchange="saveProduct('\${p.id}', this.value)"><option value=""\${!p.decision?' selected':''}>—</option><option value="reactivate"\${p.decision==='reactivate'?' selected':''}>Reactivate</option><option value="skip"\${p.decision==='skip'?' selected':''}>Skip</option><option value="delete"\${p.decision==='delete'?' selected':''}>Delete</option></select></div>
</div>
\`).join('')}
</div>
\`;
}
async function saveVendor(encVendor) {
const dec = document.getElementById('vd').value;
const notes = document.getElementById('vn').value;
await fetch('/api/vendors/' + encVendor + '/decision', {method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({decision:dec,notes})});
await loadVendors();
}
async function saveProduct(id, dec) {
await fetch('/api/products/' + encodeURIComponent(id) + '/decision', {method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({decision:dec})});
updateTotals();
}
async function confirmApply() {
const t = await fetch('/api/decisions/export').then(r=>r.json());
const c = t.counts;
const msg = 'You are about to:\\n\\n' +
'↻ Reactivate ' + c.reactivate.toLocaleString() + ' products\\n' +
'✕ DELETE ' + c.delete.toLocaleString() + ' products (PERMANENT)\\n' +
'— Skip ' + c.skip.toLocaleString() + ' products\\n' +
'? ' + c.pending.toLocaleString() + ' products are still pending (will NOT be touched)\\n\\n' +
'Phase 1 will fix mfr metafields for the reactivate cohort first.\\n\\n' +
'Type "EXECUTE" to confirm:';
const resp = prompt(msg);
if (resp !== 'EXECUTE') { alert('Cancelled.'); return; }
await fetch('/api/apply', {method:'POST'});
pollApply();
}
async function pollApply() {
const strip = document.getElementById('progress-strip');
strip.style.display = 'block';
const interval = setInterval(async () => {
const s = await fetch('/api/apply/status').then(r=>r.json());
const pct = s.total ? Math.round(((s.ok+s.fail)/s.total)*100) : 0;
strip.innerHTML = '<b>' + s.phase + '</b> · ' + pct + '% · ok=' + s.ok + ' fail=' + s.fail + (s.lastError ? ' · <span style="color:#fca5a5">last err: ' + s.lastError.slice(0,80) + '</span>' : '');
if (!s.running && s.phase === 'done') {
clearInterval(interval);
strip.innerHTML += ' · <b style="color:#86efac">DONE</b>';
updateTotals();
} else if (!s.running && s.phase === 'error') {
clearInterval(interval);
strip.innerHTML += ' · <b style="color:#fca5a5">ERROR</b>';
}
}, 2000);
}
loadVendors();
</script>
</body></html>`;
}
app.listen(PORT, '0.0.0.0', () => {
console.log(`MFR Review viewer http://0.0.0.0:${PORT} (open to LAN + Tailnet)`);
});