← back to Filemaker Mcp

scripts/watch-next-multisku.mjs

54 lines

// Watch for the next MULTI-SKU order the sync processes (order_number > BASELINE
// AND >1 FileMaker record), then print its per-SKU invoice breakdown and exit.
// Single-SKU orders are noted and skipped. Read-only.
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 = 32548;
const MAX_POLLS = 360, INTERVAL_MS = 30_000; // ~3 hours
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const seen = new Set();

function newOrders() {
  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 && !seen.has(d.orderNumber)) out.push(d); } catch {}
  }
  return out;
}

async function records(po) {
  const { records } = await findRecords('invoice', HDR, [{ 'Cust PO': '==' + po }],
    { limit: 60, sort: [{ fieldName: 'Invoice', sortOrder: 'ascend' }] }).catch(() => ({ records: [] }));
  return records.map((r) => r.fieldData);
}

for (let i = 0; i < MAX_POLLS; i++) {
  for (const o of newOrders()) {
    seen.add(o.orderNumber);
    const recs = await records(o.orderNumber);
    if (recs.length <= 1) { console.log(`(skip single-SKU order #${o.orderNumber} — ${recs.length} record)`); continue; }
    console.log(`\n🆕 MULTI-SKU ORDER #${o.orderNumber} · ${recs[0]['SOLD NAME']||''} · ${recs.length} records`);
    let sum = 0;
    recs.forEach((f, idx) => {
      const paid = Number(f['PAID ON ACCOUNT'] || 0), net = Number(f['NET 1(1)'] || 0); sum += paid;
      console.log(`   ${idx === 0 ? 'FIRST' : ' sku '} #${f['Invoice']}  NET ${String(net).padStart(9)}  PAID ${String(paid).padStart(9)}  ${String(f['DETAIL 1(1)']||'').slice(0,34)}`);
    });
    const restZero = recs.slice(1).every((f) => Number(f['PAID ON ACCOUNT'] || 0) === 0);
    console.log(`   → $${sum.toFixed(2)} total on FIRST record only; other ${recs.length-1} at $0: ${restZero ? 'YES ✓ (new code working live)' : 'NO ✗'}`);
    console.log('\n(watcher done — first real multi-SKU order observed)');
    process.exit(0);
  }
  await sleep(INTERVAL_MS);
}
console.log(`No multi-SKU order (> #${BASELINE}) within the watch window. Re-arm to keep watching.`);