← back to Fineartamerica Price Sync

bin/faa-fetch-http.js

47 lines

#!/usr/bin/env node
// Populate data/cost-cache.json with real FAA costs via the free HTTP
// configurator endpoint (lib/faa-http.js). No Browserbase, no login.
//
//   node bin/faa-fetch-http.js --url "<faa product page>" --from-shopify <productId>
//
// For each distinct config on the Shopify product, replays FAA's setter sequence
// and caches the returned cost keyed by configKey. Falls back to the page's
// artworkId when the SKU's artworkId prices null (handles the SKU-vs-listing id
// drift, e.g. Washington Top Hat SKU 65269183 vs live listing 65119339).

const { openSession, priceFramedConfig } = require('../lib/faa-http');
const { parseSku, configKey, configLabel } = require('../lib/parse-sku');
const { loadCache, saveCache } = require('../lib/faa-cost');
const { getProduct } = require('../lib/shopify');

const args = process.argv.slice(2);
const val = f => { const i = args.indexOf(f); return i >= 0 ? args[i + 1] : null; };
const URL0 = val('--url');
const PID = val('--from-shopify');

(async () => {
  if (!URL0 || !PID) { console.error('need --url and --from-shopify <productId>'); process.exit(1); }
  const p = await getProduct(PID);
  const seen = new Set(), configs = [];
  for (const v of p.variants) {
    const cfg = parseSku(v.sku); if (!cfg) continue;
    const k = configKey(cfg); if (seen.has(k)) continue; seen.add(k); configs.push(cfg);
  }
  console.log(`${configs.length} distinct FAA configs on "${p.title}"`);

  const session = await openSession(URL0);
  console.log(`FAA session sid=${session.sessionId.slice(0,10)}… pageArtwork=${session.pageArtworkId}`);
  const cache = loadCache();
  let ok = 0, fail = 0;
  for (const cfg of configs) {
    let cost = await priceFramedConfig(session, cfg);
    if (cost == null && cfg.artworkid !== session.pageArtworkId) {
      cost = await priceFramedConfig(session, { ...cfg, artworkid: session.pageArtworkId }); // fallback
    }
    if (cost != null) { cache[configKey(cfg)] = cost; ok++; console.log(`  ✓ ${configLabel(cfg)} → $${cost.toFixed(2)}`); }
    else { fail++; console.log(`  ✗ ${configLabel(cfg)} → null`); }
  }
  saveCache(cache);
  console.log(`\ncosted ${ok}, failed ${fail}. cost-cache.json updated. ($0 — free HTTP)`);
})().catch(e => { console.error(e); process.exit(1); });