152 lines
6.3 KiB
JavaScript
152 lines
6.3 KiB
JavaScript
|
|
// Create the `purchases` + `purchase_lines` PocketBase collections.
|
||
|
|
//
|
||
|
|
// A purchase order is money COMING IN against a machine: parts, repairs, servicing.
|
||
|
|
// Invoices are money coming in against a SITE, so the two are deliberately separate
|
||
|
|
// collections even though both carry a PDF, a supplier and lines.
|
||
|
|
//
|
||
|
|
// The join is the COST CODE on each line: it is the machine code as the client types it
|
||
|
|
// on the PO ("TLB06", or "SS-02"), and it is what allocates the spend to a plant item.
|
||
|
|
// A line whose cost code is not in the register is NOT booked and is reported — never
|
||
|
|
// guessed at a machine, and never booked to nothing without saying so.
|
||
|
|
//
|
||
|
|
// Idempotent: safe to re-run.
|
||
|
|
//
|
||
|
|
// Usage: node scripts/setup-purchase-collections.mjs
|
||
|
|
import PocketBase from "pocketbase";
|
||
|
|
import { readFileSync, existsSync } from "node:fs";
|
||
|
|
import { fileURLToPath } from "node:url";
|
||
|
|
import { dirname, resolve } from "node:path";
|
||
|
|
|
||
|
|
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||
|
|
const ROOT = resolve(__dirname, "..");
|
||
|
|
|
||
|
|
const envPath = resolve(ROOT, ".env.local");
|
||
|
|
if (!existsSync(envPath)) {
|
||
|
|
console.error("✗ .env.local not found. Copy .env.example to .env.local and fill it in.");
|
||
|
|
process.exit(1);
|
||
|
|
}
|
||
|
|
for (const line of readFileSync(envPath, "utf8").split("\n")) {
|
||
|
|
const t = line.trim();
|
||
|
|
if (!t || t.startsWith("#")) continue;
|
||
|
|
const i = t.indexOf("=");
|
||
|
|
if (i > 0) process.env[t.slice(0, i).trim()] = t.slice(i + 1).trim();
|
||
|
|
}
|
||
|
|
|
||
|
|
const PB_URL = process.env.NEXT_PUBLIC_PB_URL;
|
||
|
|
const EMAIL = process.env.PB_ADMIN;
|
||
|
|
const PASS = process.env.PB_PASS;
|
||
|
|
const missing = [];
|
||
|
|
if (!PB_URL) missing.push("NEXT_PUBLIC_PB_URL");
|
||
|
|
if (!EMAIL) missing.push("PB_ADMIN");
|
||
|
|
if (!PASS) missing.push("PB_PASS");
|
||
|
|
if (missing.length) {
|
||
|
|
console.error(`✗ Missing required env: ${missing.join(", ")}`);
|
||
|
|
process.exit(1);
|
||
|
|
}
|
||
|
|
|
||
|
|
const pb = new PocketBase(PB_URL);
|
||
|
|
pb.autoCancellation(false);
|
||
|
|
|
||
|
|
console.log(`→ Connecting to ${PB_URL} as ${EMAIL}`);
|
||
|
|
await pb.collection("_superusers").authWithPassword(EMAIL, PASS);
|
||
|
|
console.log(" ✓ authenticated");
|
||
|
|
|
||
|
|
const reference = await pb.collections.getOne("monthly_income");
|
||
|
|
const RULES = {
|
||
|
|
listRule: reference.listRule,
|
||
|
|
viewRule: reference.viewRule,
|
||
|
|
createRule: reference.createRule ?? null,
|
||
|
|
updateRule: reference.updateRule ?? null,
|
||
|
|
deleteRule: reference.deleteRule ?? null,
|
||
|
|
};
|
||
|
|
console.log(` · rules mirrored from monthly_income (list="${RULES.listRule}")`);
|
||
|
|
|
||
|
|
const assetsId = (await pb.collections.getOne("assets")).id;
|
||
|
|
|
||
|
|
async function ensureCollection(name, fields) {
|
||
|
|
const existing = await pb.collections.getFullList({ filter: `name = "${name}"`, perPage: 1 });
|
||
|
|
if (existing.length) {
|
||
|
|
const have = new Set(existing[0].fields.map((f) => f.name));
|
||
|
|
const absent = fields.filter((f) => !have.has(f.name));
|
||
|
|
if (!absent.length) {
|
||
|
|
console.log(` · ${name} already present (${existing[0].fields.length} fields)`);
|
||
|
|
} else {
|
||
|
|
await updateSchema(name, (cur) => [...cur, ...absent], `added to ${name}: ${absent.map((f) => f.name).join(", ")}`);
|
||
|
|
}
|
||
|
|
return existing[0].id;
|
||
|
|
}
|
||
|
|
const created = await pb.send("/api/collections", {
|
||
|
|
method: "POST",
|
||
|
|
headers: { "Content-Type": "application/json" },
|
||
|
|
body: JSON.stringify({
|
||
|
|
name, type: "base", fields,
|
||
|
|
listRule: RULES.listRule ?? "", viewRule: RULES.viewRule ?? "",
|
||
|
|
createRule: RULES.createRule ?? "", updateRule: RULES.updateRule ?? "", deleteRule: RULES.deleteRule ?? "",
|
||
|
|
}),
|
||
|
|
});
|
||
|
|
console.log(` ✓ created ${name} (${created.id}) with ${created.fields.length} fields`);
|
||
|
|
return created.id;
|
||
|
|
}
|
||
|
|
|
||
|
|
async function updateSchema(collectionName, transform, label) {
|
||
|
|
const coll = await pb.collections.getOne(collectionName);
|
||
|
|
const next = transform([...coll.fields]);
|
||
|
|
if (JSON.stringify(next) === JSON.stringify(coll.fields)) {
|
||
|
|
console.log(` · ${collectionName} schema already current`);
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
await pb.send(`/api/collections/${coll.name}`, {
|
||
|
|
method: "PATCH",
|
||
|
|
headers: { "Content-Type": "application/json" },
|
||
|
|
body: JSON.stringify({ fields: next }),
|
||
|
|
});
|
||
|
|
console.log(` ✓ ${label}`);
|
||
|
|
}
|
||
|
|
|
||
|
|
console.log("\n→ Ensuring collections");
|
||
|
|
|
||
|
|
const purchasesId = await ensureCollection("purchases", [
|
||
|
|
{ name: "po_no", type: "text", required: true },
|
||
|
|
{ name: "supplier", type: "text" },
|
||
|
|
{ name: "supplier_code", type: "text" },
|
||
|
|
{ name: "po_date", type: "text" },
|
||
|
|
{ name: "required_by", type: "text" },
|
||
|
|
{ name: "req_no", type: "text" },
|
||
|
|
{ name: "currency", type: "text" },
|
||
|
|
{ name: "subtotal", type: "number" },
|
||
|
|
{ name: "vat", type: "number" },
|
||
|
|
{ name: "total", type: "number" },
|
||
|
|
// The uploaded PO. Held on the record so a reader can check any figure against the
|
||
|
|
// source without asking for the file again — see AGENTS.md on invoices.
|
||
|
|
{ name: "source_pdf", type: "file", maxSelect: 1, maxSize: 20971520 },
|
||
|
|
{ name: "source_file", type: "text" },
|
||
|
|
// Declared explicitly: PocketBase does NOT add these to a collection created
|
||
|
|
// through the collections API, and the page sorts by `-created`.
|
||
|
|
{ name: "created", type: "date", onCreate: true, presentable: false },
|
||
|
|
{ name: "updated", type: "date", onUpdate: true, presentable: false },
|
||
|
|
]);
|
||
|
|
|
||
|
|
await ensureCollection("purchase_lines", [
|
||
|
|
{ name: "purchase", type: "relation", required: true, collectionId: purchasesId, minSelect: 1, maxSelect: 1, cascadeDelete: true },
|
||
|
|
{ name: "line_no", type: "number", required: true },
|
||
|
|
{ name: "material_code", type: "text" },
|
||
|
|
// Exactly as printed on the PO, hyphenation and all ("SS-02"), so the document can
|
||
|
|
// still be checked line by line.
|
||
|
|
{ name: "cost_code", type: "text" },
|
||
|
|
// Where the spend lands. EMPTY means the cost code was not in the plant register —
|
||
|
|
// that is a real state worth seeing, not a zero and not a guess.
|
||
|
|
{ name: "asset", type: "relation", collectionId: assetsId, minSelect: 1, maxSelect: 1, cascadeDelete: false },
|
||
|
|
{ name: "description", type: "text" },
|
||
|
|
{ name: "qty", type: "number" },
|
||
|
|
{ name: "rate", type: "number" },
|
||
|
|
{ name: "disc_pct", type: "number" },
|
||
|
|
{ name: "vat_pct", type: "number" },
|
||
|
|
{ name: "amount_excl", type: "number" },
|
||
|
|
{ name: "vat", type: "number" },
|
||
|
|
{ name: "total_incl", type: "number" },
|
||
|
|
{ name: "created", type: "date", onCreate: true, presentable: false },
|
||
|
|
{ name: "updated", type: "date", onUpdate: true, presentable: false },
|
||
|
|
]);
|
||
|
|
|
||
|
|
console.log("\n✓ purchases ready. Usage: upload POs from /running/purchases");
|
||
|
|
process.exit(0);
|