@twin.org/document-management-service 0.0.1-next.2

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.
@@ -0,0 +1,866 @@
1
+ 'use strict';
2
+
3
+ var apiModels = require('@twin.org/api-models');
4
+ var core = require('@twin.org/core');
5
+ var documentManagementModels = require('@twin.org/document-management-models');
6
+ var standardsSchemaOrg = require('@twin.org/standards-schema-org');
7
+ var standardsUnece = require('@twin.org/standards-unece');
8
+ var web = require('@twin.org/web');
9
+ var attestationModels = require('@twin.org/attestation-models');
10
+ var auditableItemGraphModels = require('@twin.org/auditable-item-graph-models');
11
+ var blobStorageModels = require('@twin.org/blob-storage-models');
12
+ var crypto = require('@twin.org/crypto');
13
+ var dataJsonLd = require('@twin.org/data-json-ld');
14
+
15
+ // Copyright 2024 IOTA Stiftung.
16
+ // SPDX-License-Identifier: Apache-2.0.
17
+ /**
18
+ * The source used when communicating about these routes.
19
+ */
20
+ const ROUTES_SOURCE = "documentManagementStorageRoutes";
21
+ /**
22
+ * The tag to associate with the routes.
23
+ */
24
+ const tagsDocumentManagement = [
25
+ {
26
+ name: "Document Management",
27
+ description: "Endpoints which are modelled to access a document management contract."
28
+ }
29
+ ];
30
+ /**
31
+ * The REST routes for document management.
32
+ * @param baseRouteName Prefix to prepend to the paths.
33
+ * @param componentName The name of the component to use in the routes stored in the ComponentFactory.
34
+ * @returns The generated routes.
35
+ */
36
+ function generateRestRoutesDocumentManagement(baseRouteName, componentName) {
37
+ const documentManagementSetRoute = {
38
+ operationId: "DocumentManagementSet",
39
+ summary: "Store a document in an auditable item graph vertex and add its content to blob storage.",
40
+ tag: tagsDocumentManagement[0].name,
41
+ method: "POST",
42
+ path: `${baseRouteName}/:auditableItemGraphId`,
43
+ handler: async (httpRequestContext, request) => documentManagementSet(httpRequestContext, componentName, request),
44
+ requestType: {
45
+ type: "IDocumentManagementSetRequest",
46
+ examples: [
47
+ {
48
+ id: "DocumentManagementSetRequestExample",
49
+ request: {
50
+ pathParams: {
51
+ auditableItemGraphId: "aig:123456"
52
+ },
53
+ body: {
54
+ documentId: "2721000",
55
+ documentIdFormat: "bol",
56
+ documentCode: standardsUnece.UneceDocumentCodes.BillOfLading,
57
+ blob: "SGVsbG8gV29ybGQ=",
58
+ annotationObject: {
59
+ "@context": "https://schema.org",
60
+ "@type": "DigitalDocument",
61
+ name: "myfile.pdf"
62
+ },
63
+ createAttestation: true
64
+ }
65
+ }
66
+ }
67
+ ]
68
+ },
69
+ responseType: [
70
+ {
71
+ type: "ICreatedResponse",
72
+ examples: [
73
+ {
74
+ id: "DocumentManagementSetResponseExample",
75
+ response: {
76
+ statusCode: web.HttpStatusCode.created,
77
+ headers: {
78
+ [web.HeaderTypes.Location]: "documents:123456:705:2721000"
79
+ }
80
+ }
81
+ }
82
+ ]
83
+ }
84
+ ]
85
+ };
86
+ const documentManagementGetRoute = {
87
+ operationId: "DocumentManagementGet",
88
+ summary: "Get the data for a document from document management",
89
+ tag: tagsDocumentManagement[0].name,
90
+ method: "GET",
91
+ path: `${baseRouteName}/:auditableItemGraphId/:documentId`,
92
+ handler: async (httpRequestContext, request) => documentManagementGet(httpRequestContext, componentName, request),
93
+ requestType: {
94
+ type: "IDocumentManagementGetRequest",
95
+ examples: [
96
+ {
97
+ id: "DocumentManagementGetRequestExample",
98
+ request: {
99
+ pathParams: {
100
+ auditableItemGraphId: "aig:1234",
101
+ documentId: "documents:123456:705:2721000"
102
+ }
103
+ }
104
+ }
105
+ ]
106
+ },
107
+ responseType: [
108
+ {
109
+ type: "IDocumentManagementGetResponse",
110
+ examples: [
111
+ {
112
+ id: "DocumentManagementGetResponseExample",
113
+ response: {
114
+ body: {
115
+ "@context": [
116
+ documentManagementModels.DocumentTypes.ContextRoot,
117
+ documentManagementModels.DocumentTypes.ContextRootCommon,
118
+ standardsSchemaOrg.SchemaOrgTypes.ContextRoot
119
+ ],
120
+ type: documentManagementModels.DocumentTypes.Document,
121
+ id: "documents:705:2721000:rev-0",
122
+ documentId: "2721000",
123
+ documentIdFormat: "bol",
124
+ documentCode: standardsUnece.UneceDocumentCodes.BillOfLading,
125
+ documentRevision: 0,
126
+ blobStorageId: "blob-memory:c57d94b088f4c6d2cb32ded014813d0c786aa00134c8ee22f84b1e2545602a70",
127
+ blobHash: "sha256:123456",
128
+ dateCreated: "2024-01-01T00:00:00Z",
129
+ annotationObject: {
130
+ "@context": "https://schema.org",
131
+ "@type": "DigitalDocument",
132
+ name: "myfile.pdf"
133
+ }
134
+ }
135
+ }
136
+ }
137
+ ]
138
+ },
139
+ {
140
+ type: "IDocumentManagementGetResponse",
141
+ mimeType: web.MimeTypes.JsonLd,
142
+ examples: [
143
+ {
144
+ id: "DocumentManagementGetResponseExample",
145
+ response: {
146
+ body: {
147
+ "@context": [
148
+ documentManagementModels.DocumentTypes.ContextRoot,
149
+ documentManagementModels.DocumentTypes.ContextRootCommon,
150
+ standardsSchemaOrg.SchemaOrgTypes.ContextRoot
151
+ ],
152
+ type: documentManagementModels.DocumentTypes.Document,
153
+ id: "documents:705:2721000:rev-0",
154
+ documentId: "2721000",
155
+ documentIdFormat: "bol",
156
+ documentCode: standardsUnece.UneceDocumentCodes.BillOfLading,
157
+ documentRevision: 0,
158
+ blobStorageId: "blob-memory:c57d94b088f4c6d2cb32ded014813d0c786aa00134c8ee22f84b1e2545602a70",
159
+ blobHash: "sha256:123456",
160
+ dateCreated: "2024-01-01T00:00:00Z",
161
+ annotationObject: {
162
+ "@context": "https://schema.org",
163
+ "@type": "DigitalDocument",
164
+ name: "myfile.pdf"
165
+ }
166
+ }
167
+ }
168
+ }
169
+ ]
170
+ },
171
+ {
172
+ type: "INotFoundResponse"
173
+ }
174
+ ]
175
+ };
176
+ const documentManagementRemoveRoute = {
177
+ operationId: "DocumentManagementRemove",
178
+ summary: "Remove an document from an auditable item graph vertex",
179
+ tag: tagsDocumentManagement[0].name,
180
+ method: "DELETE",
181
+ path: `${baseRouteName}/:auditableItemGraphId/:documentId`,
182
+ handler: async (httpRequestContext, request) => documentManagementRemove(httpRequestContext, componentName, request),
183
+ requestType: {
184
+ type: "IDocumentManagementRemoveRequest",
185
+ examples: [
186
+ {
187
+ id: "DocumentManagementRemoveRequestExample",
188
+ request: {
189
+ pathParams: {
190
+ auditableItemGraphId: "aig:1234",
191
+ documentId: "documents:123456:705:2721000"
192
+ }
193
+ }
194
+ }
195
+ ]
196
+ },
197
+ responseType: [
198
+ {
199
+ type: "INoContentResponse"
200
+ },
201
+ {
202
+ type: "INotFoundResponse"
203
+ }
204
+ ]
205
+ };
206
+ const documentManagementQueryRoute = {
207
+ operationId: "DocumentManagementQuery",
208
+ summary: "Query the items from an auditable item graph vertex",
209
+ tag: tagsDocumentManagement[0].name,
210
+ method: "GET",
211
+ path: `${baseRouteName}/:auditableItemGraphId`,
212
+ handler: async (httpRequestContext, request) => documentManagementQuery(httpRequestContext, componentName, request),
213
+ requestType: {
214
+ type: "IDocumentManagementQueryRequest",
215
+ examples: [
216
+ {
217
+ id: "DocumentManagementQueryRequestExample",
218
+ request: {
219
+ pathParams: {
220
+ auditableItemGraphId: "aig:123456"
221
+ }
222
+ }
223
+ }
224
+ ]
225
+ },
226
+ responseType: [
227
+ {
228
+ type: "IDocumentManagementQueryResponse",
229
+ examples: [
230
+ {
231
+ id: "DocumentManagementQueryResponseExample",
232
+ response: {
233
+ body: {
234
+ "@context": [documentManagementModels.DocumentTypes.ContextRoot, documentManagementModels.DocumentTypes.ContextRootCommon],
235
+ type: documentManagementModels.DocumentTypes.DocumentList,
236
+ documents: [
237
+ {
238
+ "@context": [
239
+ documentManagementModels.DocumentTypes.ContextRoot,
240
+ documentManagementModels.DocumentTypes.ContextRootCommon,
241
+ standardsSchemaOrg.SchemaOrgTypes.ContextRoot
242
+ ],
243
+ type: documentManagementModels.DocumentTypes.Document,
244
+ id: "documents:705:2721000:rev-0",
245
+ documentId: "2721000",
246
+ documentIdFormat: "bol",
247
+ documentCode: standardsUnece.UneceDocumentCodes.BillOfLading,
248
+ documentRevision: 0,
249
+ blobStorageId: "blob-memory:c57d94b088f4c6d2cb32ded014813d0c786aa00134c8ee22f84b1e2545602a70",
250
+ blobHash: "sha256:123456",
251
+ dateCreated: "2024-01-01T00:00:00Z",
252
+ annotationObject: {
253
+ "@context": "https://schema.org",
254
+ "@type": "DigitalDocument",
255
+ name: "myfile.pdf"
256
+ }
257
+ }
258
+ ]
259
+ }
260
+ }
261
+ }
262
+ ]
263
+ },
264
+ {
265
+ type: "IDocumentManagementQueryResponse",
266
+ mimeType: web.MimeTypes.JsonLd,
267
+ examples: [
268
+ {
269
+ id: "DocumentManagementListResponseJsonLdExample",
270
+ response: {
271
+ body: {
272
+ "@context": [documentManagementModels.DocumentTypes.ContextRoot, documentManagementModels.DocumentTypes.ContextRootCommon],
273
+ type: documentManagementModels.DocumentTypes.DocumentList,
274
+ documents: [
275
+ {
276
+ "@context": [
277
+ documentManagementModels.DocumentTypes.ContextRoot,
278
+ documentManagementModels.DocumentTypes.ContextRootCommon,
279
+ standardsSchemaOrg.SchemaOrgTypes.ContextRoot
280
+ ],
281
+ type: documentManagementModels.DocumentTypes.Document,
282
+ id: "documents:705:2721000:rev-0",
283
+ documentId: "2721000",
284
+ documentIdFormat: "bol",
285
+ documentCode: standardsUnece.UneceDocumentCodes.BillOfLading,
286
+ documentRevision: 0,
287
+ blobStorageId: "blob-memory:c57d94b088f4c6d2cb32ded014813d0c786aa00134c8ee22f84b1e2545602a70",
288
+ blobHash: "sha256:123456",
289
+ dateCreated: "2024-01-01T00:00:00Z",
290
+ annotationObject: {
291
+ "@context": "https://schema.org",
292
+ "@type": "DigitalDocument",
293
+ name: "myfile.pdf"
294
+ }
295
+ }
296
+ ]
297
+ }
298
+ }
299
+ }
300
+ ]
301
+ }
302
+ ]
303
+ };
304
+ return [
305
+ documentManagementSetRoute,
306
+ documentManagementGetRoute,
307
+ documentManagementRemoveRoute,
308
+ documentManagementQueryRoute
309
+ ];
310
+ }
311
+ /**
312
+ * Set a document in to an auditable item graph vertex.
313
+ * @param httpRequestContext The request context for the API.
314
+ * @param componentName The name of the component to use in the routes.
315
+ * @param request The request.
316
+ * @returns The response object with additional http response properties.
317
+ */
318
+ async function documentManagementSet(httpRequestContext, componentName, request) {
319
+ core.Guards.object(ROUTES_SOURCE, "request", request);
320
+ core.Guards.object(ROUTES_SOURCE, "request.pathParams", request.pathParams);
321
+ core.Guards.stringValue(ROUTES_SOURCE, "request.pathParams.auditableItemGraphId", request.pathParams.auditableItemGraphId);
322
+ core.Guards.object(ROUTES_SOURCE, "request.body", request.body);
323
+ core.Guards.stringBase64(ROUTES_SOURCE, "request.body.blob", request.body.blob);
324
+ const component = core.ComponentFactory.get(componentName);
325
+ const id = await component.set(request.pathParams.auditableItemGraphId, request.body.documentId, request.body.documentIdFormat, request.body.documentCode, core.Converter.base64ToBytes(request.body.blob), request.body.annotationObject, request.body.createAttestation, httpRequestContext.userIdentity, httpRequestContext.nodeIdentity);
326
+ return {
327
+ statusCode: web.HttpStatusCode.created,
328
+ headers: {
329
+ location: id
330
+ }
331
+ };
332
+ }
333
+ /**
334
+ * Get the document from the auditable item graph vertex.
335
+ * @param httpRequestContext The request context for the API.
336
+ * @param componentName The name of the component to use in the routes.
337
+ * @param request The request.
338
+ * @returns The response object with additional http response properties.
339
+ */
340
+ async function documentManagementGet(httpRequestContext, componentName, request) {
341
+ core.Guards.object(ROUTES_SOURCE, "request", request);
342
+ core.Guards.object(ROUTES_SOURCE, "request.pathParams", request.pathParams);
343
+ core.Guards.stringValue(ROUTES_SOURCE, "request.pathParams.auditableItemGraphId", request.pathParams.auditableItemGraphId);
344
+ core.Guards.stringValue(ROUTES_SOURCE, "request.pathParams.documentId", request.pathParams.documentId);
345
+ const mimeType = request.headers?.[web.HeaderTypes.Accept] === web.MimeTypes.JsonLd ? "jsonld" : "json";
346
+ const component = core.ComponentFactory.get(componentName);
347
+ const result = await component.get(request.pathParams.auditableItemGraphId, request.pathParams.documentId, {
348
+ includeBlobStorageMetadata: core.Coerce.boolean(request.query?.includeBlobStorageMetadata),
349
+ includeBlobStorageData: core.Coerce.boolean(request.query?.includeBlobStorageData),
350
+ includeAttestation: core.Coerce.boolean(request.query?.includeAttestation),
351
+ includeRemoved: core.Coerce.boolean(request.query?.includeRemoved),
352
+ maxRevisionCount: core.Coerce.integer(request.query?.maxRevisionCount)
353
+ }, request.query?.revisionCursor, httpRequestContext.userIdentity, httpRequestContext.nodeIdentity);
354
+ return {
355
+ headers: {
356
+ [web.HeaderTypes.ContentType]: mimeType === "json" ? web.MimeTypes.Json : web.MimeTypes.JsonLd
357
+ },
358
+ body: result
359
+ };
360
+ }
361
+ /**
362
+ * Remove the document from the auditable item graph vertex.
363
+ * @param httpRequestContext The request context for the API.
364
+ * @param componentName The name of the component to use in the routes.
365
+ * @param request The request.
366
+ * @returns The response object with additional http response properties.
367
+ */
368
+ async function documentManagementRemove(httpRequestContext, componentName, request) {
369
+ core.Guards.object(ROUTES_SOURCE, "request", request);
370
+ core.Guards.object(ROUTES_SOURCE, "request.pathParams", request.pathParams);
371
+ core.Guards.stringValue(ROUTES_SOURCE, "request.pathParams.auditableItemGraphId", request.pathParams.auditableItemGraphId);
372
+ core.Guards.stringValue(ROUTES_SOURCE, "request.pathParams.documentId", request.pathParams.documentId);
373
+ const component = core.ComponentFactory.get(componentName);
374
+ await component.remove(request.pathParams.auditableItemGraphId, request.pathParams.documentId, {
375
+ removeAllRevisions: request.query?.removeAllRevisions
376
+ }, httpRequestContext.userIdentity, httpRequestContext.nodeIdentity);
377
+ return {
378
+ statusCode: web.HttpStatusCode.noContent
379
+ };
380
+ }
381
+ /**
382
+ * Query the documents from an auditable item graph vertex.
383
+ * @param httpRequestContext The request context for the API.
384
+ * @param componentName The name of the component to use in the routes.
385
+ * @param request The request.
386
+ * @returns The response object with additional http response properties.
387
+ */
388
+ async function documentManagementQuery(httpRequestContext, componentName, request) {
389
+ core.Guards.object(ROUTES_SOURCE, "request", request);
390
+ core.Guards.object(ROUTES_SOURCE, "request.pathParams", request.pathParams);
391
+ core.Guards.stringValue(ROUTES_SOURCE, "request.pathParams.auditableItemGraphId", request.pathParams.auditableItemGraphId);
392
+ const mimeType = request.headers?.[web.HeaderTypes.Accept] === web.MimeTypes.JsonLd ? "jsonld" : "json";
393
+ const component = core.ComponentFactory.get(componentName);
394
+ const result = await component.query(request.pathParams.auditableItemGraphId, apiModels.HttpParameterHelper.arrayFromString(request.query?.documentCodes), {
395
+ includeRemoved: core.Coerce.boolean(request.query?.includeRemoved),
396
+ includeMostRecentRevisions: core.Coerce.boolean(request.query?.includeMostRecentRevisions)
397
+ }, request.query?.cursor, httpRequestContext.userIdentity, httpRequestContext.nodeIdentity);
398
+ return {
399
+ headers: {
400
+ [web.HeaderTypes.ContentType]: mimeType === "json" ? web.MimeTypes.Json : web.MimeTypes.JsonLd
401
+ },
402
+ body: result
403
+ };
404
+ }
405
+
406
+ /**
407
+ * Service for performing document management operations.
408
+ */
409
+ class DocumentManagementService {
410
+ /**
411
+ * The namespace supported by the document management service.
412
+ */
413
+ static NAMESPACE = "documents";
414
+ /**
415
+ * Default Page Size for cursor.
416
+ * @internal
417
+ */
418
+ static _DEFAULT_PAGE_SIZE = 20;
419
+ /**
420
+ * Runtime name for the class.
421
+ */
422
+ CLASS_NAME = "DocumentManagementService";
423
+ /**
424
+ * The component for the auditable item graph.
425
+ * @internal
426
+ */
427
+ _auditableItemGraphComponent;
428
+ /**
429
+ * The connector for the blob component.
430
+ * @internal
431
+ */
432
+ _blobStorageComponent;
433
+ /**
434
+ * The connector for the attestation.
435
+ * @internal
436
+ */
437
+ _attestationComponent;
438
+ /**
439
+ * Create a new instance of DocumentManagementService.
440
+ * @param options The options for the service.
441
+ */
442
+ constructor(options) {
443
+ this._auditableItemGraphComponent = core.ComponentFactory.get(options?.auditableItemGraphComponentType ?? "auditable-item-graph");
444
+ this._blobStorageComponent = core.ComponentFactory.get(options?.blobStorageComponentType ?? "blob-storage");
445
+ this._attestationComponent = core.ComponentFactory.get(options?.attestationComponentType ?? "attestation");
446
+ standardsSchemaOrg.SchemaOrgDataTypes.registerRedirects();
447
+ }
448
+ /**
449
+ * Store a document in an auditable item graph vertex and add its content to blob storage.
450
+ * If the document id already exists and the blob data is different a new revision will be created.
451
+ * For any other changes the current revision will be updated.
452
+ * @param auditableItemGraphId The auditable item graph vertex id to create the document on.
453
+ * @param documentId The document id to create.
454
+ * @param documentIdFormat The format of the document identifier.
455
+ * @param documentCode The code for the document type.
456
+ * @param blob The data to create the document.
457
+ * @param annotationObject Additional information to associate with the document.
458
+ * @param createAttestation Flag to create an attestation for the document, defaults to false.
459
+ * @param userIdentity The identity to perform the auditable item graph operation with.
460
+ * @param nodeIdentity The node identity to use for vault operations.
461
+ * @returns The identifier for the document which includes the auditable item graph identifier.
462
+ */
463
+ async set(auditableItemGraphId, documentId, documentIdFormat, documentCode, blob, annotationObject, createAttestation, userIdentity, nodeIdentity) {
464
+ core.Guards.stringValue(this.CLASS_NAME, "auditableItemGraphId", auditableItemGraphId);
465
+ core.Guards.stringValue(this.CLASS_NAME, "documentId", documentId);
466
+ core.Guards.arrayOneOf(this.CLASS_NAME, "documentCode", documentCode, Object.values(standardsUnece.UneceDocumentCodes));
467
+ core.Guards.uint8Array(this.CLASS_NAME, "blob", blob);
468
+ try {
469
+ const vertex = await this._auditableItemGraphComponent.get(auditableItemGraphId);
470
+ vertex.resources = vertex.resources ?? [];
471
+ // Get all the docs from the AIG vertex
472
+ const vertexDocs = this.filterDocumentsFromVertex(vertex);
473
+ // Reduce the list to those with a matching id and code
474
+ const matchingDocIds = this.findMatchingDocs(vertexDocs, documentId, documentCode, true);
475
+ // Calculate the hash for the blob.
476
+ const blobHash = this.generateBlobHash(blob);
477
+ let documentRevision;
478
+ if (core.Is.arrayValue(matchingDocIds) && matchingDocIds[0].blobHash === blobHash) {
479
+ documentRevision = matchingDocIds[0].documentRevision;
480
+ // If there is already a doc with the matching blob hash no need to create a new revision
481
+ // instead we just update the annotation object if it has changed.
482
+ if (!core.ObjectHelper.equal(matchingDocIds[0].annotationObject, annotationObject, false)) {
483
+ matchingDocIds[0].dateModified = new Date().toISOString();
484
+ matchingDocIds[0].annotationObject = annotationObject;
485
+ await this._auditableItemGraphComponent.update(vertex, userIdentity, nodeIdentity);
486
+ }
487
+ return matchingDocIds[0].id;
488
+ }
489
+ // Nothing matches the current blob hash so upload it to blob storage
490
+ const blobStorageId = await this._blobStorageComponent.create(core.Converter.bytesToBase64(blob), undefined, undefined, undefined, undefined, userIdentity, nodeIdentity);
491
+ documentRevision = matchingDocIds.length;
492
+ // We are creating a new document, if there is already docs with the same id and code we use the list length
493
+ // to determine the next revision number.
494
+ const document = {
495
+ "@context": [
496
+ documentManagementModels.DocumentTypes.ContextRoot,
497
+ documentManagementModels.DocumentTypes.ContextRootCommon,
498
+ standardsSchemaOrg.SchemaOrgTypes.ContextRoot
499
+ ],
500
+ type: documentManagementModels.DocumentTypes.Document,
501
+ id: this.createIdentifier(documentCode, documentId, documentRevision),
502
+ documentId,
503
+ documentIdFormat,
504
+ documentCode,
505
+ documentRevision,
506
+ blobStorageId,
507
+ blobHash,
508
+ dateCreated: new Date(Date.now()).toISOString()
509
+ };
510
+ // If the attestation flag is set then create it
511
+ if (createAttestation ?? false) {
512
+ document.attestationId = await this._attestationComponent.create(document, undefined, userIdentity, nodeIdentity);
513
+ }
514
+ // We assign the annotation object after the attestation was created
515
+ // as we don't want to include it in the attestation
516
+ document.annotationObject = annotationObject;
517
+ // Add the new revision in to the AIG
518
+ vertex.resources.push({
519
+ "@context": auditableItemGraphModels.AuditableItemGraphTypes.ContextRoot,
520
+ type: auditableItemGraphModels.AuditableItemGraphTypes.Resource,
521
+ resourceObject: document
522
+ });
523
+ await this._auditableItemGraphComponent.update(vertex, userIdentity, nodeIdentity);
524
+ return document.id;
525
+ }
526
+ catch (error) {
527
+ if (core.BaseError.someErrorName(error, "NotFoundError")) {
528
+ throw error;
529
+ }
530
+ throw new core.GeneralError(this.CLASS_NAME, "setFailed", undefined, error);
531
+ }
532
+ }
533
+ /**
534
+ * Get a specific document from an auditable item graph vertex.
535
+ * @param auditableItemGraphId The auditable item graph vertex id to get the document from.
536
+ * @param identifier The identifier of the document to get.
537
+ * @param options Additional options for the get operation.
538
+ * @param options.includeBlobStorageMetadata Flag to include the blob storage metadata for the document, defaults to false.
539
+ * @param options.includeBlobStorageData Flag to include the blob storage data for the document, defaults to false.
540
+ * @param options.includeAttestation Flag to include the attestation information for the document, defaults to false.
541
+ * @param options.includeRemoved Flag to include deleted documents, defaults to false.
542
+ * @param options.maxRevisionCount Max number of revisions to return, defaults to 0.
543
+ * @param revisionCursor The cursor to get the next chunk of revisions.
544
+ * @param userIdentity The identity to perform the auditable item graph operation with.
545
+ * @param nodeIdentity The node identity to use for vault operations.
546
+ * @returns The documents and revisions if requested, ordered by revision descending, cursor is set if there are more document revisions.
547
+ */
548
+ async get(auditableItemGraphId, identifier, options, revisionCursor, userIdentity, nodeIdentity) {
549
+ core.Urn.guard(this.CLASS_NAME, "auditableItemGraphId", auditableItemGraphId);
550
+ core.Urn.guard(this.CLASS_NAME, "identifier", identifier);
551
+ try {
552
+ const includeBlobStorageMetadata = options?.includeBlobStorageMetadata ?? false;
553
+ const includeBlobStorageData = options?.includeBlobStorageData ?? false;
554
+ const includeAttestation = options?.includeAttestation ?? false;
555
+ const includeRemoved = options?.includeRemoved ?? false;
556
+ const revCursor = Math.max(core.Coerce.integer(revisionCursor) ?? 0, 0);
557
+ const maxRevisionCount = Math.max(core.Coerce.integer(options?.maxRevisionCount) ?? 0);
558
+ const documentIdParts = this.parseDocumentId(identifier);
559
+ const vertex = await this._auditableItemGraphComponent.get(auditableItemGraphId);
560
+ // Get all the docs from the AIG vertex
561
+ const vertexDocs = this.filterDocumentsFromVertex(vertex);
562
+ // Reduce the list to those with a matching id and code
563
+ const matchingDocIds = this.findMatchingDocs(vertexDocs, documentIdParts.documentId, documentIdParts.documentCode, includeRemoved);
564
+ // Populate the document and revisions with the options set
565
+ const document = await this.getDocumentAndRevisions(matchingDocIds, identifier, {
566
+ includeBlobStorageMetadata,
567
+ includeBlobStorageData,
568
+ includeAttestation,
569
+ includeRemoved,
570
+ maxRevisionCount
571
+ }, revCursor, userIdentity, nodeIdentity);
572
+ return dataJsonLd.JsonLdProcessor.compact(document, document["@context"]);
573
+ }
574
+ catch (error) {
575
+ if (core.BaseError.someErrorName(error, "NotFoundError")) {
576
+ throw error;
577
+ }
578
+ throw new core.GeneralError(this.CLASS_NAME, "getFailed", undefined, error);
579
+ }
580
+ }
581
+ /**
582
+ * Remove a specific document from an auditable item graph vertex.
583
+ * The documents dateDeleted will be set, but can still be queried with the includeRemoved flag.
584
+ * @param auditableItemGraphId The auditable item graph vertex id to remove the document from.
585
+ * @param identifier The identifier of the document to remove.
586
+ * @param options Additional options for the remove operation.
587
+ * @param options.removeAllRevisions Flag to remove all revisions of the document, defaults to false.
588
+ * @param userIdentity The identity to perform the auditable item graph operation with.
589
+ * @param nodeIdentity The node identity to use for vault operations.
590
+ * @returns Nothing.
591
+ */
592
+ async remove(auditableItemGraphId, identifier, options, userIdentity, nodeIdentity) {
593
+ core.Urn.guard(this.CLASS_NAME, "auditableItemGraphId", auditableItemGraphId);
594
+ core.Urn.guard(this.CLASS_NAME, "identifier", identifier);
595
+ try {
596
+ const documentIdParts = this.parseDocumentId(identifier);
597
+ const vertex = await this._auditableItemGraphComponent.get(auditableItemGraphId);
598
+ // Get all the docs from the AIG vertex
599
+ const vertexDocs = this.filterDocumentsFromVertex(vertex);
600
+ // Reduce the list to those with a matching id and code
601
+ const matchingDocIds = this.findMatchingDocs(vertexDocs, documentIdParts.documentId, documentIdParts.documentCode, false);
602
+ const removeAllRevisions = options?.removeAllRevisions ?? false;
603
+ const now = Date.now();
604
+ if (removeAllRevisions) {
605
+ for (const doc of matchingDocIds) {
606
+ doc.dateDeleted = new Date(now).toISOString();
607
+ }
608
+ }
609
+ else {
610
+ const matchingRevision = matchingDocIds.find(d => d.documentRevision === documentIdParts.documentRevision);
611
+ if (matchingRevision) {
612
+ matchingRevision.dateDeleted = new Date(now).toISOString();
613
+ }
614
+ else {
615
+ throw new core.NotFoundError(this.CLASS_NAME, "documentRevisionNotFound", identifier);
616
+ }
617
+ }
618
+ await this._auditableItemGraphComponent.update(vertex, userIdentity, nodeIdentity);
619
+ }
620
+ catch (error) {
621
+ if (core.BaseError.someErrorName(error, "NotFoundError")) {
622
+ throw error;
623
+ }
624
+ throw new core.GeneralError(this.CLASS_NAME, "removeFailed", undefined, error);
625
+ }
626
+ }
627
+ /**
628
+ * Query an auditable item graph vertex for documents.
629
+ * @param auditableItemGraphId The auditable item graph vertex to get the documents from.
630
+ * @param documentCodes The document codes to query for, if undefined gets all document codes.
631
+ * @param options Additional options for the query operation.
632
+ * @param options.includeMostRecentRevisions Include the most recent 5 revisions, use the individual get to retrieve more.
633
+ * @param options.includeRemoved Flag to include deleted documents, defaults to false.
634
+ * @param cursor The cursor to get the next chunk of documents.
635
+ * @param userIdentity The identity to perform the auditable item graph operation with.
636
+ * @param nodeIdentity The node identity to use for vault operations.
637
+ * @returns The most recent revisions of each document, cursor is set if there are more documents.
638
+ */
639
+ async query(auditableItemGraphId, documentCodes, options, cursor, userIdentity, nodeIdentity) {
640
+ core.Urn.guard(this.CLASS_NAME, "auditableItemGraphId", auditableItemGraphId);
641
+ try {
642
+ const includeRemoved = options?.includeRemoved ?? false;
643
+ const includeMostRecentRevisions = options?.includeMostRecentRevisions ?? false;
644
+ const docCursor = Math.max(core.Coerce.integer(cursor) ?? 0, 0);
645
+ const vertex = await this._auditableItemGraphComponent.get(auditableItemGraphId);
646
+ // Get all the docs from the AIG vertex
647
+ const vertexDocs = this.filterDocumentsFromVertex(vertex);
648
+ let matchingDocIds = vertexDocs;
649
+ if (core.Is.arrayValue(documentCodes)) {
650
+ matchingDocIds = vertexDocs.filter(d => documentCodes.includes(d.documentCode));
651
+ }
652
+ const documentIdGroups = {};
653
+ let docGroupIds = [];
654
+ for (const doc of matchingDocIds) {
655
+ const docId = `${doc.documentId}:${doc.documentCode}`;
656
+ if (!docGroupIds.includes(docId)) {
657
+ docGroupIds.push(docId);
658
+ }
659
+ documentIdGroups[docId] ??= [];
660
+ documentIdGroups[docId].push(doc);
661
+ }
662
+ let nextDocCursor;
663
+ if (docGroupIds.length > docCursor + DocumentManagementService._DEFAULT_PAGE_SIZE) {
664
+ nextDocCursor = (docCursor + DocumentManagementService._DEFAULT_PAGE_SIZE).toString();
665
+ }
666
+ docGroupIds = docGroupIds.slice(docCursor, docCursor + DocumentManagementService._DEFAULT_PAGE_SIZE);
667
+ const finalDocs = [];
668
+ for (const docId of docGroupIds) {
669
+ finalDocs.push(await this.getDocumentAndRevisions(documentIdGroups[docId], docId, {
670
+ includeAttestation: false,
671
+ includeBlobStorageData: false,
672
+ includeBlobStorageMetadata: false,
673
+ includeRemoved,
674
+ maxRevisionCount: includeMostRecentRevisions ? 5 : 0
675
+ }, 0, userIdentity, nodeIdentity));
676
+ }
677
+ const docList = {
678
+ "@context": [
679
+ documentManagementModels.DocumentTypes.ContextRoot,
680
+ documentManagementModels.DocumentTypes.ContextRootCommon,
681
+ standardsSchemaOrg.SchemaOrgTypes.ContextRoot
682
+ ],
683
+ type: documentManagementModels.DocumentTypes.DocumentList,
684
+ documents: finalDocs,
685
+ cursor: nextDocCursor
686
+ };
687
+ return dataJsonLd.JsonLdProcessor.compact(docList, docList["@context"]);
688
+ }
689
+ catch (error) {
690
+ if (core.BaseError.someErrorName(error, "NotFoundError")) {
691
+ throw error;
692
+ }
693
+ throw new core.GeneralError(this.CLASS_NAME, "queryFailed", undefined, error);
694
+ }
695
+ }
696
+ /**
697
+ * Encode the document id.
698
+ * @param documentId The document identifier.
699
+ * @returns The encoded identifier.
700
+ * @internal
701
+ */
702
+ encodeDocumentIdentifier(documentId, documentRevision) {
703
+ return `${documentId}:rev-${documentRevision}`;
704
+ }
705
+ /**
706
+ * Decode the document id.
707
+ * @param documentId The document identifier.
708
+ * @returns The decoded identifier.
709
+ * @internal
710
+ */
711
+ decodeDocumentIdentifier(documentId) {
712
+ const parts = documentId.split(":");
713
+ const lastPart = parts[parts.length - 1];
714
+ let revision;
715
+ if (lastPart.startsWith("rev-")) {
716
+ revision = Number.parseInt(lastPart.slice(4), 10);
717
+ parts.pop();
718
+ }
719
+ return { documentId: parts.join(":"), documentRevision: revision };
720
+ }
721
+ /**
722
+ * Create a full identifier for a document.
723
+ * @param documentCode The document code.
724
+ * @param documentId The document identifier.
725
+ * @param documentRevision The document revision.
726
+ * @returns The full identifier.
727
+ * @internal
728
+ */
729
+ createIdentifier(documentCode, documentId, documentRevision) {
730
+ const docCode = this.parseDocumentCode(documentCode);
731
+ return `documents:${docCode}:${this.encodeDocumentIdentifier(documentId, documentRevision)}`;
732
+ }
733
+ /**
734
+ * Parse the document identifier from the full identifier.
735
+ * @param identifier The full identifier to parse.
736
+ * @returns The document identifier.
737
+ * @internal
738
+ */
739
+ parseDocumentId(identifier) {
740
+ const urn = core.Urn.fromValidString(identifier);
741
+ const remainingParts = urn.namespaceSpecificParts();
742
+ if (remainingParts.length < 2) {
743
+ throw new core.GeneralError(this.CLASS_NAME, "invalidDocumentId", { identifier });
744
+ }
745
+ const documentCode = `unece:DocumentCodeList#${remainingParts[0]}`;
746
+ const { documentId, documentRevision } = this.decodeDocumentIdentifier(urn.namespaceSpecific(1));
747
+ return { documentCode, documentId, documentRevision };
748
+ }
749
+ /**
750
+ * Parse the document code from the full identifier.
751
+ * @param documentCode The document code to parse.
752
+ * @returns The document code.
753
+ * @internal
754
+ */
755
+ parseDocumentCode(documentCode) {
756
+ // Document codes are in the format unece:DocumentCodeList#1, so we need to split the string to get the code.
757
+ const documentCodeParts = documentCode.split("#");
758
+ if (documentCodeParts.length !== 2) {
759
+ throw new core.GeneralError(this.CLASS_NAME, "invalidDocumentCode", { documentCode });
760
+ }
761
+ const docCode = Number.parseInt(documentCodeParts[1], 10);
762
+ if (!core.Is.number(docCode)) {
763
+ throw new core.GeneralError(this.CLASS_NAME, "invalidDocumentCode", { documentCode });
764
+ }
765
+ return docCode;
766
+ }
767
+ /**
768
+ * Get the documents from a vertex.
769
+ * @param vertex The vertex to get the documents from.
770
+ * @returns The documents.
771
+ * @internal
772
+ */
773
+ filterDocumentsFromVertex(vertex) {
774
+ return (vertex.resources
775
+ ?.filter(resource => core.ObjectHelper.extractProperty(resource.resourceObject, ["@type", "type"], false) ===
776
+ documentManagementModels.DocumentTypes.Document)
777
+ .map(resource => resource.resourceObject) ?? []);
778
+ }
779
+ /**
780
+ * Find matching documents in the list of existing documents.
781
+ * @param documents The documents to search.
782
+ * @param documentId The document id.
783
+ * @param documentCode The document code.
784
+ * @param includeRemoved Include deleted documents.
785
+ * @returns The matching documents.
786
+ * @internal
787
+ */
788
+ findMatchingDocs(documents, documentId, documentCode, includeRemoved) {
789
+ return documents
790
+ .filter(d => d.documentId === documentId &&
791
+ d.documentCode === documentCode &&
792
+ (includeRemoved || core.Is.empty(d.dateDeleted)))
793
+ .sort((a, b) => b.documentRevision - a.documentRevision);
794
+ }
795
+ /**
796
+ * Generate a hash for the blob data.
797
+ * @param blob The blob data to hash.
798
+ * @returns The hash.
799
+ * @internal
800
+ */
801
+ generateBlobHash(blob) {
802
+ return `sha256:${core.Converter.bytesToBase64(crypto.Sha256.sum256(blob))}`;
803
+ }
804
+ /**
805
+ * Get the documents from the auditable item graph vertex.
806
+ * @param matchingDocIds The documents which match document type and id.
807
+ * @param identifier The full document identifier.
808
+ * @param options Additional options for the get operation.
809
+ * @param options.includeBlobStorageMetadata Flag to include the blob storage metadata for the document, defaults to false.
810
+ * @param options.includeBlobStorageData Flag to include the blob storage data for the document, defaults to false.
811
+ * @param options.includeAttestation Flag to include the attestation information for the document, defaults to false.
812
+ * @param options.includeRemoved Flag to include deleted documents, defaults to false.
813
+ * @param options.maxRevisionCount Max number of revisions to return, defaults to 0.
814
+ * @param revisionCursor The cursor to get the next chunk of revisions.
815
+ * @param userIdentity The identity to perform the auditable item graph operation with.
816
+ * @param nodeIdentity The node identity to use for vault operations.
817
+ * @returns The finalised list of documents.
818
+ * @internal
819
+ */
820
+ async getDocumentAndRevisions(matchingDocIds, identifier, options, revisionCursor, userIdentity, nodeIdentity) {
821
+ const document = matchingDocIds.shift();
822
+ if (core.Is.empty(document)) {
823
+ throw new core.NotFoundError(this.CLASS_NAME, "documentRevisionNotFound", identifier);
824
+ }
825
+ let revisions;
826
+ let nextRevisionCursor;
827
+ if (options.maxRevisionCount > 0) {
828
+ revisions = matchingDocIds.slice(revisionCursor, revisionCursor + options.maxRevisionCount);
829
+ nextRevisionCursor =
830
+ matchingDocIds.length > revisionCursor + options.maxRevisionCount
831
+ ? (revisionCursor + options.maxRevisionCount).toString()
832
+ : undefined;
833
+ }
834
+ if (options.includeBlobStorageMetadata || options.includeBlobStorageData) {
835
+ const blobEntry = await this._blobStorageComponent.get(document.blobStorageId, options.includeBlobStorageData, userIdentity, nodeIdentity);
836
+ document.blobStorageEntry = blobEntry;
837
+ document["@context"].push(blobStorageModels.BlobStorageTypes.ContextRoot);
838
+ }
839
+ if (options.includeAttestation && core.Is.stringValue(document.attestationId)) {
840
+ const attestationInformation = await this._attestationComponent.get(document.attestationId);
841
+ document.attestationInformation = attestationInformation;
842
+ document["@context"].push(attestationModels.AttestationTypes.ContextRoot);
843
+ }
844
+ document.revisions = core.Is.arrayValue(revisions) ? revisions : undefined;
845
+ document.revisionCursor = nextRevisionCursor;
846
+ return document;
847
+ }
848
+ }
849
+
850
+ const restEntryPoints = [
851
+ {
852
+ name: "documents",
853
+ defaultBaseRoute: "documents",
854
+ tags: tagsDocumentManagement,
855
+ generateRoutes: generateRestRoutesDocumentManagement
856
+ }
857
+ ];
858
+
859
+ exports.DocumentManagementService = DocumentManagementService;
860
+ exports.documentManagementGet = documentManagementGet;
861
+ exports.documentManagementQuery = documentManagementQuery;
862
+ exports.documentManagementRemove = documentManagementRemove;
863
+ exports.documentManagementSet = documentManagementSet;
864
+ exports.generateRestRoutesDocumentManagement = generateRestRoutesDocumentManagement;
865
+ exports.restEntryPoints = restEntryPoints;
866
+ exports.tagsDocumentManagement = tagsDocumentManagement;