← back to Shopify Sample Shipping

create-trade-segment-undo.mjs

41 lines

#!/usr/bin/env node
// TK-11333 — UNDO for create-trade-segment.mjs.
// Deletes the `DW Trade / Designers` segment we created, and recreates the broken
// `interior-designer-res` segment from the recorded snapshot (so state returns exactly).
// DRY-RUN BY DEFAULT; --apply to write.
//
// WARNING: if any free-ship CODE still references the segment (create-freeship-codes.mjs),
// delete the codes FIRST (create-freeship-codes-undo.mjs) — this script will warn and refuse
// to delete a segment that is still in use.
import { query } from './query.mjs';
import fs from 'node:fs';

const APPLY = process.argv.includes('--apply');
const REC = new URL('./verification/trade-segment-created.json', import.meta.url);
if (!fs.existsSync(REC)) { console.error('no verification/trade-segment-created.json — nothing to undo'); process.exit(1); }
const rec = JSON.parse(fs.readFileSync(REC, 'utf8'));
const segIds = rec.segmentIds || (rec.segmentId ? [rec.segmentId] : []);
console.log('=== create-trade-segment UNDO (' + (APPLY ? 'APPLY' : 'DRY-RUN') + ') ===');
console.log('would delete segment(s):', segIds.join(', '));
if (rec.brokenSnapshot) console.log('would recreate broken segment:', rec.brokenSnapshot.name);

// safety: is the segment still referenced by a free-ship code?
try {
  const nodes = (await query(`{codeDiscountNodes(first:100){nodes{codeDiscount{__typename ... on DiscountCodeFreeShipping{title customerSelection{__typename ... on DiscountCustomerSegments{segments{id}}}}}}}}`)).codeDiscountNodes.nodes;
  const inUse = nodes.some(n => n.codeDiscount?.customerSelection?.segments?.some(s => segIds.includes(s.id)));
  if (inUse) { console.error('\nREFUSING: segment still referenced by a free-ship code. Run create-freeship-codes-undo.mjs --apply first.'); process.exit(2); }
} catch (e) { console.log('(in-use check skipped:', e.message, ')'); }

if (!APPLY) { console.log('\nDry-run only. Re-run with --apply.'); process.exit(0); }

for (const id of segIds) {
  const del = (await query(`mutation($id:ID!){segmentDelete(id:$id){deletedSegmentId userErrors{field message}}}`, { id })).segmentDelete;
  console.log('deleted segment:', del.deletedSegmentId || JSON.stringify(del.userErrors));
}
if (rec.brokenSnapshot) {
  const r = (await query(`mutation($name:String!,$q:String!){segmentCreate(name:$name,query:$q){segment{id} userErrors{field message}}}`,
    { name: rec.brokenSnapshot.name, q: rec.brokenSnapshot.query })).segmentCreate;
  console.log('recreated broken segment:', r.segment?.id || JSON.stringify(r.userErrors));
}
console.log('undo complete.');