← back to Hollywood Optc

order-history-check-held36.mjs

18 lines

import { readFileSync, writeFileSync } from 'node:fs';
const SHOP='designer-laboratory-sandbox.myshopify.com', VER='2024-10';
const TOKEN=(readFileSync(process.env.HOME+'/Projects/secrets-manager/.env','utf8').split('\n').find(l=>l.startsWith('SHOPIFY_FULL_ACCESS_TOKEN='))||'').replace('SHOPIFY_FULL_ACCESS_TOKEN=','').replace(/["'\r]/g,'').trim();
if(!TOKEN){console.error('no FULL token');process.exit(1);}
const targets=new Set(readFileSync('/tmp/held36-fromskus.txt','utf8').split('\n').map(s=>s.trim().toUpperCase()).filter(Boolean));
async function gj(url){const r=await fetch(url,{headers:{'X-Shopify-Access-Token':TOKEN}});
 if(r.status===429){await new Promise(x=>setTimeout(x,2000));return gj(url);}
 if(!r.ok)throw new Error(r.status+' '+await r.text());
 const link=r.headers.get('link')||''; const m=link.match(/<([^>]+)>;\s*rel="next"/);
 return {body:await r.json(), next:m?m[1]:null};}
const since=new Date(Date.now()-365*864e5).toISOString();
let url=`https://${SHOP}/admin/api/${VER}/orders.json?status=any&created_at_min=${since}&limit=250&fields=id,line_items`;
let orders=0,li=0,matched=0; const hits=new Map(); const mo=new Set(); let pages=0;
while(url){const {body,next}=await gj(url); for(const o of (body.orders||[])){orders++; for(const l of (o.line_items||[])){li++; const s=(l.sku||'').toUpperCase(); if(s&&targets.has(s)){matched++; mo.add(o.id); hits.set(s,(hits.get(s)||0)+1);}}} pages++; url=next; if(pages%8===0)console.error(`  ...${orders} orders / ${li} LI`);}
const res={generated_at:new Date().toISOString(),ticket:'TK-10633',scope:'held36',window:{since},orders_scanned:orders,line_items_scanned:li,target_skus:targets.size,distinct_target_skus_in_orders:hits.size,matched_line_items:matched,matched_orders:mo.size,hits:[...hits.entries()].sort((a,b)=>b[1]-a[1]).slice(0,20)};
writeFileSync('data/order-history-held36.json',JSON.stringify(res,null,2));
console.log(JSON.stringify(res,null,2));