← back to Secrets Manager

set-categories.py

42 lines

import re,json,sys,urllib.request
env=open('/Users/macstudio3/Projects/secrets-manager/.env').read()
tok=re.search(r'^SHOPIFY_CONTENT_TOKEN=(.+)$',env,re.M).group(1).strip().strip('"').strip("'")
S="designer-laboratory-sandbox.myshopify.com";A="2024-10"
APPLY='--apply' in sys.argv; FORCE='--force' in sys.argv
def api(p,method="GET",body=None):
    d=json.dumps(body).encode() if body else None
    r=urllib.request.Request(f"https://{S}/admin/api/{A}/{p}",data=d,method=method,headers={"X-Shopify-Access-Token":tok,"Content-Type":"application/json"})
    return json.load(urllib.request.urlopen(r,timeout=30))
LABEL={"grasscloth":"grasscloth","faux-leather":"faux leather","velvet":"flocked velvet","cork":"cork",
       "silk":"silk","suede":"suede","metallic":"metallic","linen":"linen","vinyl":"vinyl","mural":"mural"}
MATCH=[("faux-leather",r'faux.?leather|leather'),("velvet",r'flock|velvet'),("suede",r'suede'),("cork",r'\bcork'),
       ("silk",r'silk'),("metallic",r'metallic|mylar|foil'),("linen",r'linen'),("mural",r'mural'),
       ("grasscloth",r'grasscloth|sisal|jute|hemp|raffia|\bnatural'),("vinyl",r'vinyl')]
cols=[]
for kind in ("custom_collections","smart_collections"):
    since=0
    while True:
        d=api(f"{kind}.json?limit=250&since_id={since}&fields=id,handle,title,body_html")[kind]
        if not d: break
        for c in d:
            body=re.sub(r'<[^>]+>','',c.get('body_html') or '').strip()
            cols.append({"id":c['id'],"h":c['handle'],"t":c['title'],"blen":len(body)})
        since=d[-1]['id']
plan=[]
for c in cols:
    if c['blen']<50: continue
    hay=(c['h']+' '+c['t']).lower()
    m=next((mm for mm,rx in MATCH if re.search(rx,hay)),None)
    if m: plan.append((c,LABEL[m]))
print(f"{len(plan)} collections would get custom.category")
if not APPLY:
    for c,lab in plan[:8]: print(f"  {lab:14} <- {c['h']}")
    print(f"  (+{max(0,len(plan)-8)} more)  re-run --apply"); sys.exit(0)
ch=sk=0
for c,lab in plan:
    ex=api(f"collections/{c['id']}/metafields.json?namespace=custom&key=category")['metafields']
    if ex and not FORCE: sk+=1; continue
    r=api(f"collections/{c['id']}/metafields.json","POST",{"metafield":{"namespace":"custom","key":"category","type":"single_line_text_field","value":lab}})
    ch+= 'metafield' in r
print(f"APPLIED — set={ch} skipped={sk} of {len(plan)}")