← back to Dw Signup Fulfillment

verification/tk10836/verify-find-free-rate.js

66 lines

#!/usr/bin/env node
// TK-10836 Option D (3/n): locate the "Free Shipping (No Tracking)" + "Priority Sample Only" rates
// across ALL delivery profiles, and identify which profile Kelly's 3 sample variants belong to.
const fs=require('fs'),os=require('os');
for (const line of fs.readFileSync(os.homedir()+'/Projects/secrets-manager/.env','utf8').split('\n')) {
  const m=line.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*)$/); if(!m) continue;
  let v=m[2].trim().replace(/^['"]|['"]$/g,''); if(!process.env[m[1]]) process.env[m[1]]=v;
}
const STORE=process.env.SHOPIFY_STORE_DOMAIN||'designer-laboratory-sandbox.myshopify.com';
const TOKEN=process.env.SHOPIFY_FULL_ACCESS_TOKEN, API='2024-10';
async function gql(query,variables={}){
  const r=await fetch(`https://${STORE}/admin/api/${API}/graphql.json`,{method:'POST',
    headers:{'X-Shopify-Access-Token':TOKEN,'Content-Type':'application/json'},
    body:JSON.stringify({query,variables})});
  const j=await r.json(); if(j.errors)console.error('ERR',JSON.stringify(j.errors).slice(0,600));
  return j.data;
}
const PROFILES=`query($c:String){ deliveryProfiles(first:5, after:$c){
  pageInfo{hasNextPage endCursor}
  nodes{ id name default
    profileLocationGroups{ locationGroupZones(first:12){ nodes{
      zone{name}
      methodDefinitions(first:20){ nodes{ name active
        rateProvider{ __typename ... on DeliveryRateDefinition{ price{amount} } ... on DeliveryParticipant{ carrierService{formattedName} } }
        methodConditions{ field operator conditionCriteria{ __typename ... on MoneyV2{amount} ... on Weight{unit value} } }
      } }
    } } }
  } } }`;
(async()=>{
  let c=null,hits=[],all=[];
  do{
    const d=await gql(PROFILES,{c});
    if(!d) break;
    for(const p of d.deliveryProfiles.nodes){
      all.push(p.name);
      for(const lg of p.profileLocationGroups)
        for(const z of lg.locationGroupZones.nodes)
          for(const m of z.methodDefinitions.nodes){
            if(/free shipping|no tracking|priority|sample/i.test(m.name)){
              const rp=m.rateProvider;
              const rate=rp.price?`FLAT $${rp.price.amount}`:(rp.carrierService?`CARRIER ${rp.carrierService.formattedName}`:rp.__typename);
              const conds=(m.methodConditions||[]).map(x=>{const cc=x.conditionCriteria||{};const v=cc.amount!==undefined?`$${cc.amount}`:(cc.value!==undefined?`${cc.value}${cc.unit}`:'?');return `${x.field} ${x.operator} ${v}`;});
              hits.push({profile:p.name,zone:z.zone.name,name:m.name,active:m.active,rate,conds});
            }
          }
    }
    c=d.deliveryProfiles.pageInfo.hasNextPage?d.deliveryProfiles.pageInfo.endCursor:null;
  }while(c);
  console.log(`### ${all.length} delivery profiles scanned ###`);
  console.log('\n### MATCHING RATES (free/no-tracking/priority/sample) ###');
  if(!hits.length) console.log(' *** NONE FOUND IN ANY DELIVERY PROFILE ***');
  for(const h of hits) console.log(` - [${h.profile}] zone=${h.zone} "${h.name}" active=${h.active} | ${h.rate}\n     conds: ${h.conds.join(' AND ')||'(none)'}`);

  // Which profile do Kelly's sample variants live in?
  console.log('\n### KELLY\'S 3 SAMPLE VARIANTS -> delivery profile + weight ###');
  const names=['Brushed Finesse Pewter','Shimmer Polar White','Finesse Metallic Rose'];
  for(const n of names){
    const d=await gql(`query($q:String!){ productVariants(first:5, query:$q){ nodes{
      id title displayName sku price inventoryItem{ measurement{ weight{ unit value } } }
      deliveryProfile{ id name } product{ title } } } }`,{q:`title:*${n.split(' ')[0]}*`});
    const v=(d?.productVariants?.nodes||[]).slice(0,2);
    if(!v.length){ console.log(` - ${n}: no variant match on title query`); continue; }
    for(const x of v) console.log(` - "${x.displayName}" sku=${x.sku} price=${x.price} weight=${JSON.stringify(x.inventoryItem?.measurement?.weight)} profile=${x.deliveryProfile?.name}`);
  }
})();