79 lines
2.6 KiB
JavaScript
79 lines
2.6 KiB
JavaScript
/// <reference path="../pb_data/types.d.ts" />
|
|
//
|
|
// M3 — Promote financial fields out of the `financial` JSON blob into real
|
|
// numeric columns on `repairOrders`. This lets the FinancialDashboard run
|
|
// server-side `sum()` aggregations instead of pulling every completed RO to
|
|
// the client. It also makes the values type-safe and queryable.
|
|
//
|
|
// New columns: grossTotal, grossCost, warrTotal, warrCost, shopCharge.
|
|
// (shopCharge overlaps conceptually with the existing `shopCharges` column —
|
|
// see the migration doc. Here we add `shopCharge` as a separate field to
|
|
// match the financial-blob key the frontend currently writes. If you prefer
|
|
// to consolidate, point the frontend at `shopCharges` instead and skip this
|
|
// field.)
|
|
//
|
|
migrate(
|
|
(db) => {
|
|
const col = db.findCollectionByNameOrId('repairOrders');
|
|
if (!col) {
|
|
console.warn('[M3] repairOrders collection not found — skipping');
|
|
return;
|
|
}
|
|
|
|
for (const name of ['grossTotal', 'grossCost', 'warrTotal', 'warrCost', 'shopCharge']) {
|
|
if (!col.fields.find((f) => f.name === name)) {
|
|
col.fields.push(new NumberField({ name, required: false, min: 0 }));
|
|
}
|
|
}
|
|
db.save(col);
|
|
console.log('[M3] added financial numeric fields');
|
|
|
|
const records = Array.from(db.findRecordsByFilter(
|
|
"repairOrders",
|
|
"1=1",
|
|
"id",
|
|
500
|
|
));
|
|
let backfilled = 0;
|
|
for (const rec of records) {
|
|
let fin = {};
|
|
try {
|
|
const raw = rec.get('financial');
|
|
if (typeof raw === 'string' && raw.trim()) {
|
|
fin = JSON.parse(raw);
|
|
} else if (raw && typeof raw === 'object') {
|
|
fin = raw;
|
|
}
|
|
} catch { /* ignore corrupt blobs */ }
|
|
|
|
let changed = false;
|
|
for (const [srcKey, dstKey] of [
|
|
['grossTotal', 'grossTotal'],
|
|
['grossCost', 'grossCost'],
|
|
['warrTotal', 'warrTotal'],
|
|
['warrCost', 'warrCost'],
|
|
['shopCharge', 'shopCharge'],
|
|
]) {
|
|
const v = Number(fin && fin[srcKey]);
|
|
if (!Number.isNaN(v) && rec.get(dstKey) == null) {
|
|
rec.set(dstKey, v || 0);
|
|
changed = true;
|
|
}
|
|
}
|
|
if (changed) {
|
|
db.saveRecord(rec);
|
|
backfilled++;
|
|
}
|
|
}
|
|
console.log(`[M3] backfilled ${backfilled} records`);
|
|
},
|
|
(db) => {
|
|
const col = db.findCollectionByNameOrId('repairOrders');
|
|
if (!col) return;
|
|
for (const name of ['grossTotal', 'grossCost', 'warrTotal', 'warrCost', 'shopCharge']) {
|
|
const idx = col.fields.findIndex((f) => f.name === name);
|
|
if (idx >= 0) col.fields.splice(idx, 1);
|
|
}
|
|
db.save(col);
|
|
}
|
|
); |