@datarails-ai/dr-appspace-cli 0.12.62 → 0.12.64
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 +544 -32
- 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.64",
|
|
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-
|
|
60
|
+
var BUILD_TIME = "2026-11-03T09:55:58.483Z";
|
|
61
61
|
function formatBuildTime(iso) {
|
|
62
62
|
if (iso === "") return "";
|
|
63
63
|
const d = new Date(iso);
|
|
@@ -3031,6 +3031,26 @@ async function connect(opts) {
|
|
|
3031
3031
|
}
|
|
3032
3032
|
};
|
|
3033
3033
|
}
|
|
3034
|
+
function identityOf(client) {
|
|
3035
|
+
let claims = null;
|
|
3036
|
+
try {
|
|
3037
|
+
claims = client.claims?.() ?? null;
|
|
3038
|
+
} catch {
|
|
3039
|
+
claims = null;
|
|
3040
|
+
}
|
|
3041
|
+
const claim = (key) => {
|
|
3042
|
+
const held = claims?.[key];
|
|
3043
|
+
return typeof held === "string" || typeof held === "number" ? held : null;
|
|
3044
|
+
};
|
|
3045
|
+
return JSON.stringify([
|
|
3046
|
+
client.serverKey,
|
|
3047
|
+
client.baseUrl,
|
|
3048
|
+
client.host ?? null,
|
|
3049
|
+
client.email ?? null,
|
|
3050
|
+
claim("organization_id"),
|
|
3051
|
+
claim("user_id")
|
|
3052
|
+
]);
|
|
3053
|
+
}
|
|
3034
3054
|
var AppSpaceHttpError = class extends Error {
|
|
3035
3055
|
constructor(message, status, body) {
|
|
3036
3056
|
super(message);
|
|
@@ -3219,9 +3239,9 @@ function isOwnSnapshot(root) {
|
|
|
3219
3239
|
function isSkipped(value) {
|
|
3220
3240
|
return isObject(value) && typeof value["what"] === "string" && typeof value["why"] === "string";
|
|
3221
3241
|
}
|
|
3222
|
-
async function fromInventory(client, { fields = false, tableCap = 40 } = {}) {
|
|
3242
|
+
async function fromInventory(client, { fields = false, tableCap = 40, fresh = false } = {}) {
|
|
3223
3243
|
const fetched_at = (/* @__PURE__ */ new Date()).toISOString();
|
|
3224
|
-
const body = await client.request("/financeos/inventory");
|
|
3244
|
+
const body = await client.request(fresh ? "/financeos/inventory?fresh=1" : "/financeos/inventory");
|
|
3225
3245
|
const said2 = body.dashboard_renderer;
|
|
3226
3246
|
const renderer = said2 === "runtime" || said2 === "widgets" ? { dashboard_renderer: said2 } : {};
|
|
3227
3247
|
if (body.reachable !== true) {
|
|
@@ -3340,6 +3360,10 @@ function checksMetrics(catalog) {
|
|
|
3340
3360
|
function checksTables(catalog) {
|
|
3341
3361
|
return catalog.source !== "none" && catalog.tables.length > 0;
|
|
3342
3362
|
}
|
|
3363
|
+
function skipsNothingMore(next, than) {
|
|
3364
|
+
const skipped = new Set(than.checks_skipped.map((one) => one.what));
|
|
3365
|
+
return next.checks_skipped.every((one) => skipped.has(one.what));
|
|
3366
|
+
}
|
|
3343
3367
|
function findTable(catalog, named13) {
|
|
3344
3368
|
const want = named13.toLowerCase();
|
|
3345
3369
|
return catalog.tables.find(
|
|
@@ -22421,6 +22445,10 @@ function metricsTransport(client) {
|
|
|
22421
22445
|
claims: () => client.claims === void 0 ? null : client.claims()
|
|
22422
22446
|
};
|
|
22423
22447
|
}
|
|
22448
|
+
function modelPlanOf(contract) {
|
|
22449
|
+
const plan = obj2(obj2(obj2(obj2(contract)["data"])["model"])["plan"]);
|
|
22450
|
+
return Object.keys(plan).length === 0 ? null : plan;
|
|
22451
|
+
}
|
|
22424
22452
|
function declaredMetrics(contract) {
|
|
22425
22453
|
const data = obj2(obj2(contract)["data"]);
|
|
22426
22454
|
const metrics = obj2(data["metrics"]);
|
|
@@ -22486,7 +22514,13 @@ function catalogRow(raw) {
|
|
|
22486
22514
|
description: typeof raw["description"] === "string" ? raw["description"] : null,
|
|
22487
22515
|
category: typeof raw["category"] === "string" ? raw["category"] : isObj3(raw["category"]) && typeof raw["category"]["name"] === "string" ? raw["category"]["name"] : null,
|
|
22488
22516
|
status: typeof status["status"] === "string" ? status["status"].toUpperCase() : null,
|
|
22489
|
-
created_at: typeof raw["created_at"] === "string" ? raw["created_at"] : null
|
|
22517
|
+
created_at: typeof raw["created_at"] === "string" ? raw["created_at"] : null,
|
|
22518
|
+
calculations: (Array.isArray(raw["calculations"]) ? raw["calculations"] : []).filter(isObj3).flatMap((one) => {
|
|
22519
|
+
const formula = one["presented_formula"];
|
|
22520
|
+
if (typeof formula !== "string" || formula === "") return [];
|
|
22521
|
+
const text4 = (value) => typeof value === "string" ? value : "";
|
|
22522
|
+
return [{ scenario: text4(one["scenario"]), scenario_cycle: text4(one["scenario_cycle"]), planning_scenario: text4(one["planning_scenario"]), formula }];
|
|
22523
|
+
})
|
|
22490
22524
|
};
|
|
22491
22525
|
}
|
|
22492
22526
|
function authTableRow(raw) {
|
|
@@ -22556,12 +22590,13 @@ function rollupOf(def) {
|
|
|
22556
22590
|
}
|
|
22557
22591
|
var OPERAND_RE = /'([^']*)'|\[([^[\]]*)\]/g;
|
|
22558
22592
|
var MARK = "";
|
|
22559
|
-
function calcSkeleton(formula, idOf4) {
|
|
22593
|
+
function calcSkeleton(formula, idOf4, self = null) {
|
|
22560
22594
|
let missing = false;
|
|
22561
22595
|
const ids = /* @__PURE__ */ new Set();
|
|
22562
22596
|
const marked2 = formula.replace(OPERAND_RE, (_m, quoted3, bracketed) => {
|
|
22563
22597
|
const name = quoted3 ?? bracketed ?? "";
|
|
22564
22598
|
if (SYSTEM_VARIABLES.includes(name)) return `${MARK}${name.toLowerCase()}${MARK}`;
|
|
22599
|
+
if (self !== null && name === self) return `${MARK}self${MARK}`;
|
|
22565
22600
|
const id = idOf4(name);
|
|
22566
22601
|
if (id === null) {
|
|
22567
22602
|
missing = true;
|
|
@@ -22574,9 +22609,30 @@ function calcSkeleton(formula, idOf4) {
|
|
|
22574
22609
|
const skeleton = marked2.split(MARK).map((part, index) => index % 2 === 1 ? part : part.toLowerCase().replace(/\s+/g, "")).join("");
|
|
22575
22610
|
return { skeleton, ids: [...ids].sort((a, b) => a - b) };
|
|
22576
22611
|
}
|
|
22577
|
-
function calcReuseKey(formula, idOf4) {
|
|
22612
|
+
function calcReuseKey(formula, idOf4, calculations = [], self = null) {
|
|
22578
22613
|
const shape = calcSkeleton(formula, idOf4);
|
|
22579
|
-
|
|
22614
|
+
if (shape === null) return null;
|
|
22615
|
+
const parts = [];
|
|
22616
|
+
const ids = new Set(shape.ids);
|
|
22617
|
+
for (const one of calculations) {
|
|
22618
|
+
const inner = calcSkeleton(one.formula, idOf4, self);
|
|
22619
|
+
if (inner === null) return null;
|
|
22620
|
+
for (const id of inner.ids) ids.add(id);
|
|
22621
|
+
parts.push(`${one.scenario}|${one.scenario_cycle}|${one.planning_scenario}=${inner.skeleton}`);
|
|
22622
|
+
}
|
|
22623
|
+
const base = `calc:${shape.skeleton}|${shape.ids.join(",")}`;
|
|
22624
|
+
return parts.length === 0 ? base : `${base}|calculations:${JSON.stringify(parts.sort())}|${[...ids].sort((a, b) => a - b).join(",")}`;
|
|
22625
|
+
}
|
|
22626
|
+
function driverReuseKey(def) {
|
|
22627
|
+
return `driver:${JSON.stringify([def.unit, def.additive, def.min, def.max])}`;
|
|
22628
|
+
}
|
|
22629
|
+
function driverDefinitionOf(decl) {
|
|
22630
|
+
return {
|
|
22631
|
+
unit: typeof decl.unit === "string" ? decl.unit : "",
|
|
22632
|
+
additive: decl.additive !== false,
|
|
22633
|
+
min: typeof decl.min === "number" ? decl.min : null,
|
|
22634
|
+
max: typeof decl.max === "number" ? decl.max : null
|
|
22635
|
+
};
|
|
22580
22636
|
}
|
|
22581
22637
|
function rowReuseKey(row, byName3) {
|
|
22582
22638
|
if (row.kind === "BASE") {
|
|
@@ -22591,7 +22647,7 @@ function rowReuseKey(row, byName3) {
|
|
|
22591
22647
|
filters: row.filters
|
|
22592
22648
|
});
|
|
22593
22649
|
}
|
|
22594
|
-
if (row.kind === "CALC" && row.formula !== null) return calcReuseKey(row.formula, (name) => byName3.get(name)?.id ?? null);
|
|
22650
|
+
if (row.kind === "CALC" && row.formula !== null) return calcReuseKey(row.formula, (name) => byName3.get(name)?.id ?? null, row.calculations, row.name);
|
|
22595
22651
|
return null;
|
|
22596
22652
|
}
|
|
22597
22653
|
var METRIC_CREATED_FOOTER = "Created by App Space for the app";
|
|
@@ -22651,9 +22707,32 @@ function dependencyOrder(decls) {
|
|
|
22651
22707
|
}
|
|
22652
22708
|
function operandsOf(decls, key) {
|
|
22653
22709
|
const decl = decls[key];
|
|
22654
|
-
if (decl === void 0
|
|
22710
|
+
if (decl === void 0) return [];
|
|
22711
|
+
if (decl.kind === "driver") return baselineRefsOf(decl);
|
|
22712
|
+
if (decl.kind !== "calc" || typeof decl.formula !== "string") return [];
|
|
22655
22713
|
const found = metricFormulaProblems(decl.formula, Object.keys(decls));
|
|
22656
|
-
|
|
22714
|
+
const out = new Set(found.operands);
|
|
22715
|
+
for (const formula of Object.values(decl.calculations ?? {})) {
|
|
22716
|
+
const inner = metricFormulaProblems(formula, Object.keys(decls), { pinned: true, self: key });
|
|
22717
|
+
for (const one of inner.operands) if (one !== key) out.add(one);
|
|
22718
|
+
}
|
|
22719
|
+
return [...out].sort();
|
|
22720
|
+
}
|
|
22721
|
+
function baselineRefsOf(decl) {
|
|
22722
|
+
const from = decl.baseline_from;
|
|
22723
|
+
if (from === void 0) return [];
|
|
22724
|
+
const refs = from.rule === "l12m_ratio" ? from.ratio ?? [] : [from.metric ?? ""];
|
|
22725
|
+
return refs.filter((one) => /^@[a-z][a-z0-9_]*$/.test(one)).map((one) => one.slice(1));
|
|
22726
|
+
}
|
|
22727
|
+
function baselineSpecOf(decl) {
|
|
22728
|
+
if (decl.baseline_from !== void 0 && typeof decl.baseline_from.rule === "string") return canonicalJson(decl.baseline_from);
|
|
22729
|
+
if (typeof decl.baseline === "number") return canonicalJson({ baseline: decl.baseline });
|
|
22730
|
+
return null;
|
|
22731
|
+
}
|
|
22732
|
+
function canonicalJson(value) {
|
|
22733
|
+
if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
|
|
22734
|
+
if (isObj3(value)) return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonicalJson(value[key])}`).join(",")}}`;
|
|
22735
|
+
return JSON.stringify(value);
|
|
22657
22736
|
}
|
|
22658
22737
|
function credentialOf(claims) {
|
|
22659
22738
|
const scopes = claims === null ? void 0 : claims["scopes"];
|
|
@@ -22693,6 +22772,52 @@ function describeBase(decl, tableName) {
|
|
|
22693
22772
|
const filters = (decl.filters ?? []).map((one) => `${one.field} ${one.exclude === true ? "not in" : "in"} [${one.values.map(String).join(", ")}]`).join("; ");
|
|
22694
22773
|
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
22774
|
}
|
|
22775
|
+
function calculationsWire(decl, key, names) {
|
|
22776
|
+
const withSelf = { ...names, [key]: names[key] ?? decl.name };
|
|
22777
|
+
return Object.keys(decl.calculations ?? {}).sort().map((scenario) => ({
|
|
22778
|
+
scenario,
|
|
22779
|
+
scenario_cycle: "",
|
|
22780
|
+
planning_scenario: "",
|
|
22781
|
+
formula: wireFormula((decl.calculations ?? {})[scenario], withSelf, { pinned: true })
|
|
22782
|
+
}));
|
|
22783
|
+
}
|
|
22784
|
+
function describeCalc(wire, calculations) {
|
|
22785
|
+
const more = calculations.map((one) => `; ${one.scenario}: ${one.formula}`).join("");
|
|
22786
|
+
return `CALC ${wire}${more}`;
|
|
22787
|
+
}
|
|
22788
|
+
function describeDriver(def) {
|
|
22789
|
+
const bound = (value) => value === null ? "none" : String(value);
|
|
22790
|
+
return `DRIVER (unit ${def.unit === "" ? "none" : `"${def.unit}"`}, ${def.additive ? "additive" : "not additive"}, min ${bound(def.min)}, max ${bound(def.max)})`;
|
|
22791
|
+
}
|
|
22792
|
+
function baselineNote(decl) {
|
|
22793
|
+
if (typeof decl.baseline === "number") return `starting value ${String(decl.baseline)} (typed)`;
|
|
22794
|
+
const from = decl.baseline_from;
|
|
22795
|
+
if (from === void 0) return "no starting value";
|
|
22796
|
+
const refs = baselineRefsOf(decl).map((one) => `@${one}`).join(" / ");
|
|
22797
|
+
return `starting value read by ${from.rule} from ${refs} after it is bound`;
|
|
22798
|
+
}
|
|
22799
|
+
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)";
|
|
22800
|
+
var DEFAULT_DRIVER_CONTEXT = { scenario: "Actuals", scenario_cycle: "", planning_scenario: "" };
|
|
22801
|
+
async function readDriverRow(t, id) {
|
|
22802
|
+
const query = `scenario=Actuals&scenario_cycle=&planning_scenario=`;
|
|
22803
|
+
let answer;
|
|
22804
|
+
try {
|
|
22805
|
+
answer = await t.call("GET", `${t.host}/api/insights/metrics/${String(id)}/driver?${query}`);
|
|
22806
|
+
} catch (err) {
|
|
22807
|
+
return firstLine(err);
|
|
22808
|
+
}
|
|
22809
|
+
if (answer.status === 404 && isObj3(answer.body) && Object.keys(answer.body).length === 0) return null;
|
|
22810
|
+
if (answer.status !== 200 || !isObj3(answer.body)) return `HTTP ${String(answer.status)}${sentenceOf(answer.body) === "" ? "" : `: ${sentenceOf(answer.body)}`}`;
|
|
22811
|
+
const row = decodeEntities2(answer.body);
|
|
22812
|
+
const num = (value) => typeof value === "number" && Number.isFinite(value) ? value : null;
|
|
22813
|
+
return {
|
|
22814
|
+
unit: typeof row["unit"] === "string" ? row["unit"] : "",
|
|
22815
|
+
additive: row["is_additive"] !== false,
|
|
22816
|
+
min: num(row["min_value"]),
|
|
22817
|
+
max: num(row["max_value"]),
|
|
22818
|
+
baseline: num(row["baseline_value"])
|
|
22819
|
+
};
|
|
22820
|
+
}
|
|
22696
22821
|
function describeRow(row, tables) {
|
|
22697
22822
|
if (row.kind === "CALC") return `CALC ${row.formula ?? "(no formula)"}`;
|
|
22698
22823
|
if (row.kind !== "BASE") return row.kind === "" ? "a metric" : `a ${row.kind} metric`;
|
|
@@ -22716,7 +22841,19 @@ async function readUsage(t, appId, metricId) {
|
|
|
22716
22841
|
if (answer.status !== 200) return `App Space could not say whether it may change it (HTTP ${String(answer.status)})`;
|
|
22717
22842
|
const one = obj2(obj2(obj2(answer.body)["metrics"])[String(metricId)]);
|
|
22718
22843
|
const app = obj2(one["this_app"]);
|
|
22844
|
+
const baselines = {};
|
|
22845
|
+
for (const [key, raw] of Object.entries(obj2(app["baselines"]))) {
|
|
22846
|
+
if (!isObj3(raw)) continue;
|
|
22847
|
+
const num = (value) => typeof value === "number" && Number.isFinite(value) ? value : null;
|
|
22848
|
+
baselines[key] = {
|
|
22849
|
+
value: num(raw["value"]),
|
|
22850
|
+
spec: typeof raw["spec"] === "string" ? raw["spec"] : null,
|
|
22851
|
+
window: typeof raw["window"] === "string" ? raw["window"] : null,
|
|
22852
|
+
months: num(raw["months"])
|
|
22853
|
+
};
|
|
22854
|
+
}
|
|
22719
22855
|
return {
|
|
22856
|
+
baselines,
|
|
22720
22857
|
created_by_app_space: one["created_by_app_space"] === true,
|
|
22721
22858
|
created_by_you: one["created_by_you"] === true,
|
|
22722
22859
|
keys: Array.isArray(app["keys"]) ? app["keys"].map(String) : [],
|
|
@@ -22744,6 +22881,7 @@ async function planMetrics(contract, t, opts) {
|
|
|
22744
22881
|
const byName3 = new Map(catalog.map((row) => [row.name, row]));
|
|
22745
22882
|
const byId = new Map(catalog.map((row) => [row.id, row]));
|
|
22746
22883
|
const rowKeys2 = new Map(catalog.map((row) => [row.id, rowReuseKey(row, byName3)]));
|
|
22884
|
+
const driverRows = /* @__PURE__ */ new Map();
|
|
22747
22885
|
const usageRead = /* @__PURE__ */ new Map();
|
|
22748
22886
|
const usageOf = (appId, id) => {
|
|
22749
22887
|
let held = usageRead.get(id);
|
|
@@ -22764,7 +22902,7 @@ async function planMetrics(contract, t, opts) {
|
|
|
22764
22902
|
not_checked: [],
|
|
22765
22903
|
notes: [],
|
|
22766
22904
|
problems: [],
|
|
22767
|
-
internal: { decls, catalog, tables: null, base: {}, tableOf: {}, appName: opts.appName }
|
|
22905
|
+
internal: { decls, catalog, tables: null, base: {}, tableOf: {}, appName: opts.appName, plan: modelPlanOf(contract), baselines: {} }
|
|
22768
22906
|
};
|
|
22769
22907
|
if (t.overridden) {
|
|
22770
22908
|
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 +22935,7 @@ async function planMetrics(contract, t, opts) {
|
|
|
22797
22935
|
const resolved = /* @__PURE__ */ new Map();
|
|
22798
22936
|
for (const key of dependencyOrder(decls)) {
|
|
22799
22937
|
const decl = decls[key];
|
|
22800
|
-
const kind = decl.kind === "base" || decl.kind === "calc" ? decl.kind : null;
|
|
22938
|
+
const kind = decl.kind === "base" || decl.kind === "calc" || decl.kind === "driver" ? decl.kind : null;
|
|
22801
22939
|
const entry = { key, name: decl.name, kind, action: "refuse", metric_id: null, metric_name: null, origin: null, reuse_key: null, definition: "", note: "" };
|
|
22802
22940
|
const refuse2 = (code, message, note) => {
|
|
22803
22941
|
entry.action = "refuse";
|
|
@@ -22828,20 +22966,32 @@ async function planMetrics(contract, t, opts) {
|
|
|
22828
22966
|
if (dep.metric_id !== null) ids[operand] = dep.metric_id;
|
|
22829
22967
|
}
|
|
22830
22968
|
}
|
|
22969
|
+
let calculations = [];
|
|
22831
22970
|
if (defProblem === null) {
|
|
22832
22971
|
try {
|
|
22833
22972
|
wire = wireFormula(decl.formula, names);
|
|
22973
|
+
calculations = calculationsWire(decl, key, names);
|
|
22834
22974
|
} catch (err) {
|
|
22835
22975
|
defProblem = { code: "metric_preview", message: `metric "${key}"'s formula ${firstLine(err)}` };
|
|
22836
22976
|
}
|
|
22837
22977
|
}
|
|
22838
|
-
if (wire !== null) {
|
|
22839
|
-
entry.definition =
|
|
22978
|
+
if (wire !== null && defProblem === null) {
|
|
22979
|
+
entry.definition = describeCalc(wire, calculations);
|
|
22840
22980
|
if (pendingOperands.length === 0) {
|
|
22841
22981
|
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);
|
|
22982
|
+
entry.reuse_key = calcReuseKey(wire, (name) => nameToId.get(name) ?? null, calculations, decl.name);
|
|
22843
22983
|
}
|
|
22844
22984
|
}
|
|
22985
|
+
} else if (kind === "driver") {
|
|
22986
|
+
const def = driverDefinitionOf(decl);
|
|
22987
|
+
entry.definition = describeDriver(def);
|
|
22988
|
+
entry.reuse_key = driverReuseKey(def);
|
|
22989
|
+
const holder = byName3.get(decl.name);
|
|
22990
|
+
if (holder !== void 0 && holder.kind === "DRIVER" && !driverRows.has(holder.id)) {
|
|
22991
|
+
const held = await readDriverRow(t, holder.id);
|
|
22992
|
+
rowKeys2.set(holder.id, typeof held === "string" || held === null ? null : driverReuseKey(held));
|
|
22993
|
+
driverRows.set(holder.id, held);
|
|
22994
|
+
}
|
|
22845
22995
|
} else if (kind === "base") {
|
|
22846
22996
|
const table = tables === null ? void 0 : findAuthTable(tables, decl.table);
|
|
22847
22997
|
entry.definition = describeBase(decl, tableLabel(decl.table, table));
|
|
@@ -22888,6 +23038,14 @@ async function planMetrics(contract, t, opts) {
|
|
|
22888
23038
|
}
|
|
22889
23039
|
}
|
|
22890
23040
|
const named13 = byName3.get(decl.name);
|
|
23041
|
+
const describeHeld = (row) => {
|
|
23042
|
+
if (row.kind !== "DRIVER") return describeRow(row, tables);
|
|
23043
|
+
const held = driverRows.get(row.id);
|
|
23044
|
+
if (held === void 0) return describeRow(row, tables);
|
|
23045
|
+
if (held === null) return "DRIVER with no default row (Actuals, no cycle)";
|
|
23046
|
+
if (typeof held === "string") return `DRIVER whose default row could not be read (${held})`;
|
|
23047
|
+
return describeDriver(held);
|
|
23048
|
+
};
|
|
22891
23049
|
if (entry.reuse_key !== null) {
|
|
22892
23050
|
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
23051
|
const hit = same5[0];
|
|
@@ -22912,7 +23070,7 @@ async function planMetrics(contract, t, opts) {
|
|
|
22912
23070
|
entry.metric_id = named13.id;
|
|
22913
23071
|
entry.metric_name = named13.name;
|
|
22914
23072
|
entry.origin = "named";
|
|
22915
|
-
const theirs =
|
|
23073
|
+
const theirs = describeHeld(named13);
|
|
22916
23074
|
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
23075
|
continue;
|
|
22918
23076
|
}
|
|
@@ -22921,7 +23079,7 @@ async function planMetrics(contract, t, opts) {
|
|
|
22921
23079
|
continue;
|
|
22922
23080
|
}
|
|
22923
23081
|
if (named13 !== void 0 && kind !== null) {
|
|
22924
|
-
const theirs =
|
|
23082
|
+
const theirs = describeHeld(named13);
|
|
22925
23083
|
const sameKind = named13.kind === kind.toUpperCase();
|
|
22926
23084
|
const previous = rowKeys2.get(named13.id) ?? null;
|
|
22927
23085
|
let why = null;
|
|
@@ -22980,6 +23138,12 @@ async function planMetrics(contract, t, opts) {
|
|
|
22980
23138
|
entry.note = `${entry.definition}; extracts after creation`;
|
|
22981
23139
|
continue;
|
|
22982
23140
|
}
|
|
23141
|
+
if (kind === "driver") {
|
|
23142
|
+
entry.action = "create";
|
|
23143
|
+
entry.note = `${entry.definition}; ${baselineNote(decl)}`;
|
|
23144
|
+
if (!plan.not_checked.some((one) => one.startsWith(DRIVER_GATES))) plan.not_checked.push(`${DRIVER_GATES}: Datarails answers when the driver is created`);
|
|
23145
|
+
continue;
|
|
23146
|
+
}
|
|
22983
23147
|
entry.action = "create";
|
|
22984
23148
|
if (pendingOperands.length > 0) {
|
|
22985
23149
|
entry.after = pendingOperands;
|
|
@@ -22996,6 +23160,18 @@ async function planMetrics(contract, t, opts) {
|
|
|
22996
23160
|
entry.preview = "ok";
|
|
22997
23161
|
entry.note = `${entry.definition} preview ok`;
|
|
22998
23162
|
}
|
|
23163
|
+
if (opts.appId !== null && opts.appId !== "") {
|
|
23164
|
+
for (const entry of resolved.values()) {
|
|
23165
|
+
if (entry.kind !== "driver" || entry.metric_id === null || entry.action === "refuse" || entry.action === "create") continue;
|
|
23166
|
+
const usage = await usageOf(opts.appId, entry.metric_id);
|
|
23167
|
+
if (typeof usage !== "string") plan.internal.baselines[entry.key] = usage.baselines[entry.key];
|
|
23168
|
+
}
|
|
23169
|
+
}
|
|
23170
|
+
for (const [key, decl] of Object.entries(decls)) {
|
|
23171
|
+
if (decl.kind === "calc" && Object.keys(decl.calculations ?? {}).length > 0) {
|
|
23172
|
+
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`);
|
|
23173
|
+
}
|
|
23174
|
+
}
|
|
22999
23175
|
const order2 = Object.keys(decls);
|
|
23000
23176
|
plan.entries = [...resolved.values()].sort((a, b) => order2.indexOf(a.key) - order2.indexOf(b.key));
|
|
23001
23177
|
for (const entry of plan.entries) {
|
|
@@ -23044,6 +23220,7 @@ async function applyPlan(plan, t, opts) {
|
|
|
23044
23220
|
return out;
|
|
23045
23221
|
};
|
|
23046
23222
|
const waitFor = [];
|
|
23223
|
+
const inRow = /* @__PURE__ */ new Map();
|
|
23047
23224
|
for (const key of dependencyOrder(decls)) {
|
|
23048
23225
|
const entry = byKey2.get(key);
|
|
23049
23226
|
const decl = decls[key];
|
|
@@ -23051,6 +23228,7 @@ async function applyPlan(plan, t, opts) {
|
|
|
23051
23228
|
if (entry.action === "reuse" || entry.action === "bind") continue;
|
|
23052
23229
|
if (entry.action !== "create" && entry.action !== "edit") continue;
|
|
23053
23230
|
let wire = null;
|
|
23231
|
+
let calculations = [];
|
|
23054
23232
|
if (entry.kind === "calc" && typeof decl.formula === "string") {
|
|
23055
23233
|
const names = {};
|
|
23056
23234
|
const ids = /* @__PURE__ */ new Map();
|
|
@@ -23060,17 +23238,54 @@ async function applyPlan(plan, t, opts) {
|
|
|
23060
23238
|
ids.set(names[operand], dep?.metric_id ?? null);
|
|
23061
23239
|
}
|
|
23062
23240
|
wire = wireFormula(decl.formula, names);
|
|
23063
|
-
entry.
|
|
23241
|
+
const self = entry.metric_name ?? decl.name;
|
|
23242
|
+
calculations = calculationsWire(decl, key, { ...names, [key]: self });
|
|
23243
|
+
entry.definition = describeCalc(wire, calculations);
|
|
23064
23244
|
if (entry.action === "edit") entry.new_definition = entry.definition;
|
|
23065
|
-
entry.reuse_key = calcReuseKey(wire, (name) => ids.get(name) ?? null);
|
|
23245
|
+
entry.reuse_key = calcReuseKey(wire, (name) => ids.get(name) ?? null, calculations, self);
|
|
23066
23246
|
if (entry.preview !== "ok") {
|
|
23067
23247
|
const preview = await previewFormula(t, wire);
|
|
23068
23248
|
if (preview !== null) return fail(key, `metric "${key}": Datarails could not evaluate ${wire}: ${preview}`);
|
|
23069
23249
|
entry.preview = "ok";
|
|
23070
23250
|
}
|
|
23071
23251
|
}
|
|
23252
|
+
let baseline = null;
|
|
23253
|
+
if (entry.kind === "driver") {
|
|
23254
|
+
const refs = baselineRefsOf(decl);
|
|
23255
|
+
const pending = waitFor.filter((one) => refs.includes(one.key));
|
|
23256
|
+
if (pending.length > 0) {
|
|
23257
|
+
await waitForExtraction(t, pending, opts, out.notes);
|
|
23258
|
+
for (const one of pending) waitFor.splice(waitFor.indexOf(one), 1);
|
|
23259
|
+
}
|
|
23260
|
+
const ready = await prepareBaseline(plan, t, opts, entry, decl, entry.action === "create" ? "created" : entry.origin);
|
|
23261
|
+
if (ready.state === "problem") {
|
|
23262
|
+
out.ok = false;
|
|
23263
|
+
out.problems.push(ready.problem);
|
|
23264
|
+
return out;
|
|
23265
|
+
}
|
|
23266
|
+
inRow.set(key, ready);
|
|
23267
|
+
if (ready.state === "stamp") baseline = ready.stamp.value;
|
|
23268
|
+
if (ready.state === "stamp" && baseline === null && !driverDefinitionOf(decl).additive) {
|
|
23269
|
+
return fail(
|
|
23270
|
+
key,
|
|
23271
|
+
`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`
|
|
23272
|
+
);
|
|
23273
|
+
}
|
|
23274
|
+
}
|
|
23275
|
+
if (entry.action === "edit" && entry.kind === "driver") {
|
|
23276
|
+
const written2 = await putDriverRow(t, entry.metric_id, driverRowBody(decl, baseline));
|
|
23277
|
+
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)}`);
|
|
23278
|
+
out.created.push({ key, id: entry.metric_id, name: entry.metric_name ?? entry.name, action: "edit" });
|
|
23279
|
+
continue;
|
|
23280
|
+
}
|
|
23072
23281
|
if (entry.action === "edit") {
|
|
23073
|
-
const body2 = entry.kind === "calc" ? {
|
|
23282
|
+
const body2 = entry.kind === "calc" ? {
|
|
23283
|
+
configuration: { presented_formula: wire, ...formatOf(decl, plan, entry) },
|
|
23284
|
+
// The PATCH replaces every stored calculation: sent where the
|
|
23285
|
+
// contract states one or the metric holds one, so a dropped
|
|
23286
|
+
// calculation goes and a metric with none is changed as before.
|
|
23287
|
+
...calculations.length > 0 || (plan.internal.catalog.find((row) => row.id === entry.metric_id)?.calculations.length ?? 0) > 0 ? { calculations: calculationsBody(calculations) } : {}
|
|
23288
|
+
} : baseBody(plan.internal.base[key]);
|
|
23074
23289
|
const answer2 = await t.call("PATCH", `${t.host}/api/insights/metrics/${String(entry.metric_id)}`, body2).catch((err) => ({ status: 0, body: firstLine(err) }));
|
|
23075
23290
|
if (answer2.status < 200 || answer2.status >= 300) {
|
|
23076
23291
|
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 +23298,13 @@ async function applyPlan(plan, t, opts) {
|
|
|
23083
23298
|
category = await appSpaceCategory(t, out.notes);
|
|
23084
23299
|
}
|
|
23085
23300
|
const description = [decl.description ?? "", createdFooter(plan.internal.appName)].filter((one) => one !== "").join("\n\n");
|
|
23086
|
-
const
|
|
23301
|
+
const formatted = decl.format === void 0 ? {} : { configuration: { presented_formula: "", format: decl.format } };
|
|
23302
|
+
const body = entry.kind === "calc" ? {
|
|
23303
|
+
name: decl.name,
|
|
23304
|
+
kind: "CALC",
|
|
23305
|
+
configuration: { presented_formula: wire, ...decl.format === void 0 ? {} : { format: decl.format } },
|
|
23306
|
+
...calculations.length === 0 ? {} : { calculations: calculationsBody(calculations) }
|
|
23307
|
+
} : entry.kind === "driver" ? { name: decl.name, kind: "DRIVER", ...formatted } : { name: decl.name, kind: "BASE", ...baseBody(plan.internal.base[key]), ...formatted };
|
|
23087
23308
|
body["description"] = description;
|
|
23088
23309
|
body["is_approved_by_user"] = true;
|
|
23089
23310
|
if (category !== null) body["category"] = category;
|
|
@@ -23097,10 +23318,22 @@ async function applyPlan(plan, t, opts) {
|
|
|
23097
23318
|
}
|
|
23098
23319
|
const byName3 = new Map(again.map((row) => [row.name, row]));
|
|
23099
23320
|
const holder = byName3.get(decl.name);
|
|
23321
|
+
if (holder === void 0 && entry.kind === "driver") {
|
|
23322
|
+
return fail(
|
|
23323
|
+
key,
|
|
23324
|
+
`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`
|
|
23325
|
+
);
|
|
23326
|
+
}
|
|
23100
23327
|
if (holder === void 0) {
|
|
23101
23328
|
return fail(key, `metric "${key}": a metric named "${decl.name}" exists in this company, but its source tables are not shared with you`);
|
|
23102
23329
|
}
|
|
23103
|
-
|
|
23330
|
+
let held = rowReuseKey(holder, byName3);
|
|
23331
|
+
if (entry.kind === "driver" && holder.kind === "DRIVER") {
|
|
23332
|
+
const row = await readDriverRow(t, holder.id);
|
|
23333
|
+
held = row === null || typeof row === "string" ? null : driverReuseKey(row);
|
|
23334
|
+
}
|
|
23335
|
+
if (entry.reuse_key !== null && held === entry.reuse_key) {
|
|
23336
|
+
inRow.delete(key);
|
|
23104
23337
|
entry.action = "reuse";
|
|
23105
23338
|
entry.origin = "reused";
|
|
23106
23339
|
entry.metric_id = holder.id;
|
|
@@ -23124,8 +23357,18 @@ async function applyPlan(plan, t, opts) {
|
|
|
23124
23357
|
entry.origin = "created";
|
|
23125
23358
|
out.created.push({ key, id, name: entry.metric_name, action: "create" });
|
|
23126
23359
|
if (entry.kind === "base") waitFor.push(entry);
|
|
23360
|
+
if (entry.kind === "driver") {
|
|
23361
|
+
const written2 = await putDriverRow(t, id, driverRowBody(decl, baseline));
|
|
23362
|
+
if (written2 !== null) return fail(key, `metric "${key}": Datarails created the driver "${entry.metric_name}" (id ${String(id)}) and refused its definition: ${driverRefusal(written2)}`);
|
|
23363
|
+
}
|
|
23127
23364
|
}
|
|
23128
23365
|
if (waitFor.length > 0) await waitForExtraction(t, waitFor, opts, out.notes);
|
|
23366
|
+
const baselineProblems = await writeBaselines(plan, t, opts, out, inRow);
|
|
23367
|
+
if (baselineProblems.length > 0) {
|
|
23368
|
+
out.ok = false;
|
|
23369
|
+
out.problems.push(...baselineProblems);
|
|
23370
|
+
return out;
|
|
23371
|
+
}
|
|
23129
23372
|
const written = plan.entries.filter((entry) => out.created.some((one) => one.key === entry.key));
|
|
23130
23373
|
if (written.length > 0) {
|
|
23131
23374
|
const drifted = await readBack(t, plan, written);
|
|
@@ -23141,7 +23384,8 @@ async function applyPlan(plan, t, opts) {
|
|
|
23141
23384
|
metric_id: entry.metric_id,
|
|
23142
23385
|
origin: entry.origin,
|
|
23143
23386
|
...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 } : {}
|
|
23387
|
+
...entry.action === "edit" && typeof entry.previous_reuse_key === "string" ? { previous_reuse_key: entry.previous_reuse_key } : {},
|
|
23388
|
+
...entry.baseline === void 0 ? {} : { baseline: entry.baseline }
|
|
23145
23389
|
};
|
|
23146
23390
|
}
|
|
23147
23391
|
return out;
|
|
@@ -23168,7 +23412,11 @@ async function readBack(t, plan, written) {
|
|
|
23168
23412
|
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
23413
|
continue;
|
|
23170
23414
|
}
|
|
23171
|
-
|
|
23415
|
+
let held = rowReuseKey(row, byName3);
|
|
23416
|
+
if (entry.kind === "driver") {
|
|
23417
|
+
const driver = await readDriverRow(t, row.id);
|
|
23418
|
+
held = driver === null || typeof driver === "string" ? null : driverReuseKey(driver);
|
|
23419
|
+
}
|
|
23172
23420
|
if (held === null || entry.reuse_key === null) {
|
|
23173
23421
|
problems.push(
|
|
23174
23422
|
problem4(
|
|
@@ -23194,6 +23442,227 @@ async function readBack(t, plan, written) {
|
|
|
23194
23442
|
}
|
|
23195
23443
|
return problems;
|
|
23196
23444
|
}
|
|
23445
|
+
function calculationsBody(calculations) {
|
|
23446
|
+
return calculations.map((one) => ({
|
|
23447
|
+
scenario: one.scenario,
|
|
23448
|
+
scenario_cycle: one.scenario_cycle,
|
|
23449
|
+
planning_scenario: one.planning_scenario,
|
|
23450
|
+
presented_formula: one.formula
|
|
23451
|
+
}));
|
|
23452
|
+
}
|
|
23453
|
+
function driverRowBody(decl, baseline) {
|
|
23454
|
+
const def = driverDefinitionOf(decl);
|
|
23455
|
+
return {
|
|
23456
|
+
...DEFAULT_DRIVER_CONTEXT,
|
|
23457
|
+
unit: def.unit,
|
|
23458
|
+
is_additive: def.additive,
|
|
23459
|
+
min_value: def.min,
|
|
23460
|
+
max_value: def.max,
|
|
23461
|
+
...baseline === null ? {} : { baseline_value: baseline }
|
|
23462
|
+
};
|
|
23463
|
+
}
|
|
23464
|
+
async function putDriverRow(t, id, body) {
|
|
23465
|
+
const answer = await t.call("PUT", `${t.host}/api/insights/metrics/${String(id)}/driver`, body).catch((err) => ({ status: 0, body: firstLine(err) }));
|
|
23466
|
+
return answer.status >= 200 && answer.status < 300 ? null : answer;
|
|
23467
|
+
}
|
|
23468
|
+
function driverRefusal(answer) {
|
|
23469
|
+
const said2 = sentenceOf(decodeEntities2(answer.body));
|
|
23470
|
+
if (answer.status === 405) return `this company does not have the Planning product (budget or forecast cycle management), which every driver needs${said2 === "" ? "" : ` (${said2})`}`;
|
|
23471
|
+
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})`;
|
|
23472
|
+
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}`})`;
|
|
23473
|
+
if (answer.status === 0) return `the request did not complete (${String(answer.body)})`;
|
|
23474
|
+
return said2 === "" ? `HTTP ${String(answer.status)}` : `${said2} (HTTP ${String(answer.status)})`;
|
|
23475
|
+
}
|
|
23476
|
+
function shiftMonth([year, month], by) {
|
|
23477
|
+
const index = year * 12 + (month - 1) + by;
|
|
23478
|
+
return [Math.floor(index / 12), index % 12 + 1];
|
|
23479
|
+
}
|
|
23480
|
+
function monthText([year, month]) {
|
|
23481
|
+
return `${String(year).padStart(4, "0")}-${String(month).padStart(2, "0")}`;
|
|
23482
|
+
}
|
|
23483
|
+
function firstOpenMonth(plan, now) {
|
|
23484
|
+
const cycle = typeof plan?.cycle === "string" ? /^(\d{1,2})\+(\d{1,2})$/.exec(plan.cycle.trim()) : null;
|
|
23485
|
+
if (cycle !== null && typeof plan?.year === "number" && Number.isInteger(plan.year)) {
|
|
23486
|
+
const closed = Number(cycle[1]);
|
|
23487
|
+
if (closed >= 0 && closed <= 12) return shiftMonth([plan.year, 1], closed);
|
|
23488
|
+
}
|
|
23489
|
+
return [now.getUTCFullYear(), now.getUTCMonth() + 1];
|
|
23490
|
+
}
|
|
23491
|
+
function closedMonths(plan, now, count) {
|
|
23492
|
+
const first = firstOpenMonth(plan, now);
|
|
23493
|
+
return Array.from({ length: count }, (_, index) => shiftMonth(first, index - count));
|
|
23494
|
+
}
|
|
23495
|
+
function monthlyAmounts(body, metricId) {
|
|
23496
|
+
const data = obj2(obj2(body)["data"]);
|
|
23497
|
+
const listed = Array.isArray(data["metrics"]) ? data["metrics"] : Array.isArray(obj2(body)["metrics"]) ? obj2(body)["metrics"] : null;
|
|
23498
|
+
if (listed === null) return "the answer lists no metrics";
|
|
23499
|
+
const item = listed.filter(isObj3).find((one) => idIn(one["metric_id"]) === metricId);
|
|
23500
|
+
if (item === void 0) return `the answer has no figures for metric ${String(metricId)}`;
|
|
23501
|
+
if (isObj3(item["error"]) && typeof item["error"]["message"] === "string") return item["error"]["message"];
|
|
23502
|
+
const out = /* @__PURE__ */ new Map();
|
|
23503
|
+
for (const row of (Array.isArray(item["data"]) ? item["data"] : []).filter(isObj3)) {
|
|
23504
|
+
const date = row["date"];
|
|
23505
|
+
const amount = row["amount"] ?? row["value"];
|
|
23506
|
+
if (typeof date !== "string" || !/^\d{4}-\d{2}/.test(date)) continue;
|
|
23507
|
+
if (typeof amount !== "number" || !Number.isFinite(amount)) continue;
|
|
23508
|
+
const month = date.slice(0, 7);
|
|
23509
|
+
out.set(month, (out.get(month) ?? 0) + amount);
|
|
23510
|
+
}
|
|
23511
|
+
return out;
|
|
23512
|
+
}
|
|
23513
|
+
function baselineValue(rule, window, series, prior = []) {
|
|
23514
|
+
const at = (one, month) => one?.get(monthText(month));
|
|
23515
|
+
if (rule === "l12m_mean") {
|
|
23516
|
+
const found = window.map((month) => at(series[0], month)).filter((one) => one !== void 0);
|
|
23517
|
+
return { value: found.length === 0 ? null : found.reduce((a, b) => a + b, 0) / found.length, months: found.length };
|
|
23518
|
+
}
|
|
23519
|
+
if (rule === "l12m_ratio") {
|
|
23520
|
+
let top = 0;
|
|
23521
|
+
let bottom = 0;
|
|
23522
|
+
let months = 0;
|
|
23523
|
+
for (const month of window) {
|
|
23524
|
+
const a = at(series[0], month);
|
|
23525
|
+
const b = at(series[1], month);
|
|
23526
|
+
if (a === void 0 || b === void 0) continue;
|
|
23527
|
+
top += a;
|
|
23528
|
+
bottom += b;
|
|
23529
|
+
months += 1;
|
|
23530
|
+
}
|
|
23531
|
+
return { value: months === 0 || bottom === 0 ? null : top / bottom, months };
|
|
23532
|
+
}
|
|
23533
|
+
if (rule === "l12m_growth") {
|
|
23534
|
+
let now = 0;
|
|
23535
|
+
let before = 0;
|
|
23536
|
+
let months = 0;
|
|
23537
|
+
window.forEach((month, index) => {
|
|
23538
|
+
const a = at(series[0], month);
|
|
23539
|
+
const b = prior[index] === void 0 ? void 0 : at(series[0], prior[index]);
|
|
23540
|
+
if (a === void 0 || b === void 0) return;
|
|
23541
|
+
now += a;
|
|
23542
|
+
before += b;
|
|
23543
|
+
months += 1;
|
|
23544
|
+
});
|
|
23545
|
+
return { value: months === 0 || before === 0 ? null : now / before - 1, months };
|
|
23546
|
+
}
|
|
23547
|
+
return { value: null, months: 0 };
|
|
23548
|
+
}
|
|
23549
|
+
function lastDay([year, month]) {
|
|
23550
|
+
const day = new Date(Date.UTC(year, month, 0)).getUTCDate();
|
|
23551
|
+
return `${monthText([year, month])}-${String(day).padStart(2, "0")}`;
|
|
23552
|
+
}
|
|
23553
|
+
async function readMonthly(t, ids, from, to) {
|
|
23554
|
+
let answer;
|
|
23555
|
+
try {
|
|
23556
|
+
answer = await t.call("POST", `${t.host}/finance-os/api/metrics/v1/data`, {
|
|
23557
|
+
metric_ids: ids,
|
|
23558
|
+
aggregation_period: "month",
|
|
23559
|
+
aggregation_type: "DEFAULT",
|
|
23560
|
+
scenario: ["Actuals"],
|
|
23561
|
+
date_start: `${monthText(from)}-01`,
|
|
23562
|
+
date_end: lastDay(to)
|
|
23563
|
+
});
|
|
23564
|
+
} catch (err) {
|
|
23565
|
+
return `the Actuals could not be read (${firstLine(err)})`;
|
|
23566
|
+
}
|
|
23567
|
+
if (answer.status < 200 || answer.status >= 300) return `the Actuals could not be read (HTTP ${String(answer.status)}${sentenceOf(answer.body) === "" ? "" : `: ${sentenceOf(answer.body)}`})`;
|
|
23568
|
+
const out = [];
|
|
23569
|
+
for (const id of ids) {
|
|
23570
|
+
const one = monthlyAmounts(answer.body, id);
|
|
23571
|
+
if (typeof one === "string") return `the Actuals could not be read (${one})`;
|
|
23572
|
+
out.push(one);
|
|
23573
|
+
}
|
|
23574
|
+
return out;
|
|
23575
|
+
}
|
|
23576
|
+
async function prepareBaseline(plan, t, opts, entry, decl, origin) {
|
|
23577
|
+
const key = entry.key;
|
|
23578
|
+
const spec = baselineSpecOf(decl);
|
|
23579
|
+
if (spec === null) return { state: "none" };
|
|
23580
|
+
if (origin !== "created") return { state: "not_ours" };
|
|
23581
|
+
const before = plan.internal.baselines[key];
|
|
23582
|
+
if (before !== void 0 && before.spec === spec && before.value !== null) {
|
|
23583
|
+
return { state: "kept", stamp: { value: before.value, window: before.window, months: before.months } };
|
|
23584
|
+
}
|
|
23585
|
+
if (!plan.credential.can_write) return { state: "problem", problem: problem4("metric_scope", key, scopeSentence(key, decl.name, plan.credential, "changing")) };
|
|
23586
|
+
if (typeof decl.baseline === "number") return { state: "stamp", stamp: { value: decl.baseline, window: null, months: null }, source: "typed", reason: null };
|
|
23587
|
+
const byKey2 = new Map(plan.entries.map((one) => [one.key, one]));
|
|
23588
|
+
const now = new Date((opts.now ?? (() => Date.now()))());
|
|
23589
|
+
const rule = decl.baseline_from?.rule ?? "";
|
|
23590
|
+
const refs = baselineRefsOf(decl);
|
|
23591
|
+
const ids = refs.map((one) => byKey2.get(one)?.metric_id ?? null);
|
|
23592
|
+
const window = closedMonths(plan.internal.plan, now, 12);
|
|
23593
|
+
const prior = rule === "l12m_growth" ? window.map((month) => shiftMonth(month, -12)) : [];
|
|
23594
|
+
const span = `${monthText(window[0])}..${monthText(window[window.length - 1])}`;
|
|
23595
|
+
const source = `${rule} of ${refs.map((one) => `"${byKey2.get(one)?.metric_name ?? one}"`).join(" / ")}, ${span}`;
|
|
23596
|
+
if (ids.some((one) => one === null)) {
|
|
23597
|
+
return { state: "stamp", stamp: { value: null, window: span, months: 0 }, source, reason: "a metric it is read from is not bound" };
|
|
23598
|
+
}
|
|
23599
|
+
const read = await readMonthly(t, ids, prior[0] ?? window[0], window[window.length - 1]);
|
|
23600
|
+
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` };
|
|
23601
|
+
const { value, months } = baselineValue(rule, window, read, prior);
|
|
23602
|
+
return {
|
|
23603
|
+
state: "stamp",
|
|
23604
|
+
stamp: { value, window: span, months },
|
|
23605
|
+
source,
|
|
23606
|
+
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
|
|
23607
|
+
};
|
|
23608
|
+
}
|
|
23609
|
+
function unreadNote(label, reason) {
|
|
23610
|
+
return `${label}'s starting value was not read: ${reason ?? "nothing was found"}`;
|
|
23611
|
+
}
|
|
23612
|
+
async function writeBaselines(plan, t, opts, out, inRow) {
|
|
23613
|
+
const { decls } = plan.internal;
|
|
23614
|
+
const byKey2 = new Map(plan.entries.map((entry) => [entry.key, entry]));
|
|
23615
|
+
const problems = [];
|
|
23616
|
+
for (const key of dependencyOrder(decls)) {
|
|
23617
|
+
const entry = byKey2.get(key);
|
|
23618
|
+
const decl = decls[key];
|
|
23619
|
+
if (entry === void 0 || decl === void 0 || entry.kind !== "driver" || entry.metric_id === null) continue;
|
|
23620
|
+
const label = `"${entry.metric_name ?? entry.name}"`;
|
|
23621
|
+
const written = inRow.get(key);
|
|
23622
|
+
const ready = written ?? await prepareBaseline(plan, t, opts, entry, decl, entry.origin);
|
|
23623
|
+
if (ready.state === "none") continue;
|
|
23624
|
+
if (ready.state === "not_ours") {
|
|
23625
|
+
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`);
|
|
23626
|
+
continue;
|
|
23627
|
+
}
|
|
23628
|
+
if (ready.state === "problem") {
|
|
23629
|
+
problems.push(ready.problem);
|
|
23630
|
+
continue;
|
|
23631
|
+
}
|
|
23632
|
+
entry.baseline = ready.stamp;
|
|
23633
|
+
if (ready.state === "kept") continue;
|
|
23634
|
+
const stamp = ready.stamp;
|
|
23635
|
+
if (stamp.value === null) {
|
|
23636
|
+
out.notes.push(unreadNote(label, ready.reason));
|
|
23637
|
+
continue;
|
|
23638
|
+
}
|
|
23639
|
+
if (written === void 0) {
|
|
23640
|
+
const refused = await putDriverRow(t, entry.metric_id, { ...DEFAULT_DRIVER_CONTEXT, baseline_value: stamp.value });
|
|
23641
|
+
if (refused !== null) {
|
|
23642
|
+
problems.push(problem4("metric_create", key, `metric "${key}": Datarails refused ${label}'s starting value ${String(stamp.value)}: ${driverRefusal(refused)}`));
|
|
23643
|
+
continue;
|
|
23644
|
+
}
|
|
23645
|
+
}
|
|
23646
|
+
const back = await readDriverRow(t, entry.metric_id);
|
|
23647
|
+
if (back === null || typeof back === "string" || back.baseline === null || Math.abs(back.baseline - stamp.value) > 1e-9 * Math.max(1, Math.abs(stamp.value))) {
|
|
23648
|
+
problems.push(
|
|
23649
|
+
problem4(
|
|
23650
|
+
"metric_changed",
|
|
23651
|
+
key,
|
|
23652
|
+
`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`
|
|
23653
|
+
)
|
|
23654
|
+
);
|
|
23655
|
+
continue;
|
|
23656
|
+
}
|
|
23657
|
+
const def = driverDefinitionOf(decl);
|
|
23658
|
+
if (def.min !== null && stamp.value < def.min || def.max !== null && stamp.value > def.max) {
|
|
23659
|
+
out.notes.push(`${label} starts at ${String(stamp.value)}, outside its declared bounds [${String(def.min ?? "\u2026")}, ${String(def.max ?? "\u2026")}]`);
|
|
23660
|
+
}
|
|
23661
|
+
const was = plan.internal.baselines[key]?.value ?? null;
|
|
23662
|
+
(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 });
|
|
23663
|
+
}
|
|
23664
|
+
return problems;
|
|
23665
|
+
}
|
|
23197
23666
|
function formatOf(decl, plan, entry) {
|
|
23198
23667
|
if (decl.format !== void 0) return { format: decl.format };
|
|
23199
23668
|
const row = plan.internal.catalog.find((one) => one.id === entry.metric_id);
|
|
@@ -23347,6 +23816,12 @@ function renderApplied(plan, applied) {
|
|
|
23347
23816
|
`;
|
|
23348
23817
|
}
|
|
23349
23818
|
}
|
|
23819
|
+
for (const one of applied.baselined ?? []) {
|
|
23820
|
+
const was = one.was === null ? "" : `; was ${String(one.was)}`;
|
|
23821
|
+
const months = one.months === null ? "" : ` (${String(one.months)} months found)`;
|
|
23822
|
+
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
|
|
23823
|
+
`;
|
|
23824
|
+
}
|
|
23350
23825
|
for (const note of applied.notes) out += `note: ${note}
|
|
23351
23826
|
`;
|
|
23352
23827
|
return out;
|
|
@@ -23376,7 +23851,7 @@ function planReport(plan, applied) {
|
|
|
23376
23851
|
})),
|
|
23377
23852
|
not_checked: plan.not_checked,
|
|
23378
23853
|
notes: [...plan.notes, ...applied?.notes ?? []],
|
|
23379
|
-
...applied === void 0 ? {} : { created: applied.created, bindings: applied.bindings, ok: applied.ok }
|
|
23854
|
+
...applied === void 0 ? {} : { created: applied.created, baselined: applied.baselined ?? [], bindings: applied.bindings, ok: applied.ok }
|
|
23380
23855
|
};
|
|
23381
23856
|
}
|
|
23382
23857
|
async function checkMetricSources(t, appId, contract) {
|
|
@@ -32010,18 +32485,38 @@ async function runCompile(dir, opts) {
|
|
|
32010
32485
|
);
|
|
32011
32486
|
return 1;
|
|
32012
32487
|
}
|
|
32013
|
-
const
|
|
32488
|
+
const memo = opts.catalogMemo;
|
|
32014
32489
|
let catalog;
|
|
32490
|
+
const client = await catalogClient(opts);
|
|
32015
32491
|
try {
|
|
32016
|
-
|
|
32492
|
+
const held = memo?.entry;
|
|
32493
|
+
if (held !== void 0 && client !== null && identityOf(client) === held.who) {
|
|
32494
|
+
catalog = held.catalog;
|
|
32495
|
+
} else {
|
|
32496
|
+
catalog = await resolveCatalog(opts, client);
|
|
32497
|
+
if (memo !== void 0 && client !== null && reusable(catalog)) memo.entry = { catalog, who: identityOf(client) };
|
|
32498
|
+
}
|
|
32017
32499
|
} finally {
|
|
32018
32500
|
client?.cleanup();
|
|
32019
32501
|
}
|
|
32020
|
-
const
|
|
32021
|
-
|
|
32502
|
+
const authored = contract;
|
|
32503
|
+
const decided = decideRenderer(authored, catalog.dashboard_renderer, recorded);
|
|
32504
|
+
contract = withRenderer(authored, decided.renderer);
|
|
32022
32505
|
report.renderer = decided.renderer;
|
|
32023
32506
|
report.renderer_source = decided.source;
|
|
32024
|
-
|
|
32507
|
+
let { problems, skipped, warnings } = validateContract(contract, catalog);
|
|
32508
|
+
if (catalog.source === "inventory" && problems.some((problem6) => problem6.code === "unknown-metric")) {
|
|
32509
|
+
const first = catalog;
|
|
32510
|
+
const reread = await rereadInventory(
|
|
32511
|
+
opts,
|
|
32512
|
+
(next) => skipsNothingMore(next, first) && decideRenderer(authored, next.dashboard_renderer, recorded).renderer === decided.renderer
|
|
32513
|
+
);
|
|
32514
|
+
if (reread !== null) {
|
|
32515
|
+
catalog = reread.catalog;
|
|
32516
|
+
if (memo !== void 0) memo.entry = reread;
|
|
32517
|
+
({ problems, skipped, warnings } = validateContract(contract, catalog));
|
|
32518
|
+
}
|
|
32519
|
+
}
|
|
32025
32520
|
report.validate = {
|
|
32026
32521
|
problems,
|
|
32027
32522
|
checks_skipped: skipped,
|
|
@@ -33065,6 +33560,22 @@ async function resolveCatalog(opts, client, inventoryOpts = {}) {
|
|
|
33065
33560
|
};
|
|
33066
33561
|
}
|
|
33067
33562
|
}
|
|
33563
|
+
function reusable(catalog) {
|
|
33564
|
+
return catalog.source === "inventory" && !catalog.checks_skipped.some((one) => one.what === "sources") && checksMetrics(catalog);
|
|
33565
|
+
}
|
|
33566
|
+
async function rereadInventory(opts, accepts) {
|
|
33567
|
+
let client = null;
|
|
33568
|
+
try {
|
|
33569
|
+
client = await catalogClient(opts);
|
|
33570
|
+
if (client === null) return null;
|
|
33571
|
+
const catalog = await resolveCatalog(opts, client, { fresh: true });
|
|
33572
|
+
return reusable(catalog) && accepts(catalog) ? { catalog, who: identityOf(client) } : null;
|
|
33573
|
+
} catch {
|
|
33574
|
+
return null;
|
|
33575
|
+
} finally {
|
|
33576
|
+
client?.cleanup();
|
|
33577
|
+
}
|
|
33578
|
+
}
|
|
33068
33579
|
function runVerify(dir, kind, appId, kit) {
|
|
33069
33580
|
const verify3 = kind === "dashboard" ? verify : verify2;
|
|
33070
33581
|
const result = verify3({ app: { id: appId, version: null, dir } }, { kit });
|
|
@@ -33389,6 +33900,7 @@ async function runShipOntoLive(dir, opts) {
|
|
|
33389
33900
|
if (!hasServer(opts)) {
|
|
33390
33901
|
return refuse2("needs a server: pass -s <server> (or set DR_APP_SPACE_HOST), or log in so a stored session supplies one.");
|
|
33391
33902
|
}
|
|
33903
|
+
const catalogMemo = {};
|
|
33392
33904
|
return landWithRetries(async (createGuarded) => {
|
|
33393
33905
|
for (const name of ONTO_LIVE_OWNED) await rm4(join15(dir, name), { recursive: true, force: true });
|
|
33394
33906
|
const client = await connect(opts);
|
|
@@ -33423,7 +33935,7 @@ async function runShipOntoLive(dir, opts) {
|
|
|
33423
33935
|
`
|
|
33424
33936
|
);
|
|
33425
33937
|
}
|
|
33426
|
-
const code = await runCompile(dir, { ...opts, check: false, push: true, updateBlock: true, ontoLive: true });
|
|
33938
|
+
const code = await runCompile(dir, { ...opts, check: false, push: true, updateBlock: true, ontoLive: true, catalogMemo });
|
|
33427
33939
|
return { code, lost: code === 3 ? await lostRaceOf(dir) : null, creating: pulled === null };
|
|
33428
33940
|
}, opts);
|
|
33429
33941
|
}
|