← back to Roll On Fabric Fix

reverse.py

28 lines

#!/usr/bin/env python3
"""Reverse: re-create the legacy global.unit_of_measure metafield on each product from
data/worklist.json (new id, same namespace/key/value/type). DRY-RUN default; live needs
--apply + ROLLFIX_CONFIRM=YES."""
import os, sys, json, time, urllib.request, urllib.error
HERE = os.path.dirname(os.path.abspath(__file__)); SHOP="designer-laboratory-sandbox.myshopify.com"; API="2024-10"
def token():
    for l in open(os.path.expanduser("~/Projects/secrets-manager/.env")):
        if l.startswith("SHOPIFY_ADMIN_TOKEN="): return l.split("=",1)[1].strip()
    sys.exit("no token")
def main():
    live = "--apply" in sys.argv and os.environ.get("ROLLFIX_CONFIRM")=="YES"
    work = json.load(open(os.path.join(HERE,"data","worklist.json")))
    print(f"=== reverse [{'LIVE' if live else 'DRY-RUN'}] — re-create legacy metafield on {len(work)} ===")
    tok = token() if live else None
    for w in work:
        body={"metafield":{"namespace":"global","key":"unit_of_measure",
              "value":w['legacy_value'],"type":w.get('legacy_type') or "single_line_text_field"}}
        if not live: print(f"WOULD re-create global.unit_of_measure='{w['legacy_value']}' on {w['num']}"); continue
        try:
            req=urllib.request.Request(f"https://{SHOP}/admin/api/{API}/products/{w['num']}/metafields.json",
                data=json.dumps(body).encode(),method="POST",
                headers={"X-Shopify-Access-Token":tok,"Content-Type":"application/json"})
            urllib.request.urlopen(req,timeout=40); print(f"OK re-created on {w['num']}")
        except urllib.error.HTTPError as e: print(f"FAIL {w['num']} HTTP {e.code}")
        time.sleep(0.4)
if __name__=="__main__": main()