@icure/api 8.6.4 → 8.6.6

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 (61) hide show
  1. package/icc-api/api/IccFormApi.d.ts +81 -0
  2. package/icc-api/api/IccFormApi.js +213 -0
  3. package/icc-api/api/IccFormApi.js.map +1 -1
  4. package/icc-x-api/icc-accesslog-x-api.d.ts +93 -0
  5. package/icc-x-api/icc-accesslog-x-api.js +93 -0
  6. package/icc-x-api/icc-accesslog-x-api.js.map +1 -1
  7. package/icc-x-api/icc-calendar-item-x-api.d.ts +122 -0
  8. package/icc-x-api/icc-calendar-item-x-api.js +122 -0
  9. package/icc-x-api/icc-calendar-item-x-api.js.map +1 -1
  10. package/icc-x-api/icc-classification-x-api.d.ts +20 -0
  11. package/icc-x-api/icc-classification-x-api.js +20 -0
  12. package/icc-x-api/icc-classification-x-api.js.map +1 -1
  13. package/icc-x-api/icc-code-x-api.d.ts +23 -0
  14. package/icc-x-api/icc-code-x-api.js +23 -0
  15. package/icc-x-api/icc-code-x-api.js.map +1 -1
  16. package/icc-x-api/icc-contact-x-api.d.ts +219 -1
  17. package/icc-x-api/icc-contact-x-api.js +219 -2
  18. package/icc-x-api/icc-contact-x-api.js.map +1 -1
  19. package/icc-x-api/icc-data-owner-x-api.d.ts +14 -3
  20. package/icc-x-api/icc-data-owner-x-api.js +14 -3
  21. package/icc-x-api/icc-data-owner-x-api.js.map +1 -1
  22. package/icc-x-api/icc-device-x-api.d.ts +8 -0
  23. package/icc-x-api/icc-device-x-api.js +8 -0
  24. package/icc-x-api/icc-device-x-api.js.map +1 -1
  25. package/icc-x-api/icc-doctemplate-x-api.d.ts +26 -0
  26. package/icc-x-api/icc-doctemplate-x-api.js +26 -0
  27. package/icc-x-api/icc-doctemplate-x-api.js.map +1 -1
  28. package/icc-x-api/icc-document-x-api.d.ts +114 -1
  29. package/icc-x-api/icc-document-x-api.js +127 -1
  30. package/icc-x-api/icc-document-x-api.js.map +1 -1
  31. package/icc-x-api/icc-form-x-api.d.ts +34 -4
  32. package/icc-x-api/icc-form-x-api.js +34 -4
  33. package/icc-x-api/icc-form-x-api.js.map +1 -1
  34. package/icc-x-api/icc-hcparty-x-api.d.ts +67 -0
  35. package/icc-x-api/icc-hcparty-x-api.js +67 -0
  36. package/icc-x-api/icc-hcparty-x-api.js.map +1 -1
  37. package/icc-x-api/icc-helement-x-api.d.ts +141 -0
  38. package/icc-x-api/icc-helement-x-api.js +141 -0
  39. package/icc-x-api/icc-helement-x-api.js.map +1 -1
  40. package/icc-x-api/icc-invoice-x-api.d.ts +54 -0
  41. package/icc-x-api/icc-invoice-x-api.js +54 -0
  42. package/icc-x-api/icc-invoice-x-api.js.map +1 -1
  43. package/icc-x-api/icc-message-x-api.d.ts +162 -0
  44. package/icc-x-api/icc-message-x-api.js +162 -0
  45. package/icc-x-api/icc-message-x-api.js.map +1 -1
  46. package/icc-x-api/icc-patient-x-api.d.ts +245 -0
  47. package/icc-x-api/icc-patient-x-api.js +245 -1
  48. package/icc-x-api/icc-patient-x-api.js.map +1 -1
  49. package/icc-x-api/icc-receipt-x-api.d.ts +25 -0
  50. package/icc-x-api/icc-receipt-x-api.js +25 -0
  51. package/icc-x-api/icc-receipt-x-api.js.map +1 -1
  52. package/icc-x-api/icc-user-x-api.d.ts +25 -0
  53. package/icc-x-api/icc-user-x-api.js +25 -0
  54. package/icc-x-api/icc-user-x-api.js.map +1 -1
  55. package/package.json +1 -1
  56. package/test/icc-x-api/icc-form-x-api.js +265 -1
  57. package/test/icc-x-api/icc-form-x-api.js.map +1 -1
  58. package/test/utils/roles.js +5 -0
  59. package/test/utils/roles.js.map +1 -1
  60. package/test/utils/test_utils.js +1 -21
  61. package/test/utils/test_utils.js.map +1 -1
@@ -74,9 +74,9 @@ class IccFormXApi extends icc_api_1.IccFormApi {
74
74
  * 3.2. if it doesn't exist in the cache, it has to be loaded from Browser Local store, and then import it to WebCrypto
75
75
  * 4. Obtain the array of delegations which are delegated to his ID (hcpartyId) in this patient
76
76
  * 5. Decrypt and collect all keys (secretForeignKeys) within delegations of previous step (with obtained AES key of step 4)
77
- * 6. Do the REST call to get all contacts with (allSecretForeignKeysDelimitedByComa, hcpartyId)
77
+ * 6. Do the REST call to get all forms with (allSecretForeignKeysDelimitedByComa, hcpartyId)
78
78
  *
79
- * After these painful steps, you have the contacts of the patient.
79
+ * After these painful steps, you have the forms of the patient.
80
80
  * @deprecated use {@link findIdsBy} instead.
81
81
  * @param hcpartyId
82
82
  * @param patient
@@ -93,8 +93,14 @@ class IccFormXApi extends icc_api_1.IccFormApi {
93
93
  });
94
94
  }
95
95
  /**
96
- * Same as {@link findBy} but it will only return the ids of the forms. It can also filter the forms where Form.openingDate is between
97
- * startDate and endDate in ascending or descending order by that field. (default: ascending).
96
+ * Same as {@link findBy} but it will only return the ids of the forms. It can also filter the forms by opening date
97
+ * (the date when the form was opened/started) between startDate and endDate in ascending or descending order by that field (default: ascending).
98
+ * @param hcpartyId the id of the data owner.
99
+ * @param patient the patient whose forms to retrieve.
100
+ * @param startDate optional start date filter (inclusive). Only forms with openingDate >= startDate will be returned.
101
+ * @param endDate optional end date filter (inclusive). Only forms with openingDate <= endDate will be returned.
102
+ * @param descending if true, results are sorted by openingDate in descending order; otherwise in ascending order (default).
103
+ * @return an array of form ids.
98
104
  */
99
105
  findIdsBy(hcpartyId, patient, startDate, endDate, descending) {
100
106
  return __awaiter(this, void 0, void 0, function* () {
@@ -102,6 +108,12 @@ class IccFormXApi extends icc_api_1.IccFormApi {
102
108
  return this.findFormIdsByDataOwnerPatientOpeningDate(hcpartyId, _.uniq(extractedKeys), startDate, endDate, descending);
103
109
  });
104
110
  }
111
+ /**
112
+ * Decrypts the encrypted content of the provided forms.
113
+ * @param hcpartyId the id of the data owner attempting to decrypt the forms.
114
+ * @param forms the forms to decrypt.
115
+ * @return an array of decrypted forms. Forms that could not be decrypted will be returned as-is.
116
+ */
105
117
  decrypt(hcpartyId, forms) {
106
118
  return __awaiter(this, void 0, void 0, function* () {
107
119
  return (yield this.crypto.xapi.tryDecryptEntities(forms, utils_1.EntityWithDelegationTypeName.Form, (x) => new models.Form(x))).map(({ entity }) => entity);
@@ -201,12 +213,30 @@ class IccFormXApi extends icc_api_1.IccFormApi {
201
213
  .then((r) => r.mapSuccessAsync((e) => this.decrypt(self, [e]).then((es) => es[0])));
202
214
  });
203
215
  }
216
+ /**
217
+ * Gets all data owners that have access to the given form, along with their access levels.
218
+ * @param entity the form to check.
219
+ * @return an object containing:
220
+ * - permissionsByDataOwnerId: a map of data owner id to their access level.
221
+ * - hasUnknownAnonymousDataOwners: true if there are anonymous data owners with access that could not be identified.
222
+ */
204
223
  getDataOwnersWithAccessTo(entity) {
205
224
  return this.crypto.delegationsDeAnonymization.getDataOwnersWithAccessTo({ entity, type: utils_1.EntityWithDelegationTypeName.Form });
206
225
  }
226
+ /**
227
+ * Retrieves all encryption keys of the given form that are available to the current data owner.
228
+ * @param entity the form whose encryption keys to retrieve.
229
+ * @return an array of encryption keys in hexadecimal string format.
230
+ */
207
231
  getEncryptionKeysOf(entity) {
208
232
  return this.crypto.xapi.encryptionKeysOf({ entity, type: utils_1.EntityWithDelegationTypeName.Form }, undefined);
209
233
  }
234
+ /**
235
+ * Creates or updates de-anonymization metadata for the given form, allowing the delegates to be identified
236
+ * even if they were initially anonymous (e.g., in keyless mode).
237
+ * @param entity the form for which to create de-anonymization metadata.
238
+ * @param delegates the ids of the data owners for which to create de-anonymization information.
239
+ */
210
240
  createDelegationDeAnonymizationMetadata(entity, delegates) {
211
241
  return this.crypto.delegationsDeAnonymization.createOrUpdateDeAnonymizationInfo({ entity, type: utils_1.EntityWithDelegationTypeName.Form }, delegates);
212
242
  }
@@ -1 +1 @@
1
- {"version":3,"file":"icc-form-x-api.js","sourceRoot":"","sources":["../../icc-x-api/icc-form-x-api.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,wCAAuC;AAGvC,4BAA2B;AAC3B,kDAAiD;AAGjD,0E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ryptoXApi } from './icc-crypto-x-api'\n\nimport * as _ from 'lodash'\nimport * as models from '../icc-api/model/models'\n\nimport { IccDataOwnerXApi } from './icc-data-owner-x-api'\nimport { AuthenticationProvider, NoAuthenticationProvider } from './auth/AuthenticationProvider'\nimport { SecureDelegation } from '../icc-api/model/SecureDelegation'\nimport AccessLevelEnum = SecureDelegation.AccessLevelEnum\nimport { ShareMetadataBehaviour } from './crypto/ShareMetadataBehaviour'\nimport { ShareResult } from './utils/ShareResult'\nimport { EntityShareRequest } from '../icc-api/model/requests/EntityShareRequest'\nimport RequestedPermissionEnum = EntityShareRequest.RequestedPermissionEnum\nimport { XHR } from '../icc-api/api/XHR'\nimport { EncryptedEntityXApi } from './basexapi/EncryptedEntityXApi'\nimport { EntityWithDelegationTypeName } from './utils'\nimport { SecretIdUseOption } from './crypto/SecretIdUseOption'\n\n// noinspection JSUnusedGlobalSymbols\nexport class IccFormXApi extends IccFormApi implements EncryptedEntityXApi<models.Form> {\n crypto: IccCryptoXApi\n dataOwnerApi: IccDataOwnerXApi\n\n get headers(): Promise<Array<XHR.Header>> {\n return super.headers.then((h) => this.crypto.accessControlKeysHeaders.addAccessControlKeysHeaders(h, EntityWithDelegationTypeName.Form))\n }\n\n constructor(\n host: string,\n headers: { [key: string]: string },\n crypto: IccCryptoXApi,\n dataOwnerApi: IccDataOwnerXApi,\n private readonly autofillAuthor: boolean,\n authenticationProvider: AuthenticationProvider = new NoAuthenticationProvider(),\n fetchImpl: (input: RequestInfo, init?: RequestInit) => Promise<Response> = typeof window !== 'undefined'\n ? window.fetch\n : typeof self !== 'undefined'\n ? self.fetch\n : fetch\n ) {\n super(host, headers, authenticationProvider, fetchImpl)\n this.crypto = crypto\n this.dataOwnerApi = dataOwnerApi\n }\n\n /**\n * Creates a new instance of form with initialised encryption metadata (not in the database).\n * @param user the current user.\n * @param patient the patient this form refers to.\n * @param c initialised data for the form. Metadata such as id, creation data, etc. will be automatically initialised, but you can specify\n * other kinds of data or overwrite generated metadata with this. You can't specify encryption metadata.\n * @param options optional parameters:\n * - additionalDelegates: delegates which will have access to the entity in addition to the current data owner and delegates from the\n * auto-delegations. Must be an object which associates each data owner id with the access level to give to that data owner. May overlap with\n * auto-delegations, in such case the access level specified here will be used.\n * - sfkOption: specifies which sfk of the owning entity to use.\n * - ignoreAutoDelegations: if true the data won't be shared with the autodelegations of the user, but only with additional delegates\n * - alternateRootDelegation: by default a new entity is created with a root delegation from self to self. In keyless mode this is not possible,\n * and instead the root delegation will be from self to another. You have to specify which delegate will be part of the root delegation.\n * @return a new instance of form.\n */\n async newInstance(\n user: models.User,\n patient: models.Patient,\n c: any = {},\n options: {\n additionalDelegates?: { [dataOwnerId: string]: AccessLevelEnum }\n sfkOption?: SecretIdUseOption\n ignoreAutoDelegations?: boolean\n alternateRootDelegation?: string\n } = {}\n ) {\n const form = {\n ...(c ?? {}),\n _type: 'org.taktik.icure.entities.Form',\n id: c?.id ?? this.crypto.primitives.randomUuid(),\n created: c?.created ?? new Date().getTime(),\n modified: c?.modified ?? new Date().getTime(),\n responsible: c?.responsible ?? (this.autofillAuthor ? this.dataOwnerApi.getDataOwnerIdOf(user) : undefined),\n author: c?.author ?? (this.autofillAuthor ? user.id : undefined),\n codes: c?.codes ?? [],\n tags: c?.tags ?? [],\n }\n\n const ownerId = this.dataOwnerApi.getDataOwnerIdOf(user)\n if (ownerId !== (await this.dataOwnerApi.getCurrentDataOwnerId())) throw new Error('Can only initialise entities as current data owner.')\n const sfk = await this.crypto.xapi.resolveSecretIdUseOptions(\n { entity: patient, type: EntityWithDelegationTypeName.Patient },\n options.sfkOption ?? SecretIdUseOption.UseAnySharedWithParent\n )\n const extraDelegations = {\n ...(options.ignoreAutoDelegations == true\n ? {}\n : Object.fromEntries(\n [...(user.autoDelegations?.all ?? []), ...(user.autoDelegations?.medicalInformation ?? [])].map((d) => [d, AccessLevelEnum.WRITE])\n )),\n ...(options?.additionalDelegates ?? {}),\n }\n return new models.Form(\n await this.crypto.xapi\n .entityWithInitialisedEncryptedMetadata(\n form,\n EntityWithDelegationTypeName.Form,\n patient.id,\n sfk,\n true,\n extraDelegations,\n options.alternateRootDelegation\n )\n .then((x) => x.updatedEntity)\n )\n }\n\n // noinspection JSUnusedGlobalSymbols\n /**\n * 1. Check whether there is a delegation with 'hcpartyId' or not.\n * 2. 'fetchHcParty[hcpartyId][1]': is encrypted AES exchange key by RSA public key of him.\n * 3. Obtain the AES exchange key, by decrypting the previous step value with hcparty private key\n * 3.1. KeyPair should be fetch from cache (in jwk)\n * 3.2. if it doesn't exist in the cache, it has to be loaded from Browser Local store, and then import it to WebCrypto\n * 4. Obtain the array of delegations which are delegated to his ID (hcpartyId) in this patient\n * 5. Decrypt and collect all keys (secretForeignKeys) within delegations of previous step (with obtained AES key of step 4)\n * 6. Do the REST call to get all contacts with (allSecretForeignKeysDelimitedByComa, hcpartyId)\n *\n * After these painful steps, you have the contacts of the patient.\n * @deprecated use {@link findIdsBy} instead.\n * @param hcpartyId\n * @param patient\n * @param usingPost (Promise)\n */\n async findBy(hcpartyId: string, patient: models.Patient, usingPost: boolean = false) {\n const extractedKeys = await this.crypto.xapi.secretIdsOf({ entity: patient, type: EntityWithDelegationTypeName.Patient }, hcpartyId)\n const topmostParentId = (await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds())[0]\n let forms: Array<models.Form> = await (usingPost\n ? this.findFormsByHCPartyPatientForeignKeysUsingPost(hcpartyId!, undefined, undefined, undefined, _.uniq(extractedKeys))\n : this.findFormsByHCPartyPatientForeignKeys(hcpartyId!, _.uniq(extractedKeys).join(',')))\n return await this.decrypt(hcpartyId, forms)\n }\n\n /**\n * Same as {@link findBy} but it will only return the ids of the forms. It can also filter the forms where Form.openingDate is between\n * startDate and endDate in ascending or descending order by that field. (default: ascending).\n */\n async findIdsBy(hcpartyId: string, patient: models.Patient, startDate?: number, endDate?: number, descending?: boolean) {\n const extractedKeys = await this.crypto.xapi.secretIdsOf({ entity: patient, type: EntityWithDelegationTypeName.Patient }, hcpartyId)\n return this.findFormIdsByDataOwnerPatientOpeningDate(hcpartyId, _.uniq(extractedKeys), startDate, endDate, descending)\n }\n\n async decrypt(hcpartyId: string, forms: Array<models.Form>) {\n return (await this.crypto.xapi.tryDecryptEntities(forms, EntityWithDelegationTypeName.Form, (x) => new models.Form(x))).map(\n ({ entity }) => entity\n )\n }\n\n /**\n * @param form a form\n * @return the id of the patient that the form refers to, retrieved from the encrypted metadata. Normally there should only be one element\n * in the returned array, but in case of entity merges there could be multiple values.\n */\n async decryptPatientIdOf(form: models.Form): Promise<string[]> {\n return this.crypto.xapi.owningEntityIdsOf({ entity: form, type: EntityWithDelegationTypeName.Form }, undefined)\n }\n\n /**\n * @return if the logged data owner has write access to the content of the given form\n */\n async hasWriteAccess(form: models.Form): Promise<boolean> {\n return this.crypto.xapi.hasWriteAccess({ entity: form, type: EntityWithDelegationTypeName.Form })\n }\n\n /**\n * Share an existing form with other data owners, allowing them to access the non-encrypted data of the form and optionally also\n * the encrypted content, with read-only or read-write permissions.\n * @param delegateId the id of the data owner which will be granted access to the form.\n * @param form the form to share.\n * @param options optional parameters to customize the sharing behaviour:\n * - shareSecretIds: specifies which secret ids of the entity should be shared. If not provided all secret ids available to the current user will be shared\n * - shareEncryptionKey: specifies if the encryption key of the access log should be shared with the delegate, giving access to all encrypted\n * content of the entity, excluding other encrypted metadata (defaults to {@link ShareMetadataBehaviour.IF_AVAILABLE}). Note that by default a\n * form does not have encrypted content.\n * - sharePatientId: specifies if the id of the patient that this form refers to should be shared with the delegate (defaults to\n * {@link ShareMetadataBehaviour.IF_AVAILABLE}).\n * - requestedPermissions: the requested permissions for the delegate, defaults to {@link RequestedPermissionEnum.MAX_WRITE}.\n * @return the updated entity\n */\n async shareWith(\n delegateId: string,\n form: models.Form,\n options: {\n shareSecretIds?: string[]\n requestedPermissions?: RequestedPermissionEnum\n shareEncryptionKey?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n sharePatientId?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n } = {}\n ): Promise<models.Form> {\n return this.shareWithMany(form, { [delegateId]: options })\n }\n\n /**\n * Share an existing form with other data owners, allowing them to access the non-encrypted data of the form and optionally also\n * the encrypted content, with read-only or read-write permissions.\n * @param form the form to share.\n * @param delegates associates the id of data owners which will be granted access to the entity, to the following sharing options:\n * - shareSecretIds: specifies which secret ids of the entity should be shared. If not provided all secret ids available to the current user will be shared\n * - shareEncryptionKey: specifies if the encryption key of the access log should be shared with the delegate, giving access to all encrypted\n * content of the entity, excluding other encrypted metadata (defaults to {@link ShareMetadataBehaviour.IF_AVAILABLE}). Note that by default a\n * form does not have encrypted content.\n * - sharePatientId: specifies if the id of the patient that this form refers to should be shared with the delegate (defaults to\n * {@link ShareMetadataBehaviour.IF_AVAILABLE}).\n * - requestedPermissions: the requested permissions for the delegate, defaults to {@link RequestedPermissionEnum.MAX_WRITE}.\n * @return the updated entity\n */\n async shareWithMany(\n form: models.Form,\n delegates: {\n [delegateId: string]: {\n shareSecretIds?: string[]\n requestedPermissions?: RequestedPermissionEnum\n shareEncryptionKey?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n sharePatientId?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n }\n }\n ): Promise<models.Form> {\n return (await this.tryShareWithMany(form, delegates)).updatedEntityOrThrow\n }\n\n /**\n * Share an existing form with other data owners, allowing them to access the non-encrypted data of the form and optionally also\n * the encrypted content, with read-only or read-write permissions.\n * @param form the form to share.\n * @param delegates associates the id of data owners which will be granted access to the entity, to the following sharing options:\n * - shareSecretIds: specifies which secret ids of the entity should be shared. If not provided all secret ids available to the current user will be shared\n * - shareEncryptionKey: specifies if the encryption key of the access log should be shared with the delegate, giving access to all encrypted\n * content of the entity, excluding other encrypted metadata (defaults to {@link ShareMetadataBehaviour.IF_AVAILABLE}). Note that by default a\n * form does not have encrypted content.\n * - sharePatientId: specifies if the id of the patient that this form refers to should be shared with the delegate (defaults to\n * {@link ShareMetadataBehaviour.IF_AVAILABLE}).\n * - requestedPermissions: the requested permissions for the delegate, defaults to {@link RequestedPermissionEnum.MAX_WRITE}.\n * @return a promise which will contain the result of the operation: the updated entity if the operation was successful or details of the error if\n * the operation failed.\n */\n async tryShareWithMany(\n form: models.Form,\n delegates: {\n [delegateId: string]: {\n shareSecretIds?: string[]\n requestedPermissions?: RequestedPermissionEnum\n shareEncryptionKey?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n sharePatientId?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n }\n }\n ): Promise<ShareResult<models.Form>> {\n const self = await this.dataOwnerApi.getCurrentDataOwnerId()\n // All entities should have an encryption key.\n const entityWithEncryptionKey = await this.crypto.xapi.ensureEncryptionKeysInitialised(form, EntityWithDelegationTypeName.Form)\n const updatedEntity = entityWithEncryptionKey ? await this.modifyForm(entityWithEncryptionKey) : form\n return this.crypto.xapi\n .simpleShareOrUpdateEncryptedEntityMetadata(\n {\n entity: updatedEntity,\n type: EntityWithDelegationTypeName.Form,\n },\n Object.fromEntries(\n Object.entries(delegates).map(([delegateId, options]) => [\n delegateId,\n {\n requestedPermissions: options.requestedPermissions,\n shareEncryptionKeys: options.shareEncryptionKey,\n shareOwningEntityIds: options.sharePatientId,\n shareSecretIds: options.shareSecretIds,\n },\n ])\n ),\n (x) => this.bulkShareForms(x)\n )\n .then((r) => r.mapSuccessAsync((e) => this.decrypt(self, [e]).then((es) => es[0])))\n }\n\n getDataOwnersWithAccessTo(\n entity: models.Form\n ): Promise<{ permissionsByDataOwnerId: { [p: string]: AccessLevelEnum }; hasUnknownAnonymousDataOwners: boolean }> {\n return this.crypto.delegationsDeAnonymization.getDataOwnersWithAccessTo({ entity, type: EntityWithDelegationTypeName.Form })\n }\n\n getEncryptionKeysOf(entity: models.Form): Promise<string[]> {\n return this.crypto.xapi.encryptionKeysOf({ entity, type: EntityWithDelegationTypeName.Form }, undefined)\n }\n\n createDelegationDeAnonymizationMetadata(entity: models.Form, delegates: string[]): Promise<void> {\n return this.crypto.delegationsDeAnonymization.createOrUpdateDeAnonymizationInfo({ entity, type: EntityWithDelegationTypeName.Form }, delegates)\n }\n}\n"]}
1
+ {"version":3,"file":"icc-form-x-api.js","sourceRoot":"","sources":["../../icc-x-api/icc-form-x-api.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,wCAAuC;AAGvC,4BAA2B;AAC3B,kDAAiD;AAGjD,0EAAgG;AAChG,wEAAoE;AACpE,IAAO,eAAe,GAAG,mCAAgB,CAAC,eAAe,CAAA;AAOzD,mCAAsD;AACtD,kEAA8D;AAE9D,qCAAqC;AACrC,MAAa,WAAY,SAAQ,oBAAU;IAIzC,IAAI,OAAO;QACT,OAAO,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,MAAM,CAAC,wBAAwB,CAAC,2BAA2B,CAAC,CAAC,EAAE,oCAA4B,CAAC,IAAI,CAAC,CAAC,CAAA;IAC1I,CAAC;IAED,YACE,IAAY,EACZ,OAAkC,EAClC,MAAqB,EACrB,YAA8B,EACb,cAAuB,EACxC,yBAAiD,IAAI,iDAAwB,EAAE,EAC/E,YAA2E,OAAO,MAAM,KAAK,WAAW;QACtG,CAAC,CAAC,MAAM,CAAC,KAAK;QACd,CAAC,CAAC,OAAO,IAAI,KAAK,WAAW;YAC7B,CAAC,CAAC,IAAI,CAAC,KAAK;YACZ,CAAC,CAAC,KAAK;QAET,KAAK,CAAC,IAAI,EAAE,OAAO,EAAE,sBAAsB,EAAE,SAAS,CAAC,CAAA;QARtC,mBAAc,GAAd,cAAc,CAAS;QASxC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;QACpB,IAAI,CAAC,YAAY,GAAG,YAAY,CAAA;IAClC,CAAC;IAED;;;;;;;;;;;;;;;OAeG;IACG,WAAW;6DACf,IAAiB,EACjB,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AC,IAAI,CAAC,gBAAgB,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,oCAA4B,CAAC,IAAI,EAAE,EAAE,SAAS,CAAC,CAAA;IAC1G,CAAC;IAED;;;;;OAKG;IACH,uCAAuC,CAAC,MAAmB,EAAE,SAAmB;QAC9E,OAAO,IAAI,CAAC,MAAM,CAAC,0BAA0B,CAAC,iCAAiC,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,oCAA4B,CAAC,IAAI,EAAE,EAAE,SAAS,CAAC,CAAA;IACjJ,CAAC;CACF;AA9SD,kCA8SC","sourcesContent":["import { IccFormApi } from '../icc-api'\nimport { IccCryptoXApi } from './icc-crypto-x-api'\n\nimport * as _ from 'lodash'\nimport * as models from '../icc-api/model/models'\n\nimport { IccDataOwnerXApi } from './icc-data-owner-x-api'\nimport { AuthenticationProvider, NoAuthenticationProvider } from './auth/AuthenticationProvider'\nimport { SecureDelegation } from '../icc-api/model/SecureDelegation'\nimport AccessLevelEnum = SecureDelegation.AccessLevelEnum\nimport { ShareMetadataBehaviour } from './crypto/ShareMetadataBehaviour'\nimport { ShareResult } from './utils/ShareResult'\nimport { EntityShareRequest } from '../icc-api/model/requests/EntityShareRequest'\nimport RequestedPermissionEnum = EntityShareRequest.RequestedPermissionEnum\nimport { XHR } from '../icc-api/api/XHR'\nimport { EncryptedEntityXApi } from './basexapi/EncryptedEntityXApi'\nimport { EntityWithDelegationTypeName } from './utils'\nimport { SecretIdUseOption } from './crypto/SecretIdUseOption'\n\n// noinspection JSUnusedGlobalSymbols\nexport class IccFormXApi extends IccFormApi implements EncryptedEntityXApi<models.Form> {\n crypto: IccCryptoXApi\n dataOwnerApi: IccDataOwnerXApi\n\n get headers(): Promise<Array<XHR.Header>> {\n return super.headers.then((h) => this.crypto.accessControlKeysHeaders.addAccessControlKeysHeaders(h, EntityWithDelegationTypeName.Form))\n }\n\n constructor(\n host: string,\n headers: { [key: string]: string },\n crypto: IccCryptoXApi,\n dataOwnerApi: IccDataOwnerXApi,\n private readonly autofillAuthor: boolean,\n authenticationProvider: AuthenticationProvider = new NoAuthenticationProvider(),\n fetchImpl: (input: RequestInfo, init?: RequestInit) => Promise<Response> = typeof window !== 'undefined'\n ? window.fetch\n : typeof self !== 'undefined'\n ? self.fetch\n : fetch\n ) {\n super(host, headers, authenticationProvider, fetchImpl)\n this.crypto = crypto\n this.dataOwnerApi = dataOwnerApi\n }\n\n /**\n * Creates a new instance of form with initialised encryption metadata (not in the database).\n * @param user the current user.\n * @param patient the patient this form refers to.\n * @param c initialised data for the form. Metadata such as id, creation data, etc. will be automatically initialised, but you can specify\n * other kinds of data or overwrite generated metadata with this. You can't specify encryption metadata.\n * @param options optional parameters:\n * - additionalDelegates: delegates which will have access to the entity in addition to the current data owner and delegates from the\n * auto-delegations. Must be an object which associates each data owner id with the access level to give to that data owner. May overlap with\n * auto-delegations, in such case the access level specified here will be used.\n * - sfkOption: specifies which sfk of the owning entity to use.\n * - ignoreAutoDelegations: if true the data won't be shared with the autodelegations of the user, but only with additional delegates\n * - alternateRootDelegation: by default a new entity is created with a root delegation from self to self. In keyless mode this is not possible,\n * and instead the root delegation will be from self to another. You have to specify which delegate will be part of the root delegation.\n * @return a new instance of form.\n */\n async newInstance(\n user: models.User,\n patient: models.Patient,\n c: any = {},\n options: {\n additionalDelegates?: { [dataOwnerId: string]: AccessLevelEnum }\n sfkOption?: SecretIdUseOption\n ignoreAutoDelegations?: boolean\n alternateRootDelegation?: string\n } = {}\n ) {\n const form = {\n ...(c ?? {}),\n _type: 'org.taktik.icure.entities.Form',\n id: c?.id ?? this.crypto.primitives.randomUuid(),\n created: c?.created ?? new Date().getTime(),\n modified: c?.modified ?? new Date().getTime(),\n responsible: c?.responsible ?? (this.autofillAuthor ? this.dataOwnerApi.getDataOwnerIdOf(user) : undefined),\n author: c?.author ?? (this.autofillAuthor ? user.id : undefined),\n codes: c?.codes ?? [],\n tags: c?.tags ?? [],\n }\n\n const ownerId = this.dataOwnerApi.getDataOwnerIdOf(user)\n if (ownerId !== (await this.dataOwnerApi.getCurrentDataOwnerId())) throw new Error('Can only initialise entities as current data owner.')\n const sfk = await this.crypto.xapi.resolveSecretIdUseOptions(\n { entity: patient, type: EntityWithDelegationTypeName.Patient },\n options.sfkOption ?? SecretIdUseOption.UseAnySharedWithParent\n )\n const extraDelegations = {\n ...(options.ignoreAutoDelegations == true\n ? {}\n : Object.fromEntries(\n [...(user.autoDelegations?.all ?? []), ...(user.autoDelegations?.medicalInformation ?? [])].map((d) => [d, AccessLevelEnum.WRITE])\n )),\n ...(options?.additionalDelegates ?? {}),\n }\n return new models.Form(\n await this.crypto.xapi\n .entityWithInitialisedEncryptedMetadata(\n form,\n EntityWithDelegationTypeName.Form,\n patient.id,\n sfk,\n true,\n extraDelegations,\n options.alternateRootDelegation\n )\n .then((x) => x.updatedEntity)\n )\n }\n\n // noinspection JSUnusedGlobalSymbols\n /**\n * 1. Check whether there is a delegation with 'hcpartyId' or not.\n * 2. 'fetchHcParty[hcpartyId][1]': is encrypted AES exchange key by RSA public key of him.\n * 3. Obtain the AES exchange key, by decrypting the previous step value with hcparty private key\n * 3.1. KeyPair should be fetch from cache (in jwk)\n * 3.2. if it doesn't exist in the cache, it has to be loaded from Browser Local store, and then import it to WebCrypto\n * 4. Obtain the array of delegations which are delegated to his ID (hcpartyId) in this patient\n * 5. Decrypt and collect all keys (secretForeignKeys) within delegations of previous step (with obtained AES key of step 4)\n * 6. Do the REST call to get all forms with (allSecretForeignKeysDelimitedByComa, hcpartyId)\n *\n * After these painful steps, you have the forms of the patient.\n * @deprecated use {@link findIdsBy} instead.\n * @param hcpartyId\n * @param patient\n * @param usingPost (Promise)\n */\n async findBy(hcpartyId: string, patient: models.Patient, usingPost: boolean = false) {\n const extractedKeys = await this.crypto.xapi.secretIdsOf({ entity: patient, type: EntityWithDelegationTypeName.Patient }, hcpartyId)\n const topmostParentId = (await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds())[0]\n let forms: Array<models.Form> = await (usingPost\n ? this.findFormsByHCPartyPatientForeignKeysUsingPost(hcpartyId!, undefined, undefined, undefined, _.uniq(extractedKeys))\n : this.findFormsByHCPartyPatientForeignKeys(hcpartyId!, _.uniq(extractedKeys).join(',')))\n return await this.decrypt(hcpartyId, forms)\n }\n\n /**\n * Same as {@link findBy} but it will only return the ids of the forms. It can also filter the forms by opening date\n * (the date when the form was opened/started) between startDate and endDate in ascending or descending order by that field (default: ascending).\n * @param hcpartyId the id of the data owner.\n * @param patient the patient whose forms to retrieve.\n * @param startDate optional start date filter (inclusive). Only forms with openingDate >= startDate will be returned.\n * @param endDate optional end date filter (inclusive). Only forms with openingDate <= endDate will be returned.\n * @param descending if true, results are sorted by openingDate in descending order; otherwise in ascending order (default).\n * @return an array of form ids.\n */\n async findIdsBy(hcpartyId: string, patient: models.Patient, startDate?: number, endDate?: number, descending?: boolean) {\n const extractedKeys = await this.crypto.xapi.secretIdsOf({ entity: patient, type: EntityWithDelegationTypeName.Patient }, hcpartyId)\n return this.findFormIdsByDataOwnerPatientOpeningDate(hcpartyId, _.uniq(extractedKeys), startDate, endDate, descending)\n }\n\n /**\n * Decrypts the encrypted content of the provided forms.\n * @param hcpartyId the id of the data owner attempting to decrypt the forms.\n * @param forms the forms to decrypt.\n * @return an array of decrypted forms. Forms that could not be decrypted will be returned as-is.\n */\n async decrypt(hcpartyId: string, forms: Array<models.Form>) {\n return (await this.crypto.xapi.tryDecryptEntities(forms, EntityWithDelegationTypeName.Form, (x) => new models.Form(x))).map(\n ({ entity }) => entity\n )\n }\n\n /**\n * @param form a form\n * @return the id of the patient that the form refers to, retrieved from the encrypted metadata. Normally there should only be one element\n * in the returned array, but in case of entity merges there could be multiple values.\n */\n async decryptPatientIdOf(form: models.Form): Promise<string[]> {\n return this.crypto.xapi.owningEntityIdsOf({ entity: form, type: EntityWithDelegationTypeName.Form }, undefined)\n }\n\n /**\n * @return if the logged data owner has write access to the content of the given form\n */\n async hasWriteAccess(form: models.Form): Promise<boolean> {\n return this.crypto.xapi.hasWriteAccess({ entity: form, type: EntityWithDelegationTypeName.Form })\n }\n\n /**\n * Share an existing form with other data owners, allowing them to access the non-encrypted data of the form and optionally also\n * the encrypted content, with read-only or read-write permissions.\n * @param delegateId the id of the data owner which will be granted access to the form.\n * @param form the form to share.\n * @param options optional parameters to customize the sharing behaviour:\n * - shareSecretIds: specifies which secret ids of the entity should be shared. If not provided all secret ids available to the current user will be shared\n * - shareEncryptionKey: specifies if the encryption key of the access log should be shared with the delegate, giving access to all encrypted\n * content of the entity, excluding other encrypted metadata (defaults to {@link ShareMetadataBehaviour.IF_AVAILABLE}). Note that by default a\n * form does not have encrypted content.\n * - sharePatientId: specifies if the id of the patient that this form refers to should be shared with the delegate (defaults to\n * {@link ShareMetadataBehaviour.IF_AVAILABLE}).\n * - requestedPermissions: the requested permissions for the delegate, defaults to {@link RequestedPermissionEnum.MAX_WRITE}.\n * @return the updated entity\n */\n async shareWith(\n delegateId: string,\n form: models.Form,\n options: {\n shareSecretIds?: string[]\n requestedPermissions?: RequestedPermissionEnum\n shareEncryptionKey?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n sharePatientId?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n } = {}\n ): Promise<models.Form> {\n return this.shareWithMany(form, { [delegateId]: options })\n }\n\n /**\n * Share an existing form with other data owners, allowing them to access the non-encrypted data of the form and optionally also\n * the encrypted content, with read-only or read-write permissions.\n * @param form the form to share.\n * @param delegates associates the id of data owners which will be granted access to the entity, to the following sharing options:\n * - shareSecretIds: specifies which secret ids of the entity should be shared. If not provided all secret ids available to the current user will be shared\n * - shareEncryptionKey: specifies if the encryption key of the access log should be shared with the delegate, giving access to all encrypted\n * content of the entity, excluding other encrypted metadata (defaults to {@link ShareMetadataBehaviour.IF_AVAILABLE}). Note that by default a\n * form does not have encrypted content.\n * - sharePatientId: specifies if the id of the patient that this form refers to should be shared with the delegate (defaults to\n * {@link ShareMetadataBehaviour.IF_AVAILABLE}).\n * - requestedPermissions: the requested permissions for the delegate, defaults to {@link RequestedPermissionEnum.MAX_WRITE}.\n * @return the updated entity\n */\n async shareWithMany(\n form: models.Form,\n delegates: {\n [delegateId: string]: {\n shareSecretIds?: string[]\n requestedPermissions?: RequestedPermissionEnum\n shareEncryptionKey?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n sharePatientId?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n }\n }\n ): Promise<models.Form> {\n return (await this.tryShareWithMany(form, delegates)).updatedEntityOrThrow\n }\n\n /**\n * Share an existing form with other data owners, allowing them to access the non-encrypted data of the form and optionally also\n * the encrypted content, with read-only or read-write permissions.\n * @param form the form to share.\n * @param delegates associates the id of data owners which will be granted access to the entity, to the following sharing options:\n * - shareSecretIds: specifies which secret ids of the entity should be shared. If not provided all secret ids available to the current user will be shared\n * - shareEncryptionKey: specifies if the encryption key of the access log should be shared with the delegate, giving access to all encrypted\n * content of the entity, excluding other encrypted metadata (defaults to {@link ShareMetadataBehaviour.IF_AVAILABLE}). Note that by default a\n * form does not have encrypted content.\n * - sharePatientId: specifies if the id of the patient that this form refers to should be shared with the delegate (defaults to\n * {@link ShareMetadataBehaviour.IF_AVAILABLE}).\n * - requestedPermissions: the requested permissions for the delegate, defaults to {@link RequestedPermissionEnum.MAX_WRITE}.\n * @return a promise which will contain the result of the operation: the updated entity if the operation was successful or details of the error if\n * the operation failed.\n */\n async tryShareWithMany(\n form: models.Form,\n delegates: {\n [delegateId: string]: {\n shareSecretIds?: string[]\n requestedPermissions?: RequestedPermissionEnum\n shareEncryptionKey?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n sharePatientId?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n }\n }\n ): Promise<ShareResult<models.Form>> {\n const self = await this.dataOwnerApi.getCurrentDataOwnerId()\n // All entities should have an encryption key.\n const entityWithEncryptionKey = await this.crypto.xapi.ensureEncryptionKeysInitialised(form, EntityWithDelegationTypeName.Form)\n const updatedEntity = entityWithEncryptionKey ? await this.modifyForm(entityWithEncryptionKey) : form\n return this.crypto.xapi\n .simpleShareOrUpdateEncryptedEntityMetadata(\n {\n entity: updatedEntity,\n type: EntityWithDelegationTypeName.Form,\n },\n Object.fromEntries(\n Object.entries(delegates).map(([delegateId, options]) => [\n delegateId,\n {\n requestedPermissions: options.requestedPermissions,\n shareEncryptionKeys: options.shareEncryptionKey,\n shareOwningEntityIds: options.sharePatientId,\n shareSecretIds: options.shareSecretIds,\n },\n ])\n ),\n (x) => this.bulkShareForms(x)\n )\n .then((r) => r.mapSuccessAsync((e) => this.decrypt(self, [e]).then((es) => es[0])))\n }\n\n /**\n * Gets all data owners that have access to the given form, along with their access levels.\n * @param entity the form to check.\n * @return an object containing:\n * - permissionsByDataOwnerId: a map of data owner id to their access level.\n * - hasUnknownAnonymousDataOwners: true if there are anonymous data owners with access that could not be identified.\n */\n getDataOwnersWithAccessTo(\n entity: models.Form\n ): Promise<{ permissionsByDataOwnerId: { [p: string]: AccessLevelEnum }; hasUnknownAnonymousDataOwners: boolean }> {\n return this.crypto.delegationsDeAnonymization.getDataOwnersWithAccessTo({ entity, type: EntityWithDelegationTypeName.Form })\n }\n\n /**\n * Retrieves all encryption keys of the given form that are available to the current data owner.\n * @param entity the form whose encryption keys to retrieve.\n * @return an array of encryption keys in hexadecimal string format.\n */\n getEncryptionKeysOf(entity: models.Form): Promise<string[]> {\n return this.crypto.xapi.encryptionKeysOf({ entity, type: EntityWithDelegationTypeName.Form }, undefined)\n }\n\n /**\n * Creates or updates de-anonymization metadata for the given form, allowing the delegates to be identified\n * even if they were initially anonymous (e.g., in keyless mode).\n * @param entity the form for which to create de-anonymization metadata.\n * @param delegates the ids of the data owners for which to create de-anonymization information.\n */\n createDelegationDeAnonymizationMetadata(entity: models.Form, delegates: string[]): Promise<void> {\n return this.crypto.delegationsDeAnonymization.createOrUpdateDeAnonymizationInfo({ entity, type: EntityWithDelegationTypeName.Form }, delegates)\n }\n}\n"]}
@@ -21,15 +21,82 @@ export declare class IccHcpartyXApi extends IccHcpartyApi {
21
21
  [key: string]: string;
22
22
  }, authenticationProvider: AuthenticationProvider | undefined, authApi: IccAuthApi, fetchImpl?: (input: RequestInfo, init?: RequestInit) => Promise<Response>);
23
23
  private getHcPartyFromCache;
24
+ /**
25
+ * Ensures the healthcare party has consistent name fields. If lastName/name are set but there is no Official
26
+ * PersonName, one is created. Conversely, if an Official PersonName exists but lastName/name are missing, they
27
+ * are populated from the PersonName.
28
+ * @param hcParty the healthcare party whose names should be completed.
29
+ * @return the healthcare party with completed name fields, or undefined if the input was undefined.
30
+ */
24
31
  completeNames(hcParty?: models.HealthcareParty): models.HealthcareParty | undefined;
32
+ /**
33
+ * Stores a healthcare party promise in the local cache with a time-to-live.
34
+ * @param key the cache key (typically the healthcare party id).
35
+ * @param hcpPromise the promise resolving to the healthcare party to cache.
36
+ * @return the same promise that was cached.
37
+ */
25
38
  putHcPartyInCache(key: string, hcpPromise: Promise<HealthcareParty>): Promise<HealthcareParty>;
39
+ /**
40
+ * Creates a new healthcare party after completing its name fields.
41
+ * @param body the healthcare party to create.
42
+ * @return the created healthcare party.
43
+ */
26
44
  createHealthcareParty(body?: HealthcareParty): Promise<HealthcareParty>;
45
+ /**
46
+ * Creates a new healthcare party in the specified group after completing its name fields.
47
+ * @param groupId the id of the group in which to create the healthcare party.
48
+ * @param body the healthcare party to create.
49
+ * @return the created healthcare party.
50
+ */
27
51
  createHealthcarePartyInGroup(groupId: string, body?: HealthcareParty): Promise<HealthcareParty>;
52
+ /**
53
+ * Modifies an existing healthcare party after completing its name fields. Evicts the party from the local cache
54
+ * before modifying, and re-caches the updated version upon success.
55
+ * @param body the healthcare party with updated fields.
56
+ * @return the modified healthcare party.
57
+ */
28
58
  modifyHealthcareParty(body?: HealthcareParty): Promise<HealthcareParty | any>;
59
+ /**
60
+ * Retrieves a healthcare party by id. Returns a cached version if available and not expired, otherwise fetches
61
+ * from the server and caches the result.
62
+ * @param healthcarePartyId the id of the healthcare party to retrieve.
63
+ * @param bypassCache if true, skips the cache and fetches directly from the server.
64
+ * @return the healthcare party.
65
+ */
29
66
  getHealthcareParty(healthcarePartyId: string, bypassCache?: boolean): Promise<HealthcareParty | any>;
67
+ /**
68
+ * Retrieves the full hierarchy of healthcare party ids, from the topmost parent down to the given party.
69
+ * Recursively walks up the parentId chain.
70
+ * @param healthcarePartyId the id of the healthcare party whose hierarchy to retrieve.
71
+ * @param bypassCache if true, bypasses the cache for each party in the hierarchy.
72
+ * @return an array of healthcare party ids ordered from the topmost ancestor to the given party.
73
+ */
30
74
  getHealthcarePartyHierarchyIds(healthcarePartyId: string, bypassCache?: boolean): Promise<string[]>;
75
+ /**
76
+ * Retrieves multiple healthcare parties by their ids. Uses the cache where possible, and fetches any missing
77
+ * parties from the server in a single bulk request. Parties not found on the server are filtered out.
78
+ * @param healthcarePartyIds the list of healthcare party ids to retrieve.
79
+ * @return an array of healthcare parties (excluding any that were not found).
80
+ */
31
81
  getHealthcareParties(healthcarePartyIds: ListOfIds): Promise<Array<HealthcareParty> | any>;
82
+ /**
83
+ * Retrieves the currently logged-in healthcare party and caches it.
84
+ * @return the current healthcare party.
85
+ */
32
86
  getCurrentHealthcareParty(): Promise<HealthcareParty>;
87
+ /**
88
+ * Validates a Belgian CBE (Crossroads Bank for Enterprises) number using the modulo 97 check.
89
+ * @param cbe the CBE number to validate (non-digit characters are stripped).
90
+ * @return true if the CBE number is valid, false otherwise.
91
+ */
33
92
  isValidCbe(cbe: string): boolean;
93
+ /**
94
+ * Subscribes to real-time healthcare party events using a WebSocket connection.
95
+ * @param eventTypes the types of events to listen for (e.g. 'CREATE', 'UPDATE', 'DELETE').
96
+ * @param filter an optional filter to restrict which healthcare party events trigger the callback.
97
+ * @param eventFired the callback function invoked when a matching healthcare party event is received.
98
+ * @param options optional subscription configuration such as connection parameters and retry behaviour.
99
+ * @return a connection object that can be used to manage the WebSocket subscription lifecycle.
100
+ */
34
101
  subscribeToHealthcarePartyEvents(eventTypes: ('CREATE' | 'UPDATE' | 'DELETE')[], filter: AbstractFilter<HealthcareParty> | undefined, eventFired: (dataSample: HealthcareParty) => Promise<void>, options?: SubscriptionOptions): Promise<Connection>;
35
102
  }
@@ -46,6 +46,13 @@ class IccHcpartyXApi extends icc_api_1.IccHcpartyApi {
46
46
  }
47
47
  return null;
48
48
  }
49
+ /**
50
+ * Ensures the healthcare party has consistent name fields. If lastName/name are set but there is no Official
51
+ * PersonName, one is created. Conversely, if an Official PersonName exists but lastName/name are missing, they
52
+ * are populated from the PersonName.
53
+ * @param hcParty the healthcare party whose names should be completed.
54
+ * @return the healthcare party with completed name fields, or undefined if the input was undefined.
55
+ */
49
56
  completeNames(hcParty) {
50
57
  if (!hcParty) {
51
58
  return hcParty;
@@ -60,16 +67,39 @@ class IccHcpartyXApi extends icc_api_1.IccHcpartyApi {
60
67
  }
61
68
  return finalHcParty;
62
69
  }
70
+ /**
71
+ * Stores a healthcare party promise in the local cache with a time-to-live.
72
+ * @param key the cache key (typically the healthcare party id).
73
+ * @param hcpPromise the promise resolving to the healthcare party to cache.
74
+ * @return the same promise that was cached.
75
+ */
63
76
  putHcPartyInCache(key, hcpPromise) {
64
77
  this.hcPartyCache[key] = [Date.now() + this.CACHE_RETENTION_IN_MS, hcpPromise];
65
78
  return hcpPromise;
66
79
  }
80
+ /**
81
+ * Creates a new healthcare party after completing its name fields.
82
+ * @param body the healthcare party to create.
83
+ * @return the created healthcare party.
84
+ */
67
85
  createHealthcareParty(body) {
68
86
  return super.createHealthcareParty(this.completeNames(body));
69
87
  }
88
+ /**
89
+ * Creates a new healthcare party in the specified group after completing its name fields.
90
+ * @param groupId the id of the group in which to create the healthcare party.
91
+ * @param body the healthcare party to create.
92
+ * @return the created healthcare party.
93
+ */
70
94
  createHealthcarePartyInGroup(groupId, body) {
71
95
  return super.createHealthcarePartyInGroup(groupId, this.completeNames(body));
72
96
  }
97
+ /**
98
+ * Modifies an existing healthcare party after completing its name fields. Evicts the party from the local cache
99
+ * before modifying, and re-caches the updated version upon success.
100
+ * @param body the healthcare party with updated fields.
101
+ * @return the modified healthcare party.
102
+ */
73
103
  modifyHealthcareParty(body) {
74
104
  if (body && body.id) {
75
105
  console.log(`Evict key ${body.id} because of modification`);
@@ -77,6 +107,13 @@ class IccHcpartyXApi extends icc_api_1.IccHcpartyApi {
77
107
  }
78
108
  return super.modifyHealthcareParty(this.completeNames(body)).then((hcp) => this.putHcPartyInCache(hcp.id, Promise.resolve(hcp)));
79
109
  }
110
+ /**
111
+ * Retrieves a healthcare party by id. Returns a cached version if available and not expired, otherwise fetches
112
+ * from the server and caches the result.
113
+ * @param healthcarePartyId the id of the healthcare party to retrieve.
114
+ * @param bypassCache if true, skips the cache and fetches directly from the server.
115
+ * @return the healthcare party.
116
+ */
80
117
  getHealthcareParty(healthcarePartyId_1) {
81
118
  const _super = Object.create(null, {
82
119
  getHealthcareParty: { get: () => super.getHealthcareParty }
@@ -99,11 +136,24 @@ class IccHcpartyXApi extends icc_api_1.IccHcpartyApi {
99
136
  }
100
137
  });
101
138
  }
139
+ /**
140
+ * Retrieves the full hierarchy of healthcare party ids, from the topmost parent down to the given party.
141
+ * Recursively walks up the parentId chain.
142
+ * @param healthcarePartyId the id of the healthcare party whose hierarchy to retrieve.
143
+ * @param bypassCache if true, bypasses the cache for each party in the hierarchy.
144
+ * @return an array of healthcare party ids ordered from the topmost ancestor to the given party.
145
+ */
102
146
  getHealthcarePartyHierarchyIds(healthcarePartyId, bypassCache = false) {
103
147
  return this.getHealthcareParty(healthcarePartyId, bypassCache).then((hcp) => __awaiter(this, void 0, void 0, function* () {
104
148
  return hcp ? (hcp.parentId ? (yield this.getHealthcarePartyHierarchyIds(hcp.parentId, bypassCache)).concat([hcp.id]) : [hcp.id]) : [];
105
149
  }));
106
150
  }
151
+ /**
152
+ * Retrieves multiple healthcare parties by their ids. Uses the cache where possible, and fetches any missing
153
+ * parties from the server in a single bulk request. Parties not found on the server are filtered out.
154
+ * @param healthcarePartyIds the list of healthcare party ids to retrieve.
155
+ * @return an array of healthcare parties (excluding any that were not found).
156
+ */
107
157
  getHealthcareParties(healthcarePartyIds) {
108
158
  const _super = Object.create(null, {
109
159
  getHealthcareParties: { get: () => super.getHealthcareParties }
@@ -149,14 +199,31 @@ class IccHcpartyXApi extends icc_api_1.IccHcpartyApi {
149
199
  })).then((results) => results.filter((it) => it != null));
150
200
  });
151
201
  }
202
+ /**
203
+ * Retrieves the currently logged-in healthcare party and caches it.
204
+ * @return the current healthcare party.
205
+ */
152
206
  getCurrentHealthcareParty() {
153
207
  return super.getCurrentHealthcareParty().then((hcp) => this.putHcPartyInCache(hcp.id, Promise.resolve(hcp)));
154
208
  }
209
+ /**
210
+ * Validates a Belgian CBE (Crossroads Bank for Enterprises) number using the modulo 97 check.
211
+ * @param cbe the CBE number to validate (non-digit characters are stripped).
212
+ * @return true if the CBE number is valid, false otherwise.
213
+ */
155
214
  isValidCbe(cbe) {
156
215
  cbe = cbe.replace(new RegExp('[^(0-9)]', 'g'), '');
157
216
  cbe = cbe.length == 9 ? '0' + cbe : cbe;
158
217
  return 97 - (Number(cbe.substring(0, 8)) % 97) === Number(cbe.substring(8, 10));
159
218
  }
219
+ /**
220
+ * Subscribes to real-time healthcare party events using a WebSocket connection.
221
+ * @param eventTypes the types of events to listen for (e.g. 'CREATE', 'UPDATE', 'DELETE').
222
+ * @param filter an optional filter to restrict which healthcare party events trigger the callback.
223
+ * @param eventFired the callback function invoked when a matching healthcare party event is received.
224
+ * @param options optional subscription configuration such as connection parameters and retry behaviour.
225
+ * @return a connection object that can be used to manage the WebSocket subscription lifecycle.
226
+ */
160
227
  subscribeToHealthcarePartyEvents(eventTypes_1, filter_1, eventFired_1) {
161
228
  return __awaiter(this, arguments, void 0, function* (eventTypes, filter, eventFired, options = {}) {
162
229
  return (0, utils_1.subscribeToEntityEvents)(this.host, this.authApi, 'HealthcareParty', eventTypes, filter, eventFired, options).then((rs) => new Connection_1.ConnectionImpl(rs));
@@ -1 +1 @@
1
- {"version":3,"file":"icc-hcparty-x-api.js","sourceRoot":"","sources":["../../icc-x-api/icc-hcparty-x-api.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,wCAAsD;AAEtD,kDAAiD;AACjD,qDAA8E;AAC9E,0EAAgG;AAEhG,mCAAsE;AACtE,4DAAwE;AACxE,oDAAmD;AACnD,4CAAwC;AACxC,IAAO,QAAQ,GAAG,SAAG,CAAC,QAAQ,CAAA;AAE9B,qCAAqC;AACrC,MAAa,cAAe,SAAQ,uBAAa;IAK/C,YACE,IAAY,EACZ,OAAkC,EAClC,yBAAiD,IAAI,iDAAwB,EAAE,EAC9D,OAAmB,EACpC,YAA2E,OAAO,MAAM,KAAK,WAAW;QACtG,CAAC,CAAC,MAAM,CAAC,KAAK;QACd,CAAC,CAAC,OAAO,IAAI,KAAK,WAAW;YAC7B,CAAC,CAAC,IAAI,CAAC,KAAK;YACZ,CAAC,CAAC,KAAK;QAET,KAAK,CAAC,IAAI,EAAE,OAAO,EAAE,sBAAsB,EAAE,SAAS,CAAC,CAAA;QAPtC,YAAO,GAAP,OAAO,CAAY;QARtC,qBAAgB,GAAiD,EAAE,CAAA;QACnE,iBAAY,GAA0D,EAAE,CAAA;QAEhE,0BAAqB,GAAG,MAAO,CAAA;IAavC,CAAC;IAEO,mBAAmB,CAAC,GAAW;QACrC,MAAM,UAAU,GAAG,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC,CAAA;QACzC,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAA;QACtB,IAAI,UAAU,IAAI,UAAU,CAAC,CAAC,CAAC,GAAG,GAAG,EAAE,CAAC;YACtC,OAAO,UAAU,CAAC,CAAC,CAAC,CAAA;QACtB,CAAC;QACD,IAAI,CAAC,UAAU,EAAE,CAAC;YAChB,OAAO,CAAC,GAAG,CAAC,sBAAsB,GAAG,uBAAuB,CAAC,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jF,CAAC;IAEK,gCAAgC;6DACpC,UAA8C,EAC9C,MAAmD,EACnD,UAA0D,EAC1D,UAA+B,EAAE;YAEjC,OAAO,IAAA,+BAAuB,EAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,OAAO,EAAE,iBAAiB,EAAE,UAAU,EAAE,MAAM,EAAE,UAAU,EAAE,OAAO,CAAC,CAAC,IAAI,CACtH,CAAC,EAAE,EAAE,EAAE,CAAC,IAAI,2BAAc,CAAC,EAAE,CAAC,CAC/B,CAAA;QACH,CAAC;KAAA;CACF;AA/KD,wCA+KC","sourcesContent":["import { IccAuthApi, IccHcpartyApi } from '../icc-api'\nimport { HealthcareParty } from '../icc-api/model/HealthcareParty'\nimport * as models from '../icc-api/model/models'\nimport { findName, garnishPersonWithName, hasName } from './utils/person-util'\nimport { AuthenticationProvider, NoAuthenticationProvider } from './auth/AuthenticationProvider'\nimport { AbstractFilter } from './filters/filters'\nimport { subscribeToEntityEvents, SubscriptionOptions } from './utils'\nimport { Connection, ConnectionImpl } from '../icc-api/model/Connection'\nimport { ListOfIds } from '../icc-api/model/models'\nimport { XHR } from '../icc-api/api/XHR'\nimport XHRError = XHR.XHRError\n\n// noinspection JSUnusedGlobalSymbols\nexport class IccHcpartyXApi extends IccHcpartyApi {\n hcPartyKeysCache: { [key: string]: { [key: string]: string } } = {}\n hcPartyCache: { [key: string]: [number, Promise<HealthcareParty>] } = {}\n\n private CACHE_RETENTION_IN_MS = 300_000\n constructor(\n host: string,\n headers: { [key: string]: string },\n authenticationProvider: AuthenticationProvider = new NoAuthenticationProvider(),\n private readonly authApi: IccAuthApi,\n fetchImpl: (input: RequestInfo, init?: RequestInit) => Promise<Response> = typeof window !== 'undefined'\n ? window.fetch\n : typeof self !== 'undefined'\n ? self.fetch\n : fetch\n ) {\n super(host, headers, authenticationProvider, fetchImpl)\n }\n\n private getHcPartyFromCache(key: string) {\n const hcpInCache = this.hcPartyCache[key]\n const now = Date.now()\n if (hcpInCache && hcpInCache[0] > now) {\n return hcpInCache[1]\n }\n if (!hcpInCache) {\n console.log(`Cache miss for key ${key} because not in cache`)\n } else {\n console.log(`Cache miss for key ${key} because ${hcpInCache[0]} > ${now}`)\n }\n return null\n }\n\n completeNames(hcParty?: models.HealthcareParty): models.HealthcareParty | undefined {\n if (!hcParty) {\n return hcParty\n }\n\n let finalHcParty = hcParty\n\n if ((!!finalHcParty.lastName || !!finalHcParty.name) && !hasName(finalHcParty, models.PersonName.UseEnum.Official)) {\n finalHcParty = garnishPersonWithName(\n finalHcParty,\n models.PersonName.UseEnum.Official,\n finalHcParty.lastName,\n finalHcParty.firstName,\n finalHcParty.name\n )\n }\n\n if ((!finalHcParty.lastName || !finalHcParty.name) && !!hasName(finalHcParty, models.PersonName.UseEnum.Official)) {\n let officialName = findName(finalHcParty, models.PersonName.UseEnum.Official)\n finalHcParty = {\n ...finalHcParty,\n lastName: officialName!.lastName,\n firstName: officialName!.firstNames ? officialName!.firstNames[0] : undefined,\n name: officialName!.text,\n }\n }\n\n return finalHcParty\n }\n\n putHcPartyInCache(key: string, hcpPromise: Promise<HealthcareParty>): Promise<HealthcareParty> {\n this.hcPartyCache[key] = [Date.now() + this.CACHE_RETENTION_IN_MS, hcpPromise]\n return hcpPromise\n }\n\n createHealthcareParty(body?: HealthcareParty): Promise<HealthcareParty> {\n return super.createHealthcareParty(this.completeNames(body))\n }\n\n createHealthcarePartyInGroup(groupId: string, body?: HealthcareParty): Promise<HealthcareParty> {\n return super.createHealthcarePartyInGroup(groupId, this.completeNames(body))\n }\n\n modifyHealthcareParty(body?: HealthcareParty): Promise<HealthcareParty | any> {\n if (body && body.id) {\n console.log(`Evict key ${body.id} because of modification`)\n delete this.hcPartyCache[body.id]\n }\n\n return super.modifyHealthcareParty(this.completeNames(body)).then((hcp) => this.putHcPartyInCache(hcp.id!, Promise.resolve(hcp)))\n }\n\n async getHealthcareParty(healthcarePartyId: string, bypassCache = false): Promise<HealthcareParty | any> {\n const fromCache = bypassCache ? undefined : this.getHcPartyFromCache(healthcarePartyId)\n if (fromCache) {\n try {\n return await fromCache\n } catch {\n if (this.hcPartyCache[healthcarePartyId][1] === fromCache) {\n delete this.hcPartyCache[healthcarePartyId]\n }\n return this.getHealthcareParty(healthcarePartyId, bypassCache)\n }\n } else {\n return await this.putHcPartyInCache(healthcarePartyId, super.getHealthcareParty(healthcarePartyId))\n }\n }\n\n getHealthcarePartyHierarchyIds(healthcarePartyId: string, bypassCache = false): Promise<string[]> {\n return this.getHealthcareParty(healthcarePartyId, bypassCache).then(async (hcp: HealthcareParty) => {\n return hcp ? (hcp.parentId ? (await this.getHealthcarePartyHierarchyIds(hcp.parentId!, bypassCache)).concat([hcp.id!]) : [hcp.id!]) : []\n })\n }\n\n async getHealthcareParties(healthcarePartyIds: ListOfIds): Promise<Array<HealthcareParty> | any> {\n const ids = healthcarePartyIds.ids\n if (!ids || !ids.length) {\n return Promise.resolve([])\n }\n const cached: Array<[string, HealthcareParty | null]> = []\n for (const id of ids) {\n let hcp\n try {\n hcp = await this.getHcPartyFromCache(id)\n } catch {\n hcp = null\n delete this.hcPartyCache[id]\n }\n cached.push([id, hcp])\n }\n const toFetch = cached.filter((x) => !x[1]).map((x) => x[0])\n\n if (!toFetch.length) {\n return Promise.all(cached.map((x) => x[1]!))\n }\n\n const prom: Promise<HealthcareParty[]> = super.getHealthcareParties(new ListOfIds({ ids: toFetch }))\n return Promise.all(\n cached.map(\n (x) =>\n x[1] ??\n this.putHcPartyInCache(\n x[0],\n prom.then((hcps) => {\n const hcp = hcps.find((h) => h.id === x[0])\n if (!!hcp) {\n return hcp\n } else {\n throw new Error(`Hcp with id ${x[0]} not found`)\n }\n })\n ).catch((e) => {\n if (e instanceof XHRError) {\n throw e\n }\n return null\n })\n )\n ).then((results) => results.filter((it) => it != null))\n }\n\n getCurrentHealthcareParty(): Promise<HealthcareParty> {\n return super.getCurrentHealthcareParty().then((hcp) => this.putHcPartyInCache(hcp.id!, Promise.resolve(hcp)))\n }\n\n isValidCbe(cbe: string) {\n cbe = cbe.replace(new RegExp('[^(0-9)]', 'g'), '')\n cbe = cbe.length == 9 ? '0' + cbe : cbe\n\n return 97 - (Number(cbe.substring(0, 8)) % 97) === Number(cbe.substring(8, 10))\n }\n\n async subscribeToHealthcarePartyEvents(\n eventTypes: ('CREATE' | 'UPDATE' | 'DELETE')[],\n filter: AbstractFilter<HealthcareParty> | undefined,\n eventFired: (dataSample: HealthcareParty) => Promise<void>,\n options: SubscriptionOptions = {}\n ): Promise<Connection> {\n return subscribeToEntityEvents(this.host, this.authApi, 'HealthcareParty', eventTypes, filter, eventFired, options).then(\n (rs) => new ConnectionImpl(rs)\n )\n }\n}\n"]}
1
+ {"version":3,"file":"icc-hcparty-x-api.js","sourceRoot":"","sources":["../../icc-x-api/icc-hcparty-x-api.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,wCAAsD;AAEtD,kDAAiD;AACjD,qDAA8E;AAC9E,0EAAgG;AAEhG,mCAAsE;AACtE,4DAAwE;AACxE,oDAAmD;AACnD,4CAAwC;AACxC,IAAO,QAAQ,GAAG,SAAG,CAAC,QAAQ,CAAA;AAE9B,qCAAqC;AACrC,MAAa,cAAe,SAAQ,uBAAa;IAK/C,YACE,IAAY,EACZ,OAAkC,EAClC,yBAAiD,IAAI,iDAAwB,EAAE,EAC9D,OAAmB,EACpC,YAA2E,OAAO,MAAM,KAAK,WAAW;QACtG,CAAC,CAAC,MAAM,CAAC,KAAK;QACd,CAAC,CAAC,OAAO,IAAI,KAAK,WAAW;YAC7B,CAAC,CAAC,IAAI,CAAC,KAAK;YACZ,CAAC,CAAC,KAAK;QAET,KAAK,CAAC,IAAI,EAAE,OAAO,EAAE,sBAAsB,EAAE,SAAS,CAAC,CAAA;QAPtC,YAAO,GAAP,OAAO,CAAY;QARtC,qBAAgB,GAAiD,EAAE,CAAA;QACnE,iBAAY,GAA0D,EAAE,CAAA;QAEhE,0BAAqB,GAAG,MAAO,CAAA;IAavC,CAAC;IAEO,mBAAmB,CA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AC,GAAG,CAAC,CAAC,CAAC,CAAA;IAC/G,CAAC;IAED;;;;OAIG;IACH,UAAU,CAAC,GAAW;QACpB,GAAG,GAAG,GAAG,CAAC,OAAO,CAAC,IAAI,MAAM,CAAC,UAAU,EAAE,GAAG,CAAC,EAAE,EAAE,CAAC,CAAA;QAClD,GAAG,GAAG,GAAG,CAAC,MAAM,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,GAAG,GAAG,CAAC,CAAC,CAAC,GAAG,CAAA;QAEvC,OAAO,EAAE,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,KAAK,MAAM,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAA;IACjF,CAAC;IAED;;;;;;;OAOG;IACG,gCAAgC;6DACpC,UAA8C,EAC9C,MAAmD,EACnD,UAA0D,EAC1D,UAA+B,EAAE;YAEjC,OAAO,IAAA,+BAAuB,EAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,OAAO,EAAE,iBAAiB,EAAE,UAAU,EAAE,MAAM,EAAE,UAAU,EAAE,OAAO,CAAC,CAAC,IAAI,CACtH,CAAC,EAAE,EAAE,EAAE,CAAC,IAAI,2BAAc,CAAC,EAAE,CAAC,CAC/B,CAAA;QACH,CAAC;KAAA;CACF;AAlPD,wCAkPC","sourcesContent":["import { IccAuthApi, IccHcpartyApi } from '../icc-api'\nimport { HealthcareParty } from '../icc-api/model/HealthcareParty'\nimport * as models from '../icc-api/model/models'\nimport { findName, garnishPersonWithName, hasName } from './utils/person-util'\nimport { AuthenticationProvider, NoAuthenticationProvider } from './auth/AuthenticationProvider'\nimport { AbstractFilter } from './filters/filters'\nimport { subscribeToEntityEvents, SubscriptionOptions } from './utils'\nimport { Connection, ConnectionImpl } from '../icc-api/model/Connection'\nimport { ListOfIds } from '../icc-api/model/models'\nimport { XHR } from '../icc-api/api/XHR'\nimport XHRError = XHR.XHRError\n\n// noinspection JSUnusedGlobalSymbols\nexport class IccHcpartyXApi extends IccHcpartyApi {\n hcPartyKeysCache: { [key: string]: { [key: string]: string } } = {}\n hcPartyCache: { [key: string]: [number, Promise<HealthcareParty>] } = {}\n\n private CACHE_RETENTION_IN_MS = 300_000\n constructor(\n host: string,\n headers: { [key: string]: string },\n authenticationProvider: AuthenticationProvider = new NoAuthenticationProvider(),\n private readonly authApi: IccAuthApi,\n fetchImpl: (input: RequestInfo, init?: RequestInit) => Promise<Response> = typeof window !== 'undefined'\n ? window.fetch\n : typeof self !== 'undefined'\n ? self.fetch\n : fetch\n ) {\n super(host, headers, authenticationProvider, fetchImpl)\n }\n\n private getHcPartyFromCache(key: string) {\n const hcpInCache = this.hcPartyCache[key]\n const now = Date.now()\n if (hcpInCache && hcpInCache[0] > now) {\n return hcpInCache[1]\n }\n if (!hcpInCache) {\n console.log(`Cache miss for key ${key} because not in cache`)\n } else {\n console.log(`Cache miss for key ${key} because ${hcpInCache[0]} > ${now}`)\n }\n return null\n }\n\n /**\n * Ensures the healthcare party has consistent name fields. If lastName/name are set but there is no Official\n * PersonName, one is created. Conversely, if an Official PersonName exists but lastName/name are missing, they\n * are populated from the PersonName.\n * @param hcParty the healthcare party whose names should be completed.\n * @return the healthcare party with completed name fields, or undefined if the input was undefined.\n */\n completeNames(hcParty?: models.HealthcareParty): models.HealthcareParty | undefined {\n if (!hcParty) {\n return hcParty\n }\n\n let finalHcParty = hcParty\n\n if ((!!finalHcParty.lastName || !!finalHcParty.name) && !hasName(finalHcParty, models.PersonName.UseEnum.Official)) {\n finalHcParty = garnishPersonWithName(\n finalHcParty,\n models.PersonName.UseEnum.Official,\n finalHcParty.lastName,\n finalHcParty.firstName,\n finalHcParty.name\n )\n }\n\n if ((!finalHcParty.lastName || !finalHcParty.name) && !!hasName(finalHcParty, models.PersonName.UseEnum.Official)) {\n let officialName = findName(finalHcParty, models.PersonName.UseEnum.Official)\n finalHcParty = {\n ...finalHcParty,\n lastName: officialName!.lastName,\n firstName: officialName!.firstNames ? officialName!.firstNames[0] : undefined,\n name: officialName!.text,\n }\n }\n\n return finalHcParty\n }\n\n /**\n * Stores a healthcare party promise in the local cache with a time-to-live.\n * @param key the cache key (typically the healthcare party id).\n * @param hcpPromise the promise resolving to the healthcare party to cache.\n * @return the same promise that was cached.\n */\n putHcPartyInCache(key: string, hcpPromise: Promise<HealthcareParty>): Promise<HealthcareParty> {\n this.hcPartyCache[key] = [Date.now() + this.CACHE_RETENTION_IN_MS, hcpPromise]\n return hcpPromise\n }\n\n /**\n * Creates a new healthcare party after completing its name fields.\n * @param body the healthcare party to create.\n * @return the created healthcare party.\n */\n createHealthcareParty(body?: HealthcareParty): Promise<HealthcareParty> {\n return super.createHealthcareParty(this.completeNames(body))\n }\n\n /**\n * Creates a new healthcare party in the specified group after completing its name fields.\n * @param groupId the id of the group in which to create the healthcare party.\n * @param body the healthcare party to create.\n * @return the created healthcare party.\n */\n createHealthcarePartyInGroup(groupId: string, body?: HealthcareParty): Promise<HealthcareParty> {\n return super.createHealthcarePartyInGroup(groupId, this.completeNames(body))\n }\n\n /**\n * Modifies an existing healthcare party after completing its name fields. Evicts the party from the local cache\n * before modifying, and re-caches the updated version upon success.\n * @param body the healthcare party with updated fields.\n * @return the modified healthcare party.\n */\n modifyHealthcareParty(body?: HealthcareParty): Promise<HealthcareParty | any> {\n if (body && body.id) {\n console.log(`Evict key ${body.id} because of modification`)\n delete this.hcPartyCache[body.id]\n }\n\n return super.modifyHealthcareParty(this.completeNames(body)).then((hcp) => this.putHcPartyInCache(hcp.id!, Promise.resolve(hcp)))\n }\n\n /**\n * Retrieves a healthcare party by id. Returns a cached version if available and not expired, otherwise fetches\n * from the server and caches the result.\n * @param healthcarePartyId the id of the healthcare party to retrieve.\n * @param bypassCache if true, skips the cache and fetches directly from the server.\n * @return the healthcare party.\n */\n async getHealthcareParty(healthcarePartyId: string, bypassCache = false): Promise<HealthcareParty | any> {\n const fromCache = bypassCache ? undefined : this.getHcPartyFromCache(healthcarePartyId)\n if (fromCache) {\n try {\n return await fromCache\n } catch {\n if (this.hcPartyCache[healthcarePartyId][1] === fromCache) {\n delete this.hcPartyCache[healthcarePartyId]\n }\n return this.getHealthcareParty(healthcarePartyId, bypassCache)\n }\n } else {\n return await this.putHcPartyInCache(healthcarePartyId, super.getHealthcareParty(healthcarePartyId))\n }\n }\n\n /**\n * Retrieves the full hierarchy of healthcare party ids, from the topmost parent down to the given party.\n * Recursively walks up the parentId chain.\n * @param healthcarePartyId the id of the healthcare party whose hierarchy to retrieve.\n * @param bypassCache if true, bypasses the cache for each party in the hierarchy.\n * @return an array of healthcare party ids ordered from the topmost ancestor to the given party.\n */\n getHealthcarePartyHierarchyIds(healthcarePartyId: string, bypassCache = false): Promise<string[]> {\n return this.getHealthcareParty(healthcarePartyId, bypassCache).then(async (hcp: HealthcareParty) => {\n return hcp ? (hcp.parentId ? (await this.getHealthcarePartyHierarchyIds(hcp.parentId!, bypassCache)).concat([hcp.id!]) : [hcp.id!]) : []\n })\n }\n\n /**\n * Retrieves multiple healthcare parties by their ids. Uses the cache where possible, and fetches any missing\n * parties from the server in a single bulk request. Parties not found on the server are filtered out.\n * @param healthcarePartyIds the list of healthcare party ids to retrieve.\n * @return an array of healthcare parties (excluding any that were not found).\n */\n async getHealthcareParties(healthcarePartyIds: ListOfIds): Promise<Array<HealthcareParty> | any> {\n const ids = healthcarePartyIds.ids\n if (!ids || !ids.length) {\n return Promise.resolve([])\n }\n const cached: Array<[string, HealthcareParty | null]> = []\n for (const id of ids) {\n let hcp\n try {\n hcp = await this.getHcPartyFromCache(id)\n } catch {\n hcp = null\n delete this.hcPartyCache[id]\n }\n cached.push([id, hcp])\n }\n const toFetch = cached.filter((x) => !x[1]).map((x) => x[0])\n\n if (!toFetch.length) {\n return Promise.all(cached.map((x) => x[1]!))\n }\n\n const prom: Promise<HealthcareParty[]> = super.getHealthcareParties(new ListOfIds({ ids: toFetch }))\n return Promise.all(\n cached.map(\n (x) =>\n x[1] ??\n this.putHcPartyInCache(\n x[0],\n prom.then((hcps) => {\n const hcp = hcps.find((h) => h.id === x[0])\n if (!!hcp) {\n return hcp\n } else {\n throw new Error(`Hcp with id ${x[0]} not found`)\n }\n })\n ).catch((e) => {\n if (e instanceof XHRError) {\n throw e\n }\n return null\n })\n )\n ).then((results) => results.filter((it) => it != null))\n }\n\n /**\n * Retrieves the currently logged-in healthcare party and caches it.\n * @return the current healthcare party.\n */\n getCurrentHealthcareParty(): Promise<HealthcareParty> {\n return super.getCurrentHealthcareParty().then((hcp) => this.putHcPartyInCache(hcp.id!, Promise.resolve(hcp)))\n }\n\n /**\n * Validates a Belgian CBE (Crossroads Bank for Enterprises) number using the modulo 97 check.\n * @param cbe the CBE number to validate (non-digit characters are stripped).\n * @return true if the CBE number is valid, false otherwise.\n */\n isValidCbe(cbe: string) {\n cbe = cbe.replace(new RegExp('[^(0-9)]', 'g'), '')\n cbe = cbe.length == 9 ? '0' + cbe : cbe\n\n return 97 - (Number(cbe.substring(0, 8)) % 97) === Number(cbe.substring(8, 10))\n }\n\n /**\n * Subscribes to real-time healthcare party events using a WebSocket connection.\n * @param eventTypes the types of events to listen for (e.g. 'CREATE', 'UPDATE', 'DELETE').\n * @param filter an optional filter to restrict which healthcare party events trigger the callback.\n * @param eventFired the callback function invoked when a matching healthcare party event is received.\n * @param options optional subscription configuration such as connection parameters and retry behaviour.\n * @return a connection object that can be used to manage the WebSocket subscription lifecycle.\n */\n async subscribeToHealthcarePartyEvents(\n eventTypes: ('CREATE' | 'UPDATE' | 'DELETE')[],\n filter: AbstractFilter<HealthcareParty> | undefined,\n eventFired: (dataSample: HealthcareParty) => Promise<void>,\n options: SubscriptionOptions = {}\n ): Promise<Connection> {\n return subscribeToEntityEvents(this.host, this.authApi, 'HealthcareParty', eventTypes, filter, eventFired, options).then(\n (rs) => new ConnectionImpl(rs)\n )\n }\n}\n"]}