← back to Flock Fix Viewer

apply-theme-sqft.mjs

26 lines

// Adds guarded "Sq Ft S/R" + "Sq Ft D/R" rows to the product spec table.
// Run: node apply-theme-sqft.mjs   (idempotent; fetches fresh, only edits if not already applied)
import fs from 'fs';
const SHOP='designer-laboratory-sandbox.myshopify.com';
const MAIN='145121607731';
const KEY='snippets/product-description-meta.liquid';
const TOKEN=(fs.readFileSync(new URL('.env', 'file:///Users/macstudio3/Projects/secrets-manager/').pathname,'utf8')
  .split('\n').find(l=>l.startsWith('SHOPIFY_THEME_TOKEN='))||'').split('=').slice(1).join('=').replace(/["']/g,'').trim();
const API=`https://${SHOP}/admin/api/2024-10`;
const H={'X-Shopify-Access-Token':TOKEN,'Content-Type':'application/json'};

const anchor1="{% assign drlen = product.metafields.global.double_roll_length.value %}";
const add1=anchor1+"\n{% assign sqftsr = product.metafields.global.sqft_single_roll.value | default: product.metafields.custom.sqft_single_roll.value %}\n{% assign sqftdr = product.metafields.global.sqft_double_roll.value | default: product.metafields.custom.sqft_double_roll.value %}";
const anchor2="{% elsif len != blank %}<div class=\"dw-spec-row\"><span class=\"dw-spec-label\">{% if product.vendor == 'Designtex' %}Bolt size{% else %}Length{% endif %}</span><span class=\"dw-spec-value\">{{ len }}</span></div>{% endif %}";
const rows="\n  {% if sqftsr != blank %}<div class=\"dw-spec-row\"><span class=\"dw-spec-label\">Sq Ft S/R</span><span class=\"dw-spec-value\">{{ sqftsr }}</span></div>{% endif %}\n  {% if sqftdr != blank %}<div class=\"dw-spec-row\"><span class=\"dw-spec-label\">Sq Ft D/R</span><span class=\"dw-spec-value\">{{ sqftdr }}</span></div>{% endif %}";

const r=await (await fetch(`${API}/themes/${MAIN}/assets.json?asset%5Bkey%5D=${encodeURIComponent(KEY)}`,{headers:H})).json();
let body=r.asset.value;
fs.writeFileSync(new URL('./theme-backup/product-description-meta.PRE-SQFT.liquid',import.meta.url), body);
if(body.includes('Sq Ft S/R')){console.log('Already applied — nothing to do.');process.exit(0);}
if(body.split(anchor1).length!==2){console.error('anchor1 not found uniquely — aborting');process.exit(1);}
if(body.split(anchor2).length!==2){console.error('anchor2 not found uniquely — aborting');process.exit(1);}
body=body.replace(anchor1,add1).replace(anchor2,anchor2+rows);
const put=await (await fetch(`${API}/themes/${MAIN}/assets.json`,{method:'PUT',headers:H,body:JSON.stringify({asset:{key:KEY,value:body}})})).json();
console.log(put.asset?('OK — updated '+put.asset.key+' ('+put.asset.size+' bytes). Reload a flock product page to see Sq Ft S/R + D/R.'):('ERROR '+JSON.stringify(put)));