WFDASH-WEBAPP/scripts/backfill-po-items.mjs

52 lines
1.8 KiB
JavaScript
Raw Normal View History

import PocketBase from "pocketbase";
const PB_URL = "https://pocketbase-gnqc88suy8fqk6wyryjjdpvl.169.239.180.130.sslip.io";
const PB_ADMIN_EMAIL = "david.els1@outlook.com";
const PB_ADMIN_PASSWORD = "1234567890";
const PO_COLLECTION = "purchase_orders";
const ORDER_ITEMS_COLLECTION = "order_items";
const pb = new PocketBase(PB_URL);
await pb.collection("_superusers").authWithPassword(PB_ADMIN_EMAIL, PB_ADMIN_PASSWORD);
const pos = await pb.collection(PO_COLLECTION).getFullList({ fields: "id,po_number,order_item" });
console.log("POs found:", pos.length);
let updated = 0;
let skipped = 0;
for (const po of pos) {
const linked = await pb.collection(ORDER_ITEMS_COLLECTION).getFullList({
filter: `purchase_order = "${po.id}"`,
fields: "id",
});
// Verify each linked item actually exists in PB (some legacy PO
// rows reference order_items that have since been deleted; PB
// rejects the relation write with validation_missing_rel_records
// if we try to set the array to include a missing id). Filter
// out ghosts before writing.
const ids = linked.map((it) => it.id);
const verified = [];
for (const id of ids) {
try {
await pb.collection(ORDER_ITEMS_COLLECTION).getOne(id, { fields: "id" });
verified.push(id);
} catch {
console.log(" skipping ghost item ref", id, "on", po.po_number);
}
}
const current = Array.isArray(po.order_item) ? [...po.order_item].sort() : [];
const wanted = [...verified].sort();
const same =
current.length === wanted.length &&
current.every((v, i) => v === wanted[i]);
if (same) {
skipped++;
continue;
}
await pb.collection(PO_COLLECTION).update(po.id, { order_item: verified });
updated++;
console.log(" backfilled", po.po_number, "<-", verified.length, "items");
}
console.log("done. updated:", updated, "skipped:", skipped);