← back to Jf Fabrics Recrawl

dwjj-mfr-backfill/write-metafields.py

32 lines

#!/usr/bin/env python3
"""Backfill global.Match (+ optional enrichment) onto DWJJ products from staged JF specs.
DRY-RUN by default. Pass --live to actually write. Pass --test=1 to write only the first product."""
import json,subprocess,sys,os
DRY = '--live' not in sys.argv
TEST = next((int(a.split('=')[1]) for a in sys.argv if a.startswith('--test=')), None)
os.chdir(os.path.expanduser('~/Projects/Designer-Wallcoverings'))
TOKEN=subprocess.check_output("grep -E '^SHOPIFY_ADMIN_TOKEN=' .env|head -1|cut -d= -f2|tr -d '\"'",shell=True,text=True).strip()
DOMAIN="designer-laboratory-sandbox.myshopify.com"
def gql(q,v=None):
    body={"query":q}; body.update({"variables":v} if v else {})
    p=subprocess.run(["curl","-s","-X","POST",f"https://{DOMAIN}/admin/api/2024-10/graphql.json","-H",f"X-Shopify-Access-Token: {TOKEN}","-H","Content-Type: application/json","-d",json.dumps(body)],capture_output=True,text=True)
    return json.loads(p.stdout)
SPECS=os.path.expanduser('~/Projects/jf-fabrics-recrawl/dwjj-mfr-backfill/dwjj_specs.jsonl')
with open(SPECS, encoding='utf-8') as fh:
    recs=[json.loads(l) for l in fh if l.strip()]
targets=[r for r in recs if r.get('ok') and r.get('match')]
if TEST: targets=targets[:TEST]
M='''mutation($mf:[MetafieldsSetInput!]!){ metafieldsSet(metafields:$mf){ metafields{ key namespace } userErrors{ field message } } }'''
print(f"{'DRY-RUN' if DRY else 'LIVE'} — {len(targets)} products to write global.Match")
errs=0
for r in targets:
    val=", ".join(p.strip() for p in r['match'].split(",") if p.strip())
    if DRY:
        print(f"  {r['base']:<10} Match <- {val}"); continue
    v={"mf":[{"ownerId":r['gid'],"namespace":"global","key":"Match","type":"single_line_text_field","value":val}]}
    d=gql(M,v)
    ue=d.get('data',{}).get('metafieldsSet',{}).get('userErrors',[]) if 'data' in d else [{'message':json.dumps(d)[:120]}]
    if ue: errs+=1; print(f"  ERR {r['base']}: {ue}")
    else: print(f"  OK  {r['base']} Match={val}")
print(f"done. errors={errs}" if not DRY else "(dry-run, nothing written)")