@meshmakers/octo-services 3.5.300 → 3.5.360

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.
@@ -10,7 +10,8 @@ import { map, catchError, finalize } from 'rxjs/operators';
10
10
  import { of, firstValueFrom, map as map$1, Subject, throwError, from, switchMap, takeUntil, filter, fromEvent } from 'rxjs';
11
11
  import { HttpClient, HttpParams, HttpErrorResponse, HttpContext, HttpHeaders, HttpEventType } from '@angular/common/http';
12
12
  import { Upload } from 'tus-js-client';
13
- import { AuthorizeService } from '@meshmakers/shared-auth';
13
+ import { AuthorizeService, Roles } from '@meshmakers/shared-auth';
14
+ import { CronParserService } from '@meshmakers/shared-ui';
14
15
 
15
16
  class OctoServiceOptions {
16
17
  assetServices;
@@ -7996,6 +7997,1000 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.5", ngImpor
7996
7997
  }]
7997
7998
  }] });
7998
7999
 
8000
+ const PICKER_USERS_PAGE_SIZE = 500;
8001
+ const PICKER_USERS_MAX_PAGES = 20;
8002
+ async function loadPickerUsers(identityService, options = {}) {
8003
+ try {
8004
+ return await loadDirectoryUsers(identityService);
8005
+ }
8006
+ catch (error) {
8007
+ if (options.fallbackToGetPagedOnForbidden && error instanceof HttpErrorResponse && error.status === 403) {
8008
+ const users = await loadAdminPickerUsers(identityService);
8009
+ return users.map(user => ({ userId: user.userId, displayName: userDisplayName(user) }));
8010
+ }
8011
+ throw error;
8012
+ }
8013
+ }
8014
+ async function loadDirectoryUsers(identityService) {
8015
+ const users = [];
8016
+ for (let page = 0; page < PICKER_USERS_MAX_PAGES; page++) {
8017
+ const result = await identityService.getUserDirectoryWithFallback(users.length, PICKER_USERS_PAGE_SIZE);
8018
+ const list = result?.list ?? [];
8019
+ users.push(...list);
8020
+ if (list.length < PICKER_USERS_PAGE_SIZE || users.length >= (result?.totalCount ?? 0)) {
8021
+ break;
8022
+ }
8023
+ }
8024
+ return users;
8025
+ }
8026
+ async function loadAdminPickerUsers(identityService) {
8027
+ const users = [];
8028
+ for (let page = 0; page < PICKER_USERS_MAX_PAGES; page++) {
8029
+ const result = await identityService.getUsers(users.length, PICKER_USERS_PAGE_SIZE);
8030
+ const list = result?.list ?? [];
8031
+ users.push(...list);
8032
+ if (list.length < PICKER_USERS_PAGE_SIZE || users.length >= (result?.totalCount ?? 0)) {
8033
+ break;
8034
+ }
8035
+ }
8036
+ return users;
8037
+ }
8038
+ function userDisplayName(user) {
8039
+ const fullName = personName(user);
8040
+ return fullName.length > 0 ? fullName : (user.name ?? '');
8041
+ }
8042
+ function userPickerText(user) {
8043
+ const fullName = personName(user);
8044
+ const name = user.name ?? '';
8045
+ return fullName.length > 0 ? `${fullName} (${name})` : name;
8046
+ }
8047
+ function personName(user) {
8048
+ return [user.firstName, user.lastName]
8049
+ .filter(n => !!n && n.trim().length > 0)
8050
+ .map(n => n.trim())
8051
+ .join(' ');
8052
+ }
8053
+
8054
+ function nameSearchTerm(text) {
8055
+ return text
8056
+ .replace(/^\*+|\*+$/g, '')
8057
+ .replace(/[.+?^${}()|[\]\\]/g, '\\$&')
8058
+ .replace(/\*/g, '\\x2A')
8059
+ .replace(/^@/, '\\x40');
8060
+ }
8061
+
8062
+ function notificationErrorText(lastError) {
8063
+ return lastError?.replace(/^\[[^\]]*\]:\s*/, '') || null;
8064
+ }
8065
+ function notificationRecipientStatus(state, subscriptionDeployed, userExists, scheduleValid) {
8066
+ const active = subscriptionDeployed;
8067
+ if (!userExists)
8068
+ return { active, health: 'ERROR', problem: 'USER_DELETED', detail: null };
8069
+ if (!scheduleValid)
8070
+ return { active, health: 'ERROR', problem: 'INVALID_SCHEDULE', detail: null };
8071
+ if (state?.lastError)
8072
+ return { active, health: 'ERROR', problem: 'RUN_FAILED', detail: notificationErrorText(state.lastError) };
8073
+ return { active, health: state?.lastRunAt ? 'OK' : 'NOT_RUN', problem: null, detail: null };
8074
+ }
8075
+ function notificationSubscriptionHealth(states, deployed) {
8076
+ if (!deployed || states.length === 0)
8077
+ return null;
8078
+ if (states.some(state => state?.lastError))
8079
+ return 'ERROR';
8080
+ return states.every(state => !state?.lastRunAt) ? 'NOT_RUN' : 'OK';
8081
+ }
8082
+
8083
+ const NOTIFICATION_MIN_INTERVAL_MS = 60_000;
8084
+ const NOTIFICATION_SCHEDULE_TYPES = ['minutes', 'hourly', 'daily', 'weekly', 'monthly', 'custom'];
8085
+ const NOTIFICATION_DEFAULT_CRON = '0 0 7 * * *';
8086
+ const SAMPLE_SIZE = 20;
8087
+ function notificationScheduleIssue(nextExecutions, cron) {
8088
+ if (!cron?.trim())
8089
+ return 'EMPTY';
8090
+ let executions;
8091
+ try {
8092
+ executions = nextExecutions(cron, SAMPLE_SIZE);
8093
+ }
8094
+ catch {
8095
+ return 'INVALID';
8096
+ }
8097
+ if (executions.length === 0)
8098
+ return 'INVALID';
8099
+ for (let i = 1; i < executions.length; i++) {
8100
+ if (executions[i].getTime() - executions[i - 1].getTime() < NOTIFICATION_MIN_INTERVAL_MS) {
8101
+ return 'TOO_FREQUENT';
8102
+ }
8103
+ }
8104
+ return null;
8105
+ }
8106
+ function withScheduleTimeZone(humanReadable, cron, timeZone) {
8107
+ const zone = timeZone || 'UTC';
8108
+ const hour = cron.trim().split(/\s+/)[2] ?? '*';
8109
+ if (!/^[\d,-]+$/.test(hour))
8110
+ return humanReadable;
8111
+ const times = [...humanReadable.matchAll(/\b\d{2}:\d{2}(:\d{2})?\b/g)];
8112
+ const last = times.at(-1);
8113
+ if (!last || last.index === undefined)
8114
+ return `${humanReadable} ${zone}`;
8115
+ const end = last.index + last[0].length;
8116
+ return `${humanReadable.slice(0, end)} ${zone}${humanReadable.slice(end)}`;
8117
+ }
8118
+ function browserTimeZone() {
8119
+ return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
8120
+ }
8121
+ function notificationTimeZones() {
8122
+ const zones = ['UTC', ...Intl.supportedValuesOf('timeZone').filter(zone => zone !== 'UTC')];
8123
+ const browser = browserTimeZone();
8124
+ return zones.includes(browser) ? zones : [...zones, browser];
8125
+ }
8126
+
8127
+ const PLACEHOLDER$1 = /\$\{([^{}]*)\}/g;
8128
+ const NOTIFICATION_COUNT_PLACEHOLDER = 'count';
8129
+ function unknownNotificationPlaceholders(subjectTemplate, bodyTemplate, columns) {
8130
+ const known = new Set(columns.map(column => column.toLowerCase()));
8131
+ const unknown = [];
8132
+ const collect = (text, isKnown) => {
8133
+ for (const match of (text ?? '').matchAll(PLACEHOLDER$1)) {
8134
+ const token = match[1];
8135
+ const name = token.trim().toLowerCase();
8136
+ if (!isKnown(name) && !unknown.some(seen => seen.toLowerCase() === token.toLowerCase())) {
8137
+ unknown.push(token);
8138
+ }
8139
+ }
8140
+ };
8141
+ collect(subjectTemplate, name => name === NOTIFICATION_COUNT_PLACEHOLDER);
8142
+ collect(bodyTemplate, name => name === NOTIFICATION_COUNT_PLACEHOLDER || known.has(name));
8143
+ return unknown;
8144
+ }
8145
+ function placeholderList(names) {
8146
+ return names.map(name => '${' + name + '}').join(', ');
8147
+ }
8148
+ function notificationColumnPath(column) {
8149
+ const hops = column.split('->');
8150
+ const attribute = hops.pop() ?? column;
8151
+ return { column, trail: hops.map(hop => hop.slice(hop.indexOf('.') + 1)), attribute };
8152
+ }
8153
+
8154
+ const PLACEHOLDER = /\$\{([^{}]*)\}/g;
8155
+ const ISO_DATE_TIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/;
8156
+ const MARKDOWN_CONTROL = /&(?:amp|lt|gt|quot|#39);|[\\`*_[\]()!#|~^${}+]/g;
8157
+ function renderNotificationPreview(subjectTemplate, bodyTemplate, options) {
8158
+ const count = String(options.rows.length > 0 ? options.totalCount : 1);
8159
+ const columnOf = new Map(options.columns.map(column => [column.toLowerCase(), column]));
8160
+ const subject = fill(subjectTemplate, name => name === NOTIFICATION_COUNT_PLACEHOLDER ? count : undefined);
8161
+ const block = (valueOf) => fill(bodyTemplate, name => {
8162
+ if (name === NOTIFICATION_COUNT_PLACEHOLDER)
8163
+ return count;
8164
+ const column = columnOf.get(name);
8165
+ return column === undefined ? undefined : valueOf(column);
8166
+ });
8167
+ const body = options.rows.length > 0
8168
+ ? options.rows.map(row => block(column => encode(formatCell(cellOf(row, column)), options.markup))).join('\n\n')
8169
+ : block(column => encode(options.standIn(column), options.markup));
8170
+ return { subject, body };
8171
+ }
8172
+ function formatNotificationCell(value) {
8173
+ return formatCell(value);
8174
+ }
8175
+ function fill(template, valueOf) {
8176
+ return (template ?? '').replace(PLACEHOLDER, (token, inner) => valueOf(inner.trim().toLowerCase()) ?? token);
8177
+ }
8178
+ function cellOf(row, column) {
8179
+ const key = Object.keys(row).find(candidate => candidate.toLowerCase() === column.toLowerCase());
8180
+ return key === undefined ? null : row[key];
8181
+ }
8182
+ function formatCell(value) {
8183
+ if (value === null || value === undefined)
8184
+ return '';
8185
+ if (value instanceof Date)
8186
+ return formatDateTime(value);
8187
+ if (typeof value === 'string' && ISO_DATE_TIME.test(value)) {
8188
+ const date = new Date(value);
8189
+ return Number.isNaN(date.getTime()) ? value : formatDateTime(date);
8190
+ }
8191
+ return String(value);
8192
+ }
8193
+ function formatDateTime(date) {
8194
+ const pad = (part) => String(part).padStart(2, '0');
8195
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
8196
+ }
8197
+ function encode(text, markup) {
8198
+ if (!markup)
8199
+ return text;
8200
+ const escaped = text
8201
+ .replace(/&/g, '&amp;')
8202
+ .replace(/</g, '&lt;')
8203
+ .replace(/>/g, '&gt;')
8204
+ .replace(/"/g, '&quot;')
8205
+ .replace(/'/g, '&#39;');
8206
+ return escaped.replace(MARKDOWN_CONTROL, match => match.length > 1 ? match : `&#${match.charCodeAt(0)};`);
8207
+ }
8208
+
8209
+ const NotificationsGetSubscriptionsDocumentDto = gql `
8210
+ query NotificationsGetSubscriptions($first: Int, $after: String, $searchFilter: SearchFilter, $fieldFilter: [FieldFilter], $sortOrder: [Sort]) {
8211
+ runtime {
8212
+ systemNotificationNotificationSubscription(
8213
+ first: $first
8214
+ after: $after
8215
+ searchFilter: $searchFilter
8216
+ fieldFilter: $fieldFilter
8217
+ sortOrder: $sortOrder
8218
+ ) {
8219
+ totalCount
8220
+ pageInfo {
8221
+ hasNextPage
8222
+ endCursor
8223
+ }
8224
+ items {
8225
+ rtId
8226
+ ckTypeId
8227
+ name
8228
+ enabled
8229
+ preferences(
8230
+ ckTypeIds: ["System.Notification/NotificationPreference"]
8231
+ first: 1000
8232
+ ) {
8233
+ totalCount
8234
+ items {
8235
+ ... on SystemNotificationNotificationPreference {
8236
+ rtId
8237
+ ckTypeId
8238
+ deliveryState(ckTypeIds: ["System.Notification/NotificationDeliveryState"]) {
8239
+ items {
8240
+ ... on SystemNotificationNotificationDeliveryState {
8241
+ rtId
8242
+ ckTypeId
8243
+ lastRunAt
8244
+ lastError
8245
+ }
8246
+ }
8247
+ }
8248
+ }
8249
+ }
8250
+ }
8251
+ query(ckTypeIds: ["System/SimpleRtQuery"]) {
8252
+ items {
8253
+ ... on SystemSimpleRtQuery {
8254
+ rtId
8255
+ ckTypeId
8256
+ name
8257
+ }
8258
+ }
8259
+ }
8260
+ template(ckTypeIds: ["System.Notification/NotificationTemplate"]) {
8261
+ items {
8262
+ ... on SystemNotificationNotificationTemplate {
8263
+ rtId
8264
+ ckTypeId
8265
+ rtWellKnownName
8266
+ }
8267
+ }
8268
+ }
8269
+ }
8270
+ }
8271
+ }
8272
+ }
8273
+ `;
8274
+ class NotificationsGetSubscriptionsDtoGQL extends i1.Query {
8275
+ document = NotificationsGetSubscriptionsDocumentDto;
8276
+ constructor(apollo) {
8277
+ super(apollo);
8278
+ }
8279
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.5", ngImport: i0, type: NotificationsGetSubscriptionsDtoGQL, deps: [{ token: i1.Apollo }], target: i0.ɵɵFactoryTarget.Injectable });
8280
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.1.5", ngImport: i0, type: NotificationsGetSubscriptionsDtoGQL, providedIn: 'root' });
8281
+ }
8282
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.5", ngImport: i0, type: NotificationsGetSubscriptionsDtoGQL, decorators: [{
8283
+ type: Injectable,
8284
+ args: [{
8285
+ providedIn: 'root'
8286
+ }]
8287
+ }], ctorParameters: () => [{ type: i1.Apollo }] });
8288
+
8289
+ const NotificationsGetSubscriptionDocumentDto = gql `
8290
+ query NotificationsGetSubscription($rtId: OctoObjectId!) {
8291
+ runtime {
8292
+ systemNotificationNotificationSubscription(rtId: $rtId) {
8293
+ items {
8294
+ rtId
8295
+ ckTypeId
8296
+ name
8297
+ description
8298
+ enabled
8299
+ query(ckTypeIds: ["System/SimpleRtQuery"]) {
8300
+ items {
8301
+ ... on SystemSimpleRtQuery {
8302
+ rtId
8303
+ ckTypeId
8304
+ name
8305
+ }
8306
+ }
8307
+ }
8308
+ template(ckTypeIds: ["System.Notification/NotificationTemplate"]) {
8309
+ items {
8310
+ ... on SystemNotificationNotificationTemplate {
8311
+ rtId
8312
+ ckTypeId
8313
+ rtWellKnownName
8314
+ }
8315
+ }
8316
+ }
8317
+ }
8318
+ }
8319
+ }
8320
+ }
8321
+ `;
8322
+ class NotificationsGetSubscriptionDtoGQL extends i1.Query {
8323
+ document = NotificationsGetSubscriptionDocumentDto;
8324
+ constructor(apollo) {
8325
+ super(apollo);
8326
+ }
8327
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.5", ngImport: i0, type: NotificationsGetSubscriptionDtoGQL, deps: [{ token: i1.Apollo }], target: i0.ɵɵFactoryTarget.Injectable });
8328
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.1.5", ngImport: i0, type: NotificationsGetSubscriptionDtoGQL, providedIn: 'root' });
8329
+ }
8330
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.5", ngImport: i0, type: NotificationsGetSubscriptionDtoGQL, decorators: [{
8331
+ type: Injectable,
8332
+ args: [{
8333
+ providedIn: 'root'
8334
+ }]
8335
+ }], ctorParameters: () => [{ type: i1.Apollo }] });
8336
+
8337
+ const NotificationsGetRecipientsDocumentDto = gql `
8338
+ query NotificationsGetRecipients($rtId: OctoObjectId!, $first: Int, $after: String, $fieldFilter: [FieldFilter], $sortOrder: [Sort]) {
8339
+ runtime {
8340
+ systemNotificationNotificationSubscription(rtId: $rtId) {
8341
+ items {
8342
+ rtId
8343
+ enabled
8344
+ preferences(
8345
+ ckTypeIds: ["System.Notification/NotificationPreference"]
8346
+ first: $first
8347
+ after: $after
8348
+ fieldFilter: $fieldFilter
8349
+ sortOrder: $sortOrder
8350
+ ) {
8351
+ totalCount
8352
+ pageInfo {
8353
+ hasNextPage
8354
+ endCursor
8355
+ }
8356
+ items {
8357
+ ... on SystemNotificationNotificationPreference {
8358
+ rtId
8359
+ ckTypeId
8360
+ subjectId
8361
+ cronExpression
8362
+ timeZone
8363
+ deliveryState(ckTypeIds: ["System.Notification/NotificationDeliveryState"]) {
8364
+ items {
8365
+ ... on SystemNotificationNotificationDeliveryState {
8366
+ rtId
8367
+ ckTypeId
8368
+ subjectId
8369
+ lastRunAt
8370
+ lastSentAt
8371
+ lastError
8372
+ }
8373
+ }
8374
+ }
8375
+ }
8376
+ }
8377
+ }
8378
+ }
8379
+ }
8380
+ }
8381
+ }
8382
+ `;
8383
+ class NotificationsGetRecipientsDtoGQL extends i1.Query {
8384
+ document = NotificationsGetRecipientsDocumentDto;
8385
+ constructor(apollo) {
8386
+ super(apollo);
8387
+ }
8388
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.5", ngImport: i0, type: NotificationsGetRecipientsDtoGQL, deps: [{ token: i1.Apollo }], target: i0.ɵɵFactoryTarget.Injectable });
8389
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.1.5", ngImport: i0, type: NotificationsGetRecipientsDtoGQL, providedIn: 'root' });
8390
+ }
8391
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.5", ngImport: i0, type: NotificationsGetRecipientsDtoGQL, decorators: [{
8392
+ type: Injectable,
8393
+ args: [{
8394
+ providedIn: 'root'
8395
+ }]
8396
+ }], ctorParameters: () => [{ type: i1.Apollo }] });
8397
+
8398
+ const NotificationsGetPreferenceDocumentDto = gql `
8399
+ query NotificationsGetPreference($rtId: OctoObjectId!) {
8400
+ runtime {
8401
+ systemNotificationNotificationPreference(rtId: $rtId) {
8402
+ items {
8403
+ rtId
8404
+ ckTypeId
8405
+ subjectId
8406
+ cronExpression
8407
+ timeZone
8408
+ deliveryState(ckTypeIds: ["System.Notification/NotificationDeliveryState"]) {
8409
+ items {
8410
+ ... on SystemNotificationNotificationDeliveryState {
8411
+ rtId
8412
+ ckTypeId
8413
+ subjectId
8414
+ lastRunAt
8415
+ lastSentAt
8416
+ lastError
8417
+ }
8418
+ }
8419
+ }
8420
+ }
8421
+ }
8422
+ }
8423
+ }
8424
+ `;
8425
+ class NotificationsGetPreferenceDtoGQL extends i1.Query {
8426
+ document = NotificationsGetPreferenceDocumentDto;
8427
+ constructor(apollo) {
8428
+ super(apollo);
8429
+ }
8430
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.5", ngImport: i0, type: NotificationsGetPreferenceDtoGQL, deps: [{ token: i1.Apollo }], target: i0.ɵɵFactoryTarget.Injectable });
8431
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.1.5", ngImport: i0, type: NotificationsGetPreferenceDtoGQL, providedIn: 'root' });
8432
+ }
8433
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.5", ngImport: i0, type: NotificationsGetPreferenceDtoGQL, decorators: [{
8434
+ type: Injectable,
8435
+ args: [{
8436
+ providedIn: 'root'
8437
+ }]
8438
+ }], ctorParameters: () => [{ type: i1.Apollo }] });
8439
+
8440
+ const NotificationsCreatePreferenceDocumentDto = gql `
8441
+ mutation NotificationsCreatePreference($entities: [SystemNotificationNotificationPreferenceInput]!) {
8442
+ runtime {
8443
+ systemNotificationNotificationPreferences {
8444
+ create(entities: $entities) {
8445
+ rtId
8446
+ }
8447
+ }
8448
+ }
8449
+ }
8450
+ `;
8451
+ class NotificationsCreatePreferenceDtoGQL extends i1.Mutation {
8452
+ document = NotificationsCreatePreferenceDocumentDto;
8453
+ constructor(apollo) {
8454
+ super(apollo);
8455
+ }
8456
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.5", ngImport: i0, type: NotificationsCreatePreferenceDtoGQL, deps: [{ token: i1.Apollo }], target: i0.ɵɵFactoryTarget.Injectable });
8457
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.1.5", ngImport: i0, type: NotificationsCreatePreferenceDtoGQL, providedIn: 'root' });
8458
+ }
8459
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.5", ngImport: i0, type: NotificationsCreatePreferenceDtoGQL, decorators: [{
8460
+ type: Injectable,
8461
+ args: [{
8462
+ providedIn: 'root'
8463
+ }]
8464
+ }], ctorParameters: () => [{ type: i1.Apollo }] });
8465
+
8466
+ const NotificationsUpdatePreferenceDocumentDto = gql `
8467
+ mutation NotificationsUpdatePreference($entities: [SystemNotificationNotificationPreferenceInputUpdate]!) {
8468
+ runtime {
8469
+ systemNotificationNotificationPreferences {
8470
+ update(entities: $entities) {
8471
+ rtId
8472
+ }
8473
+ }
8474
+ }
8475
+ }
8476
+ `;
8477
+ class NotificationsUpdatePreferenceDtoGQL extends i1.Mutation {
8478
+ document = NotificationsUpdatePreferenceDocumentDto;
8479
+ constructor(apollo) {
8480
+ super(apollo);
8481
+ }
8482
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.5", ngImport: i0, type: NotificationsUpdatePreferenceDtoGQL, deps: [{ token: i1.Apollo }], target: i0.ɵɵFactoryTarget.Injectable });
8483
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.1.5", ngImport: i0, type: NotificationsUpdatePreferenceDtoGQL, providedIn: 'root' });
8484
+ }
8485
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.5", ngImport: i0, type: NotificationsUpdatePreferenceDtoGQL, decorators: [{
8486
+ type: Injectable,
8487
+ args: [{
8488
+ providedIn: 'root'
8489
+ }]
8490
+ }], ctorParameters: () => [{ type: i1.Apollo }] });
8491
+
8492
+ const NotificationsDeleteEntitiesDocumentDto = gql `
8493
+ mutation NotificationsDeleteEntities($rtEntityIds: [RtEntityId]!, $options: DeleteStrategies) {
8494
+ runtime {
8495
+ runtimeEntities {
8496
+ delete(entities: $rtEntityIds, options: $options)
8497
+ }
8498
+ }
8499
+ }
8500
+ `;
8501
+ class NotificationsDeleteEntitiesDtoGQL extends i1.Mutation {
8502
+ document = NotificationsDeleteEntitiesDocumentDto;
8503
+ constructor(apollo) {
8504
+ super(apollo);
8505
+ }
8506
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.5", ngImport: i0, type: NotificationsDeleteEntitiesDtoGQL, deps: [{ token: i1.Apollo }], target: i0.ɵɵFactoryTarget.Injectable });
8507
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.1.5", ngImport: i0, type: NotificationsDeleteEntitiesDtoGQL, providedIn: 'root' });
8508
+ }
8509
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.5", ngImport: i0, type: NotificationsDeleteEntitiesDtoGQL, decorators: [{
8510
+ type: Injectable,
8511
+ args: [{
8512
+ providedIn: 'root'
8513
+ }]
8514
+ }], ctorParameters: () => [{ type: i1.Apollo }] });
8515
+
8516
+ const NotificationsGetTemplateSubscriptionsDocumentDto = gql `
8517
+ query notificationsGetTemplateSubscriptions($rtId: OctoObjectId!) {
8518
+ runtime {
8519
+ systemNotificationNotificationTemplate(rtId: $rtId) {
8520
+ items {
8521
+ rtId
8522
+ subscriptions(
8523
+ ckTypeIds: ["System.Notification/NotificationSubscription"]
8524
+ first: 1000
8525
+ ) {
8526
+ items {
8527
+ ... on SystemNotificationNotificationSubscription {
8528
+ rtId
8529
+ ckTypeId
8530
+ name
8531
+ query(ckTypeIds: ["System/SimpleRtQuery"]) {
8532
+ items {
8533
+ ... on SystemSimpleRtQuery {
8534
+ rtId
8535
+ columns
8536
+ }
8537
+ }
8538
+ }
8539
+ }
8540
+ }
8541
+ }
8542
+ }
8543
+ }
8544
+ }
8545
+ }
8546
+ `;
8547
+ class NotificationsGetTemplateSubscriptionsDtoGQL extends i1.Query {
8548
+ document = NotificationsGetTemplateSubscriptionsDocumentDto;
8549
+ constructor(apollo) {
8550
+ super(apollo);
8551
+ }
8552
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.5", ngImport: i0, type: NotificationsGetTemplateSubscriptionsDtoGQL, deps: [{ token: i1.Apollo }], target: i0.ɵɵFactoryTarget.Injectable });
8553
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.1.5", ngImport: i0, type: NotificationsGetTemplateSubscriptionsDtoGQL, providedIn: 'root' });
8554
+ }
8555
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.5", ngImport: i0, type: NotificationsGetTemplateSubscriptionsDtoGQL, decorators: [{
8556
+ type: Injectable,
8557
+ args: [{
8558
+ providedIn: 'root'
8559
+ }]
8560
+ }], ctorParameters: () => [{ type: i1.Apollo }] });
8561
+
8562
+ const NotificationsGetQuerySampleDocumentDto = gql `
8563
+ query notificationsGetQuerySample($rtId: OctoObjectId!, $first: Int) {
8564
+ runtime {
8565
+ runtimeQuery(rtId: $rtId) {
8566
+ items {
8567
+ queryRtId
8568
+ rows(first: $first) {
8569
+ totalCount
8570
+ items {
8571
+ ... on RtSimpleQueryRow {
8572
+ rtId
8573
+ cells(first: 1000) {
8574
+ items {
8575
+ attributePath
8576
+ value
8577
+ }
8578
+ }
8579
+ }
8580
+ }
8581
+ }
8582
+ }
8583
+ }
8584
+ }
8585
+ }
8586
+ `;
8587
+ class NotificationsGetQuerySampleDtoGQL extends i1.Query {
8588
+ document = NotificationsGetQuerySampleDocumentDto;
8589
+ constructor(apollo) {
8590
+ super(apollo);
8591
+ }
8592
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.5", ngImport: i0, type: NotificationsGetQuerySampleDtoGQL, deps: [{ token: i1.Apollo }], target: i0.ɵɵFactoryTarget.Injectable });
8593
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.1.5", ngImport: i0, type: NotificationsGetQuerySampleDtoGQL, providedIn: 'root' });
8594
+ }
8595
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.5", ngImport: i0, type: NotificationsGetQuerySampleDtoGQL, decorators: [{
8596
+ type: Injectable,
8597
+ args: [{
8598
+ providedIn: 'root'
8599
+ }]
8600
+ }], ctorParameters: () => [{ type: i1.Apollo }] });
8601
+
8602
+ const NotificationsGetIdentityUsersDocumentDto = gql `
8603
+ query notificationsGetIdentityUsers($first: Int, $after: String) {
8604
+ runtime {
8605
+ systemIdentityUser(first: $first, after: $after) {
8606
+ totalCount
8607
+ items {
8608
+ rtId
8609
+ userName
8610
+ firstName
8611
+ lastName
8612
+ email
8613
+ }
8614
+ }
8615
+ }
8616
+ }
8617
+ `;
8618
+ class NotificationsGetIdentityUsersDtoGQL extends i1.Query {
8619
+ document = NotificationsGetIdentityUsersDocumentDto;
8620
+ constructor(apollo) {
8621
+ super(apollo);
8622
+ }
8623
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.5", ngImport: i0, type: NotificationsGetIdentityUsersDtoGQL, deps: [{ token: i1.Apollo }], target: i0.ɵɵFactoryTarget.Injectable });
8624
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.1.5", ngImport: i0, type: NotificationsGetIdentityUsersDtoGQL, providedIn: 'root' });
8625
+ }
8626
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.5", ngImport: i0, type: NotificationsGetIdentityUsersDtoGQL, decorators: [{
8627
+ type: Injectable,
8628
+ args: [{
8629
+ providedIn: 'root'
8630
+ }]
8631
+ }], ctorParameters: () => [{ type: i1.Apollo }] });
8632
+
8633
+ class NotificationRecipientCandidatesService {
8634
+ identityService = inject(IdentityService);
8635
+ authorizeService = inject(AuthorizeService);
8636
+ async load() {
8637
+ if (!this.authorizeService.isInRole(Roles.UserManagement)) {
8638
+ return (await loadPickerUsers(this.identityService)).map(user => ({
8639
+ id: user.userId,
8640
+ name: user.displayName,
8641
+ email: null,
8642
+ label: user.displayName
8643
+ }));
8644
+ }
8645
+ return (await loadAdminPickerUsers(this.identityService)).map(user => ({
8646
+ id: user.userId,
8647
+ name: user.name,
8648
+ email: user.email || null,
8649
+ label: user.email ? `${user.email} (${user.name})` : user.name
8650
+ }));
8651
+ }
8652
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.5", ngImport: i0, type: NotificationRecipientCandidatesService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
8653
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.1.5", ngImport: i0, type: NotificationRecipientCandidatesService, providedIn: 'root' });
8654
+ }
8655
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.5", ngImport: i0, type: NotificationRecipientCandidatesService, decorators: [{
8656
+ type: Injectable,
8657
+ args: [{ providedIn: 'root' }]
8658
+ }] });
8659
+ class GraphQlNotificationRecipientCandidatesService {
8660
+ getIdentityUsersGQL = inject(NotificationsGetIdentityUsersDtoGQL);
8661
+ async load() {
8662
+ const candidates = [];
8663
+ let read = 0;
8664
+ for (let page = 0; page < PICKER_USERS_MAX_PAGES; page++) {
8665
+ const result = await firstValueFrom(this.getIdentityUsersGQL.fetch({
8666
+ variables: { first: PICKER_USERS_PAGE_SIZE, after: GraphQL.offsetToCursor(read) },
8667
+ fetchPolicy: 'network-only'
8668
+ }));
8669
+ const connection = result.data?.runtime?.systemIdentityUser;
8670
+ const items = connection?.items ?? [];
8671
+ read += items.length;
8672
+ candidates.push(...items.filter(user => user !== null).map(user => graphQlCandidate(user)));
8673
+ if (items.length < PICKER_USERS_PAGE_SIZE || read >= (connection?.totalCount ?? 0)) {
8674
+ break;
8675
+ }
8676
+ }
8677
+ return candidates;
8678
+ }
8679
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.5", ngImport: i0, type: GraphQlNotificationRecipientCandidatesService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
8680
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.1.5", ngImport: i0, type: GraphQlNotificationRecipientCandidatesService, providedIn: 'root' });
8681
+ }
8682
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.5", ngImport: i0, type: GraphQlNotificationRecipientCandidatesService, decorators: [{
8683
+ type: Injectable,
8684
+ args: [{ providedIn: 'root' }]
8685
+ }] });
8686
+ function graphQlCandidate(user) {
8687
+ const fullName = [user.firstName, user.lastName].map(part => part?.trim()).filter(part => !!part).join(' ');
8688
+ const name = fullName || user.userName || user.rtId;
8689
+ const email = user.email || null;
8690
+ return { id: user.rtId, name, email, label: email ? `${email} (${name})` : name };
8691
+ }
8692
+ const NOTIFICATION_RECIPIENT_CANDIDATES = new InjectionToken('NOTIFICATION_RECIPIENT_CANDIDATES', { providedIn: 'root', factory: () => inject(NotificationRecipientCandidatesService) });
8693
+
8694
+ const RECIPIENT_PAGE = 1000;
8695
+ class NotificationRecipientRefusedError extends Error {
8696
+ reason;
8697
+ existingRtId;
8698
+ constructor(reason, existingRtId = null) {
8699
+ super(`Notification recipient refused: ${reason}`);
8700
+ this.reason = reason;
8701
+ this.existingRtId = existingRtId;
8702
+ this.name = 'NotificationRecipientRefusedError';
8703
+ }
8704
+ }
8705
+ function namedRef(item) {
8706
+ if (!item?.rtId || !item.ckTypeId)
8707
+ return null;
8708
+ return { rtId: item.rtId, ckTypeId: item.ckTypeId, name: item.name ?? item.rtWellKnownName ?? item.rtId };
8709
+ }
8710
+ function deliveryStateOf(subjectId, states) {
8711
+ const recorded = states?.find(state => state !== null);
8712
+ if (!recorded)
8713
+ return null;
8714
+ if (recorded.subjectId && recorded.subjectId !== subjectId) {
8715
+ return { rtId: recorded.rtId, ckTypeId: recorded.ckTypeId };
8716
+ }
8717
+ return recorded;
8718
+ }
8719
+ function toEntityId(ref) {
8720
+ return { rtId: ref.rtId, ckTypeId: ref.ckTypeId };
8721
+ }
8722
+ class NotificationSubscriptionService {
8723
+ getSubscriptionsGQL = inject(NotificationsGetSubscriptionsDtoGQL);
8724
+ getSubscriptionGQL = inject(NotificationsGetSubscriptionDtoGQL);
8725
+ getRecipientsGQL = inject(NotificationsGetRecipientsDtoGQL);
8726
+ getPreferenceGQL = inject(NotificationsGetPreferenceDtoGQL);
8727
+ createPreferenceGQL = inject(NotificationsCreatePreferenceDtoGQL);
8728
+ updatePreferenceGQL = inject(NotificationsUpdatePreferenceDtoGQL);
8729
+ deleteEntitiesGQL = inject(NotificationsDeleteEntitiesDtoGQL);
8730
+ getTemplateSubscriptionsGQL = inject(NotificationsGetTemplateSubscriptionsDtoGQL);
8731
+ getQuerySampleGQL = inject(NotificationsGetQuerySampleDtoGQL);
8732
+ communication = inject(CommunicationService);
8733
+ cronParser = inject(CronParserService);
8734
+ candidates = inject(NOTIFICATION_RECIPIENT_CANDIDATES);
8735
+ async getSubscriptions(request) {
8736
+ const result = await firstValueFrom(this.getSubscriptionsGQL.fetch({
8737
+ variables: {
8738
+ first: request.take,
8739
+ after: GraphQL.offsetToCursor(request.skip),
8740
+ sortOrder: request.sort ?? null,
8741
+ fieldFilter: request.fieldFilter ?? null,
8742
+ searchFilter: request.searchFilter ?? null
8743
+ },
8744
+ fetchPolicy: 'network-only'
8745
+ }));
8746
+ const connection = result.data?.runtime?.systemNotificationNotificationSubscription;
8747
+ const items = (connection?.items ?? []).filter((item) => item !== null);
8748
+ const summaries = await Promise.all(items.map(async (item) => this.summaryOf(item, await this.allPreferences(item))));
8749
+ return { items: summaries, totalCount: connection?.totalCount ?? 0 };
8750
+ }
8751
+ async getSubscription(rtId) {
8752
+ const result = await firstValueFrom(this.getSubscriptionGQL.fetch({ variables: { rtId }, fetchPolicy: 'network-only' }));
8753
+ const item = result.data?.runtime?.systemNotificationNotificationSubscription?.items?.find(entry => entry !== null);
8754
+ if (!item)
8755
+ return null;
8756
+ return {
8757
+ rtId: item.rtId,
8758
+ ckTypeId: item.ckTypeId,
8759
+ name: item.name,
8760
+ description: item.description ?? null,
8761
+ enabled: item.enabled,
8762
+ query: namedRef(item.query?.items?.find(entry => entry !== null)),
8763
+ template: namedRef(item.template?.items?.find(entry => entry !== null))
8764
+ };
8765
+ }
8766
+ deploy(tenantId, subscriptionRtId) {
8767
+ return this.communication.deployNotificationSubscription(tenantId, subscriptionRtId);
8768
+ }
8769
+ undeploy(tenantId, subscriptionRtId) {
8770
+ return this.communication.undeployNotificationSubscription(tenantId, subscriptionRtId);
8771
+ }
8772
+ loadUsers() {
8773
+ return this.candidates.load();
8774
+ }
8775
+ scheduleIssue(cronExpression) {
8776
+ return notificationScheduleIssue((cron, count) => this.cronParser.getNextExecutions(cron, count), cronExpression);
8777
+ }
8778
+ async getRecipients(subscriptionRtId, request) {
8779
+ const users = await this.usersById();
8780
+ const fieldFilter = [];
8781
+ const term = request.searchText?.trim().toLowerCase();
8782
+ if (term) {
8783
+ const matching = [...(users?.values() ?? [])].filter(user => user.label.toLowerCase().includes(term)).map(user => user.id);
8784
+ if (matching.length === 0)
8785
+ return { items: [], totalCount: 0 };
8786
+ fieldFilter.push({ attributePath: 'subjectId', operator: FieldFilterOperatorsDto.InDto, comparisonValue: matching });
8787
+ }
8788
+ const result = await firstValueFrom(this.getRecipientsGQL.fetch({
8789
+ variables: {
8790
+ rtId: subscriptionRtId,
8791
+ first: request.take,
8792
+ after: GraphQL.offsetToCursor(request.skip),
8793
+ sortOrder: request.sort ?? null,
8794
+ fieldFilter: fieldFilter.length > 0 ? fieldFilter : null
8795
+ },
8796
+ fetchPolicy: 'network-only'
8797
+ }));
8798
+ const subscription = result.data?.runtime?.systemNotificationNotificationSubscription?.items?.find(item => item !== null);
8799
+ const connection = subscription?.preferences;
8800
+ const deployed = subscription?.enabled ?? false;
8801
+ const items = (connection?.items ?? []).filter((item) => item !== null && 'subjectId' in item);
8802
+ return {
8803
+ items: items.map(item => this.recipientOf(item, deployed, users)),
8804
+ totalCount: connection?.totalCount ?? 0
8805
+ };
8806
+ }
8807
+ async getRecipient(rtId, subscriptionDeployed) {
8808
+ const [result, users] = await Promise.all([
8809
+ firstValueFrom(this.getPreferenceGQL.fetch({ variables: { rtId }, fetchPolicy: 'network-only' })),
8810
+ this.usersById()
8811
+ ]);
8812
+ const item = result.data?.runtime?.systemNotificationNotificationPreference?.items?.find(entry => entry !== null);
8813
+ return item ? this.recipientOf(item, subscriptionDeployed, users) : null;
8814
+ }
8815
+ async addRecipient(tenantId, subscription, input) {
8816
+ this.refuseInvalidSchedule(input.cronExpression);
8817
+ const existing = await this.findRecipient(subscription.rtId, input.subjectId);
8818
+ if (existing)
8819
+ throw new NotificationRecipientRefusedError('DUPLICATE', existing);
8820
+ const result = await firstValueFrom(this.createPreferenceGQL.mutate({
8821
+ variables: {
8822
+ entities: [{
8823
+ subjectId: input.subjectId,
8824
+ cronExpression: input.cronExpression,
8825
+ skipExistingRows: false,
8826
+ timeZone: input.timeZone,
8827
+ subscription: [{ modOption: AssociationModOptionsDto.CreateDto, target: toEntityId(subscription) }]
8828
+ }]
8829
+ }
8830
+ }));
8831
+ const rtId = result.data?.runtime?.systemNotificationNotificationPreferences?.create?.[0]?.rtId;
8832
+ if (!rtId)
8833
+ throw new Error('The recipient was not created');
8834
+ return { rtId, scheduleSyncError: await this.syncSchedule(tenantId, [rtId]) };
8835
+ }
8836
+ async updateRecipient(tenantId, rtId, input) {
8837
+ this.refuseInvalidSchedule(input.cronExpression);
8838
+ await firstValueFrom(this.updatePreferenceGQL.mutate({
8839
+ variables: { entities: [{ rtId, item: { cronExpression: input.cronExpression, timeZone: input.timeZone } }] }
8840
+ }));
8841
+ return { rtId, scheduleSyncError: await this.syncSchedule(tenantId, [rtId]) };
8842
+ }
8843
+ async deleteRecipients(tenantId, recipients) {
8844
+ if (recipients.length === 0)
8845
+ return { deliveryStateError: null, scheduleSyncError: null };
8846
+ await firstValueFrom(this.deleteEntitiesGQL.mutate({ variables: { rtEntityIds: recipients.map(toEntityId) } }));
8847
+ const states = recipients.flatMap(recipient => recipient.deliveryState ? [toEntityId(recipient.deliveryState)] : []);
8848
+ let deliveryStateError = null;
8849
+ if (states.length > 0) {
8850
+ try {
8851
+ await firstValueFrom(this.deleteEntitiesGQL.mutate({ variables: { rtEntityIds: states, options: DeleteStrategiesDto.EraseDto } }));
8852
+ }
8853
+ catch (error) {
8854
+ deliveryStateError = error;
8855
+ }
8856
+ }
8857
+ return { deliveryStateError, scheduleSyncError: await this.syncSchedule(tenantId, recipients.map(recipient => recipient.rtId)) };
8858
+ }
8859
+ async getTemplateSubscriptions(templateRtId) {
8860
+ const result = await firstValueFrom(this.getTemplateSubscriptionsGQL.fetch({
8861
+ variables: { rtId: templateRtId },
8862
+ fetchPolicy: 'network-only'
8863
+ }));
8864
+ const template = result.data?.runtime?.systemNotificationNotificationTemplate?.items?.find(item => item !== null);
8865
+ return (template?.subscriptions?.items ?? []).flatMap(item => {
8866
+ if (!item || !('rtId' in item))
8867
+ return [];
8868
+ const query = item.query?.items?.find(entry => entry !== null && 'columns' in entry);
8869
+ return [{
8870
+ rtId: item.rtId,
8871
+ ckTypeId: item.ckTypeId,
8872
+ name: item.name,
8873
+ queryRtId: query?.rtId ?? null,
8874
+ queryColumns: query?.columns ? query.columns.filter((column) => !!column) : null
8875
+ }];
8876
+ });
8877
+ }
8878
+ async getQuerySample(queryRtId, take) {
8879
+ try {
8880
+ const result = await firstValueFrom(this.getQuerySampleGQL.fetch({
8881
+ variables: { rtId: queryRtId, first: take },
8882
+ fetchPolicy: 'network-only',
8883
+ errorPolicy: 'none',
8884
+ context: { [OCTO_SILENT_ERRORS]: true }
8885
+ }));
8886
+ const rows = result.data?.runtime?.runtimeQuery?.items?.find(item => item !== null)?.rows;
8887
+ if (!rows)
8888
+ return null;
8889
+ return {
8890
+ totalCount: rows.totalCount ?? 0,
8891
+ rows: (rows.items ?? []).flatMap(row => row && 'cells' in row
8892
+ ? [Object.fromEntries((row.cells?.items ?? []).flatMap(cell => cell ? [[cell.attributePath, cell.value]] : []))]
8893
+ : [])
8894
+ };
8895
+ }
8896
+ catch {
8897
+ return null;
8898
+ }
8899
+ }
8900
+ refuseInvalidSchedule(cronExpression) {
8901
+ const issue = this.scheduleIssue(cronExpression);
8902
+ if (issue)
8903
+ throw new NotificationRecipientRefusedError(issue);
8904
+ }
8905
+ async findRecipient(subscriptionRtId, subjectId) {
8906
+ const result = await firstValueFrom(this.getRecipientsGQL.fetch({
8907
+ variables: {
8908
+ rtId: subscriptionRtId,
8909
+ first: 1,
8910
+ fieldFilter: [{ attributePath: 'subjectId', operator: FieldFilterOperatorsDto.EqualsDto, comparisonValue: subjectId }]
8911
+ },
8912
+ fetchPolicy: 'network-only'
8913
+ }));
8914
+ const preferences = result.data?.runtime?.systemNotificationNotificationSubscription?.items?.find(item => item !== null)?.preferences;
8915
+ return preferences?.items?.find(item => item !== null && 'rtId' in item)?.rtId ?? null;
8916
+ }
8917
+ async syncSchedule(tenantId, preferenceRtIds) {
8918
+ let failure = null;
8919
+ for (const rtId of preferenceRtIds) {
8920
+ try {
8921
+ await this.communication.syncNotificationSchedule(tenantId, rtId);
8922
+ }
8923
+ catch (error) {
8924
+ failure ??= error;
8925
+ }
8926
+ }
8927
+ return failure;
8928
+ }
8929
+ async usersById() {
8930
+ try {
8931
+ return new Map((await this.candidates.load()).map(user => [user.id, user]));
8932
+ }
8933
+ catch {
8934
+ return null;
8935
+ }
8936
+ }
8937
+ recipientOf(item, subscriptionDeployed, users) {
8938
+ const state = deliveryStateOf(item.subjectId, item.deliveryState?.items);
8939
+ const user = users?.get(item.subjectId);
8940
+ const userExists = users === null || users.size === 0 || !!user;
8941
+ return {
8942
+ rtId: item.rtId,
8943
+ ckTypeId: item.ckTypeId,
8944
+ subjectId: item.subjectId,
8945
+ userLabel: user?.label ?? item.subjectId,
8946
+ cronExpression: item.cronExpression,
8947
+ timeZone: item.timeZone ?? null,
8948
+ lastSentAt: state?.lastSentAt ?? null,
8949
+ deliveryState: state ? { rtId: state.rtId, ckTypeId: state.ckTypeId } : null,
8950
+ status: notificationRecipientStatus(state, subscriptionDeployed, userExists, this.scheduleIssue(item.cronExpression) === null)
8951
+ };
8952
+ }
8953
+ summaryOf(item, allPreferences) {
8954
+ const preferences = allPreferences.filter((p) => p !== null && 'rtId' in p);
8955
+ const states = preferences.map(p => p.deliveryState?.items?.find(state => state !== null));
8956
+ return {
8957
+ rtId: item.rtId,
8958
+ ckTypeId: item.ckTypeId,
8959
+ name: item.name,
8960
+ enabled: item.enabled,
8961
+ recipientCount: preferences.length,
8962
+ health: notificationSubscriptionHealth(states, item.enabled),
8963
+ preferences: preferences.map(p => ({ rtId: p.rtId, ckTypeId: p.ckTypeId })),
8964
+ deliveryStates: preferences.flatMap(p => (p.deliveryState?.items ?? [])
8965
+ .filter(state => state !== null)
8966
+ .map(state => ({ rtId: state.rtId, ckTypeId: state.ckTypeId }))),
8967
+ query: namedRef(item.query?.items?.find(entry => entry !== null)),
8968
+ template: namedRef(item.template?.items?.find(entry => entry !== null))
8969
+ };
8970
+ }
8971
+ async allPreferences(item) {
8972
+ const preferences = [...(item.preferences?.items ?? [])];
8973
+ const total = item.preferences?.totalCount ?? preferences.length;
8974
+ while (preferences.length < total) {
8975
+ const result = await firstValueFrom(this.getRecipientsGQL.fetch({
8976
+ variables: { rtId: item.rtId, first: RECIPIENT_PAGE, after: GraphQL.offsetToCursor(preferences.length) },
8977
+ fetchPolicy: 'network-only'
8978
+ }));
8979
+ const page = result.data?.runtime?.systemNotificationNotificationSubscription?.items?.[0]?.preferences?.items ?? [];
8980
+ if (page.length === 0)
8981
+ break;
8982
+ preferences.push(...page);
8983
+ }
8984
+ return preferences;
8985
+ }
8986
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.5", ngImport: i0, type: NotificationSubscriptionService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
8987
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.1.5", ngImport: i0, type: NotificationSubscriptionService, providedIn: 'root' });
8988
+ }
8989
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.5", ngImport: i0, type: NotificationSubscriptionService, decorators: [{
8990
+ type: Injectable,
8991
+ args: [{ providedIn: 'root' }]
8992
+ }] });
8993
+
7999
8994
  /**
8000
8995
  * Service for the tenant Reporting feature toggle.
8001
8996
  *
@@ -8677,5 +9672,5 @@ function provideOctoServices(octoServiceOptions) {
8677
9672
  * Generated bundle index. Do not edit.
8678
9673
  */
8679
9674
 
8680
- export { AggregationInputTypesDto, AggregationTypeDto, AggregationTypesDto, AiService, ArchiveStorageHealthDto, AssetRepoGraphQlDataSource, AssetRepoService, AssociationModOptionsDto, AttributeOwnershipDto, AttributeSelectorService, AttributeValueTypeDto, BasicEnergyCarrierTypeDto, BasicEnergyDataQualityDto, BasicEnergyFacilityTypeDto, BasicEnergyProductionTypeDto, BasicEnergyStateDto, BasicLegalEntityTypeDto, BasicSalutationDto, BasicTypeOfTelephoneBasicDto, BasicTypeOfTelephoneEnhancedDto, BasicUnitOfMeasureDto, BinaryDownloadUnavailableError, BlueprintConflictResolutionDto, BlueprintUpdateModeDto, BotSecretsService, BotService, BucketAlignmentDto, BucketAlignmentInputDto, CK_UPGRADE_BLOCKED_CODE, CONFIGURATION_SERVICE, CREDENTIAL_ATTRIBUTE_NAME_SUFFIXES, CkExtensionUpdateOperationsDto, CkModelCatalogService, CkModelService, CkRollupFunctionDto, CkTypeAttributeService, CkTypeMetaData, CkTypeSelectorService, CommunicationService, DEFAULT_SECRET_STATUS_LABELS, DeepGraphDirectionDto, DeleteStrategiesDto, DeploymentState, EnergyCommunityBillingCycleDto, EnergyCommunityBillingDocumentStateDto, EnergyCommunityBillingTypeDto, EnergyCommunityTaxProcedureCreditNoteDto, EnvironmentCarbonScopeDto, EnvironmentComplianceCategoryDto, EnvironmentComplianceStatusDto, EnvironmentEnergySourceDto, EnvironmentGoalStateDto, FILES_LINKED_COUNTS_MAX, FILES_RESERVED_ROOT_NAMES, FILES_UNAVAILABLE_TTL_MS, FieldFilterOperatorsDto, FileDownloadService, FilesClientService, FilesPathError, FormulaResultTypeDto, GetCkModelByIdDocumentDto, GetCkModelByIdDtoGQL, GetCkRecordAttributesDocumentDto, GetCkRecordAttributesDtoGQL, GetCkTypeAttributesDocumentDto, GetCkTypeAttributesDtoGQL, GetCkTypeAvailableQueryColumnsDocumentDto, GetCkTypeAvailableQueryColumnsDtoGQL, GetCkTypesDocumentDto, GetCkTypesDtoGQL, GetDerivedCkTypesDocumentDto, GetDerivedCkTypesDtoGQL, GetEntitiesByCkTypeDocumentDto, GetEntitiesByCkTypeDtoGQL, GraphDirectionDto, GraphQL, GraphQLCloneIgnoredProperties, GraphQLCommonIgnoredProperties, GraphQlDataSource, HealthService, HealthStatus, IDENTITY_PROVIDER_TYPE_LABELS, IdentityProviderType, IdentityService, ImportStrategyDto, IndustryBasicAlarmPriorityDto, IndustryBasicAlarmSourceTypeDto, IndustryBasicAlarmStateDto, IndustryBasicAlarmTypeDto, IndustryBasicIecDataTypeDto, IndustryBasicMachineCapabilitiesDto, IndustryBasicMachineStateDto, IndustryEnergyDemandResponseMarketDto, IndustryEnergyDemandResponseStatusDto, IndustryEnergyTariffTypeDto, IndustryMaintenanceAggregationTypeDto, IndustryMaintenanceCostCategoryDto, IndustryMaintenanceEnergyBalanceGroupDto, IndustryMaintenanceEnergyBalanceProductDto, IndustryMaintenanceEnergyBalanceUnitDto, IndustryMaintenanceOrderPriorityDto, IndustryMaintenanceOrderStateDto, IndustryMaintenanceOrderTypeDto, IndustryMaintenanceServiceTypeDto, IndustryManufacturingFeedbackSyncStateDto, IndustryManufacturingProductionOrderItemStateDto, IndustryManufacturingProductionOrderStateDto, JobManagementService, LevelMetaData, LoggerSeverity, ModelStateDto, MultiplicitiesDto, NavigationFilterModeDto, OCTO_HANDLES_CK_UPGRADE_BLOCKED, OCTO_SILENT_ERRORS, OctoErrorLink, OctoGraphQLServiceBase, OctoSdkDemoCustomerStatusDto, OctoSdkDemoNetworkOperatorDto, OctoSdkDemoOperatingStatusDto, OctoServiceOptions, OctoServicesModule, PagedGraphResultDto, ProgressValue, ProgressWindowService, QueryModeDto, ReportingService, RtAssociationMetaData, RuntimeEntityDialogDataSource, RuntimeEntitySelectDataSource, SECRET_DUMP_RESTORE_ERROR_DUMP_DELETED, SECRET_DUMP_RESTORE_ERROR_DUMP_KEY_MISSING, SECRET_LEGACY_V1_KEY_ID, SECRET_STATUS_WARNING_DUMP_KEY_MISSING, SECRET_STATUS_WARNING_NO_KEY_RING, SECRET_STATUS_WARNING_NO_LEGACY_V1_KEY, SECRET_VALUE_TYPE, SearchFilterTypesDto, SecretStorageFormDto, SecretUsageMatchDto, SeriesComparisonPolicyDto, SeriesResolutionSignalDto, SortOrdersDto, SystemAggregationTypesDto, SystemAiApprovalModeDto, SystemAiApprovalReasonDto, SystemAiApprovalStatusDto, SystemAiAuthModeDto, SystemAiConflictModeDto, SystemAiCredentialKindDto, SystemAiJobKindDto, SystemAiJobStatusDto, SystemAiKnowledgeKindDto, SystemAiLeaseStatusDto, SystemAiModelTierDto, SystemAiRiskLevelDto, SystemAiSessionEventKindDto, SystemAiSessionStatusDto, SystemAiSubscriptionScopeDto, SystemAiTicketScopeDto, SystemAiTicketStatusDto, SystemAiWorkspaceModeDto, SystemCommunicationAdapterSharingModeDto, SystemCommunicationCommunicationStateDto, SystemCommunicationConfigurationStateDto, SystemCommunicationDeploymentStateDto, SystemCommunicationEnvironmentDto, SystemCommunicationHelmChannelDto, SystemCommunicationHelmRepositoryPurposeDto, SystemCommunicationLifecycleModeDto, SystemCommunicationLifecycleStateDto, SystemCommunicationPipelineExecutionClassDto, SystemCommunicationPipelineExecutionStatusDto, SystemCommunicationPipelineTriggerTypeDto, SystemCommunicationPoolScaleUpPolicyDto, SystemCommunicationSignalRegistrationActionDto, SystemCommunicationSignalRegistrationStateDto, SystemEnvironmentModesDto, SystemFieldFilterOperatorDto, SystemIdentityDataPolicyEnforcementModeDto, SystemIdentityDataPolicyScopeDto, SystemIdentityIdentifierKindDto, SystemIdentityIdentifierSourceDto, SystemIdentityTokenExpirationDto, SystemIdentityTokenTypeDto, SystemIdentityTokenUsageDto, SystemIdentityTrustLevelDto, SystemMaintenanceLevelsDto, SystemNavigationFilterModesDto, SystemNotificationEventLevelsDto, SystemNotificationEventSourcesDto, SystemNotificationEventStatesDto, SystemNotificationNotificationTypesDto, SystemNotificationRenderingTypesDto, SystemQueryTypesDto, SystemSortOrdersDto, SystemStreamDataBucketAlignmentDto, SystemStreamDataCkArchiveStatusDto, SystemStreamDataCkComputedColumnResultTypeDto, SystemStreamDataCkComputedColumnStateDto, SystemStreamDataCkConflictKeyOrderDto, SystemStreamDataCkRecomputeChangeKindDto, SystemStreamDataCkRecomputeChangeSourceDto, SystemStreamDataCkRecomputeJobStateDto, SystemStreamDataCkRecomputeTriggerDto, SystemStreamDataCkRollupFunctionDto, TENANT_ID_PROVIDER, TusUploadService, UpdateTypeDto, buildTusEndpoint, ckBlockersOf, ckFirstBlockerReason, filesGraphQlErrorCode, formatSecretStatus, isCkBlocked, isCkUpgradeBlockedGraphQlError, isCredentialLikeAttributeName, isSecretAttributeCandidate, isSecretPresent, isSecretQueryColumn, isSecretStateObject, isSecretValueType, isTextualValueType, octoDataIdFromObject, parseCkUpgradeBlockedError, parseCkUpgradeBlockedGraphQlError, parseContentDispositionFileName, parseFilesProblem, result as possibleTypes, provideOctoServices, secretInputValue, secretStateFromAttribute, secretStatusOf, toAttributeNameFilter, toCamelCaseAttributeName, toSecretState, toUniqueCamelCaseNames };
9675
+ export { AggregationInputTypesDto, AggregationTypeDto, AggregationTypesDto, AiService, ArchiveStorageHealthDto, AssetRepoGraphQlDataSource, AssetRepoService, AssociationModOptionsDto, AttributeOwnershipDto, AttributeSelectorService, AttributeValueTypeDto, BasicEnergyCarrierTypeDto, BasicEnergyDataQualityDto, BasicEnergyFacilityTypeDto, BasicEnergyProductionTypeDto, BasicEnergyStateDto, BasicLegalEntityTypeDto, BasicSalutationDto, BasicTypeOfTelephoneBasicDto, BasicTypeOfTelephoneEnhancedDto, BasicUnitOfMeasureDto, BinaryDownloadUnavailableError, BlueprintConflictResolutionDto, BlueprintUpdateModeDto, BotSecretsService, BotService, BucketAlignmentDto, BucketAlignmentInputDto, CK_UPGRADE_BLOCKED_CODE, CONFIGURATION_SERVICE, CREDENTIAL_ATTRIBUTE_NAME_SUFFIXES, CkExtensionUpdateOperationsDto, CkModelCatalogService, CkModelService, CkRollupFunctionDto, CkTypeAttributeService, CkTypeMetaData, CkTypeSelectorService, CommunicationService, DEFAULT_SECRET_STATUS_LABELS, DeepGraphDirectionDto, DeleteStrategiesDto, DeploymentState, EnergyCommunityBillingCycleDto, EnergyCommunityBillingDocumentStateDto, EnergyCommunityBillingTypeDto, EnergyCommunityTaxProcedureCreditNoteDto, EnvironmentCarbonScopeDto, EnvironmentComplianceCategoryDto, EnvironmentComplianceStatusDto, EnvironmentEnergySourceDto, EnvironmentGoalStateDto, FILES_LINKED_COUNTS_MAX, FILES_RESERVED_ROOT_NAMES, FILES_UNAVAILABLE_TTL_MS, FieldFilterOperatorsDto, FileDownloadService, FilesClientService, FilesPathError, FormulaResultTypeDto, GetCkModelByIdDocumentDto, GetCkModelByIdDtoGQL, GetCkRecordAttributesDocumentDto, GetCkRecordAttributesDtoGQL, GetCkTypeAttributesDocumentDto, GetCkTypeAttributesDtoGQL, GetCkTypeAvailableQueryColumnsDocumentDto, GetCkTypeAvailableQueryColumnsDtoGQL, GetCkTypesDocumentDto, GetCkTypesDtoGQL, GetDerivedCkTypesDocumentDto, GetDerivedCkTypesDtoGQL, GetEntitiesByCkTypeDocumentDto, GetEntitiesByCkTypeDtoGQL, GraphDirectionDto, GraphQL, GraphQLCloneIgnoredProperties, GraphQLCommonIgnoredProperties, GraphQlDataSource, GraphQlNotificationRecipientCandidatesService, HealthService, HealthStatus, IDENTITY_PROVIDER_TYPE_LABELS, IdentityProviderType, IdentityService, ImportStrategyDto, IndustryBasicAlarmPriorityDto, IndustryBasicAlarmSourceTypeDto, IndustryBasicAlarmStateDto, IndustryBasicAlarmTypeDto, IndustryBasicIecDataTypeDto, IndustryBasicMachineCapabilitiesDto, IndustryBasicMachineStateDto, IndustryEnergyDemandResponseMarketDto, IndustryEnergyDemandResponseStatusDto, IndustryEnergyTariffTypeDto, IndustryMaintenanceAggregationTypeDto, IndustryMaintenanceCostCategoryDto, IndustryMaintenanceEnergyBalanceGroupDto, IndustryMaintenanceEnergyBalanceProductDto, IndustryMaintenanceEnergyBalanceUnitDto, IndustryMaintenanceOrderPriorityDto, IndustryMaintenanceOrderStateDto, IndustryMaintenanceOrderTypeDto, IndustryMaintenanceServiceTypeDto, IndustryManufacturingFeedbackSyncStateDto, IndustryManufacturingProductionOrderItemStateDto, IndustryManufacturingProductionOrderStateDto, JobManagementService, LevelMetaData, LoggerSeverity, ModelStateDto, MultiplicitiesDto, NOTIFICATION_COUNT_PLACEHOLDER, NOTIFICATION_DEFAULT_CRON, NOTIFICATION_MIN_INTERVAL_MS, NOTIFICATION_RECIPIENT_CANDIDATES, NOTIFICATION_SCHEDULE_TYPES, NavigationFilterModeDto, NotificationRecipientCandidatesService, NotificationRecipientRefusedError, NotificationSubscriptionService, OCTO_HANDLES_CK_UPGRADE_BLOCKED, OCTO_SILENT_ERRORS, OctoErrorLink, OctoGraphQLServiceBase, OctoSdkDemoCustomerStatusDto, OctoSdkDemoNetworkOperatorDto, OctoSdkDemoOperatingStatusDto, OctoServiceOptions, OctoServicesModule, PICKER_USERS_MAX_PAGES, PICKER_USERS_PAGE_SIZE, PagedGraphResultDto, ProgressValue, ProgressWindowService, QueryModeDto, ReportingService, RtAssociationMetaData, RuntimeEntityDialogDataSource, RuntimeEntitySelectDataSource, SECRET_DUMP_RESTORE_ERROR_DUMP_DELETED, SECRET_DUMP_RESTORE_ERROR_DUMP_KEY_MISSING, SECRET_LEGACY_V1_KEY_ID, SECRET_STATUS_WARNING_DUMP_KEY_MISSING, SECRET_STATUS_WARNING_NO_KEY_RING, SECRET_STATUS_WARNING_NO_LEGACY_V1_KEY, SECRET_VALUE_TYPE, SearchFilterTypesDto, SecretStorageFormDto, SecretUsageMatchDto, SeriesComparisonPolicyDto, SeriesResolutionSignalDto, SortOrdersDto, SystemAggregationTypesDto, SystemAiApprovalModeDto, SystemAiApprovalReasonDto, SystemAiApprovalStatusDto, SystemAiAuthModeDto, SystemAiConflictModeDto, SystemAiCredentialKindDto, SystemAiJobKindDto, SystemAiJobStatusDto, SystemAiKnowledgeKindDto, SystemAiLeaseStatusDto, SystemAiModelTierDto, SystemAiRiskLevelDto, SystemAiSessionEventKindDto, SystemAiSessionStatusDto, SystemAiSubscriptionScopeDto, SystemAiTicketScopeDto, SystemAiTicketStatusDto, SystemAiWorkspaceModeDto, SystemCommunicationAdapterSharingModeDto, SystemCommunicationCommunicationStateDto, SystemCommunicationConfigurationStateDto, SystemCommunicationDeploymentStateDto, SystemCommunicationEnvironmentDto, SystemCommunicationHelmChannelDto, SystemCommunicationHelmRepositoryPurposeDto, SystemCommunicationLifecycleModeDto, SystemCommunicationLifecycleStateDto, SystemCommunicationPipelineExecutionClassDto, SystemCommunicationPipelineExecutionStatusDto, SystemCommunicationPipelineTriggerTypeDto, SystemCommunicationPoolScaleUpPolicyDto, SystemCommunicationSignalRegistrationActionDto, SystemCommunicationSignalRegistrationStateDto, SystemEnvironmentModesDto, SystemFieldFilterOperatorDto, SystemIdentityDataPolicyEnforcementModeDto, SystemIdentityDataPolicyScopeDto, SystemIdentityIdentifierKindDto, SystemIdentityIdentifierSourceDto, SystemIdentityTokenExpirationDto, SystemIdentityTokenTypeDto, SystemIdentityTokenUsageDto, SystemIdentityTrustLevelDto, SystemMaintenanceLevelsDto, SystemNavigationFilterModesDto, SystemNotificationEventLevelsDto, SystemNotificationEventSourcesDto, SystemNotificationEventStatesDto, SystemNotificationNotificationTypesDto, SystemNotificationRenderingTypesDto, SystemQueryTypesDto, SystemSortOrdersDto, SystemStreamDataBucketAlignmentDto, SystemStreamDataCkArchiveStatusDto, SystemStreamDataCkComputedColumnResultTypeDto, SystemStreamDataCkComputedColumnStateDto, SystemStreamDataCkConflictKeyOrderDto, SystemStreamDataCkRecomputeChangeKindDto, SystemStreamDataCkRecomputeChangeSourceDto, SystemStreamDataCkRecomputeJobStateDto, SystemStreamDataCkRecomputeTriggerDto, SystemStreamDataCkRollupFunctionDto, TENANT_ID_PROVIDER, TusUploadService, UpdateTypeDto, browserTimeZone, buildTusEndpoint, ckBlockersOf, ckFirstBlockerReason, filesGraphQlErrorCode, formatNotificationCell, formatSecretStatus, isCkBlocked, isCkUpgradeBlockedGraphQlError, isCredentialLikeAttributeName, isSecretAttributeCandidate, isSecretPresent, isSecretQueryColumn, isSecretStateObject, isSecretValueType, isTextualValueType, loadAdminPickerUsers, loadPickerUsers, nameSearchTerm, notificationColumnPath, notificationErrorText, notificationRecipientStatus, notificationScheduleIssue, notificationSubscriptionHealth, notificationTimeZones, octoDataIdFromObject, parseCkUpgradeBlockedError, parseCkUpgradeBlockedGraphQlError, parseContentDispositionFileName, parseFilesProblem, placeholderList, result as possibleTypes, provideOctoServices, renderNotificationPreview, secretInputValue, secretStateFromAttribute, secretStatusOf, toAttributeNameFilter, toCamelCaseAttributeName, toSecretState, toUniqueCamelCaseNames, unknownNotificationPlaceholders, userDisplayName, userPickerText, withScheduleTimeZone };
8681
9676
  //# sourceMappingURL=meshmakers-octo-services.mjs.map