@openinc/parse-server-opendash 4.31.5 → 4.32.0

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.
Files changed (53) hide show
  1. package/dist/featuremap.json +4 -0
  2. package/dist/features/bde/shifts/shiftValidation.d.ts +13 -0
  3. package/dist/features/bde/shifts/shiftValidation.js +96 -0
  4. package/dist/features/openservice/alarms/index.d.ts +0 -2
  5. package/dist/features/openservice/alarms/index.js +1 -3
  6. package/dist/features/openservice/init.js +2 -0
  7. package/dist/features/openservice/kpis/initKpiFeature.d.ts +13 -0
  8. package/dist/features/openservice/kpis/initKpiFeature.js +41 -0
  9. package/dist/features/openservice/kpis/kpiJob.d.ts +46 -0
  10. package/dist/features/openservice/kpis/kpiJob.js +273 -0
  11. package/dist/features/openservice/kpis/kpiMaths.d.ts +51 -0
  12. package/dist/features/openservice/kpis/kpiMaths.js +62 -0
  13. package/dist/features/openservice/tickets/ticketFailure.d.ts +37 -0
  14. package/dist/features/openservice/tickets/ticketFailure.js +99 -0
  15. package/dist/features/openservice/tickets/ticketRules.d.ts +8 -0
  16. package/dist/features/openservice/tickets/ticketRules.js +10 -0
  17. package/dist/features/permissions/types/Permissions.d.ts +3 -1
  18. package/dist/features/permissions/types/Permissions.js +5 -0
  19. package/dist/functions/openinc-openservice-kpi-recompute.d.ts +16 -0
  20. package/dist/functions/openinc-openservice-kpi-recompute.js +44 -0
  21. package/dist/hooks/BDE_ShiftException.d.ts +1 -0
  22. package/dist/hooks/BDE_ShiftException.js +22 -0
  23. package/dist/hooks/BDE_ShiftModel.d.ts +1 -0
  24. package/dist/hooks/BDE_ShiftModel.js +24 -0
  25. package/dist/hooks/BDE_WorkTime.js +4 -1
  26. package/dist/hooks/Service_EquipmentAnnotation.d.ts +1 -0
  27. package/dist/hooks/Service_EquipmentAnnotation.js +15 -0
  28. package/dist/hooks/Service_KpiDefinition.d.ts +1 -0
  29. package/dist/hooks/Service_KpiDefinition.js +65 -0
  30. package/dist/hooks/Service_Ticket.js +8 -0
  31. package/dist/types/BDE_ShiftException.d.ts +34 -0
  32. package/dist/types/BDE_ShiftException.js +57 -0
  33. package/dist/types/BDE_ShiftModel.d.ts +34 -0
  34. package/dist/types/BDE_ShiftModel.js +57 -0
  35. package/dist/types/Service_EquipmentAnnotation.d.ts +35 -0
  36. package/dist/types/Service_EquipmentAnnotation.js +57 -0
  37. package/dist/types/Service_KpiDefinition.d.ts +34 -0
  38. package/dist/types/Service_KpiDefinition.js +57 -0
  39. package/dist/types/Service_Ticket.d.ts +9 -0
  40. package/dist/types/Service_Ticket.js +18 -0
  41. package/dist/types/index.d.ts +8 -0
  42. package/dist/types/index.js +11 -3
  43. package/package.json +15 -14
  44. package/pnpm-workspace.yaml +4 -0
  45. package/schema/BDE_ShiftException.json +57 -0
  46. package/schema/BDE_ShiftModel.json +58 -0
  47. package/schema/Service_EquipmentAnnotation.json +57 -0
  48. package/schema/Service_KpiDefinition.json +56 -0
  49. package/schema/Service_Ticket.json +9 -0
  50. package/dist/features/openservice/alarms/schedule/listAlarmTriggers.d.ts +0 -41
  51. package/dist/features/openservice/alarms/schedule/listAlarmTriggers.js +0 -159
  52. package/dist/functions/openinc-openservice-alarm-triggers.d.ts +0 -13
  53. package/dist/functions/openinc-openservice-alarm-triggers.js +0 -29
@@ -13,6 +13,8 @@
13
13
  "OD3_BDE_QAOrder": "BDE",
14
14
  "OD3_BDE_QAResult": "BDE",
15
15
  "OD3_BDE_Result": "BDE",
16
+ "OD3_BDE_ShiftException": "BDE",
17
+ "OD3_BDE_ShiftModel": "BDE",
16
18
  "OD3_BDE_Unit": "BDE",
17
19
  "OD3_BDE_WorkOrder": "BDE",
18
20
  "OD3_BDE_WorkTime": "BDE",
@@ -113,7 +115,9 @@
113
115
  "OD3_RAG_Request": "RAG",
114
116
  "OD3_Report": "CORE",
115
117
  "OD3_Service_Equipment": "SERVICE",
118
+ "OD3_Service_EquipmentAnnotation": "SERVICE",
116
119
  "OD3_Service_FormConfig": "SERVICE",
120
+ "OD3_Service_KpiDefinition": "SERVICE",
117
121
  "OD3_Service_MigrationMap": "SERVICE",
118
122
  "OD3_Service_Occurrence": "SERVICE",
119
123
  "OD3_Service_Project": "SERVICE",
@@ -0,0 +1,13 @@
1
+ /**
2
+ * The shifts of a model: each with ISO weekdays (1 = Monday … 7 = Sunday), a
3
+ * start and an end, optionally breaks. An end at or before the start is a night
4
+ * shift, not an error.
5
+ */
6
+ export declare function assertShifts(shifts: unknown): void;
7
+ /** Whether this runtime knows the IANA time zone. */
8
+ export declare function assertTimezone(zone: unknown): void;
9
+ /** The machines (sources) a shift model or exception is assigned to. */
10
+ export declare function assertSourcePointers(sources: unknown): void;
11
+ export declare const SHIFT_EXCEPTION_KINDS: readonly ["closed", "extra"];
12
+ /** An exception: a known kind, and a start before its end. */
13
+ export declare function assertShiftException(object: Parse.Object): void;
@@ -0,0 +1,96 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.SHIFT_EXCEPTION_KINDS = void 0;
7
+ exports.assertShifts = assertShifts;
8
+ exports.assertTimezone = assertTimezone;
9
+ exports.assertSourcePointers = assertSourcePointers;
10
+ exports.assertShiftException = assertShiftException;
11
+ // Shape checks for the shift calendar of the BDE (OD3_BDE_ShiftModel,
12
+ // OD3_BDE_ShiftException). The times themselves are computed with
13
+ // `@opendash/schedule` (`plannedOperatingTime`); this only keeps out what that
14
+ // maths could not read.
15
+ const node_1 = __importDefault(require("parse/node"));
16
+ const index_js_1 = require("../../../types/index.js");
17
+ const CLOCK = /^(\d{1,2}):(\d{2})$/;
18
+ /** Whether `value` is a wall-clock time `"HH:mm"` between 00:00 and 24:00. */
19
+ function isClock(value) {
20
+ const match = typeof value === "string" ? CLOCK.exec(value) : null;
21
+ if (!match)
22
+ return false;
23
+ const minutes = Number(match[1]) * 60 + Number(match[2]);
24
+ return Number(match[2]) < 60 && minutes <= 24 * 60;
25
+ }
26
+ function refuse(message) {
27
+ throw new node_1.default.Error(node_1.default.Error.VALIDATION_ERROR, message);
28
+ }
29
+ /**
30
+ * The shifts of a model: each with ISO weekdays (1 = Monday … 7 = Sunday), a
31
+ * start and an end, optionally breaks. An end at or before the start is a night
32
+ * shift, not an error.
33
+ */
34
+ function assertShifts(shifts) {
35
+ if (!Array.isArray(shifts))
36
+ refuse("shifts must be a list.");
37
+ shifts.forEach((shift, index) => {
38
+ const at = `Shift ${index + 1}`;
39
+ if (!shift || typeof shift !== "object")
40
+ refuse(`${at} is not an object.`);
41
+ const days = shift.days;
42
+ if (!Array.isArray(days) ||
43
+ days.length === 0 ||
44
+ !days.every((day) => Number.isInteger(day) && day >= 1 && day <= 7)) {
45
+ refuse(`${at} needs weekdays from 1 (Monday) to 7 (Sunday).`);
46
+ }
47
+ const { start, end, breaks } = shift;
48
+ if (!isClock(start) || !isClock(end)) {
49
+ refuse(`${at} needs a start and an end as "HH:mm".`);
50
+ }
51
+ if (breaks === undefined)
52
+ return;
53
+ if (!Array.isArray(breaks) ||
54
+ !breaks.every((pause) => !!pause &&
55
+ isClock(pause.start) &&
56
+ isClock(pause.end))) {
57
+ refuse(`${at} has a break without a start and an end as "HH:mm".`);
58
+ }
59
+ });
60
+ }
61
+ /** Whether this runtime knows the IANA time zone. */
62
+ function assertTimezone(zone) {
63
+ if (zone === undefined || zone === null || zone === "")
64
+ return;
65
+ try {
66
+ new Intl.DateTimeFormat("en-US", { timeZone: String(zone) });
67
+ }
68
+ catch {
69
+ refuse(`Unknown time zone "${String(zone)}".`);
70
+ }
71
+ }
72
+ /** The machines (sources) a shift model or exception is assigned to. */
73
+ function assertSourcePointers(sources) {
74
+ if (sources === undefined || sources === null)
75
+ return;
76
+ if (!Array.isArray(sources) ||
77
+ !sources.every((source) => !!source &&
78
+ source.className === index_js_1.Source.className &&
79
+ typeof (source.objectId ??
80
+ source.id) === "string")) {
81
+ refuse(`sources must be a list of ${index_js_1.Source.className} pointers.`);
82
+ }
83
+ }
84
+ exports.SHIFT_EXCEPTION_KINDS = ["closed", "extra"];
85
+ /** An exception: a known kind, and a start before its end. */
86
+ function assertShiftException(object) {
87
+ const kind = object.get("kind");
88
+ if (!exports.SHIFT_EXCEPTION_KINDS.includes(kind)) {
89
+ refuse(`kind must be one of ${exports.SHIFT_EXCEPTION_KINDS.join(", ")}.`);
90
+ }
91
+ const start = object.get("start");
92
+ const end = object.get("end");
93
+ if (!start || !end || end.getTime() <= start.getTime()) {
94
+ refuse("A shift exception needs a start before its end.");
95
+ }
96
+ }
@@ -24,7 +24,5 @@ export type { AlarmScheduleFields } from "./schedule/alarmScheduleFields.js";
24
24
  export { createAlarmSchedule, tenantForAlarmSchedule, } from "./schedule/createAlarmSchedule.js";
25
25
  export type { AlarmScheduleResult } from "./schedule/createAlarmSchedule.js";
26
26
  export { ensureAlarmScheduleAction, ensureAlarmScheduleWebhook, } from "./schedule/ensureAlarmScheduleAction.js";
27
- export { listAlarmTriggers } from "./schedule/listAlarmTriggers.js";
28
- export type { AlarmTriggerRow } from "./schedule/listAlarmTriggers.js";
29
27
  export { ALARM_SCHEDULE_ACTION_ID, ALARM_SCHEDULE_SECRET_CONFIG_KEY, } from "./schedule/AlarmScheduleTypes.js";
30
28
  export type { AlarmScheduleParams, ScheduleAlarmContext, } from "./schedule/AlarmScheduleTypes.js";
@@ -10,7 +10,7 @@
10
10
  * them would silently start creating duplicates. `README.md` has the wiring.
11
11
  */
12
12
  Object.defineProperty(exports, "__esModule", { value: true });
13
- exports.ALARM_SCHEDULE_SECRET_CONFIG_KEY = exports.ALARM_SCHEDULE_ACTION_ID = exports.listAlarmTriggers = exports.ensureAlarmScheduleWebhook = exports.ensureAlarmScheduleAction = exports.tenantForAlarmSchedule = exports.createAlarmSchedule = exports.dueDate = exports.alarmScheduleFields = exports.ALARM_TICKET_SECRET_CONFIG_KEY = exports.ALARM_TICKET_ACTION_ID = exports.ensureAlarmTicketAction = exports.tenantForAlarmTicket = exports.createAlarmTicket = exports.alarmTicketFields = exports.tenantForSecret = exports.resolveEquipment = exports.sensorLabel = exports.renderTitleTemplate = exports.formatValue = exports.firedAt = exports.alarmOrigin = exports.alarmKey = exports.alarmDetailLines = void 0;
13
+ exports.ALARM_SCHEDULE_SECRET_CONFIG_KEY = exports.ALARM_SCHEDULE_ACTION_ID = exports.ensureAlarmScheduleWebhook = exports.ensureAlarmScheduleAction = exports.tenantForAlarmSchedule = exports.createAlarmSchedule = exports.dueDate = exports.alarmScheduleFields = exports.ALARM_TICKET_SECRET_CONFIG_KEY = exports.ALARM_TICKET_ACTION_ID = exports.ensureAlarmTicketAction = exports.tenantForAlarmTicket = exports.createAlarmTicket = exports.alarmTicketFields = exports.tenantForSecret = exports.resolveEquipment = exports.sensorLabel = exports.renderTitleTemplate = exports.formatValue = exports.firedAt = exports.alarmOrigin = exports.alarmKey = exports.alarmDetailLines = void 0;
14
14
  // The shared base, here at the root because both actions read it: payload
15
15
  // shape, identity, and the two lookups every action needs.
16
16
  var alarmIdentity_js_1 = require("./alarmIdentity.js");
@@ -46,8 +46,6 @@ Object.defineProperty(exports, "tenantForAlarmSchedule", { enumerable: true, get
46
46
  var ensureAlarmScheduleAction_js_1 = require("./schedule/ensureAlarmScheduleAction.js");
47
47
  Object.defineProperty(exports, "ensureAlarmScheduleAction", { enumerable: true, get: function () { return ensureAlarmScheduleAction_js_1.ensureAlarmScheduleAction; } });
48
48
  Object.defineProperty(exports, "ensureAlarmScheduleWebhook", { enumerable: true, get: function () { return ensureAlarmScheduleAction_js_1.ensureAlarmScheduleWebhook; } });
49
- var listAlarmTriggers_js_1 = require("./schedule/listAlarmTriggers.js");
50
- Object.defineProperty(exports, "listAlarmTriggers", { enumerable: true, get: function () { return listAlarmTriggers_js_1.listAlarmTriggers; } });
51
49
  var AlarmScheduleTypes_js_1 = require("./schedule/AlarmScheduleTypes.js");
52
50
  Object.defineProperty(exports, "ALARM_SCHEDULE_ACTION_ID", { enumerable: true, get: function () { return AlarmScheduleTypes_js_1.ALARM_SCHEDULE_ACTION_ID; } });
53
51
  Object.defineProperty(exports, "ALARM_SCHEDULE_SECRET_CONFIG_KEY", { enumerable: true, get: function () { return AlarmScheduleTypes_js_1.ALARM_SCHEDULE_SECRET_CONFIG_KEY; } });
@@ -6,6 +6,7 @@ const initKanbanStates_js_1 = require("./kanbanState/initKanbanStates.js");
6
6
  const initMessages_js_1 = require("./messages/initMessages.js");
7
7
  const initSchedulesFeature_js_1 = require("./schedules/initSchedulesFeature.js");
8
8
  const initServiceSchedulesFeature_js_1 = require("./serviceSchedules/initServiceSchedulesFeature.js");
9
+ const initKpiFeature_js_1 = require("./kpis/initKpiFeature.js");
9
10
  const index_js_1 = require("../config/index.js");
10
11
  const index_js_2 = require("./alarms/index.js");
11
12
  const checkStatus_js_1 = require("./schedules/checkStatus.js");
@@ -41,6 +42,7 @@ async function init(generations) {
41
42
  // --- v2 (`Service_*`) ----------------------------------------------------
42
43
  if (generations.v2) {
43
44
  await (0, initServiceSchedulesFeature_js_1.initServiceSchedulesFeature)();
45
+ await (0, initKpiFeature_js_1.initKpiFeature)();
44
46
  await (0, index_js_2.ensureAlarmTicketAction)();
45
47
  await (0, index_js_2.ensureAlarmScheduleAction)();
46
48
  await (0, index_js_2.ensureAlarmScheduleWebhook)();
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Keeps the KPI series current: every night for the last weeks of every
3
+ * tenant (operating time grows by a day even when no ticket changes), and a
4
+ * minute after something that changes them — a ticket on a machine, a KPI
5
+ * definition, a shift model — for that tenant alone.
6
+ */
7
+ export declare function initKpiFeature(): Promise<void>;
8
+ /**
9
+ * Recompute one tenant's series soon. Saves come in bursts — a ticket form
10
+ * writes, its rules write again, a BDE disruption carries over — so the work
11
+ * waits until the tenant has been quiet for a minute.
12
+ */
13
+ export declare function scheduleKpiRecompute(tenantId: string | undefined): void;
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.initKpiFeature = initKpiFeature;
4
+ exports.scheduleKpiRecompute = scheduleKpiRecompute;
5
+ const cron_1 = require("cron");
6
+ const kpiJob_js_1 = require("./kpiJob.js");
7
+ const LOG = "[open.SERVICE KPIs]";
8
+ /** Quiet time after the last change before a tenant's series are recomputed. */
9
+ const DEBOUNCE_MS = 60_000;
10
+ const pending = new Map();
11
+ let started = false;
12
+ /**
13
+ * Keeps the KPI series current: every night for the last weeks of every
14
+ * tenant (operating time grows by a day even when no ticket changes), and a
15
+ * minute after something that changes them — a ticket on a machine, a KPI
16
+ * definition, a shift model — for that tenant alone.
17
+ */
18
+ async function initKpiFeature() {
19
+ if (started)
20
+ return;
21
+ started = true;
22
+ new cron_1.CronJob("0 30 2 * * *", () => {
23
+ (0, kpiJob_js_1.recomputeKpis)()
24
+ .then((result) => console.log(`${LOG} nightly run:`, result))
25
+ .catch((error) => console.error(`${LOG} nightly run failed:`, error));
26
+ }, null, true, "Europe/Berlin");
27
+ }
28
+ /**
29
+ * Recompute one tenant's series soon. Saves come in bursts — a ticket form
30
+ * writes, its rules write again, a BDE disruption carries over — so the work
31
+ * waits until the tenant has been quiet for a minute.
32
+ */
33
+ function scheduleKpiRecompute(tenantId) {
34
+ if (!started || !tenantId)
35
+ return;
36
+ clearTimeout(pending.get(tenantId));
37
+ pending.set(tenantId, setTimeout(() => {
38
+ pending.delete(tenantId);
39
+ (0, kpiJob_js_1.recomputeKpis)({ tenantId }).catch((error) => console.error(`${LOG} tenant ${tenantId} failed:`, error));
40
+ }, DEBOUNCE_MS));
41
+ }
@@ -0,0 +1,46 @@
1
+ import { type DataItemValueTypeInterface } from "../../openware/index.js";
2
+ /** How far back a regular run recomputes — late corrections included. */
3
+ export declare const KPI_RECOMPUTE_DAYS = 35;
4
+ /**
5
+ * The dimensions of a KPI series, in the order of `KPI_SERIES_DIMENSIONS`
6
+ * (`@opendash/openservice-shared`), which the reporting widgets read. Base
7
+ * quantities per day (see `KpiDayValues`); the ratios — MTBF, MTTR,
8
+ * availability — are sums of them divided over whatever range a widget shows.
9
+ */
10
+ export declare const KPI_VALUE_TYPES: DataItemValueTypeInterface[];
11
+ export interface KpiRunResult {
12
+ tenants: number;
13
+ /** Series written: one per definition and machine. */
14
+ series: number;
15
+ /** Why nothing was computed, when nothing was. */
16
+ skipped?: string;
17
+ /** With `dryRun`: what would have been written, summed over the range. */
18
+ preview?: KpiSeriesPreview[];
19
+ }
20
+ /** One series of a dry run: where it would go and its sums. */
21
+ export interface KpiSeriesPreview {
22
+ source: string;
23
+ id: string;
24
+ name: string;
25
+ equipment: string;
26
+ operatingTime: "shifts" | "calendar";
27
+ days: number;
28
+ /** Sums of the dimensions, in the order of {@link KPI_VALUE_TYPES}. */
29
+ totals: number[];
30
+ }
31
+ /**
32
+ * Recomputes the KPI series of the last `days` days — of one tenant, or of
33
+ * all. Recomputing, not appending: a ticket corrected last week changes last
34
+ * week's values, so they are written again (openware's update endpoint keeps
35
+ * one value per timestamp).
36
+ *
37
+ * Only on instances with openware: without it the series would have nowhere
38
+ * to go, and the analytics plugin shows a notice in their place.
39
+ */
40
+ export declare function recomputeKpis({ days, tenantId, now, dryRun, }?: {
41
+ days?: number;
42
+ tenantId?: string;
43
+ now?: Date;
44
+ /** Compute, but return a summary instead of writing to openware. */
45
+ dryRun?: boolean;
46
+ }): Promise<KpiRunResult>;
@@ -0,0 +1,273 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.KPI_VALUE_TYPES = exports.KPI_RECOMPUTE_DAYS = void 0;
7
+ exports.recomputeKpis = recomputeKpis;
8
+ // Computes the maintenance KPI series of every tenant and writes them to
9
+ // openware, where the monitoring widgets pick them like any sensor.
10
+ const node_1 = __importDefault(require("parse/node"));
11
+ const openservice_shared_1 = require("@opendash/openservice-shared");
12
+ const schedule_1 = require("@opendash/schedule");
13
+ const index_js_1 = require("../../config/index.js");
14
+ const index_js_2 = require("../../openware/index.js");
15
+ const index_js_3 = require("../../../types/index.js");
16
+ const ticketRules_js_1 = require("../tickets/ticketRules.js");
17
+ const kpiMaths_js_1 = require("./kpiMaths.js");
18
+ const LOG = "[open.SERVICE KPIs]";
19
+ const DAY_MS = 86_400_000;
20
+ /** How far back a regular run recomputes — late corrections included. */
21
+ exports.KPI_RECOMPUTE_DAYS = 35;
22
+ const DIMENSION_TYPES = {
23
+ operatingHours: { name: "Betriebszeit", unit: "h", type: "Number" },
24
+ downtimeHours: { name: "Ausfallzeit", unit: "h", type: "Number" },
25
+ failures: { name: "Ausfälle", unit: "", type: "Number" },
26
+ repairs: { name: "Instandsetzungen", unit: "", type: "Number" },
27
+ repairHours: { name: "Instandsetzungsdauer", unit: "h", type: "Number" },
28
+ activeRepairHours: {
29
+ name: "Aktive Reparaturzeit",
30
+ unit: "h",
31
+ type: "Number",
32
+ },
33
+ };
34
+ /**
35
+ * The dimensions of a KPI series, in the order of `KPI_SERIES_DIMENSIONS`
36
+ * (`@opendash/openservice-shared`), which the reporting widgets read. Base
37
+ * quantities per day (see `KpiDayValues`); the ratios — MTBF, MTTR,
38
+ * availability — are sums of them divided over whatever range a widget shows.
39
+ */
40
+ exports.KPI_VALUE_TYPES = openservice_shared_1.KPI_SERIES_DIMENSIONS.map((dimension) => DIMENSION_TYPES[dimension]);
41
+ function parseCondition(raw) {
42
+ if (!raw)
43
+ return undefined;
44
+ try {
45
+ return JSON.parse(raw);
46
+ }
47
+ catch {
48
+ return undefined;
49
+ }
50
+ }
51
+ /** The tenant's definitions; the default one seeded when it has none. */
52
+ async function definitionsOf(tenant) {
53
+ const existing = await new node_1.default.Query(index_js_3.Service_KpiDefinition)
54
+ .equalTo("tenant", tenant)
55
+ .limit(1000)
56
+ .find({ useMasterKey: true });
57
+ if (existing.length > 0)
58
+ return existing;
59
+ const seeded = new index_js_3.Service_KpiDefinition({
60
+ label: openservice_shared_1.DEFAULT_KPI_DEFINITION.label,
61
+ condition: JSON.stringify(openservice_shared_1.DEFAULT_KPI_DEFINITION.condition),
62
+ isDefault: true,
63
+ active: true,
64
+ tenant,
65
+ });
66
+ await seeded.save(null, { useMasterKey: true });
67
+ console.log(`${LOG} tenant ${tenant.id}: seeded "${seeded.label}"`);
68
+ return [seeded];
69
+ }
70
+ /** `OD3_Source` rows of a tenant: by id, with their tag and parent. */
71
+ async function sourcesOf(tenant) {
72
+ const rows = await new node_1.default.Query(index_js_3.Source)
73
+ .equalTo("tenant", tenant)
74
+ .findAll({ useMasterKey: true });
75
+ const byId = new Map();
76
+ const byTag = new Map();
77
+ for (const row of rows) {
78
+ const tag = row.get("tag");
79
+ byId.set(row.id, {
80
+ tag,
81
+ parentId: row.get("parent")?.id,
82
+ });
83
+ if (tag)
84
+ byTag.set(tag, row.id);
85
+ }
86
+ return { byId, byTag };
87
+ }
88
+ const ids = (value) => Array.isArray(value)
89
+ ? value
90
+ .map((entry) => entry ?? {})
91
+ .map((entry) => entry.id ?? entry.objectId)
92
+ .filter((id) => typeof id === "string")
93
+ : [];
94
+ /** Rows of a BDE class; none when the instance runs without the BDE. */
95
+ async function bdeRows(query) {
96
+ try {
97
+ return await query.findAll({ useMasterKey: true });
98
+ }
99
+ catch (error) {
100
+ console.warn(`${LOG} could not read ${query.className}:`, error);
101
+ return [];
102
+ }
103
+ }
104
+ /**
105
+ * The operating time of one machine: the shift models on its source and the
106
+ * sources above it, the exceptions that concern any of them. `undefined` when
107
+ * no model applies — the caller falls back to calendar time.
108
+ */
109
+ function operatingTimeOf(sourceId, sources, models, exceptions, from, to) {
110
+ const chain = [];
111
+ for (let id = sourceId; id && !chain.includes(id); id = sources.get(id)?.parentId) {
112
+ chain.push(id);
113
+ }
114
+ const assignments = [];
115
+ chain.forEach((id, depth) => {
116
+ for (const model of models) {
117
+ if (!ids(model.get("sources")).includes(id))
118
+ continue;
119
+ assignments.push({
120
+ depth,
121
+ pattern: {
122
+ id: model.id,
123
+ // Checked on save (shiftValidation.ts), so read as stored.
124
+ shifts: (model.get("shifts") ?? []),
125
+ validFrom: model.get("validFrom"),
126
+ timezone: model.get("timezone") || undefined,
127
+ },
128
+ });
129
+ }
130
+ });
131
+ if (assignments.length === 0)
132
+ return undefined;
133
+ const concerned = exceptions
134
+ .filter((exception) => {
135
+ const scope = ids(exception.get("sources"));
136
+ return scope.length === 0 || scope.some((id) => chain.includes(id));
137
+ })
138
+ .map((exception) => ({
139
+ kind: exception.get("kind"),
140
+ start: exception.get("start"),
141
+ end: exception.get("end"),
142
+ }));
143
+ return (0, schedule_1.plannedOperatingTime)({ assignments, exceptions: concerned, from, to });
144
+ }
145
+ /** Computes and writes the series of one tenant; returns how many. */
146
+ async function recomputeTenant(tenant, from, now, preview) {
147
+ const definitions = (await definitionsOf(tenant)).filter((definition) => definition.get("active") !== false);
148
+ if (definitions.length === 0)
149
+ return 0;
150
+ const allEquipment = await new node_1.default.Query(index_js_3.Service_Equipment)
151
+ .equalTo("tenant", tenant)
152
+ .notEqualTo("deleted", true)
153
+ .findAll({ useMasterKey: true });
154
+ const equipmentById = new Map(allEquipment.map((row) => [row.id, row]));
155
+ // A machine without a tag of its own lives in its hall's source: its series
156
+ // goes there, and the hall's shift model is its operating time.
157
+ const tagOf = (row, depth = 0) => !row || depth > 20
158
+ ? undefined
159
+ : (row.get("sourceTags")?.[0] ??
160
+ tagOf(equipmentById.get(row.get("parent")?.id ?? ""), depth + 1));
161
+ const tags = new Map(allEquipment.flatMap((row) => {
162
+ const tag = tagOf(row);
163
+ return tag ? [[row.id, tag]] : [];
164
+ }));
165
+ const equipment = allEquipment.filter((row) => tags.has(row.id));
166
+ if (equipment.length === 0) {
167
+ console.log(`${LOG} tenant ${tenant.id}: no machine has a source tag, nothing to write`);
168
+ return 0;
169
+ }
170
+ const sources = await sourcesOf(tenant);
171
+ const models = await bdeRows(new node_1.default.Query(index_js_3.BDE_ShiftModel).equalTo("tenant", tenant));
172
+ const exceptions = await bdeRows(new node_1.default.Query(index_js_3.BDE_ShiftException)
173
+ .equalTo("tenant", tenant)
174
+ .greaterThan("end", from)
175
+ .lessThan("start", now));
176
+ const cancelled = new Set((await new node_1.default.Query(index_js_3.Service_Status)
177
+ .equalTo("tenant", tenant)
178
+ .equalTo("category", "cancelled")
179
+ .findAll({ useMasterKey: true })).map((status) => status.id));
180
+ // Failures that touch the range. Archived tickets count (the master key
181
+ // sees them); a ticket created up to a week after the range can still carry
182
+ // a corrected start inside it.
183
+ const touching = node_1.default.Query.or(new node_1.default.Query(index_js_3.Service_Ticket).doesNotExist("closedAt"), new node_1.default.Query(index_js_3.Service_Ticket).greaterThanOrEqualTo("closedAt", from), new node_1.default.Query(index_js_3.Service_Ticket).greaterThanOrEqualTo("failureEnd", from))
184
+ .equalTo("tenant", tenant)
185
+ .containedIn("equipment", equipment)
186
+ .lessThanOrEqualTo("createdAt", new Date(now.getTime() + 7 * DAY_MS));
187
+ const tickets = (await touching.findAll({ useMasterKey: true })).filter((ticket) => !cancelled.has(ticket.get("status")?.id ?? ""));
188
+ const days = (0, kpiMaths_js_1.calendarDays)(from, now, schedule_1.DEFAULT_SHIFT_TIMEZONE);
189
+ let written = 0;
190
+ for (const machine of equipment) {
191
+ const tag = tags.get(machine.id);
192
+ const sourceId = sources.byTag.get(tag);
193
+ const shiftTime = operatingTimeOf(sourceId, sources.byId, models, exceptions, from, now);
194
+ const operating = shiftTime ?? [{ start: from, end: now }];
195
+ const ownTickets = tickets.filter((ticket) => ticket.get("equipment")?.id ===
196
+ machine.id);
197
+ for (const definition of definitions) {
198
+ const condition = parseCondition(definition.get("condition"));
199
+ const failures = ownTickets
200
+ .filter((ticket) => (0, ticketRules_js_1.ticketMeetsCondition)(ticket, condition))
201
+ .map((ticket) => ({
202
+ start: (ticket.get("failureStart") ?? ticket.createdAt),
203
+ end: ticket.get("failureEnd") ?? ticket.get("closedAt"),
204
+ activeRepairMinutes: ticket.get("actualDuration"),
205
+ }));
206
+ const values = (0, kpiMaths_js_1.kpiDayValues)({ days, operating, failures, now });
207
+ const item = {
208
+ id: (0, openservice_shared_1.kpiSeriesId)(definition.id, machine.id),
209
+ name: `${definition.get("label")} · ${machine.get("label")}`,
210
+ source: tag,
211
+ meta: {
212
+ openservice: {
213
+ kpiDefinition: definition.id,
214
+ equipment: machine.id,
215
+ equipmentLabel: machine.get("label"),
216
+ operatingTime: shiftTime ? "shifts" : "calendar",
217
+ },
218
+ },
219
+ valueTypes: exports.KPI_VALUE_TYPES,
220
+ values: values.map((day) => ({
221
+ date: day.date.getTime(),
222
+ value: openservice_shared_1.KPI_SERIES_DIMENSIONS.map((dimension) => day[dimension]),
223
+ })),
224
+ };
225
+ if (preview) {
226
+ preview.push({
227
+ source: item.source,
228
+ id: item.id,
229
+ name: item.name,
230
+ equipment: machine.get("label"),
231
+ operatingTime: shiftTime ? "shifts" : "calendar",
232
+ days: item.values.length,
233
+ totals: exports.KPI_VALUE_TYPES.map((_, index) => Math.round(item.values.reduce((sum, day) => sum + day.value[index], 0) * 1000) / 1000),
234
+ });
235
+ }
236
+ else {
237
+ await (0, index_js_2.publishDataItem)(item, undefined, true);
238
+ }
239
+ written++;
240
+ }
241
+ }
242
+ console.log(`${LOG} tenant ${tenant.id}: ${written} series over ${days.length} days`);
243
+ return written;
244
+ }
245
+ /**
246
+ * Recomputes the KPI series of the last `days` days — of one tenant, or of
247
+ * all. Recomputing, not appending: a ticket corrected last week changes last
248
+ * week's values, so they are written again (openware's update endpoint keeps
249
+ * one value per timestamp).
250
+ *
251
+ * Only on instances with openware: without it the series would have nowhere
252
+ * to go, and the analytics plugin shows a notice in their place.
253
+ */
254
+ async function recomputeKpis({ days = exports.KPI_RECOMPUTE_DAYS, tenantId, now = new Date(), dryRun = false, } = {}) {
255
+ if (!dryRun && !index_js_1.ConfigInstance.getInstance().getBoolean("OPENWARE")) {
256
+ return { tenants: 0, series: 0, skipped: "OPENWARE is off" };
257
+ }
258
+ const from = (0, kpiMaths_js_1.calendarDays)(new Date(now.getTime() - days * DAY_MS), now, schedule_1.DEFAULT_SHIFT_TIMEZONE)[0].start;
259
+ const tenants = tenantId
260
+ ? [index_js_3.Tenant.createWithoutData(tenantId)]
261
+ : await new node_1.default.Query(index_js_3.Tenant).findAll({ useMasterKey: true });
262
+ const preview = dryRun ? [] : undefined;
263
+ let series = 0;
264
+ for (const tenant of tenants) {
265
+ try {
266
+ series += await recomputeTenant(tenant, from, now, preview);
267
+ }
268
+ catch (error) {
269
+ console.error(`${LOG} tenant ${tenant.id} failed:`, error);
270
+ }
271
+ }
272
+ return { tenants: tenants.length, series, preview };
273
+ }
@@ -0,0 +1,51 @@
1
+ import { type TimeInterval } from "@opendash/schedule";
2
+ /** A failure as the KPI maths sees it — a ticket that met a definition. */
3
+ export interface KpiFailure {
4
+ start: Date;
5
+ /** Unset while the machine is still down. */
6
+ end?: Date;
7
+ /** Active repair work entered on the ticket (`actualDuration`), minutes. */
8
+ activeRepairMinutes?: number;
9
+ }
10
+ /**
11
+ * One day of one machine under one KPI definition. **Base quantities only**:
12
+ * they add up over any range, the ratios do not — an average of daily MTBFs is
13
+ * no MTBF. Over a range,
14
+ *
15
+ * - MTBF = Σ(operatingHours − downtimeHours) / Σfailures
16
+ * - mean down time (MDT) = ΣrepairHours / Σrepairs
17
+ * - MTTR (active repair) = ΣactiveRepairHours / Σrepairs
18
+ * - availability = 1 − ΣdowntimeHours / ΣoperatingHours
19
+ */
20
+ export interface KpiDayValues {
21
+ /** Start of the day, in the plant's time zone. */
22
+ date: Date;
23
+ /** Planned operating time of the day (shift model, else calendar time). */
24
+ operatingHours: number;
25
+ /** The part of it the machine was down — failure windows ∩ operating time. */
26
+ downtimeHours: number;
27
+ /** Failures that began on the day. */
28
+ failures: number;
29
+ /** Failures that ended on the day: the machine ran again. */
30
+ repairs: number;
31
+ /** Length of those failures, start to end (time to restore). */
32
+ repairHours: number;
33
+ /** Active repair work entered on those tickets. */
34
+ activeRepairHours: number;
35
+ }
36
+ /** Days `[start, next start)` covering `[from, to)`, on `zone`'s calendar. */
37
+ export declare function calendarDays(from: Date, to: Date, zone: string): TimeInterval[];
38
+ /**
39
+ * The base quantities of one machine for each of `days`.
40
+ *
41
+ * `operating` is the planned operating time over the whole range; a failure
42
+ * still open counts as down until `now`. Downtime is only counted inside
43
+ * operating time: a machine that broke on Friday evening and was repaired on
44
+ * Monday morning was not "down" over a weekend it would not have run.
45
+ */
46
+ export declare function kpiDayValues({ days, operating, failures, now, }: {
47
+ days: TimeInterval[];
48
+ operating: TimeInterval[];
49
+ failures: KpiFailure[];
50
+ now: Date;
51
+ }): KpiDayValues[];
@@ -0,0 +1,62 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.calendarDays = calendarDays;
7
+ exports.kpiDayValues = kpiDayValues;
8
+ // The maintenance KPIs of one machine, day by day. Pure: tickets, operating
9
+ // time and days in, numbers out — so it can be checked by hand.
10
+ const dayjs_1 = __importDefault(require("dayjs"));
11
+ const timezone_js_1 = __importDefault(require("dayjs/plugin/timezone.js"));
12
+ const utc_js_1 = __importDefault(require("dayjs/plugin/utc.js"));
13
+ const schedule_1 = require("@opendash/schedule");
14
+ dayjs_1.default.extend(utc_js_1.default);
15
+ dayjs_1.default.extend(timezone_js_1.default);
16
+ const HOUR_MS = 3_600_000;
17
+ /** Days `[start, next start)` covering `[from, to)`, on `zone`'s calendar. */
18
+ function calendarDays(from, to, zone) {
19
+ const days = [];
20
+ let date = (0, dayjs_1.default)(from).tz(zone).format("YYYY-MM-DD");
21
+ for (;;) {
22
+ const start = dayjs_1.default.tz(`${date} 00:00:00`, zone).toDate();
23
+ if (start.getTime() >= to.getTime())
24
+ break;
25
+ const next = dayjs_1.default.utc(date).add(1, "day").format("YYYY-MM-DD");
26
+ const end = dayjs_1.default.tz(`${next} 00:00:00`, zone).toDate();
27
+ days.push({ start, end });
28
+ date = next;
29
+ }
30
+ return days;
31
+ }
32
+ const round = (value) => Math.round(value * 1000) / 1000;
33
+ function within(day, date) {
34
+ const time = date.getTime();
35
+ return time >= day.start.getTime() && time < day.end.getTime();
36
+ }
37
+ /**
38
+ * The base quantities of one machine for each of `days`.
39
+ *
40
+ * `operating` is the planned operating time over the whole range; a failure
41
+ * still open counts as down until `now`. Downtime is only counted inside
42
+ * operating time: a machine that broke on Friday evening and was repaired on
43
+ * Monday morning was not "down" over a weekend it would not have run.
44
+ */
45
+ function kpiDayValues({ days, operating, failures, now, }) {
46
+ const down = (0, schedule_1.intersectIntervals)((0, schedule_1.mergeIntervals)(failures.map((failure) => ({
47
+ start: failure.start,
48
+ end: failure.end ?? now,
49
+ }))), operating);
50
+ return days.map((day) => {
51
+ const ended = failures.filter((failure) => failure.end && within(day, failure.end));
52
+ return {
53
+ date: day.start,
54
+ operatingHours: round((0, schedule_1.intervalsDuration)((0, schedule_1.intersectIntervals)(operating, [day])) / HOUR_MS),
55
+ downtimeHours: round((0, schedule_1.intervalsDuration)((0, schedule_1.intersectIntervals)(down, [day])) / HOUR_MS),
56
+ failures: failures.filter((failure) => within(day, failure.start)).length,
57
+ repairs: ended.length,
58
+ repairHours: round(ended.reduce((sum, failure) => sum + Math.max(0, failure.end.getTime() - failure.start.getTime()), 0) / HOUR_MS),
59
+ activeRepairHours: round(ended.reduce((sum, failure) => sum + (failure.activeRepairMinutes ?? 0), 0) / 60),
60
+ };
61
+ });
62
+ }