← back to Dw Signup Fulfillment

verification/tk10836/verify-rate-vs-subtotal.js

68 lines

#!/usr/bin/env node
// TK-10836 Option D (5/n): DISCRIMINATOR TEST — on real sample-only orders, does the $0.00
// "Free Shipping (No Tracking)" rate correlate with a NON-ZERO item subtotal?
// Hypothesis under test: when the DW Free Samples automatic zeroes items to $0.00, the free
// rate is suppressed and only "Priority Sample Only" $24.95 remains.
// Falsifier: any order with item subtotal $0.00 that still shipped Free Shipping (No Tracking).
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(q,v={}){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:q,variables:v})});
  const j=await r.json(); if(j.errors)console.error('ERR',JSON.stringify(j.errors).slice(0,600)); return j.data;}
const Q=`query($c:String){ orders(first:50, after:$c, query:"created_at:>2026-01-01", sortKey:CREATED_AT){
  pageInfo{hasNextPage endCursor}
  nodes{ name createdAt
    currentSubtotalPriceSet{ shopMoney{amount} }
    subtotalPriceSet{ shopMoney{amount} }
    totalDiscountsSet{ shopMoney{amount} }
    totalShippingPriceSet{ shopMoney{amount} }
    shippingLine{ title }
    shippingAddress{ provinceCode countryCodeV2 }
    discountCodes
    lineItems(first:25){ nodes{ quantity sku title
      originalUnitPriceSet{shopMoney{amount}} discountedTotalSet{shopMoney{amount}} } } } } }`;
(async()=>{
  let c=null, rows=[];
  do{
    const d=await gql(Q,{c}); if(!d) break;
    for(const o of d.orders.nodes){
      const lis=o.lineItems.nodes;
      if(!lis.length) continue;
      const sampleOnly=lis.every(li=>/(^|-)sample/i.test(li.sku||'')||/sample|memo|swatch/i.test(li.title||''));
      if(!sampleOnly) continue;
      const itemsCharged=lis.reduce((s,li)=>s+Number(li.discountedTotalSet?.shopMoney?.amount||0),0);
      rows.push({
        name:o.name, date:o.createdAt.slice(0,10),
        st:Number(o.subtotalPriceSet?.shopMoney?.amount||0),
        charged:itemsCharged,
        disc:Number(o.totalDiscountsSet?.shopMoney?.amount||0),
        ship:Number(o.totalShippingPriceSet?.shopMoney?.amount||0),
        rate:o.shippingLine?.title||'(none)',
        geo:`${o.shippingAddress?.provinceCode||'?'}/${o.shippingAddress?.countryCodeV2||'?'}`,
        codes:(o.discountCodes||[]).join(','), n:lis.length });
    }
    c=d.orders.pageInfo.hasNextPage?d.orders.pageInfo.endCursor:null;
  }while(c);
  const dom=rows.filter(r=>r.geo.endsWith('/US'));
  console.log(`sample-only orders since 2026-01-01: ${rows.length} (US domestic: ${dom.length})\n`);
  const zero=dom.filter(r=>r.charged===0), nonzero=dom.filter(r=>r.charged>0);
  const isFree=r=>r.ship===0;
  console.log(`### GROUP A — items charged $0.00 (fully-comped samples)  n=${zero.length}`);
  console.log(`    shipped FREE: ${zero.filter(isFree).length}   shipped PAID: ${zero.filter(r=>!isFree(r)).length}`);
  for(const r of zero) console.log(`      ${r.name} ${r.date} ${r.geo} items=$${r.charged.toFixed(2)} ship=$${r.ship.toFixed(2)} "${r.rate}" codes=[${r.codes}] n=${r.n}`);
  console.log(`\n### GROUP B — items charged > $0.00  n=${nonzero.length}`);
  console.log(`    shipped FREE: ${nonzero.filter(isFree).length}   shipped PAID: ${nonzero.filter(r=>!isFree(r)).length}`);
  const byRate={}; for(const r of nonzero) byRate[r.rate]=(byRate[r.rate]||0)+1;
  console.log('    rate mix: '+JSON.stringify(byRate));
  console.log('\n### VERDICT');
  if(zero.length===0) console.log('  INCONCLUSIVE — no $0.00-item sample orders exist to test (Kelly would be the first).');
  else if(zero.filter(isFree).length>0) console.log(`  HYPOTHESIS FALSIFIED — ${zero.filter(isFree).length} fully-comped order(s) DID ship $0.00; the free rate survives a $0.00 subtotal.`);
  else console.log(`  HYPOTHESIS SUPPORTED — 0 of ${zero.length} fully-comped orders shipped free; every one paid.`);
  fs.writeFileSync('verification/tk10836/rate-vs-subtotal.json',JSON.stringify({generated:new Date().toISOString(),rows},null,2));
})();