@openinc/parse-server-opendash 4.4.6 → 4.5.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 (70) hide show
  1. package/dist/featuremap.json +6 -7
  2. package/dist/features/config/index.d.ts +4 -1
  3. package/dist/features/config/index.js +6 -1
  4. package/dist/features/config/services/ensureConfigs.d.ts +29 -0
  5. package/dist/features/config/services/ensureConfigs.js +133 -0
  6. package/dist/features/config/types/ConfigKeys.d.ts +87 -7
  7. package/dist/features/config/types/ConfigKeys.js +112 -11
  8. package/dist/features/openservice/alarms/actionParams.d.ts +29 -0
  9. package/dist/features/openservice/alarms/actionParams.js +63 -0
  10. package/dist/features/openservice/alarms/index.d.ts +1 -1
  11. package/dist/features/openservice/alarms/index.js +2 -1
  12. package/dist/features/openservice/alarms/schedule/createAlarmSchedule.d.ts +1 -1
  13. package/dist/features/openservice/alarms/schedule/createAlarmSchedule.js +23 -1
  14. package/dist/features/openservice/alarms/schedule/ensureAlarmScheduleAction.d.ts +17 -0
  15. package/dist/features/openservice/alarms/schedule/ensureAlarmScheduleAction.js +83 -1
  16. package/dist/features/openservice/alarms/schedule/listAlarmTriggers.js +44 -22
  17. package/dist/features/openservice/alarms/ticket/createAlarmTicket.d.ts +1 -1
  18. package/dist/features/openservice/alarms/ticket/createAlarmTicket.js +10 -1
  19. package/dist/features/openservice/alarms/ticket/ensureAlarmTicketAction.js +18 -1
  20. package/dist/features/openservice/init.js +8 -3
  21. package/dist/features/openservice/serviceProviders/ProviderAccessTypes.d.ts +23 -0
  22. package/dist/features/openservice/serviceProviders/ProviderAccessTypes.js +17 -0
  23. package/dist/features/openservice/serviceProviders/grantProviderAccess.d.ts +35 -0
  24. package/dist/features/openservice/serviceProviders/grantProviderAccess.js +172 -0
  25. package/dist/features/openservice/serviceProviders/index.d.ts +5 -0
  26. package/dist/features/openservice/serviceProviders/index.js +12 -0
  27. package/dist/features/openservice/serviceProviders/providerRoleSetup.d.ts +63 -0
  28. package/dist/features/openservice/serviceProviders/providerRoleSetup.js +110 -0
  29. package/dist/features/openservice/setupStatus.d.ts +55 -0
  30. package/dist/features/openservice/setupStatus.js +139 -0
  31. package/dist/features/permissions/types/Permissions.d.ts +1 -0
  32. package/dist/features/permissions/types/Permissions.js +5 -0
  33. package/dist/functions/openinc-auth-login-passwordless.js +7 -2
  34. package/dist/functions/openinc-auth-validate-token.js +6 -0
  35. package/dist/functions/openinc-auth.common.js +13 -0
  36. package/dist/functions/openinc-openservice-provider-access.d.ts +22 -0
  37. package/dist/functions/openinc-openservice-provider-access.js +54 -0
  38. package/dist/functions/openinc-openservice-provider-setup.d.ts +19 -0
  39. package/dist/functions/openinc-openservice-provider-setup.js +57 -0
  40. package/dist/functions/openinc-openservice-setup.d.ts +24 -0
  41. package/dist/functions/openinc-openservice-setup.js +140 -0
  42. package/dist/hooks/Config_open_service.js +34 -10
  43. package/dist/hooks/Service_Equipment.js +6 -11
  44. package/dist/hooks/Service_Schedule_Execution.js +127 -7
  45. package/dist/scripts/migration/lib/articleMeta.d.ts +20 -7
  46. package/dist/scripts/migration/lib/articleMeta.js +20 -14
  47. package/dist/scripts/migration/passes/05-articles.d.ts +17 -8
  48. package/dist/scripts/migration/passes/05-articles.js +43 -24
  49. package/dist/types/BDE_Article.d.ts +27 -3
  50. package/dist/types/BDE_Article.js +48 -0
  51. package/dist/types/Service_MigrationMap.d.ts +26 -0
  52. package/dist/types/Service_MigrationMap.js +45 -0
  53. package/dist/types/Service_Occurrence.d.ts +31 -0
  54. package/dist/types/Service_Occurrence.js +51 -0
  55. package/dist/types/Service_Schedule_Execution.d.ts +6 -0
  56. package/dist/types/Service_Schedule_Execution.js +12 -0
  57. package/dist/types/index.d.ts +4 -4
  58. package/dist/types/index.js +5 -5
  59. package/package.json +1 -1
  60. package/schema/BDE_Article.json +41 -6
  61. package/schema/Service_FormConfig.json +10 -10
  62. package/schema/{Service_TriggerState.json → Service_Occurrence.json} +21 -9
  63. package/schema/Service_Schedule_Execution.json +8 -0
  64. package/dist/hooks/Service_TriggerState.d.ts +0 -1
  65. package/dist/hooks/Service_TriggerState.js +0 -17
  66. package/dist/types/Service_MeterReading.d.ts +0 -35
  67. package/dist/types/Service_MeterReading.js +0 -57
  68. package/dist/types/Service_TriggerState.d.ts +0 -31
  69. package/dist/types/Service_TriggerState.js +0 -51
  70. package/schema/Service_MeterReading.json +0 -54
@@ -1,3 +1,20 @@
1
+ /**
2
+ * The HTTP call that carries the action out.
3
+ *
4
+ * `type: "webhook"` means the executor runs an `OD3_AlarmWebhook` row rather
5
+ * than calling anything itself. That row used to be created by hand — and a
6
+ * hand-made one is how an installation ends up with `payload: "{}"`, which
7
+ * reaches the endpoint carrying neither secret nor event, so nothing happens
8
+ * and nothing says why.
9
+ *
10
+ * Found again by `url`, not by name: the url is what makes two rows the same
11
+ * webhook, a name is free text somebody renames.
12
+ *
13
+ * ⚠️ **The url is relative.** That is what the existing hand-made rows use and
14
+ * what this server answers, but whether the executor resolves it against the
15
+ * Parse base or needs an absolute address is open.WARE's business. If a fired
16
+ * alarm never arrives, check this first.
17
+ */
1
18
  export declare function ensureAlarmScheduleWebhook(): Promise<void>;
2
19
  /**
3
20
  * Make "schedule a maintenance appointment" selectable in the alarm dialog.
@@ -8,7 +8,72 @@ exports.ensureAlarmScheduleAction = ensureAlarmScheduleAction;
8
8
  const node_1 = __importDefault(require("parse/node"));
9
9
  const index_js_1 = require("../../../../types/index.js");
10
10
  const AlarmScheduleTypes_js_1 = require("./AlarmScheduleTypes.js");
11
+ /** Name of the webhook row. Free text — the url is what identifies it. */
12
+ const WEBHOOK_NAME = "open.SERVICE: Wartungstermin anlegen";
13
+ /**
14
+ * What the executor posts. Placeholders are substituted by open.WARE.
15
+ *
16
+ * Kept identical to the action row's own `payload`: the two are the same
17
+ * contract written down twice, and a difference between them is a bug waiting
18
+ * for whichever one the executor happens to read.
19
+ */
20
+ const WEBHOOK_PAYLOAD = JSON.stringify({
21
+ secret: "{{secret}}",
22
+ event: {
23
+ alarmId: "{{alarm.id}}",
24
+ name: "{{alarm.name}}",
25
+ userId: "{{alarm.user}}",
26
+ item_id: "{{item.id}}",
27
+ item_source: "{{item.source}}",
28
+ item_dimension: "{{item.dimension}}",
29
+ value: "{{value}}",
30
+ condition: "{{condition}}",
31
+ firedAt: "{{timestamp}}",
32
+ },
33
+ params: "{{action}}",
34
+ });
35
+ /**
36
+ * The HTTP call that carries the action out.
37
+ *
38
+ * `type: "webhook"` means the executor runs an `OD3_AlarmWebhook` row rather
39
+ * than calling anything itself. That row used to be created by hand — and a
40
+ * hand-made one is how an installation ends up with `payload: "{}"`, which
41
+ * reaches the endpoint carrying neither secret nor event, so nothing happens
42
+ * and nothing says why.
43
+ *
44
+ * Found again by `url`, not by name: the url is what makes two rows the same
45
+ * webhook, a name is free text somebody renames.
46
+ *
47
+ * ⚠️ **The url is relative.** That is what the existing hand-made rows use and
48
+ * what this server answers, but whether the executor resolves it against the
49
+ * Parse base or needs an absolute address is open.WARE's business. If a fired
50
+ * alarm never arrives, check this first.
51
+ */
11
52
  async function ensureAlarmScheduleWebhook() {
53
+ const url = "/parse/functions/openinc-openservice-alarm-create-schedule";
54
+ const existing = await new node_1.default.Query(index_js_1.AlarmWebhook)
55
+ .equalTo("url", url)
56
+ .first({ useMasterKey: true });
57
+ if (existing) {
58
+ // An empty payload is the failure this function exists to prevent, so it
59
+ // is repaired. One somebody deliberately customised is left alone.
60
+ const payload = existing.get("payload");
61
+ if (!payload || payload.trim() === "" || payload.trim() === "{}") {
62
+ existing.set("payload", WEBHOOK_PAYLOAD);
63
+ await existing.save(null, { useMasterKey: true });
64
+ console.log(`[AlarmSchedule] Filled in the empty payload of "${url}"`);
65
+ }
66
+ return;
67
+ }
68
+ const webhook = new index_js_1.AlarmWebhook();
69
+ webhook.set("name", WEBHOOK_NAME);
70
+ webhook.set("url", url);
71
+ webhook.set("method", "POST");
72
+ webhook.set("payload", WEBHOOK_PAYLOAD);
73
+ webhook.set("header", { "Content-Type": "application/json" });
74
+ webhook.set("extraOptions", {});
75
+ await webhook.save(null, { useMasterKey: true });
76
+ console.log(`[AlarmSchedule] Registered webhook "${WEBHOOK_NAME}"`);
12
77
  }
13
78
  /**
14
79
  * Make "schedule a maintenance appointment" selectable in the alarm dialog.
@@ -34,8 +99,19 @@ async function ensureAlarmScheduleAction() {
34
99
  const existing = await new node_1.default.Query(index_js_1.AlarmAction)
35
100
  .equalTo("topic", AlarmScheduleTypes_js_1.ALARM_SCHEDULE_ACTION_ID)
36
101
  .first({ useMasterKey: true });
37
- if (existing)
102
+ if (existing) {
103
+ // The form definition is code, not customer configuration, so it is kept
104
+ // up to date rather than frozen at whatever the first boot wrote. Without
105
+ // this a fix to `FORM_FIELDS` would only ever reach a fresh database —
106
+ // which is how every existing installation ended up with pickers that
107
+ // store whole objects instead of ids.
108
+ if (JSON.stringify(existing.get("formFields")) !== JSON.stringify(FORM_FIELDS)) {
109
+ existing.set("formFields", FORM_FIELDS);
110
+ await existing.save(null, { useMasterKey: true });
111
+ console.log(`[AlarmSchedule] Updated form fields of "${AlarmScheduleTypes_js_1.ALARM_SCHEDULE_ACTION_ID}"`);
112
+ }
38
113
  return;
114
+ }
39
115
  const action = new index_js_1.AlarmAction();
40
116
  action.set("label", "Wartungstermin anlegen (open.SERVICE)");
41
117
  action.set("type", "webhook");
@@ -90,6 +166,9 @@ const FORM_FIELDS = [
90
166
  className: "OD3_Service_Schedule_Template",
91
167
  displayField: "title",
92
168
  mode: "single",
169
+ // Without this the picker stores the whole selected object instead of
170
+ // its id — see actionParams.ts.
171
+ valueField: "objectId",
93
172
  },
94
173
  hint: "Arbeitsschritte und Einstellungen werden beim Auslösen kopiert. Ohne Vorlage entsteht ein Termin ohne Schritte.",
95
174
  },
@@ -101,6 +180,9 @@ const FORM_FIELDS = [
101
180
  className: "OD3_Service_Equipment",
102
181
  displayField: "label",
103
182
  mode: "single",
183
+ // Without this the picker stores the whole selected object instead of
184
+ // its id — see actionParams.ts.
185
+ valueField: "objectId",
104
186
  },
105
187
  hint: "Ohne Angabe wird über die Quellen-Tags der Maschine geraten — oder der Plan bleibt ohne Maschine.",
106
188
  },
@@ -6,6 +6,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.listAlarmTriggers = listAlarmTriggers;
7
7
  const node_1 = __importDefault(require("parse/node"));
8
8
  const index_js_1 = require("../../../../types/index.js");
9
+ const actionParams_js_1 = require("../actionParams.js");
9
10
  const AlarmScheduleTypes_js_1 = require("./AlarmScheduleTypes.js");
10
11
  /**
11
12
  * Every alarm in this tenant whose action creates a maintenance plan.
@@ -24,11 +25,39 @@ async function listAlarmTriggers(user) {
24
25
  const tenant = user.get("tenant");
25
26
  if (!tenant)
26
27
  return [];
27
- const alarms = await new node_1.default.Query(index_js_1.Alarm)
28
+ // Which `OD3_AlarmAction` row is ours. Needed as an id because that is what
29
+ // an alarm stores to point at it.
30
+ const actionRow = await new node_1.default.Query(index_js_1.AlarmAction)
31
+ .equalTo("topic", AlarmScheduleTypes_js_1.ALARM_SCHEDULE_ACTION_ID)
32
+ .first({ useMasterKey: true });
33
+ // Two spellings, because an alarm's `action` object carries both and neither
34
+ // is guaranteed:
35
+ //
36
+ // - `topic` is the stable name (`"openservice-create-schedule"`). It gets
37
+ // into the alarm by being spread in from the action row
38
+ // (`mapAlarmActionsReverse`), so it is missing if that row had not loaded
39
+ // yet when the alarm was saved.
40
+ // - `actionId` is the **objectId** of the action row, written by
41
+ // `AlarmCreate`. Always present, but it says nothing about which action it
42
+ // is without resolving the row first.
43
+ //
44
+ // Matching on `actionId` against the topic string — which is what this did —
45
+ // compares an objectId with `"openservice-create-schedule"` and therefore
46
+ // never matches anything: the overview was always empty.
47
+ const byTopic = new node_1.default.Query(index_js_1.Alarm)
28
48
  .equalTo("tenant", tenant)
29
49
  // `action` is an Object column; Mongo reads the dotted path into it. The
30
50
  // generated type only knows `any`, hence the cast.
31
- .equalTo("action.actionId", AlarmScheduleTypes_js_1.ALARM_SCHEDULE_ACTION_ID)
51
+ .equalTo("action.topic", AlarmScheduleTypes_js_1.ALARM_SCHEDULE_ACTION_ID);
52
+ const queries = [byTopic];
53
+ if (actionRow?.id) {
54
+ queries.push(new node_1.default.Query(index_js_1.Alarm)
55
+ .equalTo("tenant", tenant)
56
+ .equalTo("action.actionId", actionRow.id));
57
+ }
58
+ // The tenant constraint sits inside each branch rather than on the combined
59
+ // query, so no `or` semantics can widen it past the caller's own tenant.
60
+ const alarms = await (queries.length > 1 ? node_1.default.Query.or(...queries) : byTopic)
32
61
  .include("user")
33
62
  .limit(500)
34
63
  .find({ useMasterKey: true });
@@ -36,11 +65,11 @@ async function listAlarmTriggers(user) {
36
65
  return [];
37
66
  const plansByOrigin = await schedulesByOrigin(tenant, alarms);
38
67
  const templateTitles = await titlesFor(alarms
39
- .map((alarm) => templateIdOf(alarm))
68
+ .map((alarm) => templateIdOf(alarm, actionRow?.id))
40
69
  .filter((id) => !!id));
41
70
  return alarms.map((alarm) => {
42
71
  const action = (alarm.get("action") ?? {});
43
- const templateId = templateIdOf(alarm);
72
+ const templateId = templateIdOf(alarm, actionRow?.id);
44
73
  const source = alarm.get("item_source");
45
74
  const id = alarm.get("item_id");
46
75
  const dimension = alarm.get("item_dimension");
@@ -54,8 +83,8 @@ async function listAlarmTriggers(user) {
54
83
  owner: alarm.get("user")?.get("username"),
55
84
  templateId,
56
85
  templateTitle: templateId ? templateTitles.get(templateId) : undefined,
57
- equipmentId: stringField(action, "equipmentId"),
58
- dueInDays: numberField(action, "dueInDays"),
86
+ equipmentId: (0, actionParams_js_1.paramId)(action["equipmentId"]),
87
+ dueInDays: (0, actionParams_js_1.paramNumber)(action["dueInDays"]),
59
88
  schedules: plansByOrigin.get(`alarm:${alarm.id}`) ?? [],
60
89
  };
61
90
  });
@@ -110,24 +139,17 @@ async function titlesFor(templateIds) {
110
139
  /**
111
140
  * The template id out of the alarm's action settings.
112
141
  *
113
- * The alarm dialog prefixes each field with the action id
114
- * (`<actionId>__<key>`, see `AlarmCreate.tsx`), so both spellings are accepted:
115
- * the plain key is what the executor forwards as `params`.
142
+ * `AlarmCreate` prefixes its *form state* with the action row's objectId
143
+ * (`<objectId>__<key>`) but writes the value back under the plain key, so
144
+ * `templateId` is the spelling that reaches the database. The prefixed variant
145
+ * is still accepted as a fallback — with the objectId, which is what the prefix
146
+ * is actually built from. The previous fallback used the topic string and could
147
+ * therefore never match.
116
148
  */
117
- function templateIdOf(alarm) {
149
+ function templateIdOf(alarm, actionRowId) {
118
150
  const action = (alarm.get("action") ?? {});
119
- return (stringField(action, "templateId") ??
120
- stringField(action, `${AlarmScheduleTypes_js_1.ALARM_SCHEDULE_ACTION_ID}__templateId`));
121
- }
122
- function stringField(source, key) {
123
- const value = source[key];
124
- return typeof value === "string" && value ? value : undefined;
125
- }
126
- function numberField(source, key) {
127
- const value = source[key];
128
- return typeof value === "number" && Number.isFinite(value)
129
- ? value
130
- : undefined;
151
+ return ((0, actionParams_js_1.paramId)(action["templateId"]) ??
152
+ (actionRowId ? (0, actionParams_js_1.paramId)(action[`${actionRowId}__templateId`]) : undefined));
131
153
  }
132
154
  function sensorLabel(source, id, dimension) {
133
155
  const sensor = [source, id].filter(Boolean).join("/");
@@ -22,7 +22,7 @@ export interface AlarmTicketResult {
22
22
  * Deliberately thin: number, ACL, assignment notifications and the tenant's
23
23
  * watcher rules all happen in the `Service_Ticket` hooks, on every write path.
24
24
  */
25
- export declare function createAlarmTicket(tenant: Tenant, event: AlarmEvent, params?: AlarmTicketParams): Promise<AlarmTicketResult>;
25
+ export declare function createAlarmTicket(tenant: Tenant, event: AlarmEvent, rawParams?: AlarmTicketParams): Promise<AlarmTicketResult>;
26
26
  /**
27
27
  * The tenant a call belongs to, identified by its shared secret.
28
28
  *
@@ -7,6 +7,7 @@ exports.createAlarmTicket = createAlarmTicket;
7
7
  exports.tenantForAlarmTicket = tenantForAlarmTicket;
8
8
  const node_1 = __importDefault(require("parse/node"));
9
9
  const index_js_1 = require("../../../../types/index.js");
10
+ const actionParams_js_1 = require("../actionParams.js");
10
11
  const alarmIdentity_js_1 = require("../alarmIdentity.js");
11
12
  const resolveEquipment_js_1 = require("../resolveEquipment.js");
12
13
  const tenantForSecret_js_1 = require("../tenantForSecret.js");
@@ -25,10 +26,18 @@ const AlarmTicketTypes_js_1 = require("./AlarmTicketTypes.js");
25
26
  * Deliberately thin: number, ACL, assignment notifications and the tenant's
26
27
  * watcher rules all happen in the `Service_Ticket` hooks, on every write path.
27
28
  */
28
- async function createAlarmTicket(tenant, event, params = {}) {
29
+ async function createAlarmTicket(tenant, event, rawParams = {}) {
29
30
  if (!(0, alarmIdentity_js_1.alarmKey)(event)) {
30
31
  throw new node_1.default.Error(node_1.default.Error.INVALID_QUERY, "The alarm payload identifies no alarm: pass alarmId, or item_source/item_id.");
31
32
  }
33
+ // Same normalisation as the schedule action: the reference fields can arrive
34
+ // as whole objects from alarms configured before the form set a `valueField`
35
+ // (see `actionParams.ts`).
36
+ const params = {
37
+ ...rawParams,
38
+ equipmentId: (0, actionParams_js_1.paramId)(rawParams.equipmentId),
39
+ projectId: (0, actionParams_js_1.paramId)(rawParams.projectId),
40
+ };
32
41
  const fields = (0, alarmTicketFields_js_1.alarmTicketFields)(event, params);
33
42
  if (!params.duplicate) {
34
43
  const open = await findOpenTicket(tenant, fields.origin);
@@ -32,8 +32,19 @@ async function ensureAlarmTicketAction() {
32
32
  const existing = await new node_1.default.Query(index_js_1.AlarmAction)
33
33
  .equalTo("topic", AlarmTicketTypes_js_1.ALARM_TICKET_ACTION_ID)
34
34
  .first({ useMasterKey: true });
35
- if (existing)
35
+ if (existing) {
36
+ // The form definition is code, not customer configuration, so it is kept
37
+ // up to date rather than frozen at whatever the first boot wrote. Without
38
+ // this a fix to `FORM_FIELDS` would only ever reach a fresh database —
39
+ // which is how every existing installation ended up with pickers that
40
+ // store whole objects instead of ids.
41
+ if (JSON.stringify(existing.get("formFields")) !== JSON.stringify(FORM_FIELDS)) {
42
+ existing.set("formFields", FORM_FIELDS);
43
+ await existing.save(null, { useMasterKey: true });
44
+ console.log(`[AlarmTicket] Updated form fields of "${AlarmTicketTypes_js_1.ALARM_TICKET_ACTION_ID}"`);
45
+ }
36
46
  return;
47
+ }
37
48
  const action = new index_js_1.AlarmAction();
38
49
  action.set("label", "Ticket erstellen (open.SERVICE)");
39
50
  action.set("type", "webhook");
@@ -99,6 +110,9 @@ const FORM_FIELDS = [
99
110
  className: "OD3_Service_Equipment",
100
111
  displayField: "label",
101
112
  mode: "single",
113
+ // Without this the picker stores the whole selected object instead of
114
+ // its id — see actionParams.ts.
115
+ valueField: "objectId",
102
116
  },
103
117
  hint: "Ohne Angabe wird über die Quellen-Tags der Maschine geraten — oder das Ticket bleibt ohne Maschine.",
104
118
  },
@@ -110,6 +124,9 @@ const FORM_FIELDS = [
110
124
  className: "OD3_Service_Project",
111
125
  displayField: "label",
112
126
  mode: "single",
127
+ // Without this the picker stores the whole selected object instead of
128
+ // its id — see actionParams.ts.
129
+ valueField: "objectId",
113
130
  },
114
131
  },
115
132
  {
@@ -6,7 +6,8 @@ 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 index_js_1 = require("./alarms/index.js");
9
+ const index_js_1 = require("../config/index.js");
10
+ const index_js_2 = require("./alarms/index.js");
10
11
  const checkStatus_js_1 = require("./schedules/checkStatus.js");
11
12
  const reassignScheduleExecutions_js_1 = require("./schedules/reassignScheduleExecutions.js");
12
13
  const initTicket_js_1 = require("./ticket/initTicket.js");
@@ -34,7 +35,11 @@ async function init() {
34
35
  await (0, initSchedulesFeature_js_1.initSchedulesFeature)();
35
36
  // --- v2 (`Service_*`) ----------------------------------------------------
36
37
  await (0, initServiceSchedulesFeature_js_1.initServiceSchedulesFeature)();
37
- await (0, index_js_1.ensureAlarmTicketAction)();
38
- await (0, index_js_1.ensureAlarmScheduleAction)();
38
+ await (0, index_js_2.ensureAlarmTicketAction)();
39
+ await (0, index_js_2.ensureAlarmScheduleAction)();
40
+ await (0, index_js_2.ensureAlarmScheduleWebhook)();
41
+ // Last, so the rows it reports as missing are the ones a human still has to
42
+ // supply rather than ones a later bootstrap would have created anyway.
43
+ await (0, index_js_1.ensureConfigs)();
39
44
  console.log("open.SERVICE feature initialized.");
40
45
  }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * External service provider access, as a user rather than a link token.
3
+ *
4
+ * Decided on 2026-09-16. The token route (`openinc-openservice-provider-view`
5
+ * plus a bespoke read-only page) was specified but never built, so this
6
+ * replaces a plan, not an implementation — the cheapest moment to change one.
7
+ */
8
+ /**
9
+ * Role name prefix, one role per tenant: `od-service-provider-<tenantId>`.
10
+ *
11
+ * Follows the `od-tenant-user-<id>` / `od-tenant-admin-<id>` convention the
12
+ * rest of the stack uses, so the role sorts and reads like the others.
13
+ */
14
+ export declare const PROVIDER_ROLE_PREFIX: "od-service-provider-";
15
+ /** Outcome of granting one provider access to one plan. */
16
+ export interface ProviderGrantResult {
17
+ userId: string;
18
+ /** The address the login link goes to. */
19
+ email: string;
20
+ /** `true` when an account had to be created for this contact. */
21
+ created: boolean;
22
+ scheduleId: string;
23
+ }
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ /**
3
+ * External service provider access, as a user rather than a link token.
4
+ *
5
+ * Decided on 2026-09-16. The token route (`openinc-openservice-provider-view`
6
+ * plus a bespoke read-only page) was specified but never built, so this
7
+ * replaces a plan, not an implementation — the cheapest moment to change one.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.PROVIDER_ROLE_PREFIX = void 0;
11
+ /**
12
+ * Role name prefix, one role per tenant: `od-service-provider-<tenantId>`.
13
+ *
14
+ * Follows the `od-tenant-user-<id>` / `od-tenant-admin-<id>` convention the
15
+ * rest of the stack uses, so the role sorts and reads like the others.
16
+ */
17
+ exports.PROVIDER_ROLE_PREFIX = "od-service-provider-";
@@ -0,0 +1,35 @@
1
+ import { Tenant } from "../../../types/index.js";
2
+ import { type ProviderGrantResult } from "./ProviderAccessTypes.js";
3
+ /**
4
+ * Give an external service provider access to one maintenance plan — as a
5
+ * **user**, not as a link token.
6
+ *
7
+ * **Why a user.** A token would mean re-inventing authorisation: which fields
8
+ * it may see, how long it lives, how it is revoked, and a bespoke read-only
9
+ * page to render it. A user needs none of that. `syncAssignmentAcl` already
10
+ * answers "who may see this plan" from `assignedUsers`, un-assigning already
11
+ * takes access away again, and an execution the provider signs carries a real
12
+ * `performedBy` instead of an anonymous token — which is the difference between
13
+ * a protocol an auditor accepts and one they do not.
14
+ *
15
+ * The convenience of the token link survives: `openinc-auth-login-passwordless`
16
+ * mails a real session, so the provider still just clicks a link in their
17
+ * email. They simply arrive as somebody rather than as nobody.
18
+ *
19
+ * **Deliberately explicit.** Nothing here runs by itself. Turning a row in an
20
+ * address book into an account that can log in is a decision, and it is made by
21
+ * a person pressing a button — never as a side effect of sending a
22
+ * notification.
23
+ */
24
+ export declare function grantProviderAccess(tenant: Tenant, contactId: string, scheduleId: string): Promise<ProviderGrantResult>;
25
+ /**
26
+ * Take access to one plan away again.
27
+ *
28
+ * Only the assignment is removed — the account and the role stay. A provider
29
+ * usually works on several plans over time, and deleting the user because one
30
+ * job ended would orphan the `performedBy` on every protocol they signed.
31
+ */
32
+ export declare function revokeProviderAccess(tenant: Tenant, contactId: string, scheduleId: string): Promise<{
33
+ scheduleId: string;
34
+ userId?: string;
35
+ }>;
@@ -0,0 +1,172 @@
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.grantProviderAccess = grantProviderAccess;
7
+ exports.revokeProviderAccess = revokeProviderAccess;
8
+ const crypto_1 = require("crypto");
9
+ const node_1 = __importDefault(require("parse/node"));
10
+ const index_js_1 = require("../../../types/index.js");
11
+ const ProviderAccessTypes_js_1 = require("./ProviderAccessTypes.js");
12
+ /**
13
+ * Give an external service provider access to one maintenance plan — as a
14
+ * **user**, not as a link token.
15
+ *
16
+ * **Why a user.** A token would mean re-inventing authorisation: which fields
17
+ * it may see, how long it lives, how it is revoked, and a bespoke read-only
18
+ * page to render it. A user needs none of that. `syncAssignmentAcl` already
19
+ * answers "who may see this plan" from `assignedUsers`, un-assigning already
20
+ * takes access away again, and an execution the provider signs carries a real
21
+ * `performedBy` instead of an anonymous token — which is the difference between
22
+ * a protocol an auditor accepts and one they do not.
23
+ *
24
+ * The convenience of the token link survives: `openinc-auth-login-passwordless`
25
+ * mails a real session, so the provider still just clicks a link in their
26
+ * email. They simply arrive as somebody rather than as nobody.
27
+ *
28
+ * **Deliberately explicit.** Nothing here runs by itself. Turning a row in an
29
+ * address book into an account that can log in is a decision, and it is made by
30
+ * a person pressing a button — never as a side effect of sending a
31
+ * notification.
32
+ */
33
+ async function grantProviderAccess(tenant, contactId, scheduleId) {
34
+ const contact = await new node_1.default.Query(index_js_1.Contact)
35
+ .equalTo("objectId", contactId)
36
+ .equalTo("tenant", tenant)
37
+ .notEqualTo("deleted", true)
38
+ .first({ useMasterKey: true });
39
+ if (!contact) {
40
+ throw new node_1.default.Error(node_1.default.Error.OBJECT_NOT_FOUND, "No such contact in this tenant.");
41
+ }
42
+ const email = contact.get("email")?.trim();
43
+ if (!email) {
44
+ // Without an address there is nothing to send a login to, and nothing to
45
+ // identify an existing account by. Better a clear refusal than an account
46
+ // nobody can reach.
47
+ throw new node_1.default.Error(node_1.default.Error.INVALID_QUERY, "This contact has no email address — add one before granting access.");
48
+ }
49
+ const schedule = await new node_1.default.Query(index_js_1.Service_Schedule)
50
+ .equalTo("objectId", scheduleId)
51
+ .equalTo("tenant", tenant)
52
+ .doesNotExist("deletedAt")
53
+ .first({ useMasterKey: true });
54
+ if (!schedule) {
55
+ throw new node_1.default.Error(node_1.default.Error.OBJECT_NOT_FOUND, "No such maintenance plan in this tenant.");
56
+ }
57
+ const { user, created } = await ensureProviderUser(tenant, contact, email);
58
+ await ensureProviderRole(tenant, user);
59
+ // The grant itself. `afterSave` rebuilds the plan's ACL from its assignments,
60
+ // so this one line is what actually makes the plan readable to them.
61
+ schedule.relation("assignedUsers").add(user);
62
+ await schedule.save(null, { useMasterKey: true });
63
+ // Remember the account on the contact, so the next grant reuses it instead of
64
+ // creating a second one — and so the UI can show that access exists.
65
+ if (!contact.get("user")) {
66
+ contact.set("user", user);
67
+ await contact.save(null, { useMasterKey: true });
68
+ }
69
+ return { userId: user.id, email, created, scheduleId: schedule.id };
70
+ }
71
+ /**
72
+ * Take access to one plan away again.
73
+ *
74
+ * Only the assignment is removed — the account and the role stay. A provider
75
+ * usually works on several plans over time, and deleting the user because one
76
+ * job ended would orphan the `performedBy` on every protocol they signed.
77
+ */
78
+ async function revokeProviderAccess(tenant, contactId, scheduleId) {
79
+ const contact = await new node_1.default.Query(index_js_1.Contact)
80
+ .equalTo("objectId", contactId)
81
+ .equalTo("tenant", tenant)
82
+ .include("user")
83
+ .first({ useMasterKey: true });
84
+ const user = contact?.get("user");
85
+ if (!user)
86
+ return { scheduleId };
87
+ const schedule = await new node_1.default.Query(index_js_1.Service_Schedule)
88
+ .equalTo("objectId", scheduleId)
89
+ .equalTo("tenant", tenant)
90
+ .first({ useMasterKey: true });
91
+ if (!schedule) {
92
+ throw new node_1.default.Error(node_1.default.Error.OBJECT_NOT_FOUND, "No such maintenance plan in this tenant.");
93
+ }
94
+ schedule.relation("assignedUsers").remove(user);
95
+ await schedule.save(null, { useMasterKey: true });
96
+ return { scheduleId, userId: user.id };
97
+ }
98
+ /**
99
+ * The account behind a contact — the existing one wherever possible.
100
+ *
101
+ * Matched by email, because that is the identity the provider already has and
102
+ * the one the login link is sent to. A provider who works for two customers on
103
+ * the same open.DASH keeps one account.
104
+ *
105
+ * The account is created **without a usable password**: there is no password to
106
+ * leak or to phone somebody about, and the only way in is the emailed session
107
+ * link. `emailVerified` stays false — clicking the link is what proves the
108
+ * address, and nothing here should assert it on their behalf.
109
+ */
110
+ async function ensureProviderUser(tenant, contact, email) {
111
+ const linked = contact.get("user");
112
+ if (linked?.id) {
113
+ const fetched = await new node_1.default.Query("_User")
114
+ .equalTo("objectId", linked.id)
115
+ .first({ useMasterKey: true });
116
+ if (fetched)
117
+ return { user: fetched, created: false };
118
+ }
119
+ const existing = await new node_1.default.Query("_User")
120
+ .equalTo("email", email.toLowerCase())
121
+ .first({ useMasterKey: true });
122
+ if (existing)
123
+ return { user: existing, created: false };
124
+ const user = new node_1.default.User();
125
+ user.set("username", email.toLowerCase());
126
+ user.set("email", email.toLowerCase());
127
+ // Random and never returned: the account is reached by emailed session link.
128
+ user.set("password", randomSecret());
129
+ user.set("tenant", tenant);
130
+ user.set("name", [contact.get("firstname"), contact.get("lastname")]
131
+ .filter(Boolean)
132
+ .join(" ")
133
+ .trim() || email);
134
+ await user.save(null, { useMasterKey: true });
135
+ return { user, created: true };
136
+ }
137
+ /**
138
+ * The tenant's service-provider role, created on first use.
139
+ *
140
+ * One role per tenant (`od-service-provider-<tenant>`), so an administrator can
141
+ * grant it the capabilities providers should have — the plugin access and
142
+ * performing executions — without touching the plans themselves. The role
143
+ * carries **no** capability from here: which ones a provider gets is a policy
144
+ * decision per customer, and silently granting them would be this function
145
+ * deciding it.
146
+ */
147
+ async function ensureProviderRole(tenant, user) {
148
+ const name = `${ProviderAccessTypes_js_1.PROVIDER_ROLE_PREFIX}${tenant.id}`;
149
+ let role = await new node_1.default.Query(node_1.default.Role)
150
+ .equalTo("name", name)
151
+ .first({ useMasterKey: true });
152
+ if (!role) {
153
+ const acl = new node_1.default.ACL();
154
+ acl.setRoleReadAccess("od-admin", true);
155
+ acl.setRoleWriteAccess("od-admin", true);
156
+ acl.setRoleReadAccess(`od-tenant-admin-${tenant.id}`, true);
157
+ acl.setRoleWriteAccess(`od-tenant-admin-${tenant.id}`, true);
158
+ role = new node_1.default.Role(name, acl);
159
+ role.set("tenant", tenant);
160
+ await role.save(null, { useMasterKey: true });
161
+ console.log(`[ProviderAccess] Created role ${name}`);
162
+ }
163
+ role.getUsers().add(user);
164
+ await role.save(null, { useMasterKey: true });
165
+ }
166
+ function randomSecret() {
167
+ // 32 bytes of hex — never shown, never reused, never needed again. Node's
168
+ // `randomBytes` rather than the global WebCrypto, matching how
169
+ // `openinc-auth-login-microsoft` fills the same field and staying independent
170
+ // of which Node version the image ships.
171
+ return (0, crypto_1.randomBytes)(32).toString("hex");
172
+ }
@@ -0,0 +1,5 @@
1
+ export { grantProviderAccess, revokeProviderAccess, } from "./grantProviderAccess.js";
2
+ export { PROVIDER_ROLE_PREFIX } from "./ProviderAccessTypes.js";
3
+ export { PROVIDER_CAPABILITIES, providerRoleStatus, setProviderCapabilities, } from "./providerRoleSetup.js";
4
+ export type { ProviderCapabilityState, ProviderRoleStatus, } from "./providerRoleSetup.js";
5
+ export type { ProviderGrantResult } from "./ProviderAccessTypes.js";
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.setProviderCapabilities = exports.providerRoleStatus = exports.PROVIDER_CAPABILITIES = exports.PROVIDER_ROLE_PREFIX = exports.revokeProviderAccess = exports.grantProviderAccess = void 0;
4
+ var grantProviderAccess_js_1 = require("./grantProviderAccess.js");
5
+ Object.defineProperty(exports, "grantProviderAccess", { enumerable: true, get: function () { return grantProviderAccess_js_1.grantProviderAccess; } });
6
+ Object.defineProperty(exports, "revokeProviderAccess", { enumerable: true, get: function () { return grantProviderAccess_js_1.revokeProviderAccess; } });
7
+ var ProviderAccessTypes_js_1 = require("./ProviderAccessTypes.js");
8
+ Object.defineProperty(exports, "PROVIDER_ROLE_PREFIX", { enumerable: true, get: function () { return ProviderAccessTypes_js_1.PROVIDER_ROLE_PREFIX; } });
9
+ var providerRoleSetup_js_1 = require("./providerRoleSetup.js");
10
+ Object.defineProperty(exports, "PROVIDER_CAPABILITIES", { enumerable: true, get: function () { return providerRoleSetup_js_1.PROVIDER_CAPABILITIES; } });
11
+ Object.defineProperty(exports, "providerRoleStatus", { enumerable: true, get: function () { return providerRoleSetup_js_1.providerRoleStatus; } });
12
+ Object.defineProperty(exports, "setProviderCapabilities", { enumerable: true, get: function () { return providerRoleSetup_js_1.setProviderCapabilities; } });