← back to Flock Fix Viewer

spec-privatelabel-flock.mjs

82 lines

// (c) House private-label defaults for ROP/ERE/PRNC flock (Phillipe Romano). Real MFR unverifiable
// feed-side (absent from vendor_catalog/romo_catalog/clean staging) — Steve authorized house defaults.
// American paper-backed flocked-velvet spec set + sqft from each product's OWN roll data. No per-pattern
// repeat (unverified). No price. Reversible + ledgered + snapshot. --apply to write.
import fs from 'fs'; import os from 'os'; import path from 'path';
const SHOP='designer-laboratory-sandbox.myshopify.com';
const TOKEN=fs.readFileSync(new URL('./.token',import.meta.url),'utf8').trim();
const LEDGER=path.join(os.homedir(),'.claude/yolo-queue/executed-reversible/ledger.jsonl');
const SNAP=new URL('./spec-privatelabel-flock-snapshot.json',import.meta.url);
const DRY=!process.argv.includes('--apply');
const API=`https://${SHOP}/admin/api/2024-10`;
const H={'X-Shopify-Access-Token':TOKEN,'Content-Type':'application/json'};
const sleep=ms=>new Promise(r=>setTimeout(r,ms));
const gql=async(q,v={})=>(await (await fetch(`${API}/graphql.json`,{method:'POST',headers:H,body:JSON.stringify({query:q,variables:v})})).json());
const MULTILINE=new Set(['custom.material','custom.google_product_category']);
const typeFor=(ns,k)=>MULTILINE.has(ns+'.'+k)?'multi_line_text_field':'single_line_text_field';
const r2=n=>Math.round(n*100)/100;
const HOUSE=[ // [globalKey, customKey, value]
  ['Match','match_type','Straight'],
  ['application','application','Paste the Paper'],
  ['Substrate','backing','Paper'],
  ['removability','removal','Strippable'],
  ['print_type','print_type','Flock'],
  ['material','material','Flocked Velvet'],
];
// Parse width_in + single-roll length_ft from either the original combined width
// value (20.5"x16.5') or the normalized width/length metafield pair.
function parseWL(width,length){ if(!width) return null;
  const nums=(String(width).match(/[\d.]+/g)||[]).map(parseFloat);
  if(nums.length<2 && length){
    const lengthNums=(String(length).match(/[\d.]+/g)||[]).map(parseFloat);
    if(lengthNums.length) nums.push(lengthNums[0]);
  }
  if(nums.length<2) return null;
  const [w,l]=nums;
  if(!(w>=12&&w<=56)) return null;         // sane flock width in inches
  if(!(l>=3&&l<=40)) return null;          // single-roll length in feet
  return {wi:w, lenft:l};
}
(async()=>{
  let cur=null,all=[];
  const Q=`query($c:String){ products(first:100, query:"vendor:'Phillipe Romano' status:active", after:$c){ pageInfo{hasNextPage endCursor}
    edges{node{ id handle title
      variants(first:4){edges{node{sku title}}}
      w:metafield(namespace:"global",key:"width"){value}
      l:metafield(namespace:"global",key:"length"){value}
      gpt:metafield(namespace:"global",key:"print_type"){value}
    }}}}`;
  do{const r=await gql(Q,{c:cur});const p=r?.data?.products;if(!p){console.error(JSON.stringify(r));break;}all=all.concat(p.edges);cur=p.pageInfo.hasNextPage?p.pageInfo.endCursor:null;}while(cur);
  const rollSku=n=>{const v=n.variants.edges.map(e=>e.node).find(v=>!/sample/i.test(v.title||''))||n.variants.edges[0]?.node;return v?.sku||'';};
  const targets=all.map(e=>e.node).filter(n=>/^(ROP|ERE|PRNC)-/i.test(rollSku(n)) && /flock/i.test(n.title));
  console.log('active Phillipe Romano ROP/ERE/PRNC flock:',targets.length);
  const snap=[]; let applied=0, skipped=[];
  for(const n of targets){
    const wl=parseWL(n.w?.value,n.l?.value);
    if(!wl){ skipped.push(`${rollSku(n)} bad-dimensions width="${n.w?.value}" length="${n.l?.value}"`); continue; }
    const sr=r2((wl.wi/12)*wl.lenft), dr=r2(sr*2);
    const pairs=[
      ['width',null,`${wl.wi} in`],
      ['length',null,`${wl.lenft} ft (single roll)`],
      ...HOUSE,
      ['sqft_single_roll',null,sr+' Sq Ft'],['sqft_double_roll',null,dr+' Sq Ft'],
    ];
    if(DRY){ console.log(`  ${rollSku(n).padEnd(13)} W=${wl.wi}in L=${wl.lenft}ft SR=${sr} DR=${dr}  ${n.title.slice(0,40)}`); continue; }
    const mf=[];
    for(const [gk,ck,val] of pairs){ if(val==null) continue;
      mf.push({ownerId:n.id,namespace:'global',key:gk,type:typeFor('global',gk),value:val});
      if(ck) mf.push({ownerId:n.id,namespace:'custom',key:ck,type:typeFor('custom',ck),value:val});
    }
    mf.push({ownerId:n.id,namespace:'custom',key:'sqft_single_roll',type:'single_line_text_field',value:sr+' Sq Ft'});
    mf.push({ownerId:n.id,namespace:'custom',key:'sqft_double_roll',type:'single_line_text_field',value:dr+' Sq Ft'});
    const rr=await gql('mutation($mf:[MetafieldsSetInput!]!){metafieldsSet(metafields:$mf){userErrors{field message}}}',{mf});
    const errs=rr?.data?.metafieldsSet?.userErrors; if(errs&&errs.length){console.log('  FAIL',n.handle,JSON.stringify(errs));continue;}
    snap.push({id:n.id,handle:n.handle,sku:rollSku(n),oldWidth:n.w?.value||null});
    fs.appendFileSync(LEDGER,JSON.stringify({ts:new Date().toISOString(),agent:'vp-dw-commerce:spec-pl-flock',ticket:'TK-11128',action:`house private-label flock specs (${rollSku(n)}: ${wl.wi}in x ${wl.lenft}ft single, paper flock paste-the-paper strippable, sqft; no per-pattern repeat) on ${n.handle}`,blast_radius:1,undo_cmd:`delete added spec metafields on ${n.id} (old width="${n.w?.value}")`,verify:'PDP shows flock spec set + sqft'})+'\n');
    applied++; await sleep(220);
  }
  if(!DRY) fs.writeFileSync(SNAP,JSON.stringify(snap,null,1));
  console.log(`${DRY?'DRY':'DONE'} applied=${applied} skipped=${skipped.length}`);
  if(skipped.length) console.log('  SKIP:',skipped.join(' | '));
})();