← back to Filemaker Mcp

scripts/watch-next-order.mjs

54 lines

// Watch for the NEXT Shopify order the sync processes (order_number > BASELINE),
// then print its FileMaker per-SKU invoice breakdown and exit. Polls the sync
// ledger; on a hit, queries FileMaker (read-only). Auto-exits after the cap.
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import { findRecords } from '../src/fm-client.js';
const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
for (const l of readFileSync(join(ROOT, '.env'), 'utf8').split('\n')) {
  const m = l.match(/^([A-Z0-9_]+)=(.*)$/); if (m && !process.env[m[1]]) process.env[m[1]] = m[2];
}
const HDR = 'Invoice to Client Copy';
const LEDGER = join(ROOT, 'data', 'sync-ledger.jsonl');
const BASELINE = 32547;
const MAX_POLLS = 240, INTERVAL_MS = 30_000; // ~2 hours

const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

function newProcessedOrders() {
  let lines = [];
  try { lines = readFileSync(LEDGER, 'utf8').trim().split('\n'); } catch { return []; }
  const out = [];
  for (const l of lines) {
    try { const d = JSON.parse(l); if (d.action === 'processed' && Number(d.orderNumber) > BASELINE) out.push(d); } catch {}
  }
  return out;
}

async function report(order) {
  const { records } = await findRecords('invoice', HDR, [{ 'Cust PO': '==' + order.orderNumber }],
    { limit: 60, sort: [{ fieldName: 'Invoice', sortOrder: 'ascend' }] }).catch(() => ({ records: [] }));
  console.log(`\n🆕 NEW ORDER PROCESSED — #${order.orderNumber} (${order.company || ''}) at ${order.ts?.slice(0,19)}`);
  console.log(`   sync reported: first invoice ${order.invoiceNumber} · $${order.invoiceTotal} · ${order.invoiceCount ?? '?'} record(s)`);
  console.log(`   FileMaker records (Cust PO ${order.orderNumber}):`);
  let sum = 0;
  records.forEach((r, i) => {
    const f = r.fieldData, paid = Number(f['PAID ON ACCOUNT'] || 0), net = Number(f['NET 1(1)'] || 0);
    sum += paid;
    console.log(`     ${i === 0 ? 'FIRST ' : 'sku   '} #${f['Invoice']}  NET ${String(net).padStart(8)}  PAID ${String(paid).padStart(8)}  ${String(f['DETAIL 1(1)']||'').slice(0,34)}`);
  });
  console.log(`   → sum of PAID across the ${records.length} record(s) = $${sum.toFixed(2)} (should equal the order total; money on the FIRST only)`);
}

for (let i = 0; i < MAX_POLLS; i++) {
  const hits = newProcessedOrders();
  if (hits.length) {
    for (const o of hits) await report(o);
    console.log('\n(watcher done — first real per-SKU order observed)');
    process.exit(0);
  }
  await sleep(INTERVAL_MS);
}
console.log(`No new order (> #${BASELINE}) processed within the watch window. Re-arm if you still want to catch the first one.`);