← back to Secrets Manager

coordonne-collab-audit/coco-backfill.js

35 lines

#!/usr/bin/env node
// Feed-first ($0) five-field backfill for the 54 Coco Dávez rows.
// Pulls description + material + REAL B-code sku from the Woo Store API:
//   https://coordonne.com/wp-json/wc/store/v1/products/<wpid>
//   wpid = numeric tail of the internal mfr_sku COORD-<wpid>.
const fs = require('fs'), path = require('path');
const rows = JSON.parse(fs.readFileSync(path.join(__dirname, 'coco-rows.json'), 'utf8'));
const ent = { '&#8217;': '’', '&#8216;': '‘', '&#8220;': '“', '&#8221;': '”', '&#8211;': '–', '&#8212;': '—', '&#8230;': '…', '&amp;': '&', '&nbsp;': ' ', '&quot;': '"', '&#039;': "'", '&#39;': "'" };
const strip = h => (h || '').replace(/<[^>]+>/g, ' ').replace(/&#?\w+;/g, m => ent[m] || m).replace(/\s+/g, ' ').trim();

(async () => {
  const out = [];
  for (const row of rows) {
    const wpid = (row.mfr_sku || '').replace(/^COORD-/, '');
    let rec = { dw_sku: row.dw_sku, internal_mfr: row.mfr_sku, wpid };
    try {
      const r = await fetch(`https://coordonne.com/wp-json/wc/store/v1/products/${wpid}`);
      const j = await r.json();
      rec.woo_name = j.name;
      rec.real_sku = j.sku || null;                   // real B/C-code manufacturer SKU
      rec.description = strip(j.description) || strip(j.short_description);
      const qa = (j.attributes || []).find(a => /quality|material/i.test(a.name));
      rec.material = qa ? (qa.terms || []).map(t => t.name).join(' / ') : row.material;
      rec.price_woo = j.prices ? (parseInt(j.prices.price, 10) / Math.pow(10, j.prices.currency_minor_unit || 2)) : null;
      rec.ok = !!(rec.description && rec.real_sku);
    } catch (e) { rec.error = e.message; rec.ok = false; }
    out.push(rec);
    process.stderr.write(`${row.dw_sku} wpid=${wpid} sku=${rec.real_sku||'-'} desc=${(rec.description||'').length} name="${rec.woo_name||''}"\n`);
    await new Promise(r => setTimeout(r, 200));
  }
  fs.writeFileSync(path.join(__dirname, 'coco-backfill.json'), JSON.stringify(out, null, 2));
  const missing = out.filter(o => !o.ok);
  console.log(JSON.stringify({ total: out.length, complete: out.filter(o => o.ok).length, missing: missing.map(m => ({ dw_sku: m.dw_sku, real_sku: m.real_sku, desc: (m.description || '').length, err: m.error })) }, null, 2));
})();