DEV Community

Murabyte
Murabyte

Posted on

Validate purchase, sale and allocation CSVs in JavaScript: 5 checks

Disclosure: I make VendorTrace CSV at Murabyte, which is mentioned at the end.

If you reconcile purchases against sales from CSV exports, bad rows hide in the joins. Here is a short JavaScript validator for three files: purchases, sales and allocation links. It runs in the browser or Node and catches the usual problems before you trust a report.

The data

  • purchases: purchase_id, vendor, sku, qty
  • sales: sale_id, customer, sku, qty
  • allocations: alloc_id, purchase_id, sale_id, qty

The checks

function validate(purchases, sales, allocs) {
  const errors = [];
  const P = new Map(purchases.map(p => [p.purchase_id, p]));
  const S = new Map(sales.map(s => [s.sale_id, s]));
  const seen = new Set();
  const usedP = {}, usedS = {};

  for (const a of allocs) {
    if (seen.has(a.alloc_id)) errors.push(['duplicate alloc', a.alloc_id]);
    seen.add(a.alloc_id);
    const p = P.get(a.purchase_id), s = S.get(a.sale_id);
    if (!p || !s) { errors.push(['unknown link', a.alloc_id]); continue; }
    if (p.sku !== s.sku) errors.push(['sku mismatch', a.alloc_id]);
    const q = Number(a.qty);
    if (!Number.isInteger(q) || q <= 0) { errors.push(['bad qty', a.alloc_id]); continue; }
    usedP[p.purchase_id] = (usedP[p.purchase_id] || 0) + q;
    usedS[s.sale_id] = (usedS[s.sale_id] || 0) + q;
  }
  for (const p of purchases) if ((usedP[p.purchase_id] || 0) > Number(p.qty)) errors.push(['over-allocated purchase', p.purchase_id]);
  for (const s of sales) if ((usedS[s.sale_id] || 0) > Number(s.qty)) errors.push(['over-allocated sale', s.sale_id]);
  return errors;
}
Enter fullscreen mode Exit fullscreen mode

Why SKU matching alone is not enough

If two vendors supplied the same SKU, a match by SKU cannot say whose stock was sold. You need explicit allocation links, and this validator only checks the links you supply.

Two more habits

  1. Read CSV text as UTF-8 and keep IDs as strings, so leading zeros survive.
  2. Escape cell values that start with =, +, - or @ when you export, so spreadsheets do not run them as formulas.

If you want a finished tool

VendorTrace CSV is a local browser app I make at Murabyte. It loads the three CSV files, shows accepted vendor-to-customer allocations, flags exceptions like the ones above, and reports unused purchase quantity and uncovered sales. It makes no network requests. It is not a live QuickBooks connector and needs explicit allocation links. $9: https://murabyte.gumroad.com/l/xcbvw

javascript #csv #inventory #webdev #murabyte

Written with AI assistance and reviewed by Murabyte.

Top comments (0)