@datarails-ai/dr-appspace-cli 0.12.62 → 0.12.63
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +475 -24
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -13,7 +13,7 @@ import { fileURLToPath as fileURLToPath6 } from "url";
|
|
|
13
13
|
// package.json
|
|
14
14
|
var package_default = {
|
|
15
15
|
name: "@datarails-ai/dr-appspace-cli",
|
|
16
|
-
version: "0.12.
|
|
16
|
+
version: "0.12.63",
|
|
17
17
|
description: "Datarails App Space CLI \u2014 build, try, push and publish App Space apps",
|
|
18
18
|
type: "module",
|
|
19
19
|
engines: {
|
|
@@ -57,7 +57,7 @@ var package_default = {
|
|
|
57
57
|
};
|
|
58
58
|
|
|
59
59
|
// src/buildInfo.ts
|
|
60
|
-
var BUILD_TIME = "2026-11-02T15:
|
|
60
|
+
var BUILD_TIME = "2026-11-02T15:28:06.153Z";
|
|
61
61
|
function formatBuildTime(iso) {
|
|
62
62
|
if (iso === "") return "";
|
|
63
63
|
const d = new Date(iso);
|
|
@@ -22421,6 +22421,10 @@ function metricsTransport(client) {
|
|
|
22421
22421
|
claims: () => client.claims === void 0 ? null : client.claims()
|
|
22422
22422
|
};
|
|
22423
22423
|
}
|
|
22424
|
+
function modelPlanOf(contract) {
|
|
22425
|
+
const plan = obj2(obj2(obj2(obj2(contract)["data"])["model"])["plan"]);
|
|
22426
|
+
return Object.keys(plan).length === 0 ? null : plan;
|
|
22427
|
+
}
|
|
22424
22428
|
function declaredMetrics(contract) {
|
|
22425
22429
|
const data = obj2(obj2(contract)["data"]);
|
|
22426
22430
|
const metrics = obj2(data["metrics"]);
|
|
@@ -22486,7 +22490,13 @@ function catalogRow(raw) {
|
|
|
22486
22490
|
description: typeof raw["description"] === "string" ? raw["description"] : null,
|
|
22487
22491
|
category: typeof raw["category"] === "string" ? raw["category"] : isObj3(raw["category"]) && typeof raw["category"]["name"] === "string" ? raw["category"]["name"] : null,
|
|
22488
22492
|
status: typeof status["status"] === "string" ? status["status"].toUpperCase() : null,
|
|
22489
|
-
created_at: typeof raw["created_at"] === "string" ? raw["created_at"] : null
|
|
22493
|
+
created_at: typeof raw["created_at"] === "string" ? raw["created_at"] : null,
|
|
22494
|
+
calculations: (Array.isArray(raw["calculations"]) ? raw["calculations"] : []).filter(isObj3).flatMap((one) => {
|
|
22495
|
+
const formula = one["presented_formula"];
|
|
22496
|
+
if (typeof formula !== "string" || formula === "") return [];
|
|
22497
|
+
const text4 = (value) => typeof value === "string" ? value : "";
|
|
22498
|
+
return [{ scenario: text4(one["scenario"]), scenario_cycle: text4(one["scenario_cycle"]), planning_scenario: text4(one["planning_scenario"]), formula }];
|
|
22499
|
+
})
|
|
22490
22500
|
};
|
|
22491
22501
|
}
|
|
22492
22502
|
function authTableRow(raw) {
|
|
@@ -22556,12 +22566,13 @@ function rollupOf(def) {
|
|
|
22556
22566
|
}
|
|
22557
22567
|
var OPERAND_RE = /'([^']*)'|\[([^[\]]*)\]/g;
|
|
22558
22568
|
var MARK = "";
|
|
22559
|
-
function calcSkeleton(formula, idOf4) {
|
|
22569
|
+
function calcSkeleton(formula, idOf4, self = null) {
|
|
22560
22570
|
let missing = false;
|
|
22561
22571
|
const ids = /* @__PURE__ */ new Set();
|
|
22562
22572
|
const marked2 = formula.replace(OPERAND_RE, (_m, quoted3, bracketed) => {
|
|
22563
22573
|
const name = quoted3 ?? bracketed ?? "";
|
|
22564
22574
|
if (SYSTEM_VARIABLES.includes(name)) return `${MARK}${name.toLowerCase()}${MARK}`;
|
|
22575
|
+
if (self !== null && name === self) return `${MARK}self${MARK}`;
|
|
22565
22576
|
const id = idOf4(name);
|
|
22566
22577
|
if (id === null) {
|
|
22567
22578
|
missing = true;
|
|
@@ -22574,9 +22585,30 @@ function calcSkeleton(formula, idOf4) {
|
|
|
22574
22585
|
const skeleton = marked2.split(MARK).map((part, index) => index % 2 === 1 ? part : part.toLowerCase().replace(/\s+/g, "")).join("");
|
|
22575
22586
|
return { skeleton, ids: [...ids].sort((a, b) => a - b) };
|
|
22576
22587
|
}
|
|
22577
|
-
function calcReuseKey(formula, idOf4) {
|
|
22588
|
+
function calcReuseKey(formula, idOf4, calculations = [], self = null) {
|
|
22578
22589
|
const shape = calcSkeleton(formula, idOf4);
|
|
22579
|
-
|
|
22590
|
+
if (shape === null) return null;
|
|
22591
|
+
const parts = [];
|
|
22592
|
+
const ids = new Set(shape.ids);
|
|
22593
|
+
for (const one of calculations) {
|
|
22594
|
+
const inner = calcSkeleton(one.formula, idOf4, self);
|
|
22595
|
+
if (inner === null) return null;
|
|
22596
|
+
for (const id of inner.ids) ids.add(id);
|
|
22597
|
+
parts.push(`${one.scenario}|${one.scenario_cycle}|${one.planning_scenario}=${inner.skeleton}`);
|
|
22598
|
+
}
|
|
22599
|
+
const base = `calc:${shape.skeleton}|${shape.ids.join(",")}`;
|
|
22600
|
+
return parts.length === 0 ? base : `${base}|calculations:${JSON.stringify(parts.sort())}|${[...ids].sort((a, b) => a - b).join(",")}`;
|
|
22601
|
+
}
|
|
22602
|
+
function driverReuseKey(def) {
|
|
22603
|
+
return `driver:${JSON.stringify([def.unit, def.additive, def.min, def.max])}`;
|
|
22604
|
+
}
|
|
22605
|
+
function driverDefinitionOf(decl) {
|
|
22606
|
+
return {
|
|
22607
|
+
unit: typeof decl.unit === "string" ? decl.unit : "",
|
|
22608
|
+
additive: decl.additive !== false,
|
|
22609
|
+
min: typeof decl.min === "number" ? decl.min : null,
|
|
22610
|
+
max: typeof decl.max === "number" ? decl.max : null
|
|
22611
|
+
};
|
|
22580
22612
|
}
|
|
22581
22613
|
function rowReuseKey(row, byName3) {
|
|
22582
22614
|
if (row.kind === "BASE") {
|
|
@@ -22591,7 +22623,7 @@ function rowReuseKey(row, byName3) {
|
|
|
22591
22623
|
filters: row.filters
|
|
22592
22624
|
});
|
|
22593
22625
|
}
|
|
22594
|
-
if (row.kind === "CALC" && row.formula !== null) return calcReuseKey(row.formula, (name) => byName3.get(name)?.id ?? null);
|
|
22626
|
+
if (row.kind === "CALC" && row.formula !== null) return calcReuseKey(row.formula, (name) => byName3.get(name)?.id ?? null, row.calculations, row.name);
|
|
22595
22627
|
return null;
|
|
22596
22628
|
}
|
|
22597
22629
|
var METRIC_CREATED_FOOTER = "Created by App Space for the app";
|
|
@@ -22651,9 +22683,32 @@ function dependencyOrder(decls) {
|
|
|
22651
22683
|
}
|
|
22652
22684
|
function operandsOf(decls, key) {
|
|
22653
22685
|
const decl = decls[key];
|
|
22654
|
-
if (decl === void 0
|
|
22686
|
+
if (decl === void 0) return [];
|
|
22687
|
+
if (decl.kind === "driver") return baselineRefsOf(decl);
|
|
22688
|
+
if (decl.kind !== "calc" || typeof decl.formula !== "string") return [];
|
|
22655
22689
|
const found = metricFormulaProblems(decl.formula, Object.keys(decls));
|
|
22656
|
-
|
|
22690
|
+
const out = new Set(found.operands);
|
|
22691
|
+
for (const formula of Object.values(decl.calculations ?? {})) {
|
|
22692
|
+
const inner = metricFormulaProblems(formula, Object.keys(decls), { pinned: true, self: key });
|
|
22693
|
+
for (const one of inner.operands) if (one !== key) out.add(one);
|
|
22694
|
+
}
|
|
22695
|
+
return [...out].sort();
|
|
22696
|
+
}
|
|
22697
|
+
function baselineRefsOf(decl) {
|
|
22698
|
+
const from = decl.baseline_from;
|
|
22699
|
+
if (from === void 0) return [];
|
|
22700
|
+
const refs = from.rule === "l12m_ratio" ? from.ratio ?? [] : [from.metric ?? ""];
|
|
22701
|
+
return refs.filter((one) => /^@[a-z][a-z0-9_]*$/.test(one)).map((one) => one.slice(1));
|
|
22702
|
+
}
|
|
22703
|
+
function baselineSpecOf(decl) {
|
|
22704
|
+
if (decl.baseline_from !== void 0 && typeof decl.baseline_from.rule === "string") return canonicalJson(decl.baseline_from);
|
|
22705
|
+
if (typeof decl.baseline === "number") return canonicalJson({ baseline: decl.baseline });
|
|
22706
|
+
return null;
|
|
22707
|
+
}
|
|
22708
|
+
function canonicalJson(value) {
|
|
22709
|
+
if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
|
|
22710
|
+
if (isObj3(value)) return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonicalJson(value[key])}`).join(",")}}`;
|
|
22711
|
+
return JSON.stringify(value);
|
|
22657
22712
|
}
|
|
22658
22713
|
function credentialOf(claims) {
|
|
22659
22714
|
const scopes = claims === null ? void 0 : claims["scopes"];
|
|
@@ -22693,6 +22748,52 @@ function describeBase(decl, tableName) {
|
|
|
22693
22748
|
const filters = (decl.filters ?? []).map((one) => `${one.field} ${one.exclude === true ? "not in" : "in"} [${one.values.map(String).join(", ")}]`).join("; ");
|
|
22694
22749
|
return `BASE on "${tableName}" (${decl.value ?? "?"} by ${decl.date ?? "?"}, ${(decl.aggregate ?? "?").toUpperCase()}${decl.time_aggregation === void 0 ? "" : `, ${decl.time_aggregation.toUpperCase()} over time`})${filters === "" ? "" : ` where ${filters}`}`;
|
|
22695
22750
|
}
|
|
22751
|
+
function calculationsWire(decl, key, names) {
|
|
22752
|
+
const withSelf = { ...names, [key]: names[key] ?? decl.name };
|
|
22753
|
+
return Object.keys(decl.calculations ?? {}).sort().map((scenario) => ({
|
|
22754
|
+
scenario,
|
|
22755
|
+
scenario_cycle: "",
|
|
22756
|
+
planning_scenario: "",
|
|
22757
|
+
formula: wireFormula((decl.calculations ?? {})[scenario], withSelf, { pinned: true })
|
|
22758
|
+
}));
|
|
22759
|
+
}
|
|
22760
|
+
function describeCalc(wire, calculations) {
|
|
22761
|
+
const more = calculations.map((one) => `; ${one.scenario}: ${one.formula}`).join("");
|
|
22762
|
+
return `CALC ${wire}${more}`;
|
|
22763
|
+
}
|
|
22764
|
+
function describeDriver(def) {
|
|
22765
|
+
const bound = (value) => value === null ? "none" : String(value);
|
|
22766
|
+
return `DRIVER (unit ${def.unit === "" ? "none" : `"${def.unit}"`}, ${def.additive ? "additive" : "not additive"}, min ${bound(def.min)}, max ${bound(def.max)})`;
|
|
22767
|
+
}
|
|
22768
|
+
function baselineNote(decl) {
|
|
22769
|
+
if (typeof decl.baseline === "number") return `starting value ${String(decl.baseline)} (typed)`;
|
|
22770
|
+
const from = decl.baseline_from;
|
|
22771
|
+
if (from === void 0) return "no starting value";
|
|
22772
|
+
const refs = baselineRefsOf(decl).map((one) => `@${one}`).join(" / ");
|
|
22773
|
+
return `starting value read by ${from.rule} from ${refs} after it is bound`;
|
|
22774
|
+
}
|
|
22775
|
+
var DRIVER_GATES = "whether this company has the Planning product and scenario_bound_calculations on, and whether you are an admin or contributor (a driver needs all three)";
|
|
22776
|
+
var DEFAULT_DRIVER_CONTEXT = { scenario: "Actuals", scenario_cycle: "", planning_scenario: "" };
|
|
22777
|
+
async function readDriverRow(t, id) {
|
|
22778
|
+
const query = `scenario=Actuals&scenario_cycle=&planning_scenario=`;
|
|
22779
|
+
let answer;
|
|
22780
|
+
try {
|
|
22781
|
+
answer = await t.call("GET", `${t.host}/api/insights/metrics/${String(id)}/driver?${query}`);
|
|
22782
|
+
} catch (err) {
|
|
22783
|
+
return firstLine(err);
|
|
22784
|
+
}
|
|
22785
|
+
if (answer.status === 404 && isObj3(answer.body) && Object.keys(answer.body).length === 0) return null;
|
|
22786
|
+
if (answer.status !== 200 || !isObj3(answer.body)) return `HTTP ${String(answer.status)}${sentenceOf(answer.body) === "" ? "" : `: ${sentenceOf(answer.body)}`}`;
|
|
22787
|
+
const row = decodeEntities2(answer.body);
|
|
22788
|
+
const num = (value) => typeof value === "number" && Number.isFinite(value) ? value : null;
|
|
22789
|
+
return {
|
|
22790
|
+
unit: typeof row["unit"] === "string" ? row["unit"] : "",
|
|
22791
|
+
additive: row["is_additive"] !== false,
|
|
22792
|
+
min: num(row["min_value"]),
|
|
22793
|
+
max: num(row["max_value"]),
|
|
22794
|
+
baseline: num(row["baseline_value"])
|
|
22795
|
+
};
|
|
22796
|
+
}
|
|
22696
22797
|
function describeRow(row, tables) {
|
|
22697
22798
|
if (row.kind === "CALC") return `CALC ${row.formula ?? "(no formula)"}`;
|
|
22698
22799
|
if (row.kind !== "BASE") return row.kind === "" ? "a metric" : `a ${row.kind} metric`;
|
|
@@ -22716,7 +22817,19 @@ async function readUsage(t, appId, metricId) {
|
|
|
22716
22817
|
if (answer.status !== 200) return `App Space could not say whether it may change it (HTTP ${String(answer.status)})`;
|
|
22717
22818
|
const one = obj2(obj2(obj2(answer.body)["metrics"])[String(metricId)]);
|
|
22718
22819
|
const app = obj2(one["this_app"]);
|
|
22820
|
+
const baselines = {};
|
|
22821
|
+
for (const [key, raw] of Object.entries(obj2(app["baselines"]))) {
|
|
22822
|
+
if (!isObj3(raw)) continue;
|
|
22823
|
+
const num = (value) => typeof value === "number" && Number.isFinite(value) ? value : null;
|
|
22824
|
+
baselines[key] = {
|
|
22825
|
+
value: num(raw["value"]),
|
|
22826
|
+
spec: typeof raw["spec"] === "string" ? raw["spec"] : null,
|
|
22827
|
+
window: typeof raw["window"] === "string" ? raw["window"] : null,
|
|
22828
|
+
months: num(raw["months"])
|
|
22829
|
+
};
|
|
22830
|
+
}
|
|
22719
22831
|
return {
|
|
22832
|
+
baselines,
|
|
22720
22833
|
created_by_app_space: one["created_by_app_space"] === true,
|
|
22721
22834
|
created_by_you: one["created_by_you"] === true,
|
|
22722
22835
|
keys: Array.isArray(app["keys"]) ? app["keys"].map(String) : [],
|
|
@@ -22744,6 +22857,7 @@ async function planMetrics(contract, t, opts) {
|
|
|
22744
22857
|
const byName3 = new Map(catalog.map((row) => [row.name, row]));
|
|
22745
22858
|
const byId = new Map(catalog.map((row) => [row.id, row]));
|
|
22746
22859
|
const rowKeys2 = new Map(catalog.map((row) => [row.id, rowReuseKey(row, byName3)]));
|
|
22860
|
+
const driverRows = /* @__PURE__ */ new Map();
|
|
22747
22861
|
const usageRead = /* @__PURE__ */ new Map();
|
|
22748
22862
|
const usageOf = (appId, id) => {
|
|
22749
22863
|
let held = usageRead.get(id);
|
|
@@ -22764,7 +22878,7 @@ async function planMetrics(contract, t, opts) {
|
|
|
22764
22878
|
not_checked: [],
|
|
22765
22879
|
notes: [],
|
|
22766
22880
|
problems: [],
|
|
22767
|
-
internal: { decls, catalog, tables: null, base: {}, tableOf: {}, appName: opts.appName }
|
|
22881
|
+
internal: { decls, catalog, tables: null, base: {}, tableOf: {}, appName: opts.appName, plan: modelPlanOf(contract), baselines: {} }
|
|
22768
22882
|
};
|
|
22769
22883
|
if (t.overridden) {
|
|
22770
22884
|
plan.notes.push(`metrics are read and created on ${t.host} (the Datarails host of ${t.serverKey}), not on --app-space-host ${t.appSpace}`);
|
|
@@ -22797,7 +22911,7 @@ async function planMetrics(contract, t, opts) {
|
|
|
22797
22911
|
const resolved = /* @__PURE__ */ new Map();
|
|
22798
22912
|
for (const key of dependencyOrder(decls)) {
|
|
22799
22913
|
const decl = decls[key];
|
|
22800
|
-
const kind = decl.kind === "base" || decl.kind === "calc" ? decl.kind : null;
|
|
22914
|
+
const kind = decl.kind === "base" || decl.kind === "calc" || decl.kind === "driver" ? decl.kind : null;
|
|
22801
22915
|
const entry = { key, name: decl.name, kind, action: "refuse", metric_id: null, metric_name: null, origin: null, reuse_key: null, definition: "", note: "" };
|
|
22802
22916
|
const refuse2 = (code, message, note) => {
|
|
22803
22917
|
entry.action = "refuse";
|
|
@@ -22828,20 +22942,32 @@ async function planMetrics(contract, t, opts) {
|
|
|
22828
22942
|
if (dep.metric_id !== null) ids[operand] = dep.metric_id;
|
|
22829
22943
|
}
|
|
22830
22944
|
}
|
|
22945
|
+
let calculations = [];
|
|
22831
22946
|
if (defProblem === null) {
|
|
22832
22947
|
try {
|
|
22833
22948
|
wire = wireFormula(decl.formula, names);
|
|
22949
|
+
calculations = calculationsWire(decl, key, names);
|
|
22834
22950
|
} catch (err) {
|
|
22835
22951
|
defProblem = { code: "metric_preview", message: `metric "${key}"'s formula ${firstLine(err)}` };
|
|
22836
22952
|
}
|
|
22837
22953
|
}
|
|
22838
|
-
if (wire !== null) {
|
|
22839
|
-
entry.definition =
|
|
22954
|
+
if (wire !== null && defProblem === null) {
|
|
22955
|
+
entry.definition = describeCalc(wire, calculations);
|
|
22840
22956
|
if (pendingOperands.length === 0) {
|
|
22841
22957
|
const nameToId = new Map(Object.entries(names).map(([operand, name]) => [name, ids[operand] ?? null]));
|
|
22842
|
-
entry.reuse_key = calcReuseKey(wire, (name) => nameToId.get(name) ?? null);
|
|
22958
|
+
entry.reuse_key = calcReuseKey(wire, (name) => nameToId.get(name) ?? null, calculations, decl.name);
|
|
22843
22959
|
}
|
|
22844
22960
|
}
|
|
22961
|
+
} else if (kind === "driver") {
|
|
22962
|
+
const def = driverDefinitionOf(decl);
|
|
22963
|
+
entry.definition = describeDriver(def);
|
|
22964
|
+
entry.reuse_key = driverReuseKey(def);
|
|
22965
|
+
const holder = byName3.get(decl.name);
|
|
22966
|
+
if (holder !== void 0 && holder.kind === "DRIVER" && !driverRows.has(holder.id)) {
|
|
22967
|
+
const held = await readDriverRow(t, holder.id);
|
|
22968
|
+
rowKeys2.set(holder.id, typeof held === "string" || held === null ? null : driverReuseKey(held));
|
|
22969
|
+
driverRows.set(holder.id, held);
|
|
22970
|
+
}
|
|
22845
22971
|
} else if (kind === "base") {
|
|
22846
22972
|
const table = tables === null ? void 0 : findAuthTable(tables, decl.table);
|
|
22847
22973
|
entry.definition = describeBase(decl, tableLabel(decl.table, table));
|
|
@@ -22888,6 +23014,14 @@ async function planMetrics(contract, t, opts) {
|
|
|
22888
23014
|
}
|
|
22889
23015
|
}
|
|
22890
23016
|
const named13 = byName3.get(decl.name);
|
|
23017
|
+
const describeHeld = (row) => {
|
|
23018
|
+
if (row.kind !== "DRIVER") return describeRow(row, tables);
|
|
23019
|
+
const held = driverRows.get(row.id);
|
|
23020
|
+
if (held === void 0) return describeRow(row, tables);
|
|
23021
|
+
if (held === null) return "DRIVER with no default row (Actuals, no cycle)";
|
|
23022
|
+
if (typeof held === "string") return `DRIVER whose default row could not be read (${held})`;
|
|
23023
|
+
return describeDriver(held);
|
|
23024
|
+
};
|
|
22891
23025
|
if (entry.reuse_key !== null) {
|
|
22892
23026
|
const same5 = catalog.filter((row) => rowKeys2.get(row.id) === entry.reuse_key).sort((a, b) => Number(b.name === decl.name) - Number(a.name === decl.name) || (a.created_at ?? "").localeCompare(b.created_at ?? "") || a.id - b.id);
|
|
22893
23027
|
const hit = same5[0];
|
|
@@ -22912,7 +23046,7 @@ async function planMetrics(contract, t, opts) {
|
|
|
22912
23046
|
entry.metric_id = named13.id;
|
|
22913
23047
|
entry.metric_name = named13.name;
|
|
22914
23048
|
entry.origin = "named";
|
|
22915
|
-
const theirs =
|
|
23049
|
+
const theirs = describeHeld(named13);
|
|
22916
23050
|
entry.note = kind === null ? "by name" : entry.reuse_key === null ? `by name (the contract's definition could not be compared here: ${defProblem?.message ?? "an operand is created on push"})` : `by name; its definition differs: ${theirs} against the contract's ${entry.definition}`;
|
|
22917
23051
|
continue;
|
|
22918
23052
|
}
|
|
@@ -22921,7 +23055,7 @@ async function planMetrics(contract, t, opts) {
|
|
|
22921
23055
|
continue;
|
|
22922
23056
|
}
|
|
22923
23057
|
if (named13 !== void 0 && kind !== null) {
|
|
22924
|
-
const theirs =
|
|
23058
|
+
const theirs = describeHeld(named13);
|
|
22925
23059
|
const sameKind = named13.kind === kind.toUpperCase();
|
|
22926
23060
|
const previous = rowKeys2.get(named13.id) ?? null;
|
|
22927
23061
|
let why = null;
|
|
@@ -22980,6 +23114,12 @@ async function planMetrics(contract, t, opts) {
|
|
|
22980
23114
|
entry.note = `${entry.definition}; extracts after creation`;
|
|
22981
23115
|
continue;
|
|
22982
23116
|
}
|
|
23117
|
+
if (kind === "driver") {
|
|
23118
|
+
entry.action = "create";
|
|
23119
|
+
entry.note = `${entry.definition}; ${baselineNote(decl)}`;
|
|
23120
|
+
if (!plan.not_checked.some((one) => one.startsWith(DRIVER_GATES))) plan.not_checked.push(`${DRIVER_GATES}: Datarails answers when the driver is created`);
|
|
23121
|
+
continue;
|
|
23122
|
+
}
|
|
22983
23123
|
entry.action = "create";
|
|
22984
23124
|
if (pendingOperands.length > 0) {
|
|
22985
23125
|
entry.after = pendingOperands;
|
|
@@ -22996,6 +23136,18 @@ async function planMetrics(contract, t, opts) {
|
|
|
22996
23136
|
entry.preview = "ok";
|
|
22997
23137
|
entry.note = `${entry.definition} preview ok`;
|
|
22998
23138
|
}
|
|
23139
|
+
if (opts.appId !== null && opts.appId !== "") {
|
|
23140
|
+
for (const entry of resolved.values()) {
|
|
23141
|
+
if (entry.kind !== "driver" || entry.metric_id === null || entry.action === "refuse" || entry.action === "create") continue;
|
|
23142
|
+
const usage = await usageOf(opts.appId, entry.metric_id);
|
|
23143
|
+
if (typeof usage !== "string") plan.internal.baselines[entry.key] = usage.baselines[entry.key];
|
|
23144
|
+
}
|
|
23145
|
+
}
|
|
23146
|
+
for (const [key, decl] of Object.entries(decls)) {
|
|
23147
|
+
if (decl.kind === "calc" && Object.keys(decl.calculations ?? {}).length > 0) {
|
|
23148
|
+
plan.not_checked.push(`the ${Object.keys(decl.calculations ?? {}).join(", ")} calculation of "${decl.name}" (${key}): Datarails checks it when it is written, under scenario_bound_calculations and the Planning product`);
|
|
23149
|
+
}
|
|
23150
|
+
}
|
|
22999
23151
|
const order2 = Object.keys(decls);
|
|
23000
23152
|
plan.entries = [...resolved.values()].sort((a, b) => order2.indexOf(a.key) - order2.indexOf(b.key));
|
|
23001
23153
|
for (const entry of plan.entries) {
|
|
@@ -23044,6 +23196,7 @@ async function applyPlan(plan, t, opts) {
|
|
|
23044
23196
|
return out;
|
|
23045
23197
|
};
|
|
23046
23198
|
const waitFor = [];
|
|
23199
|
+
const inRow = /* @__PURE__ */ new Map();
|
|
23047
23200
|
for (const key of dependencyOrder(decls)) {
|
|
23048
23201
|
const entry = byKey2.get(key);
|
|
23049
23202
|
const decl = decls[key];
|
|
@@ -23051,6 +23204,7 @@ async function applyPlan(plan, t, opts) {
|
|
|
23051
23204
|
if (entry.action === "reuse" || entry.action === "bind") continue;
|
|
23052
23205
|
if (entry.action !== "create" && entry.action !== "edit") continue;
|
|
23053
23206
|
let wire = null;
|
|
23207
|
+
let calculations = [];
|
|
23054
23208
|
if (entry.kind === "calc" && typeof decl.formula === "string") {
|
|
23055
23209
|
const names = {};
|
|
23056
23210
|
const ids = /* @__PURE__ */ new Map();
|
|
@@ -23060,17 +23214,54 @@ async function applyPlan(plan, t, opts) {
|
|
|
23060
23214
|
ids.set(names[operand], dep?.metric_id ?? null);
|
|
23061
23215
|
}
|
|
23062
23216
|
wire = wireFormula(decl.formula, names);
|
|
23063
|
-
entry.
|
|
23217
|
+
const self = entry.metric_name ?? decl.name;
|
|
23218
|
+
calculations = calculationsWire(decl, key, { ...names, [key]: self });
|
|
23219
|
+
entry.definition = describeCalc(wire, calculations);
|
|
23064
23220
|
if (entry.action === "edit") entry.new_definition = entry.definition;
|
|
23065
|
-
entry.reuse_key = calcReuseKey(wire, (name) => ids.get(name) ?? null);
|
|
23221
|
+
entry.reuse_key = calcReuseKey(wire, (name) => ids.get(name) ?? null, calculations, self);
|
|
23066
23222
|
if (entry.preview !== "ok") {
|
|
23067
23223
|
const preview = await previewFormula(t, wire);
|
|
23068
23224
|
if (preview !== null) return fail(key, `metric "${key}": Datarails could not evaluate ${wire}: ${preview}`);
|
|
23069
23225
|
entry.preview = "ok";
|
|
23070
23226
|
}
|
|
23071
23227
|
}
|
|
23228
|
+
let baseline = null;
|
|
23229
|
+
if (entry.kind === "driver") {
|
|
23230
|
+
const refs = baselineRefsOf(decl);
|
|
23231
|
+
const pending = waitFor.filter((one) => refs.includes(one.key));
|
|
23232
|
+
if (pending.length > 0) {
|
|
23233
|
+
await waitForExtraction(t, pending, opts, out.notes);
|
|
23234
|
+
for (const one of pending) waitFor.splice(waitFor.indexOf(one), 1);
|
|
23235
|
+
}
|
|
23236
|
+
const ready = await prepareBaseline(plan, t, opts, entry, decl, entry.action === "create" ? "created" : entry.origin);
|
|
23237
|
+
if (ready.state === "problem") {
|
|
23238
|
+
out.ok = false;
|
|
23239
|
+
out.problems.push(ready.problem);
|
|
23240
|
+
return out;
|
|
23241
|
+
}
|
|
23242
|
+
inRow.set(key, ready);
|
|
23243
|
+
if (ready.state === "stamp") baseline = ready.stamp.value;
|
|
23244
|
+
if (ready.state === "stamp" && baseline === null && !driverDefinitionOf(decl).additive) {
|
|
23245
|
+
return fail(
|
|
23246
|
+
key,
|
|
23247
|
+
`metric "${key}": a driver that does not add up over months (additive: false) needs a starting value, and Datarails refuses one without; ${unreadNote(`"${entry.metric_name ?? decl.name}"`, ready.reason)}. Type it ("baseline"), or ship again once the metrics it is read from hold the months`
|
|
23248
|
+
);
|
|
23249
|
+
}
|
|
23250
|
+
}
|
|
23251
|
+
if (entry.action === "edit" && entry.kind === "driver") {
|
|
23252
|
+
const written2 = await putDriverRow(t, entry.metric_id, driverRowBody(decl, baseline));
|
|
23253
|
+
if (written2 !== null) return fail(key, `metric "${key}": Datarails refused to change the driver "${entry.metric_name ?? entry.name}" (id ${String(entry.metric_id)}) in place: ${driverRefusal(written2)}`);
|
|
23254
|
+
out.created.push({ key, id: entry.metric_id, name: entry.metric_name ?? entry.name, action: "edit" });
|
|
23255
|
+
continue;
|
|
23256
|
+
}
|
|
23072
23257
|
if (entry.action === "edit") {
|
|
23073
|
-
const body2 = entry.kind === "calc" ? {
|
|
23258
|
+
const body2 = entry.kind === "calc" ? {
|
|
23259
|
+
configuration: { presented_formula: wire, ...formatOf(decl, plan, entry) },
|
|
23260
|
+
// The PATCH replaces every stored calculation: sent where the
|
|
23261
|
+
// contract states one or the metric holds one, so a dropped
|
|
23262
|
+
// calculation goes and a metric with none is changed as before.
|
|
23263
|
+
...calculations.length > 0 || (plan.internal.catalog.find((row) => row.id === entry.metric_id)?.calculations.length ?? 0) > 0 ? { calculations: calculationsBody(calculations) } : {}
|
|
23264
|
+
} : baseBody(plan.internal.base[key]);
|
|
23074
23265
|
const answer2 = await t.call("PATCH", `${t.host}/api/insights/metrics/${String(entry.metric_id)}`, body2).catch((err) => ({ status: 0, body: firstLine(err) }));
|
|
23075
23266
|
if (answer2.status < 200 || answer2.status >= 300) {
|
|
23076
23267
|
return fail(key, `metric "${key}": Datarails refused to change "${entry.metric_name ?? entry.name}" (id ${String(entry.metric_id)}) in place: ${refusalSentence(answer2, entry, plan)}`);
|
|
@@ -23083,7 +23274,13 @@ async function applyPlan(plan, t, opts) {
|
|
|
23083
23274
|
category = await appSpaceCategory(t, out.notes);
|
|
23084
23275
|
}
|
|
23085
23276
|
const description = [decl.description ?? "", createdFooter(plan.internal.appName)].filter((one) => one !== "").join("\n\n");
|
|
23086
|
-
const
|
|
23277
|
+
const formatted = decl.format === void 0 ? {} : { configuration: { presented_formula: "", format: decl.format } };
|
|
23278
|
+
const body = entry.kind === "calc" ? {
|
|
23279
|
+
name: decl.name,
|
|
23280
|
+
kind: "CALC",
|
|
23281
|
+
configuration: { presented_formula: wire, ...decl.format === void 0 ? {} : { format: decl.format } },
|
|
23282
|
+
...calculations.length === 0 ? {} : { calculations: calculationsBody(calculations) }
|
|
23283
|
+
} : entry.kind === "driver" ? { name: decl.name, kind: "DRIVER", ...formatted } : { name: decl.name, kind: "BASE", ...baseBody(plan.internal.base[key]), ...formatted };
|
|
23087
23284
|
body["description"] = description;
|
|
23088
23285
|
body["is_approved_by_user"] = true;
|
|
23089
23286
|
if (category !== null) body["category"] = category;
|
|
@@ -23097,10 +23294,22 @@ async function applyPlan(plan, t, opts) {
|
|
|
23097
23294
|
}
|
|
23098
23295
|
const byName3 = new Map(again.map((row) => [row.name, row]));
|
|
23099
23296
|
const holder = byName3.get(decl.name);
|
|
23297
|
+
if (holder === void 0 && entry.kind === "driver") {
|
|
23298
|
+
return fail(
|
|
23299
|
+
key,
|
|
23300
|
+
`metric "${key}": a metric named "${decl.name}" exists in this company and is not one you can see \u2014 a driver is hidden from every list where scenario_bound_calculations is off, and a metric over tables not shared with you is hidden from you; give the contract's driver another name, or ask an admin`
|
|
23301
|
+
);
|
|
23302
|
+
}
|
|
23100
23303
|
if (holder === void 0) {
|
|
23101
23304
|
return fail(key, `metric "${key}": a metric named "${decl.name}" exists in this company, but its source tables are not shared with you`);
|
|
23102
23305
|
}
|
|
23103
|
-
|
|
23306
|
+
let held = rowReuseKey(holder, byName3);
|
|
23307
|
+
if (entry.kind === "driver" && holder.kind === "DRIVER") {
|
|
23308
|
+
const row = await readDriverRow(t, holder.id);
|
|
23309
|
+
held = row === null || typeof row === "string" ? null : driverReuseKey(row);
|
|
23310
|
+
}
|
|
23311
|
+
if (entry.reuse_key !== null && held === entry.reuse_key) {
|
|
23312
|
+
inRow.delete(key);
|
|
23104
23313
|
entry.action = "reuse";
|
|
23105
23314
|
entry.origin = "reused";
|
|
23106
23315
|
entry.metric_id = holder.id;
|
|
@@ -23124,8 +23333,18 @@ async function applyPlan(plan, t, opts) {
|
|
|
23124
23333
|
entry.origin = "created";
|
|
23125
23334
|
out.created.push({ key, id, name: entry.metric_name, action: "create" });
|
|
23126
23335
|
if (entry.kind === "base") waitFor.push(entry);
|
|
23336
|
+
if (entry.kind === "driver") {
|
|
23337
|
+
const written2 = await putDriverRow(t, id, driverRowBody(decl, baseline));
|
|
23338
|
+
if (written2 !== null) return fail(key, `metric "${key}": Datarails created the driver "${entry.metric_name}" (id ${String(id)}) and refused its definition: ${driverRefusal(written2)}`);
|
|
23339
|
+
}
|
|
23127
23340
|
}
|
|
23128
23341
|
if (waitFor.length > 0) await waitForExtraction(t, waitFor, opts, out.notes);
|
|
23342
|
+
const baselineProblems = await writeBaselines(plan, t, opts, out, inRow);
|
|
23343
|
+
if (baselineProblems.length > 0) {
|
|
23344
|
+
out.ok = false;
|
|
23345
|
+
out.problems.push(...baselineProblems);
|
|
23346
|
+
return out;
|
|
23347
|
+
}
|
|
23129
23348
|
const written = plan.entries.filter((entry) => out.created.some((one) => one.key === entry.key));
|
|
23130
23349
|
if (written.length > 0) {
|
|
23131
23350
|
const drifted = await readBack(t, plan, written);
|
|
@@ -23141,7 +23360,8 @@ async function applyPlan(plan, t, opts) {
|
|
|
23141
23360
|
metric_id: entry.metric_id,
|
|
23142
23361
|
origin: entry.origin,
|
|
23143
23362
|
...entry.reuse_key === null ? {} : { reuse_key: entry.reuse_key },
|
|
23144
|
-
...entry.action === "edit" && typeof entry.previous_reuse_key === "string" ? { previous_reuse_key: entry.previous_reuse_key } : {}
|
|
23363
|
+
...entry.action === "edit" && typeof entry.previous_reuse_key === "string" ? { previous_reuse_key: entry.previous_reuse_key } : {},
|
|
23364
|
+
...entry.baseline === void 0 ? {} : { baseline: entry.baseline }
|
|
23145
23365
|
};
|
|
23146
23366
|
}
|
|
23147
23367
|
return out;
|
|
@@ -23168,7 +23388,11 @@ async function readBack(t, plan, written) {
|
|
|
23168
23388
|
problems.push(problem4("metric_changed", entry.key, `metric "${entry.key}": ${label} is not among this company's metrics you can read, just after this ship wrote it; nothing was pushed`));
|
|
23169
23389
|
continue;
|
|
23170
23390
|
}
|
|
23171
|
-
|
|
23391
|
+
let held = rowReuseKey(row, byName3);
|
|
23392
|
+
if (entry.kind === "driver") {
|
|
23393
|
+
const driver = await readDriverRow(t, row.id);
|
|
23394
|
+
held = driver === null || typeof driver === "string" ? null : driverReuseKey(driver);
|
|
23395
|
+
}
|
|
23172
23396
|
if (held === null || entry.reuse_key === null) {
|
|
23173
23397
|
problems.push(
|
|
23174
23398
|
problem4(
|
|
@@ -23194,6 +23418,227 @@ async function readBack(t, plan, written) {
|
|
|
23194
23418
|
}
|
|
23195
23419
|
return problems;
|
|
23196
23420
|
}
|
|
23421
|
+
function calculationsBody(calculations) {
|
|
23422
|
+
return calculations.map((one) => ({
|
|
23423
|
+
scenario: one.scenario,
|
|
23424
|
+
scenario_cycle: one.scenario_cycle,
|
|
23425
|
+
planning_scenario: one.planning_scenario,
|
|
23426
|
+
presented_formula: one.formula
|
|
23427
|
+
}));
|
|
23428
|
+
}
|
|
23429
|
+
function driverRowBody(decl, baseline) {
|
|
23430
|
+
const def = driverDefinitionOf(decl);
|
|
23431
|
+
return {
|
|
23432
|
+
...DEFAULT_DRIVER_CONTEXT,
|
|
23433
|
+
unit: def.unit,
|
|
23434
|
+
is_additive: def.additive,
|
|
23435
|
+
min_value: def.min,
|
|
23436
|
+
max_value: def.max,
|
|
23437
|
+
...baseline === null ? {} : { baseline_value: baseline }
|
|
23438
|
+
};
|
|
23439
|
+
}
|
|
23440
|
+
async function putDriverRow(t, id, body) {
|
|
23441
|
+
const answer = await t.call("PUT", `${t.host}/api/insights/metrics/${String(id)}/driver`, body).catch((err) => ({ status: 0, body: firstLine(err) }));
|
|
23442
|
+
return answer.status >= 200 && answer.status < 300 ? null : answer;
|
|
23443
|
+
}
|
|
23444
|
+
function driverRefusal(answer) {
|
|
23445
|
+
const said2 = sentenceOf(decodeEntities2(answer.body));
|
|
23446
|
+
if (answer.status === 405) return `this company does not have the Planning product (budget or forecast cycle management), which every driver needs${said2 === "" ? "" : ` (${said2})`}`;
|
|
23447
|
+
if (/turned off/i.test(said2)) return `scenario-bound calculations are turned off for this company (the scenario_bound_calculations flag), and drivers exist only behind it (${said2})`;
|
|
23448
|
+
if (answer.status === 403) return `only an admin or a contributor (a Data Manager) may write a driver, or this credential lacks metrics:write (403${said2 === "" ? "" : `: ${said2}`})`;
|
|
23449
|
+
if (answer.status === 0) return `the request did not complete (${String(answer.body)})`;
|
|
23450
|
+
return said2 === "" ? `HTTP ${String(answer.status)}` : `${said2} (HTTP ${String(answer.status)})`;
|
|
23451
|
+
}
|
|
23452
|
+
function shiftMonth([year, month], by) {
|
|
23453
|
+
const index = year * 12 + (month - 1) + by;
|
|
23454
|
+
return [Math.floor(index / 12), index % 12 + 1];
|
|
23455
|
+
}
|
|
23456
|
+
function monthText([year, month]) {
|
|
23457
|
+
return `${String(year).padStart(4, "0")}-${String(month).padStart(2, "0")}`;
|
|
23458
|
+
}
|
|
23459
|
+
function firstOpenMonth(plan, now) {
|
|
23460
|
+
const cycle = typeof plan?.cycle === "string" ? /^(\d{1,2})\+(\d{1,2})$/.exec(plan.cycle.trim()) : null;
|
|
23461
|
+
if (cycle !== null && typeof plan?.year === "number" && Number.isInteger(plan.year)) {
|
|
23462
|
+
const closed = Number(cycle[1]);
|
|
23463
|
+
if (closed >= 0 && closed <= 12) return shiftMonth([plan.year, 1], closed);
|
|
23464
|
+
}
|
|
23465
|
+
return [now.getUTCFullYear(), now.getUTCMonth() + 1];
|
|
23466
|
+
}
|
|
23467
|
+
function closedMonths(plan, now, count) {
|
|
23468
|
+
const first = firstOpenMonth(plan, now);
|
|
23469
|
+
return Array.from({ length: count }, (_, index) => shiftMonth(first, index - count));
|
|
23470
|
+
}
|
|
23471
|
+
function monthlyAmounts(body, metricId) {
|
|
23472
|
+
const data = obj2(obj2(body)["data"]);
|
|
23473
|
+
const listed = Array.isArray(data["metrics"]) ? data["metrics"] : Array.isArray(obj2(body)["metrics"]) ? obj2(body)["metrics"] : null;
|
|
23474
|
+
if (listed === null) return "the answer lists no metrics";
|
|
23475
|
+
const item = listed.filter(isObj3).find((one) => idIn(one["metric_id"]) === metricId);
|
|
23476
|
+
if (item === void 0) return `the answer has no figures for metric ${String(metricId)}`;
|
|
23477
|
+
if (isObj3(item["error"]) && typeof item["error"]["message"] === "string") return item["error"]["message"];
|
|
23478
|
+
const out = /* @__PURE__ */ new Map();
|
|
23479
|
+
for (const row of (Array.isArray(item["data"]) ? item["data"] : []).filter(isObj3)) {
|
|
23480
|
+
const date = row["date"];
|
|
23481
|
+
const amount = row["amount"] ?? row["value"];
|
|
23482
|
+
if (typeof date !== "string" || !/^\d{4}-\d{2}/.test(date)) continue;
|
|
23483
|
+
if (typeof amount !== "number" || !Number.isFinite(amount)) continue;
|
|
23484
|
+
const month = date.slice(0, 7);
|
|
23485
|
+
out.set(month, (out.get(month) ?? 0) + amount);
|
|
23486
|
+
}
|
|
23487
|
+
return out;
|
|
23488
|
+
}
|
|
23489
|
+
function baselineValue(rule, window, series, prior = []) {
|
|
23490
|
+
const at = (one, month) => one?.get(monthText(month));
|
|
23491
|
+
if (rule === "l12m_mean") {
|
|
23492
|
+
const found = window.map((month) => at(series[0], month)).filter((one) => one !== void 0);
|
|
23493
|
+
return { value: found.length === 0 ? null : found.reduce((a, b) => a + b, 0) / found.length, months: found.length };
|
|
23494
|
+
}
|
|
23495
|
+
if (rule === "l12m_ratio") {
|
|
23496
|
+
let top = 0;
|
|
23497
|
+
let bottom = 0;
|
|
23498
|
+
let months = 0;
|
|
23499
|
+
for (const month of window) {
|
|
23500
|
+
const a = at(series[0], month);
|
|
23501
|
+
const b = at(series[1], month);
|
|
23502
|
+
if (a === void 0 || b === void 0) continue;
|
|
23503
|
+
top += a;
|
|
23504
|
+
bottom += b;
|
|
23505
|
+
months += 1;
|
|
23506
|
+
}
|
|
23507
|
+
return { value: months === 0 || bottom === 0 ? null : top / bottom, months };
|
|
23508
|
+
}
|
|
23509
|
+
if (rule === "l12m_growth") {
|
|
23510
|
+
let now = 0;
|
|
23511
|
+
let before = 0;
|
|
23512
|
+
let months = 0;
|
|
23513
|
+
window.forEach((month, index) => {
|
|
23514
|
+
const a = at(series[0], month);
|
|
23515
|
+
const b = prior[index] === void 0 ? void 0 : at(series[0], prior[index]);
|
|
23516
|
+
if (a === void 0 || b === void 0) return;
|
|
23517
|
+
now += a;
|
|
23518
|
+
before += b;
|
|
23519
|
+
months += 1;
|
|
23520
|
+
});
|
|
23521
|
+
return { value: months === 0 || before === 0 ? null : now / before - 1, months };
|
|
23522
|
+
}
|
|
23523
|
+
return { value: null, months: 0 };
|
|
23524
|
+
}
|
|
23525
|
+
function lastDay([year, month]) {
|
|
23526
|
+
const day = new Date(Date.UTC(year, month, 0)).getUTCDate();
|
|
23527
|
+
return `${monthText([year, month])}-${String(day).padStart(2, "0")}`;
|
|
23528
|
+
}
|
|
23529
|
+
async function readMonthly(t, ids, from, to) {
|
|
23530
|
+
let answer;
|
|
23531
|
+
try {
|
|
23532
|
+
answer = await t.call("POST", `${t.host}/finance-os/api/metrics/v1/data`, {
|
|
23533
|
+
metric_ids: ids,
|
|
23534
|
+
aggregation_period: "month",
|
|
23535
|
+
aggregation_type: "DEFAULT",
|
|
23536
|
+
scenario: ["Actuals"],
|
|
23537
|
+
date_start: `${monthText(from)}-01`,
|
|
23538
|
+
date_end: lastDay(to)
|
|
23539
|
+
});
|
|
23540
|
+
} catch (err) {
|
|
23541
|
+
return `the Actuals could not be read (${firstLine(err)})`;
|
|
23542
|
+
}
|
|
23543
|
+
if (answer.status < 200 || answer.status >= 300) return `the Actuals could not be read (HTTP ${String(answer.status)}${sentenceOf(answer.body) === "" ? "" : `: ${sentenceOf(answer.body)}`})`;
|
|
23544
|
+
const out = [];
|
|
23545
|
+
for (const id of ids) {
|
|
23546
|
+
const one = monthlyAmounts(answer.body, id);
|
|
23547
|
+
if (typeof one === "string") return `the Actuals could not be read (${one})`;
|
|
23548
|
+
out.push(one);
|
|
23549
|
+
}
|
|
23550
|
+
return out;
|
|
23551
|
+
}
|
|
23552
|
+
async function prepareBaseline(plan, t, opts, entry, decl, origin) {
|
|
23553
|
+
const key = entry.key;
|
|
23554
|
+
const spec = baselineSpecOf(decl);
|
|
23555
|
+
if (spec === null) return { state: "none" };
|
|
23556
|
+
if (origin !== "created") return { state: "not_ours" };
|
|
23557
|
+
const before = plan.internal.baselines[key];
|
|
23558
|
+
if (before !== void 0 && before.spec === spec && before.value !== null) {
|
|
23559
|
+
return { state: "kept", stamp: { value: before.value, window: before.window, months: before.months } };
|
|
23560
|
+
}
|
|
23561
|
+
if (!plan.credential.can_write) return { state: "problem", problem: problem4("metric_scope", key, scopeSentence(key, decl.name, plan.credential, "changing")) };
|
|
23562
|
+
if (typeof decl.baseline === "number") return { state: "stamp", stamp: { value: decl.baseline, window: null, months: null }, source: "typed", reason: null };
|
|
23563
|
+
const byKey2 = new Map(plan.entries.map((one) => [one.key, one]));
|
|
23564
|
+
const now = new Date((opts.now ?? (() => Date.now()))());
|
|
23565
|
+
const rule = decl.baseline_from?.rule ?? "";
|
|
23566
|
+
const refs = baselineRefsOf(decl);
|
|
23567
|
+
const ids = refs.map((one) => byKey2.get(one)?.metric_id ?? null);
|
|
23568
|
+
const window = closedMonths(plan.internal.plan, now, 12);
|
|
23569
|
+
const prior = rule === "l12m_growth" ? window.map((month) => shiftMonth(month, -12)) : [];
|
|
23570
|
+
const span = `${monthText(window[0])}..${monthText(window[window.length - 1])}`;
|
|
23571
|
+
const source = `${rule} of ${refs.map((one) => `"${byKey2.get(one)?.metric_name ?? one}"`).join(" / ")}, ${span}`;
|
|
23572
|
+
if (ids.some((one) => one === null)) {
|
|
23573
|
+
return { state: "stamp", stamp: { value: null, window: span, months: 0 }, source, reason: "a metric it is read from is not bound" };
|
|
23574
|
+
}
|
|
23575
|
+
const read = await readMonthly(t, ids, prior[0] ?? window[0], window[window.length - 1]);
|
|
23576
|
+
if (typeof read === "string") return { state: "stamp", stamp: { value: null, window: span, months: 0 }, source, reason: `${read}; its pages open with no default until the next ship reads it` };
|
|
23577
|
+
const { value, months } = baselineValue(rule, window, read, prior);
|
|
23578
|
+
return {
|
|
23579
|
+
state: "stamp",
|
|
23580
|
+
stamp: { value, window: span, months },
|
|
23581
|
+
source,
|
|
23582
|
+
reason: value === null ? `${String(months)} of the 12 months ${span} hold a figure to compute it from (a metric still being prepared reads empty)` : null
|
|
23583
|
+
};
|
|
23584
|
+
}
|
|
23585
|
+
function unreadNote(label, reason) {
|
|
23586
|
+
return `${label}'s starting value was not read: ${reason ?? "nothing was found"}`;
|
|
23587
|
+
}
|
|
23588
|
+
async function writeBaselines(plan, t, opts, out, inRow) {
|
|
23589
|
+
const { decls } = plan.internal;
|
|
23590
|
+
const byKey2 = new Map(plan.entries.map((entry) => [entry.key, entry]));
|
|
23591
|
+
const problems = [];
|
|
23592
|
+
for (const key of dependencyOrder(decls)) {
|
|
23593
|
+
const entry = byKey2.get(key);
|
|
23594
|
+
const decl = decls[key];
|
|
23595
|
+
if (entry === void 0 || decl === void 0 || entry.kind !== "driver" || entry.metric_id === null) continue;
|
|
23596
|
+
const label = `"${entry.metric_name ?? entry.name}"`;
|
|
23597
|
+
const written = inRow.get(key);
|
|
23598
|
+
const ready = written ?? await prepareBaseline(plan, t, opts, entry, decl, entry.origin);
|
|
23599
|
+
if (ready.state === "none") continue;
|
|
23600
|
+
if (ready.state === "not_ours") {
|
|
23601
|
+
out.notes.push(`${label}'s starting value is the company's own: App Space did not create this driver, so it writes nothing into it`);
|
|
23602
|
+
continue;
|
|
23603
|
+
}
|
|
23604
|
+
if (ready.state === "problem") {
|
|
23605
|
+
problems.push(ready.problem);
|
|
23606
|
+
continue;
|
|
23607
|
+
}
|
|
23608
|
+
entry.baseline = ready.stamp;
|
|
23609
|
+
if (ready.state === "kept") continue;
|
|
23610
|
+
const stamp = ready.stamp;
|
|
23611
|
+
if (stamp.value === null) {
|
|
23612
|
+
out.notes.push(unreadNote(label, ready.reason));
|
|
23613
|
+
continue;
|
|
23614
|
+
}
|
|
23615
|
+
if (written === void 0) {
|
|
23616
|
+
const refused = await putDriverRow(t, entry.metric_id, { ...DEFAULT_DRIVER_CONTEXT, baseline_value: stamp.value });
|
|
23617
|
+
if (refused !== null) {
|
|
23618
|
+
problems.push(problem4("metric_create", key, `metric "${key}": Datarails refused ${label}'s starting value ${String(stamp.value)}: ${driverRefusal(refused)}`));
|
|
23619
|
+
continue;
|
|
23620
|
+
}
|
|
23621
|
+
}
|
|
23622
|
+
const back = await readDriverRow(t, entry.metric_id);
|
|
23623
|
+
if (back === null || typeof back === "string" || back.baseline === null || Math.abs(back.baseline - stamp.value) > 1e-9 * Math.max(1, Math.abs(stamp.value))) {
|
|
23624
|
+
problems.push(
|
|
23625
|
+
problem4(
|
|
23626
|
+
"metric_changed",
|
|
23627
|
+
key,
|
|
23628
|
+
`metric "${key}": ${label}'s starting value was written as ${String(stamp.value)} and reads back as ${typeof back === "object" && back !== null ? String(back.baseline) : `nothing (${String(back)})`}; nothing was pushed`
|
|
23629
|
+
)
|
|
23630
|
+
);
|
|
23631
|
+
continue;
|
|
23632
|
+
}
|
|
23633
|
+
const def = driverDefinitionOf(decl);
|
|
23634
|
+
if (def.min !== null && stamp.value < def.min || def.max !== null && stamp.value > def.max) {
|
|
23635
|
+
out.notes.push(`${label} starts at ${String(stamp.value)}, outside its declared bounds [${String(def.min ?? "\u2026")}, ${String(def.max ?? "\u2026")}]`);
|
|
23636
|
+
}
|
|
23637
|
+
const was = plan.internal.baselines[key]?.value ?? null;
|
|
23638
|
+
(out.baselined ??= []).push({ key, id: entry.metric_id, name: entry.metric_name ?? entry.name, value: stamp.value, was, window: stamp.window, months: stamp.months, source: ready.source });
|
|
23639
|
+
}
|
|
23640
|
+
return problems;
|
|
23641
|
+
}
|
|
23197
23642
|
function formatOf(decl, plan, entry) {
|
|
23198
23643
|
if (decl.format !== void 0) return { format: decl.format };
|
|
23199
23644
|
const row = plan.internal.catalog.find((one) => one.id === entry.metric_id);
|
|
@@ -23347,6 +23792,12 @@ function renderApplied(plan, applied) {
|
|
|
23347
23792
|
`;
|
|
23348
23793
|
}
|
|
23349
23794
|
}
|
|
23795
|
+
for (const one of applied.baselined ?? []) {
|
|
23796
|
+
const was = one.was === null ? "" : `; was ${String(one.was)}`;
|
|
23797
|
+
const months = one.months === null ? "" : ` (${String(one.months)} months found)`;
|
|
23798
|
+
out += `metric "${one.key}": "${one.name}" (id ${String(one.id)}) starts at ${String(one.value)}, ${one.source}${months}${was}; written into Datarails and read back
|
|
23799
|
+
`;
|
|
23800
|
+
}
|
|
23350
23801
|
for (const note of applied.notes) out += `note: ${note}
|
|
23351
23802
|
`;
|
|
23352
23803
|
return out;
|
|
@@ -23376,7 +23827,7 @@ function planReport(plan, applied) {
|
|
|
23376
23827
|
})),
|
|
23377
23828
|
not_checked: plan.not_checked,
|
|
23378
23829
|
notes: [...plan.notes, ...applied?.notes ?? []],
|
|
23379
|
-
...applied === void 0 ? {} : { created: applied.created, bindings: applied.bindings, ok: applied.ok }
|
|
23830
|
+
...applied === void 0 ? {} : { created: applied.created, baselined: applied.baselined ?? [], bindings: applied.bindings, ok: applied.ok }
|
|
23380
23831
|
};
|
|
23381
23832
|
}
|
|
23382
23833
|
async function checkMetricSources(t, appId, contract) {
|