← back to Filemaker Mcp
grs-mfr-restore.mjs
26 lines
#!/usr/bin/env node
// Reverse a GRS mfr apply from its restore JSONL: put back old dwc/custom metafields + mirror column.
import fs from 'fs';
import https from 'https';
import { execSync } from 'child_process';
import path from 'path';
for (const l of fs.readFileSync(path.join(process.env.HOME, 'Projects/secrets-manager/.env'), 'utf8').split('\n')) { const m = l.match(/^([A-Z_][A-Z0-9_]*)=(.*)$/); if (m && !(m[1] in process.env)) process.env[m[1]] = m[2]; }
const TOKEN = process.env.SHOPIFY_ADMIN_TOKEN, DOMAIN = 'designer-laboratory-sandbox.myshopify.com';
const PSQL = 'psql -h /tmp -d dw_unified -tAc';
const FILE = process.argv[2]; if (!FILE) { console.error('usage: node grs-mfr-restore.mjs <RESTORE.jsonl>'); process.exit(1); }
function gql(query, variables) { return new Promise((res, rej) => { const b = JSON.stringify({ query, variables }); const r = https.request({ host: DOMAIN, path: '/admin/api/2024-10/graphql.json', method: 'POST', headers: { 'X-Shopify-Access-Token': TOKEN, 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(b) } }, x => { let d = ''; x.on('data', c => d += c); x.on('end', () => { try { res(JSON.parse(d)); } catch (e) { rej(new Error(d)); } }); }); r.on('error', rej); r.write(b); r.end(); }); }
const sqlesc = s => String(s ?? '').replace(/'/g, "''");
const lines = fs.readFileSync(FILE, 'utf8').split('\n').filter(Boolean).map(JSON.parse);
let n = 0;
for (const r of lines) {
const gid = `gid://shopify/Product/${r.product_id}`;
await gql(`mutation($mf:[MetafieldsSetInput!]!){ metafieldsSet(metafields:$mf){ userErrors{ message } } }`,
{ mf: [
{ ownerId: gid, namespace: 'dwc', key: 'manufacturer_sku', type: 'single_line_text_field', value: r.old_dwc || '' },
{ ownerId: gid, namespace: 'custom', key: 'manufacturer_sku', type: 'single_line_text_field', value: r.old_custom || '' },
] });
execSync(`${PSQL} "UPDATE shopify_products SET mfr_sku='${sqlesc(r.old_mirror)}' WHERE regexp_replace(shopify_id,'.*/','')='${r.product_id}'"`);
n++;
}
console.log(`restored ${n} products from ${FILE}`);