@docbrasil/api-systemmanager 1.0.86 → 1.0.88

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 (57) hide show
  1. package/api/admin/doctypes.js +76 -76
  2. package/api/admin/document.js +332 -332
  3. package/api/admin/form.js +151 -151
  4. package/api/admin/index.js +46 -46
  5. package/api/admin/list.js +133 -133
  6. package/api/admin/message.js +194 -194
  7. package/api/admin/notification.js +233 -233
  8. package/api/admin/organization.js +124 -124
  9. package/api/admin/plugin.js +116 -116
  10. package/api/admin/policy.js +78 -78
  11. package/api/admin/processes.js +370 -370
  12. package/api/admin/task.js +125 -125
  13. package/api/admin/user.js +185 -185
  14. package/api/dispatch.js +101 -101
  15. package/api/general/geoLocation.js +88 -88
  16. package/api/general/index.js +22 -22
  17. package/api/login.js +267 -267
  18. package/api/session.js +85 -85
  19. package/api/user/datasource.js +144 -144
  20. package/api/user/document.js +731 -687
  21. package/api/user/index.js +39 -39
  22. package/api/user/notification.js +101 -101
  23. package/api/user/organization.js +230 -230
  24. package/api/user/process.js +191 -191
  25. package/api/user/register.js +205 -205
  26. package/api/user/task.js +201 -201
  27. package/api/user/task_available.js +135 -135
  28. package/api/user/user.js +287 -287
  29. package/api/utils/cypher.js +37 -37
  30. package/api/utils/promises.js +118 -118
  31. package/bundleRollup.js +158 -158
  32. package/dist/bundle.cjs +4876 -4832
  33. package/dist/bundle.mjs +1 -1
  34. package/doc/api.md +372 -666
  35. package/doc.md +653 -653
  36. package/helper/boom.js +487 -487
  37. package/helper/cryptojs.js +6067 -6067
  38. package/index.js +85 -85
  39. package/package-lock.json +4635 -4635
  40. package/package.json +68 -67
  41. package/readme.md +25 -25
  42. package/tests/admin/document.spec.js +45 -45
  43. package/tests/admin/form.spec.js +74 -74
  44. package/tests/admin/list.spec.js +86 -86
  45. package/tests/admin/message.js +92 -92
  46. package/tests/admin/notification.spec.js +174 -174
  47. package/tests/admin/pluginspec..js +71 -71
  48. package/tests/admin/policy.spec.js +71 -71
  49. package/tests/admin/processes.spec.js +119 -119
  50. package/tests/admin/users.spec.js +127 -127
  51. package/tests/documents.spec.js +164 -164
  52. package/tests/login.spec.js +91 -91
  53. package/tests/session.spec..js +58 -58
  54. package/tests/user/documents.js +164 -164
  55. package/tests/user/organization.js +122 -122
  56. package/tests/user/process.js +71 -71
  57. package/tests/user/user.js +88 -88
@@ -1,687 +1,731 @@
1
- import _ from 'lodash';
2
- import Boom from '@hapi/boom';
3
- import Joi from 'joi';
4
- import Moment from 'moment';
5
-
6
- /**
7
- * Class for documents, permission user
8
- * @class
9
- */
10
- class Documents {
11
-
12
- constructor(options) {
13
- Joi.assert(options, Joi.object().required());
14
- Joi.assert(options.parent, Joi.object().required());
15
-
16
- const self = this;
17
- self.parent = options.parent;
18
- self._client = self.parent.dispatch.getClient();
19
- }
20
-
21
- /**
22
- * @author Augusto Pissarra <abernardo.br@gmail.com>
23
- * @description Get the return data and check for errors
24
- * @param {object} retData Response HTTP
25
- * @return {*}
26
- * @private
27
- */
28
- _returnData(retData, def = {}) {
29
- if (retData.status !== 200) {
30
- throw Boom.badRequest(_.get(retData, 'message', 'No error message reported!'))
31
- } else {
32
- return _.get(retData, 'data', def);
33
- }
34
- }
35
-
36
- /**
37
- * @author CloudBrasil <abernardo.br@gmail.com>
38
- * @description Set header with new session
39
- * @param {string} session Session, token JWT
40
- * @return {object} header with new session
41
- * @private
42
- */
43
- _setHeader(session) {
44
- return {
45
- headers: {
46
- authorization: session,
47
- }
48
- };
49
- }
50
-
51
- /**
52
- * @author CloudBrasil <abernardo.br@gmail.com>
53
- * @description Create document with informed data
54
- * @param {object} params Object for add new document
55
- * @param {string} params.orgname Organization name
56
- * @param {string} params.areaId Doc area id (_id database)
57
- * @param {string} params.docId Document id (_id database)
58
- * @param {string} [params.documentDate=new\ Date()] Date of document
59
- * @param {string} params.filename File name
60
- * @param {string} params.type Mimetype of the document (image/png)
61
- * @param {string} params.name Doument name
62
- * @param {string} [params.content=''] Content of document
63
- * @param {string} [params.description=''] Description of document
64
- * @param {string} [params.category=''] Category of document
65
- * @param {array} [params.tags=[]] Tags of document
66
- * @param {string} params.docTypeId Document type id (_id database)
67
- * @param {boolean} [params.hasPhisicalStorage=false] Has Phisical Storage
68
- * @param {string} [params.boxId=''] Box ID
69
- * @param {string} [params.storageStatus=''] Storage status
70
- * @param {boolean} [params.ocrDocumentBackend=false] Ocr document backend
71
- * @param {number} params.bytes Size document in bytes
72
- * @param {object} [params.docAreaPermission={}] Permission to doc area
73
- * @param {object} [params.docTypeFieldsData={}] Fields data "extraField'
74
- * @param {string} params.signedUrl SIgned URL
75
- * @param {string} [params.urlType='S3'] URL type
76
- * @param {string} [params.addType='S3_SIGNED'] Add type
77
- * @return {{documentDate: *, docId: *, docAreaPermission: *, document: *, docTypeFieldsData: *, description: *, storageStatus: *, type: *, content: *, tags: *, addType: *, urlType: *, areaId: *, orgname: *, docTypeId: *, bytes: *, name: *, category: *, hasPhisicalStorage: *, signedUrl: *, ocrDocumentBackend: *, boxId: *}}
78
- * @private
79
- */
80
- _formatDocument(params) {
81
- try {
82
- return {
83
- orgname: _.get(params, 'orgname'),
84
- areaId: _.get(params, 'areaId'),
85
- docId: _.get(params, 'docId'),
86
- documentDate: _.get(params, 'documentDate', Moment().format()),
87
- document: _.get(params, 'document'),
88
- type: _.get(params, 'type'),
89
- name: _.get(params, 'name'),
90
- content: _.get(params, 'content', ''),
91
- description: _.get(params, 'description', ''),
92
- category: _.get(params, 'category', ''),
93
- tags: _.get(params, 'tags', []),
94
- docTypeId: _.get(params, 'docTypeId'),
95
- hasPhisicalStorage: _.get(params, 'hasPhisicalStorage', false),
96
- boxId: _.get(params, 'boxId', ''),
97
- storageStatus: _.get(params, 'storageStatus', ''),
98
- ocrDocumentBackend: _.get(params, 'ocrDocumentBackend', false),
99
- bytes: _.get(params, 'bytes'),
100
- docAreaPermission: _.get(params, 'docAreaPermission', {}),
101
- docTypeFields: _.get(params, 'docTypeFields', []), // {"extraId": userId},
102
- docTypeFieldsData: _.get(params, 'docTypeFieldsData', {}), // {"extraId": userId},
103
- signedUrl: _.get(params, 'signedUrl', ''),
104
- urlType: _.get(params, 'urlType', 'S3'),
105
- addType: _.get(params, 'addType', 'S3_SIGNED'),
106
- };
107
- } catch (ex) {
108
- throw ex;
109
- }
110
- }
111
-
112
- /**
113
- * @author CloudBrasil <abernardo.br@gmail.com>
114
- * @description Transform objtect query in query string
115
- * @param {object} searchQuery object wicth query
116
- * @return {string} Retutn string query
117
- * @private
118
- */
119
- _queryReducer(searchQuery) {
120
- return Object.keys(searchQuery).reduce((query, key, idx, sourceList) => {
121
- idx++;
122
-
123
- const data = key === 'ix'
124
- ? JSON.stringify(searchQuery[key])
125
- : searchQuery[key];
126
-
127
- const querySearch = sourceList.length === idx
128
- ? `${key}=${data}`
129
- : `${key}=${data}&`;
130
-
131
- query += querySearch;
132
- return query;
133
- }, '');
134
- }
135
-
136
- /**
137
- * @author CloudBrasil <abernardo.br@gmail.com>
138
- * @description Create new document
139
- * @param {object} params Object for add new document
140
- * @param {string} params.orgname Organization name
141
- * @param {string} params.areaId Doc area id (_id database)
142
- * @param {string} params.docId Document id (_id database)
143
- * @param {string} [params.documentDate=new Date()] Date of document
144
- * @param {string} params.document The path to the file. If S3, the key to S3, gotten after getting a signed URL
145
- * @param {string} params.filename File name
146
- * @param {string} params.type Mimetype of the document (image/png)
147
- * @param {string} params.name Document name
148
- * @param {string} [params.content=''] Content of document
149
- * @param {string} [params.description=''] Description of document
150
- * @param {string} [params.category=''] Category of document
151
- * @param {array} [params.tags=[]] Tags of document
152
- * @param {string} params.docTypeId Document type id (_id database)
153
- * @param {boolean} [params.hasPhisicalStorage=false] Has Phisical Storage
154
- * @param {string} [params.boxId=''] Box ID
155
- * @param {string} [params.storageStatus=''] Storage status
156
- * @param {boolean} [params.ocrDocumentBackend=false] Ocr document backend
157
- * @param {number} params.bytes Size document in bytes
158
- * @param {object} [params.docAreaPermission={}] Permission to doc area
159
- * @param {object} [params.docTypeFieldsData={}] Fields data "extraField'
160
- * @param {string} params.signedUrl SIgned URL
161
- * @param {string} [params.urlType='S3'] URL type
162
- * @param {string} [params.addType='S3_SIGNED'] Add type
163
- * @param {string} params.orgId Organization id (_id database)
164
- * @param {string} session Session, token JWT
165
- * @return {Promise}
166
- * @public
167
- * @async
168
- * @example
169
- *
170
- * const API = require('@docbrasil/api-systemmanager');
171
- * const api = new API();
172
- * const params = {
173
- * orgname: 'cloundbrasil',
174
- * areaId: '5edf9f8ee896b817e45b8dac',
175
- * docId: '5edf86fbe896b817e45b8da6',
176
- * fileName: 'foto',
177
- * type: 'image/png',
178
- * name: 'Fotografia',
179
- * docTypeId = '5edf9f8ee896b817e45b8dac',
180
- * bytes: 12345,
181
- * signedUrl: 'https://s3.amazonaws.com...'
182
- * docTypeFieldsData: {extraUser: '12349f8ee896b817e45b8dac'},
183
- * orgId: '5df7f19618430c89a41a19d2',
184
- * };
185
- * const session = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...';
186
- * await api.user.document.add(params, session);
187
- */
188
- async add(params, session) {
189
- const self = this;
190
-
191
- try {
192
- Joi.assert(params, Joi.object().required().error(new Error('params is required')));
193
- Joi.assert(params.orgname, Joi.string().required().error(new Error('orgname is required')));
194
- Joi.assert(params.areaId, Joi.string().required().error(new Error('areaId is required')));
195
- Joi.assert(params.docId, Joi.string().required().error(new Error('docId is required')));
196
- Joi.assert(params.type, Joi.string().required().error(new Error('type is required')));
197
- Joi.assert(params.name, Joi.string().required().error(new Error('name is required')));
198
- Joi.assert(params.docTypeId, Joi.string().required().error(new Error('docTypeId is required')));
199
- Joi.assert(params.bytes, Joi.number().required().error(new Error('bytes is required')));
200
- Joi.assert(params.orgId, Joi.string().required().error(new Error('orgId is required')));
201
- Joi.assert(session, Joi.string().required().error(new Error('session is required')));
202
-
203
- // Get fields required, and set data default to create document
204
- const payloadToSend = self._formatDocument(params);
205
-
206
- Joi.assert(payloadToSend.documentDate, Joi.string().allow('').error(new Error('documentData is required after formatting payload')));
207
- Joi.assert(payloadToSend.content, Joi.string().allow('').error(new Error('content is required after formatting payload')));
208
- Joi.assert(payloadToSend.description, Joi.string().allow('').error(new Error('description is required after formatting payload')));
209
- Joi.assert(payloadToSend.category, Joi.string().allow('').error(new Error('catetory is required after formatting payload')));
210
- Joi.assert(payloadToSend.tags, Joi.array().error(new Error('tags is required after formatting payload')));
211
- Joi.assert(payloadToSend.hasPhisicalStorage, Joi.boolean().error(new Error('hasPhisicalStorage is required after formatting payload')));
212
- Joi.assert(payloadToSend.boxId, Joi.string().allow('').error(new Error('boxId is required after formatting payload')));
213
- Joi.assert(payloadToSend.storageStatus, Joi.string().allow('').error(new Error('storageStatus is required after formatting payload')));
214
- Joi.assert(payloadToSend.ocrDocumentBackend, Joi.boolean().error(new Error('ocrDocumentBackend is required after formatting payload')));
215
- Joi.assert(payloadToSend.docAreaPermission, Joi.object().allow({}).error(new Error('docAreaPermission is required after formatting payload')));
216
- Joi.assert(payloadToSend.docTypeFieldsData, Joi.object().allow({}).error(new Error('docTypeFieldsData is required after formatting payload')));
217
- Joi.assert(payloadToSend.urlType, Joi.string().allow('').error(new Error('urlType is required after formatting payload')));
218
- Joi.assert(payloadToSend.addType, Joi.string().allow('').error(new Error('addType is required after formatting payload')));
219
-
220
- const {areaId, orgId} = params;
221
- const apiCall = self._client
222
- .put(`/organizations/${orgId}/areas/${areaId}/documents`, payloadToSend, self._setHeader(session));
223
-
224
- return self._returnData(await apiCall);
225
- } catch (ex) {
226
- throw ex;
227
- }
228
- }
229
-
230
- /**
231
- * @author CloudBrasil <abernardo.br@gmail.com>
232
- * @param {object} params Object with params
233
- * @param {string} params.index Field to search
234
- * @param {string} params.txtToSearch Text to search
235
- * @param {string} [params.compare=*] Filter to search (=, ~, *, =*, *=, *?)
236
- * @param {string} params.docId Document id for serach
237
- * @param {string} params.docAreaId Doc area id
238
- * @param {string} params.tag Tag of the document
239
- * @param {string} [params.projection=""] Projection to return fields
240
- * @param {string} [params.sort="Mais+recentes"] Sort data
241
- * @param {string} params.orgId Organization id (_id database)
242
- * @param {string} params.pagination Set pagination
243
- * @param {number} [params.pagination.page=1] Page
244
- * @param {number} [params.pagination.perPage=100] perPage Itens per page
245
- * @param {string} session Session, token JWT
246
- * @return {Promise}
247
- * @public
248
- * @async
249
- * @example
250
- *
251
- * const API = require('@docbrasil/api-systemmanager');
252
- * const api = new API();
253
- * const params - {
254
- * index: 'extraCity',
255
- * txtToSearch: 'São',
256
- * docId: '5df7f19618430c89a41a19d2',
257
- * docAreaId: '5edd11c46b6ce9729c2c297c',
258
- * tag: 'Nome da cidade',
259
- * orgId: '1234d01dc4af3941d42f8c5c'
260
- * };
261
- * const session = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...';
262
- * await api.user.document.findByIdAndRemove(params, session);
263
- */
264
- async find(params, session) {
265
- const self = this;
266
-
267
- try {
268
- Joi.assert(params, Joi.object().required());
269
- Joi.assert(params.index, Joi.string().required());
270
- Joi.assert(params.txtToSearch, Joi.string().allow(null));
271
- Joi.assert(params.compare, Joi.string().allow(null));
272
- Joi.assert(params.docId, Joi.string().required());
273
- Joi.assert(params.docAreaId, Joi.string().required());
274
- Joi.assert(params.tag, Joi.string().required());
275
- Joi.assert(params.projection, Joi.string());
276
- Joi.assert(params.orgId, Joi.string().required());
277
- Joi.assert(params.sort, Joi.string());
278
-
279
- if (_.hasIn(params, 'pagination')) {
280
- Joi.assert(params.pagination, Joi.object());
281
- Joi.assert(params.pagination.page, Joi.number());
282
- Joi.assert(params.pagination.perPage, Joi.number());
283
- }
284
-
285
- Joi.assert(session, Joi.string().required());
286
-
287
- const orgId = _.get(params, 'orgId');
288
- const index = _.get(params, 'index');
289
- const txtToSearch = _.get(params, 'txtToSearch', null);
290
- const compare = _.get(params, 'compare', '*');
291
- const tag = _.get(params, 'tag');
292
- const defaultSearch = {
293
- p: 100, // Per page
294
- i: 1, // Initial page
295
- s: 'Mais+recentes', // Sort to search
296
- ai: '', // Doc Area Id lists emprego_net
297
- di: '', // Document Type Id
298
- m: 'w', // Default
299
- pj: '' // Projection
300
- };
301
-
302
- // Mount query to search autocomplete
303
- defaultSearch.p = _.get(params, 'pagination.perPage', 100);
304
- defaultSearch.i = _.get(params, 'pagination.page', 1);
305
- defaultSearch.s = _.get(params, 'sort', 'Mais+recentes');
306
- defaultSearch.ai = _.get(params, 'docAreaId');
307
- defaultSearch.di = _.get(params, 'docId');
308
- defaultSearch.pj = `_id,${_.get(params, 'projection', '')}`;
309
-
310
- if (!_.isNull(txtToSearch)) {
311
- defaultSearch.ix = {ix: [[index, txtToSearch, compare, 'string', tag]]};
312
- }
313
-
314
- const query = self._queryReducer(defaultSearch);
315
- const apiCall = self._client.get(`/organizations/${orgId}/documents/search?${query}`, self._setHeader(session));
316
- return self._returnData(await apiCall);
317
- } catch (ex) {
318
- throw ex;
319
- }
320
- }
321
-
322
- /**
323
- * @author CloudBrasil <abernardo.br@gmail.com>
324
- * @description Remove document by id
325
- * @param {object} params Params to remove document
326
- * @param {string} params.docId Document Id (_id database)
327
- * @param {string} params.orgId Organizarion id (_id database)
328
- * @param {string} session Session, token JWT
329
- * @return {Promise<object>} data The returned data
330
- * @return {number} data.removed The quantity of removed documents
331
- * @return {array<object>} data.errors Array of errors
332
- * @return {string} data.errors.id Id of the document that had an error
333
- * @return {string} data.errors.code Error code
334
- * @return {string} data.errors.message Error message
335
- * @public
336
- * @async
337
- * @example
338
- *
339
- * const API = require('@docbrasil/api-systemmanager');
340
- * const api = new API();
341
- * const params - {
342
- * docId: '5dadd01dc4af3941d42f8c5c',
343
- * orgIdId: '5df7f19618430c89a41a19d2',
344
- * };
345
- * const session = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...';
346
- * await api.user.document.findByIdAndRemove(params, session);
347
- */
348
- async findByIdAndRemove(params, session) {
349
- const self = this;
350
-
351
- try {
352
- Joi.assert(params, Joi.object().required());
353
- Joi.assert(params.docId, Joi.string().required());
354
- Joi.assert(params.orgId, Joi.string().required());
355
- Joi.assert(session, Joi.string().required());
356
-
357
- const {docId, orgId} = params;
358
- const payloadToSend = {documents: [{_id: docId}]};
359
- const apiCall = self._client.post(`/organizations/${orgId}/documents/remove`, payloadToSend, self._setHeader(session));
360
- return self._returnData(await apiCall);
361
- } catch (ex) {
362
- throw ex;
363
- }
364
- }
365
-
366
- /**
367
- * @author CloudBrasil <abernardo.br@gmail.com>
368
- * @description Remove documents
369
- * @param {object} params Params to remove document
370
- * @param {array<string>} params.documents An array ids of documents (_id database)
371
- * @param {array<string>} params.documents._id The document id (_id database)
372
- * @param {string} params.orgId Organizarion id (_id database)
373
- * @param {string} session Session, token JWT
374
- * @return {Promise<object>} data The returned data
375
- * @return {number} data.removed The quantity of removed documents
376
- * @return {array<object>} data.errors Array of errors
377
- * @return {string} data.errors.id Id of the document that had an error
378
- * @return {string} data.errors.code Error code
379
- * @return {string} data.errors.message Error message
380
- * @public
381
- * @async
382
- * @example
383
- *
384
- * const API = require('@docbrasil/api-systemmanager');
385
- * const api = new API();
386
- * const params - {
387
- * documents: [{ _id: '5dadd01dc4af3941d42f8c5c' }],
388
- * orgId: '5df7f19618430c89a41a19d2',
389
- * };
390
- * const session = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...';
391
- * await api.user.document.findByIdsAndRemove(params, session);
392
- */
393
- async findByIdsAndRemove(params, session) {
394
- const self = this;
395
-
396
- try {
397
- Joi.assert(params, Joi.object().required());
398
- Joi.assert(params.documents, Joi.array().required());
399
- Joi.assert(params.orgId, Joi.string().required());
400
- Joi.assert(session, Joi.string().required());
401
-
402
- const {documents, orgId} = params;
403
- const payloadToSend = { documents };
404
- const apiCall = self._client.post(`/organizations/${orgId}/documents/remove`, payloadToSend, self._setHeader(session));
405
- return self._returnData(await apiCall);
406
- } catch (ex) {
407
- throw ex;
408
- }
409
- }
410
-
411
- /**
412
- *
413
- * @author CloudBrasil <abernardo.br@gmail.com>
414
- * @description Request signed url url to put or get
415
- * @param {object} params Params to request signed url
416
- * @param {string} params.methodType Method type HTTP get or put
417
- * @param {string} params.docId Document id
418
- * @param {string} params.fileName File name
419
- * @param {string} params.docAreaId docAreaId of the document
420
- * @param {string} params.type mimeType image/png image/jpg others
421
- * @param {string} params.document Name document to request if method type is get
422
- * @param {string} params.orgId Organization id (_id database)
423
- * @param {string} session Session, token JWT
424
- * @return {Promise<object>} doc Returned document data with the signed url
425
- * @return {string} doc.docId Document id
426
- * @return {string} doc.name The name of the document, which is the fileName
427
- * @return {string} doc.areaId docAreaId of the document
428
- * @return {string} doc.type the document mimi type
429
- * @return {string} doc.signedUrl the signed URL to upload
430
- * @public
431
- * @async
432
- * @example
433
- *
434
- * const API = require('@docbrasil/api-systemmanager');
435
- * const api = new API();
436
- * const params - {
437
- * methodType: 'put',
438
- * docId: '5dadd01dc4af3941d42f8c5c',
439
- * docAreaId: '5df7f19618430c89a41a19d2',
440
- * fileName: 'Foto',
441
- * type: 'image/png'
442
- * orgId: '5df7f19618430c89a41a19f8'
443
- * };
444
- * const session = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...';
445
- * // each doc: { docId, name, areaId, type, signedUrl }
446
- * const { docs } = await api.user.document.signedUrl(params, session);
447
- *
448
- * @example
449
- *
450
- * const API = require('@docbrasil/api-systemmanager');
451
- * const api = new API();
452
- * const params - {
453
- * methodType: 'get',
454
- * document: 'pinkandthebrain/5df7f19618430c89a41a19d2/5dadd01dc4af3941d42f8c5c/9dadd01dc4af3941d42f6dd4.pdf',
455
- * };
456
- * const session = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...';
457
- * const base64Data = await api.user.document.signedUrl(params, session);
458
- */
459
- async signedUrl(params, session) {
460
- const self = this;
461
-
462
- try {
463
- Joi.assert(params, Joi.object().required());
464
- Joi.assert(params.methodType, Joi.string().required());
465
- Joi.assert(params.orgId, Joi.string().required());
466
- Joi.assert(session, Joi.string().required());
467
-
468
- const {methodType} = params;
469
-
470
- if (methodType === 'put') {
471
- Joi.assert(params, Joi.object().required());
472
- Joi.assert(params.docId, Joi.string().required());
473
- Joi.assert(params.docAreaId, Joi.string().required());
474
- Joi.assert(params.fileName, Joi.string().required());
475
- Joi.assert(params.type, Joi.string().required());
476
- } else {
477
- Joi.assert(params.document, Joi.string().required());
478
- }
479
-
480
- const {orgId} = params;
481
- let payloadToSend;
482
-
483
- if (params.methodType === 'put') {
484
- const {docId, fileName: name, docAreaId: areaId, type} = params;
485
- payloadToSend = {docs: [{docId, name, areaId, type}]};
486
- } else {
487
- const {document} = params;
488
- payloadToSend = {docs: [{document}]};
489
- }
490
-
491
- const apiCall = self._client
492
- .post(`/organizations/${orgId}/documents/getDocumentSignedUrl/${methodType}`, payloadToSend, self._setHeader(session));
493
-
494
- return self._returnData(await apiCall);
495
- } catch (ex) {
496
- throw ex;
497
- }
498
- }
499
-
500
- /**
501
- *
502
- * @author CloudBrasil <abernardo.br@gmail.com>
503
- * @description Request signed url url to put or get
504
- * @param {object} params Params to request signed url
505
- * @param {array} params.docs the list of documents to get the signed urls
506
- * @param {string} params.docs.docId Document id
507
- * @param {string} params.docs.name File name
508
- * @param {string} params.docs.areaId docAreaId of the document
509
- * @param {string} params.docs.type mimeType image/png image/jpg others
510
- * @param {string} params.docs.document Name document to request if method type is get
511
- * @param {string} params.methodType Method type HTTP get or put
512
- * @param {string} params.orgId Organization id (_id database)
513
- * @param {string} session Session, token JWT
514
- * @return {Promise<object>} doc Returned document data with the signed url
515
- * @return {string} doc.docId Document id
516
- * @return {string} doc.name The name of the document, which is the fileName
517
- * @return {string} doc.areaId docAreaId of the document
518
- * @return {string} doc.type the document mimi type
519
- * @return {string} doc.signedUrl the signed URL to upload
520
- * @public
521
- * @async
522
- * @example
523
- *
524
- * const API = require('@docbrasil/api-systemmanager');
525
- * const api = new API();
526
- * const params - {
527
- * methodType: 'put',
528
- * orgId: '5df7f19618430c89a41a19f8'
529
- * docs: [
530
- * {
531
- * docId: '5dadd01dc4af3941d42f8c5c',
532
- * areaId: '5df7f19618430c89a41a19d2',
533
- * name: 'Foto.png',
534
- * type: 'image/png'
535
- * }
536
- * ]
537
- * };
538
- * const session = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...';
539
- * // each doc: { docId, name, areaId, type, signedUrl }
540
- * const { docs } = await api.user.document.signedUrls(params, session);
541
- *
542
- * @example
543
- *
544
- * const API = require('@docbrasil/api-systemmanager');
545
- * const api = new API();
546
- * const params - {
547
- * methodType: 'get',
548
- * docs: [
549
- * { document: 'pinkandthebrain/5df7f19618430c89a41a19d2/5dadd01dc4af3941d42f8c5c/9dadd01dc4af3941d42f6dd4.pdf' }
550
- * ],
551
- * };
552
- * const session = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...';
553
- * const base64Data = await api.user.document.signedUrls(params, session);
554
- */
555
- async signedUrls(params, session) {
556
- const self = this;
557
-
558
- try {
559
- Joi.assert(params, Joi.object().required());
560
- Joi.assert(params.docs, Joi.array().required());
561
- Joi.assert(params.orgId, Joi.string().required());
562
- Joi.assert(session, Joi.string().required());
563
-
564
- const {orgId, methodType = 'put', docs = []} = params;
565
- const apiCall = self._client
566
- .post(`/organizations/${orgId}/documents/getDocumentSignedUrl/${methodType}`, { docs }, self._setHeader(session));
567
-
568
- return self._returnData(await apiCall);
569
- } catch (ex) {
570
- throw ex;
571
- }
572
- }
573
-
574
- /**
575
- * Uploads the file
576
- * @param {object} params Params to upload document
577
- * @param {buffer} params.content The content of the file (Buffer)
578
- * @param {string} params.signedUrl The signed URL
579
- * @param {string} params.type The file mime type
580
- * @param {string} params.onUploadProgress A callback for the upload progress. It will return a progressEvent.
581
- * @return {Promise<boolean>} True if success
582
- *
583
- * @public
584
- * @async
585
- * @example
586
- *
587
- * const FS = require('fs');
588
- * const Path = require('path');
589
- * const API = require('@docbrasil/api-systemmanager');
590
- * const api = new API();
591
- * const params - {
592
- * content: FS.readFileSync(Path.join(__dirname, '.mypdf.pdf')),
593
- * signedUrl: 'https://signedurl.com/token...',
594
- * type: 'application/pdf'
595
- * };
596
- * const retData = await api.user.document.uploadSignedDocument(params);
597
- *
598
- * onUploadProgress return the progressEvent
599
- * - lengthComputable: A Boolean that indicates whether or not the total number of bytes is known.
600
- * - loaded: The number of bytes of the file that have been uploaded.
601
- * - total: The total number of bytes in the file.
602
- */
603
- async uploadSignedDocument(params= {}) {
604
- const { content, signedUrl, type } = params;
605
- Joi.assert(params, Joi.object().required());
606
- Joi.assert(params.content, Joi.required());
607
- Joi.assert(params.signedUrl, Joi.string().required());
608
- Joi.assert(params.type, Joi.string().required());
609
-
610
- const self = this;
611
- const reqOpts = {
612
- headers: {
613
- 'Content-Type': type
614
- },
615
- maxContentLength: Infinity,
616
- maxBodyLength: Infinity
617
- };
618
-
619
- const onUploadProgress = params.onUploadProgress;
620
-
621
- if(onUploadProgress) {
622
- reqOpts.onUploadProgress = onUploadProgress;
623
- }
624
-
625
- const apiCall = self._client
626
- .put(signedUrl, content, reqOpts);
627
- self._returnData(await apiCall);
628
- return true;
629
- }
630
-
631
- /**
632
- * @author CloudBrasil <abernardo.br@gmail.com>
633
- * Checks if a document can be added and it does not repeat its primary key
634
- * @param params
635
- * @param params.orgId {string} the organization id
636
- * @param params.docTypeId {string} the id of the doc type
637
- * @param params.docs {array<object>} an array of documents
638
- * @param params.docs.id {string} an unique id representing the document
639
- * @param params.docs.docTypeFields {object} thje docTypeFields of the document
640
- * @param params.docs.docTypeFieldsData {object} thje docTypeFieldsData of the document
641
- * @param session
642
- * @return {Promise<array>} Return the array of the documents that are repeated. If not document is repeaded, then if returns an empty array.
643
- * @return id {array<string>} the id of the repeated document
644
- * @public
645
- * @async
646
- * @example
647
- *
648
- * const API = require('@docbrasil/api-systemmanager');
649
- * const api = new API();
650
- * const docTypeFields = [...]; // the doc type fields array
651
- * const docTypeFieldsData = {...}; // the data of this fields
652
- * const params - {
653
- * docs: [{ id: '5dadd01dc4af3941d42f8c5c', docTypeFields, docTypeFieldsData }],
654
- * orgId: '5df7f19618430c89a41a19d2',
655
- * docTypeId: '5df7f19618430c89a41a19d5',
656
- * };
657
- * const session = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...';
658
- * const retDocs = await api.user.document.checkPrimaryKeys(params, session);
659
- *
660
- */
661
- async checkPrimaryKeys(params, session) {
662
- Joi.assert(params, Joi.object().required().label('params'));
663
- Joi.assert(params.orgId, Joi.string().required().label('orgId'));
664
- Joi.assert(params.docTypeId, Joi.string().required().label('docTypeId'));
665
- Joi.assert(params.docs, Joi.array().required().label('docs'));
666
- Joi.assert(session, Joi.string().required().label('session'));
667
-
668
- const { docs = [], orgId = '', docTypeId = '' } = params;
669
-
670
- if(docs.length === 0) return;
671
-
672
- try {
673
- const self = this;
674
- const payloadToSend = {
675
- docs,
676
- docTypeId
677
- };
678
- const apiCall = self._client.post(`/organizations/${orgId}/documents/can/add`, payloadToSend, self._setHeader(session));
679
- return self._returnData(await apiCall);
680
- } catch (ex) {
681
- throw ex;
682
- }
683
- }
684
-
685
- }
686
-
687
- export default Documents;
1
+ import _ from 'lodash';
2
+ import Boom from '@hapi/boom';
3
+ import Joi from 'joi';
4
+ import Moment from 'moment';
5
+
6
+ /**
7
+ * Class for documents, permission user
8
+ * @class
9
+ */
10
+ class Documents {
11
+
12
+ constructor(options) {
13
+ Joi.assert(options, Joi.object().required());
14
+ Joi.assert(options.parent, Joi.object().required());
15
+
16
+ const self = this;
17
+ self.parent = options.parent;
18
+ self._client = self.parent.dispatch.getClient();
19
+ }
20
+
21
+ /**
22
+ * @author Augusto Pissarra <abernardo.br@gmail.com>
23
+ * @description Get the return data and check for errors
24
+ * @param {object} retData Response HTTP
25
+ * @return {*}
26
+ * @private
27
+ */
28
+ _returnData(retData, def = {}) {
29
+ if (retData.status !== 200) {
30
+ throw Boom.badRequest(_.get(retData, 'message', 'No error message reported!'))
31
+ } else {
32
+ return _.get(retData, 'data', def);
33
+ }
34
+ }
35
+
36
+ /**
37
+ * @author CloudBrasil <abernardo.br@gmail.com>
38
+ * @description Set header with new session
39
+ * @param {string} session Session, token JWT
40
+ * @return {object} header with new session
41
+ * @private
42
+ */
43
+ _setHeader(session) {
44
+ return {
45
+ headers: {
46
+ authorization: session,
47
+ }
48
+ };
49
+ }
50
+
51
+ /**
52
+ * @author CloudBrasil <abernardo.br@gmail.com>
53
+ * @description Create document with informed data
54
+ * @param {object} params Object for add new document
55
+ * @param {string} params.orgname Organization name
56
+ * @param {string} params.areaId Doc area id (_id database)
57
+ * @param {string} params.docId Document id (_id database)
58
+ * @param {string} [params.documentDate=new\ Date()] Date of document
59
+ * @param {string} params.filename File name
60
+ * @param {string} params.type Mimetype of the document (image/png)
61
+ * @param {string} params.name Doument name
62
+ * @param {string} [params.content=''] Content of document
63
+ * @param {string} [params.description=''] Description of document
64
+ * @param {string} [params.category=''] Category of document
65
+ * @param {array} [params.tags=[]] Tags of document
66
+ * @param {string} params.docTypeId Document type id (_id database)
67
+ * @param {boolean} [params.hasPhisicalStorage=false] Has Phisical Storage
68
+ * @param {string} [params.boxId=''] Box ID
69
+ * @param {string} [params.storageStatus=''] Storage status
70
+ * @param {boolean} [params.ocrDocumentBackend=false] Ocr document backend
71
+ * @param {number} params.bytes Size document in bytes
72
+ * @param {object} [params.docAreaPermission={}] Permission to doc area
73
+ * @param {object} [params.docTypeFieldsData={}] Fields data "extraField'
74
+ * @param {string} params.signedUrl SIgned URL
75
+ * @param {string} [params.urlType='S3'] URL type
76
+ * @param {string} [params.addType='S3_SIGNED'] Add type
77
+ * @return {{documentDate: *, docId: *, docAreaPermission: *, document: *, docTypeFieldsData: *, description: *, storageStatus: *, type: *, content: *, tags: *, addType: *, urlType: *, areaId: *, orgname: *, docTypeId: *, bytes: *, name: *, category: *, hasPhisicalStorage: *, signedUrl: *, ocrDocumentBackend: *, boxId: *}}
78
+ * @private
79
+ */
80
+ _formatDocument(params) {
81
+ try {
82
+ return {
83
+ orgname: _.get(params, 'orgname'),
84
+ areaId: _.get(params, 'areaId'),
85
+ docId: _.get(params, 'docId'),
86
+ documentDate: _.get(params, 'documentDate', Moment().format()),
87
+ document: _.get(params, 'document'),
88
+ type: _.get(params, 'type'),
89
+ name: _.get(params, 'name'),
90
+ content: _.get(params, 'content', ''),
91
+ description: _.get(params, 'description', ''),
92
+ category: _.get(params, 'category', ''),
93
+ tags: _.get(params, 'tags', []),
94
+ docTypeId: _.get(params, 'docTypeId'),
95
+ hasPhisicalStorage: _.get(params, 'hasPhisicalStorage', false),
96
+ boxId: _.get(params, 'boxId', ''),
97
+ storageStatus: _.get(params, 'storageStatus', ''),
98
+ ocrDocumentBackend: _.get(params, 'ocrDocumentBackend', false),
99
+ bytes: _.get(params, 'bytes'),
100
+ docAreaPermission: _.get(params, 'docAreaPermission', {}),
101
+ docTypeFields: _.get(params, 'docTypeFields', []), // {"extraId": userId},
102
+ docTypeFieldsData: _.get(params, 'docTypeFieldsData', {}), // {"extraId": userId},
103
+ signedUrl: _.get(params, 'signedUrl', ''),
104
+ urlType: _.get(params, 'urlType', 'S3'),
105
+ addType: _.get(params, 'addType', 'S3_SIGNED'),
106
+ };
107
+ } catch (ex) {
108
+ throw ex;
109
+ }
110
+ }
111
+
112
+ /**
113
+ * @author CloudBrasil <abernardo.br@gmail.com>
114
+ * @description Transform objtect query in query string
115
+ * @param {object} searchQuery object wicth query
116
+ * @return {string} Retutn string query
117
+ * @private
118
+ */
119
+ _queryReducer(searchQuery) {
120
+ return Object.keys(searchQuery).reduce((query, key, idx, sourceList) => {
121
+ idx++;
122
+
123
+ const data = key === 'ix'
124
+ ? JSON.stringify(searchQuery[key])
125
+ : searchQuery[key];
126
+
127
+ const querySearch = sourceList.length === idx
128
+ ? `${key}=${data}`
129
+ : `${key}=${data}&`;
130
+
131
+ query += querySearch;
132
+ return query;
133
+ }, '');
134
+ }
135
+
136
+ /**
137
+ * @author CloudBrasil <abernardo.br@gmail.com>
138
+ * @description Create new document
139
+ * @param {object} params Object for add new document
140
+ * @param {string} params.orgname Organization name
141
+ * @param {string} params.areaId Doc area id (_id database)
142
+ * @param {string} params.docId Document id (_id database)
143
+ * @param {string} [params.documentDate=new Date()] Date of document
144
+ * @param {string} params.document The path to the file. If S3, the key to S3, gotten after getting a signed URL
145
+ * @param {string} params.filename File name
146
+ * @param {string} params.type Mimetype of the document (image/png)
147
+ * @param {string} params.name Document name
148
+ * @param {string} [params.content=''] Content of document
149
+ * @param {string} [params.description=''] Description of document
150
+ * @param {string} [params.category=''] Category of document
151
+ * @param {array} [params.tags=[]] Tags of document
152
+ * @param {string} params.docTypeId Document type id (_id database)
153
+ * @param {boolean} [params.hasPhisicalStorage=false] Has Phisical Storage
154
+ * @param {string} [params.boxId=''] Box ID
155
+ * @param {string} [params.storageStatus=''] Storage status
156
+ * @param {boolean} [params.ocrDocumentBackend=false] Ocr document backend
157
+ * @param {number} params.bytes Size document in bytes
158
+ * @param {object} [params.docAreaPermission={}] Permission to doc area
159
+ * @param {object} [params.docTypeFieldsData={}] Fields data "extraField'
160
+ * @param {string} params.signedUrl SIgned URL
161
+ * @param {string} [params.urlType='S3'] URL type
162
+ * @param {string} [params.addType='S3_SIGNED'] Add type
163
+ * @param {string} params.orgId Organization id (_id database)
164
+ * @param {string} session Session, token JWT
165
+ * @return {Promise}
166
+ * @public
167
+ * @async
168
+ * @example
169
+ *
170
+ * const API = require('@docbrasil/api-systemmanager');
171
+ * const api = new API();
172
+ * const params = {
173
+ * orgname: 'cloundbrasil',
174
+ * areaId: '5edf9f8ee896b817e45b8dac',
175
+ * docId: '5edf86fbe896b817e45b8da6',
176
+ * fileName: 'foto',
177
+ * type: 'image/png',
178
+ * name: 'Fotografia',
179
+ * docTypeId = '5edf9f8ee896b817e45b8dac',
180
+ * bytes: 12345,
181
+ * signedUrl: 'https://s3.amazonaws.com...'
182
+ * docTypeFieldsData: {extraUser: '12349f8ee896b817e45b8dac'},
183
+ * orgId: '5df7f19618430c89a41a19d2',
184
+ * };
185
+ * const session = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...';
186
+ * await api.user.document.add(params, session);
187
+ */
188
+ async add(params, session) {
189
+ const self = this;
190
+
191
+ try {
192
+ Joi.assert(params, Joi.object().required().error(new Error('params is required')));
193
+ Joi.assert(params.orgname, Joi.string().required().error(new Error('orgname is required')));
194
+ Joi.assert(params.areaId, Joi.string().required().error(new Error('areaId is required')));
195
+ Joi.assert(params.docId, Joi.string().required().error(new Error('docId is required')));
196
+ Joi.assert(params.type, Joi.string().required().error(new Error('type is required')));
197
+ Joi.assert(params.name, Joi.string().required().error(new Error('name is required')));
198
+ Joi.assert(params.docTypeId, Joi.string().required().error(new Error('docTypeId is required')));
199
+ Joi.assert(params.bytes, Joi.number().required().error(new Error('bytes is required')));
200
+ Joi.assert(params.orgId, Joi.string().required().error(new Error('orgId is required')));
201
+ Joi.assert(session, Joi.string().required().error(new Error('session is required')));
202
+
203
+ // Get fields required, and set data default to create document
204
+ const payloadToSend = self._formatDocument(params);
205
+
206
+ Joi.assert(payloadToSend.documentDate, Joi.string().allow('').error(new Error('documentData is required after formatting payload')));
207
+ Joi.assert(payloadToSend.content, Joi.string().allow('').error(new Error('content is required after formatting payload')));
208
+ Joi.assert(payloadToSend.description, Joi.string().allow('').error(new Error('description is required after formatting payload')));
209
+ Joi.assert(payloadToSend.category, Joi.string().allow('').error(new Error('catetory is required after formatting payload')));
210
+ Joi.assert(payloadToSend.tags, Joi.array().error(new Error('tags is required after formatting payload')));
211
+ Joi.assert(payloadToSend.hasPhisicalStorage, Joi.boolean().error(new Error('hasPhisicalStorage is required after formatting payload')));
212
+ Joi.assert(payloadToSend.boxId, Joi.string().allow('').error(new Error('boxId is required after formatting payload')));
213
+ Joi.assert(payloadToSend.storageStatus, Joi.string().allow('').error(new Error('storageStatus is required after formatting payload')));
214
+ Joi.assert(payloadToSend.ocrDocumentBackend, Joi.boolean().error(new Error('ocrDocumentBackend is required after formatting payload')));
215
+ Joi.assert(payloadToSend.docAreaPermission, Joi.object().allow({}).error(new Error('docAreaPermission is required after formatting payload')));
216
+ Joi.assert(payloadToSend.docTypeFieldsData, Joi.object().allow({}).error(new Error('docTypeFieldsData is required after formatting payload')));
217
+ Joi.assert(payloadToSend.urlType, Joi.string().allow('').error(new Error('urlType is required after formatting payload')));
218
+ Joi.assert(payloadToSend.addType, Joi.string().allow('').error(new Error('addType is required after formatting payload')));
219
+
220
+ const {areaId, orgId} = params;
221
+ const apiCall = self._client
222
+ .put(`/organizations/${orgId}/areas/${areaId}/documents`, payloadToSend, self._setHeader(session));
223
+
224
+ return self._returnData(await apiCall);
225
+ } catch (ex) {
226
+ throw ex;
227
+ }
228
+ }
229
+
230
+ /**
231
+ * @author CloudBrasil <abernardo.br@gmail.com>
232
+ * @param {object} params Object with params
233
+ * @param {string} params.index Field to search
234
+ * @param {string} params.txtToSearch Text to search
235
+ * @param {string} [params.compare=*] Filter to search (=, ~, *, =*, *=, *?)
236
+ * @param {string} params.docId Document id for serach
237
+ * @param {string} params.docAreaId Doc area id
238
+ * @param {string} params.tag Tag of the document
239
+ * @param {string} [params.projection=""] Projection to return fields
240
+ * @param {string} [params.sort="Mais+recentes"] Sort data
241
+ * @param {string} params.orgId Organization id (_id database)
242
+ * @param {string} params.pagination Set pagination
243
+ * @param {number} [params.pagination.page=1] Page
244
+ * @param {number} [params.pagination.perPage=100] perPage Itens per page
245
+ * @param {string} session Session, token JWT
246
+ * @return {Promise}
247
+ * @public
248
+ * @async
249
+ * @example
250
+ *
251
+ * const API = require('@docbrasil/api-systemmanager');
252
+ * const api = new API();
253
+ * const params - {
254
+ * index: 'extraCity',
255
+ * txtToSearch: 'São',
256
+ * docId: '5df7f19618430c89a41a19d2',
257
+ * docAreaId: '5edd11c46b6ce9729c2c297c',
258
+ * tag: 'Nome da cidade',
259
+ * orgId: '1234d01dc4af3941d42f8c5c'
260
+ * };
261
+ * const session = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...';
262
+ * await api.user.document.findByIdAndRemove(params, session);
263
+ */
264
+ async find(params, session) {
265
+ const self = this;
266
+
267
+ try {
268
+ Joi.assert(params, Joi.object().required());
269
+ Joi.assert(params.index, Joi.string().required());
270
+ Joi.assert(params.txtToSearch, Joi.string().allow(null));
271
+ Joi.assert(params.compare, Joi.string().allow(null));
272
+ Joi.assert(params.docId, Joi.string().required());
273
+ Joi.assert(params.docAreaId, Joi.string().required());
274
+ Joi.assert(params.tag, Joi.string().required());
275
+ Joi.assert(params.projection, Joi.string());
276
+ Joi.assert(params.orgId, Joi.string().required());
277
+ Joi.assert(params.sort, Joi.string());
278
+
279
+ if (_.hasIn(params, 'pagination')) {
280
+ Joi.assert(params.pagination, Joi.object());
281
+ Joi.assert(params.pagination.page, Joi.number());
282
+ Joi.assert(params.pagination.perPage, Joi.number());
283
+ }
284
+
285
+ Joi.assert(session, Joi.string().required());
286
+
287
+ const orgId = _.get(params, 'orgId');
288
+ const index = _.get(params, 'index');
289
+ const txtToSearch = _.get(params, 'txtToSearch', null);
290
+ const compare = _.get(params, 'compare', '*');
291
+ const tag = _.get(params, 'tag');
292
+ const defaultSearch = {
293
+ p: 100, // Per page
294
+ i: 1, // Initial page
295
+ s: 'Mais+recentes', // Sort to search
296
+ ai: '', // Doc Area Id lists emprego_net
297
+ di: '', // Document Type Id
298
+ m: 'w', // Default
299
+ pj: '' // Projection
300
+ };
301
+
302
+ // Mount query to search autocomplete
303
+ defaultSearch.p = _.get(params, 'pagination.perPage', 100);
304
+ defaultSearch.i = _.get(params, 'pagination.page', 1);
305
+ defaultSearch.s = _.get(params, 'sort', 'Mais+recentes');
306
+ defaultSearch.ai = _.get(params, 'docAreaId');
307
+ defaultSearch.di = _.get(params, 'docId');
308
+ defaultSearch.pj = `_id,${_.get(params, 'projection', '')}`;
309
+
310
+ if (!_.isNull(txtToSearch)) {
311
+ defaultSearch.ix = {ix: [[index, txtToSearch, compare, 'string', tag]]};
312
+ }
313
+
314
+ const query = self._queryReducer(defaultSearch);
315
+ const apiCall = self._client.get(`/organizations/${orgId}/documents/search?${query}`, self._setHeader(session));
316
+ return self._returnData(await apiCall);
317
+ } catch (ex) {
318
+ throw ex;
319
+ }
320
+ }
321
+
322
+ /**
323
+ * @author CloudBrasil <abernardo.br@gmail.com>
324
+ * @description Remove document by id
325
+ * @param {object} params Params to remove document
326
+ * @param {string} params.docId Document Id (_id database)
327
+ * @param {string} params.orgId Organizarion id (_id database)
328
+ * @param {string} session Session, token JWT
329
+ * @return {Promise<object>} data The returned data
330
+ * @return {number} data.removed The quantity of removed documents
331
+ * @return {array<object>} data.errors Array of errors
332
+ * @return {string} data.errors.id Id of the document that had an error
333
+ * @return {string} data.errors.code Error code
334
+ * @return {string} data.errors.message Error message
335
+ * @public
336
+ * @async
337
+ * @example
338
+ *
339
+ * const API = require('@docbrasil/api-systemmanager');
340
+ * const api = new API();
341
+ * const params - {
342
+ * docId: '5dadd01dc4af3941d42f8c5c',
343
+ * orgIdId: '5df7f19618430c89a41a19d2',
344
+ * };
345
+ * const session = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...';
346
+ * await api.user.document.findByIdAndRemove(params, session);
347
+ */
348
+ async findByIdAndRemove(params, session) {
349
+ const self = this;
350
+
351
+ try {
352
+ Joi.assert(params, Joi.object().required());
353
+ Joi.assert(params.docId, Joi.string().required());
354
+ Joi.assert(params.orgId, Joi.string().required());
355
+ Joi.assert(session, Joi.string().required());
356
+
357
+ const {docId, orgId} = params;
358
+ const payloadToSend = {documents: [{_id: docId}]};
359
+ const apiCall = self._client.post(`/organizations/${orgId}/documents/remove`, payloadToSend, self._setHeader(session));
360
+ return self._returnData(await apiCall);
361
+ } catch (ex) {
362
+ throw ex;
363
+ }
364
+ }
365
+
366
+ /**
367
+ * @author CloudBrasil <abernardo.br@gmail.com>
368
+ * @description Remove documents
369
+ * @param {object} params Params to remove document
370
+ * @param {array<string>} params.documents An array ids of documents (_id database)
371
+ * @param {array<string>} params.documents._id The document id (_id database)
372
+ * @param {string} params.orgId Organizarion id (_id database)
373
+ * @param {string} session Session, token JWT
374
+ * @return {Promise<object>} data The returned data
375
+ * @return {number} data.removed The quantity of removed documents
376
+ * @return {array<object>} data.errors Array of errors
377
+ * @return {string} data.errors.id Id of the document that had an error
378
+ * @return {string} data.errors.code Error code
379
+ * @return {string} data.errors.message Error message
380
+ * @public
381
+ * @async
382
+ * @example
383
+ *
384
+ * const API = require('@docbrasil/api-systemmanager');
385
+ * const api = new API();
386
+ * const params - {
387
+ * documents: [{ _id: '5dadd01dc4af3941d42f8c5c' }],
388
+ * orgId: '5df7f19618430c89a41a19d2',
389
+ * };
390
+ * const session = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...';
391
+ * await api.user.document.findByIdsAndRemove(params, session);
392
+ */
393
+ async findByIdsAndRemove(params, session) {
394
+ const self = this;
395
+
396
+ try {
397
+ Joi.assert(params, Joi.object().required());
398
+ Joi.assert(params.documents, Joi.array().required());
399
+ Joi.assert(params.orgId, Joi.string().required());
400
+ Joi.assert(session, Joi.string().required());
401
+
402
+ const {documents, orgId} = params;
403
+ const payloadToSend = { documents };
404
+ const apiCall = self._client.post(`/organizations/${orgId}/documents/remove`, payloadToSend, self._setHeader(session));
405
+ return self._returnData(await apiCall);
406
+ } catch (ex) {
407
+ throw ex;
408
+ }
409
+ }
410
+
411
+ /**
412
+ *
413
+ * @author CloudBrasil <abernardo.br@gmail.com>
414
+ * @description Request signed url url to put or get
415
+ * @param {object} params Params to request signed url
416
+ * @param {string} params.methodType Method type HTTP get or put
417
+ * @param {string} params.docId Document id
418
+ * @param {string} params.fileName File name
419
+ * @param {string} params.docAreaId docAreaId of the document
420
+ * @param {string} params.type mimeType image/png image/jpg others
421
+ * @param {string} params.document Name document to request if method type is get
422
+ * @param {string} params.orgId Organization id (_id database)
423
+ * @param {string} session Session, token JWT
424
+ * @return {Promise<object>} doc Returned document data with the signed url
425
+ * @return {string} doc.docId Document id
426
+ * @return {string} doc.name The name of the document, which is the fileName
427
+ * @return {string} doc.areaId docAreaId of the document
428
+ * @return {string} doc.type the document mimi type
429
+ * @return {string} doc.signedUrl the signed URL to upload
430
+ * @public
431
+ * @async
432
+ * @example
433
+ *
434
+ * const API = require('@docbrasil/api-systemmanager');
435
+ * const api = new API();
436
+ * const params - {
437
+ * methodType: 'put',
438
+ * docId: '5dadd01dc4af3941d42f8c5c',
439
+ * docAreaId: '5df7f19618430c89a41a19d2',
440
+ * fileName: 'Foto',
441
+ * type: 'image/png'
442
+ * orgId: '5df7f19618430c89a41a19f8'
443
+ * };
444
+ * const session = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...';
445
+ * // each doc: { docId, name, areaId, type, signedUrl }
446
+ * const { docs } = await api.user.document.signedUrl(params, session);
447
+ *
448
+ * @example
449
+ *
450
+ * const API = require('@docbrasil/api-systemmanager');
451
+ * const api = new API();
452
+ * const params - {
453
+ * methodType: 'get',
454
+ * document: 'pinkandthebrain/5df7f19618430c89a41a19d2/5dadd01dc4af3941d42f8c5c/9dadd01dc4af3941d42f6dd4.pdf',
455
+ * };
456
+ * const session = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...';
457
+ * const base64Data = await api.user.document.signedUrl(params, session);
458
+ */
459
+ async signedUrl(params, session) {
460
+ const self = this;
461
+
462
+ try {
463
+ Joi.assert(params, Joi.object().required());
464
+ Joi.assert(params.methodType, Joi.string().required());
465
+ Joi.assert(params.orgId, Joi.string().required());
466
+ Joi.assert(session, Joi.string().required());
467
+
468
+ const {methodType} = params;
469
+
470
+ if (methodType === 'put') {
471
+ Joi.assert(params, Joi.object().required());
472
+ Joi.assert(params.docId, Joi.string().required());
473
+ Joi.assert(params.docAreaId, Joi.string().required());
474
+ Joi.assert(params.fileName, Joi.string().required());
475
+ Joi.assert(params.type, Joi.string().required());
476
+ } else {
477
+ Joi.assert(params.document, Joi.string().required());
478
+ }
479
+
480
+ const {orgId} = params;
481
+ let payloadToSend;
482
+
483
+ if (params.methodType === 'put') {
484
+ const {docId, fileName: name, docAreaId: areaId, type} = params;
485
+ payloadToSend = {docs: [{docId, name, areaId, type}]};
486
+ } else {
487
+ const {document} = params;
488
+ payloadToSend = {docs: [{document}]};
489
+ }
490
+
491
+ const apiCall = self._client
492
+ .post(`/organizations/${orgId}/documents/getDocumentSignedUrl/${methodType}`, payloadToSend, self._setHeader(session));
493
+
494
+ return self._returnData(await apiCall);
495
+ } catch (ex) {
496
+ throw ex;
497
+ }
498
+ }
499
+
500
+ /**
501
+ *
502
+ * @author CloudBrasil <abernardo.br@gmail.com>
503
+ * @description Request signed url url to put or get
504
+ * @param {object} params Params to request signed url
505
+ * @param {array} params.docs the list of documents to get the signed urls
506
+ * @param {string} params.docs.docId Document id
507
+ * @param {string} params.docs.name File name
508
+ * @param {string} params.docs.areaId docAreaId of the document
509
+ * @param {string} params.docs.type mimeType image/png image/jpg others
510
+ * @param {string} params.docs.document Name document to request if method type is get
511
+ * @param {string} params.methodType Method type HTTP get or put
512
+ * @param {string} params.orgId Organization id (_id database)
513
+ * @param {string} session Session, token JWT
514
+ * @return {Promise<object>} doc Returned document data with the signed url
515
+ * @return {string} doc.docId Document id
516
+ * @return {string} doc.name The name of the document, which is the fileName
517
+ * @return {string} doc.areaId docAreaId of the document
518
+ * @return {string} doc.type the document mimi type
519
+ * @return {string} doc.signedUrl the signed URL to upload
520
+ * @public
521
+ * @async
522
+ * @example
523
+ *
524
+ * const API = require('@docbrasil/api-systemmanager');
525
+ * const api = new API();
526
+ * const params - {
527
+ * methodType: 'put',
528
+ * orgId: '5df7f19618430c89a41a19f8'
529
+ * docs: [
530
+ * {
531
+ * docId: '5dadd01dc4af3941d42f8c5c',
532
+ * areaId: '5df7f19618430c89a41a19d2',
533
+ * name: 'Foto.png',
534
+ * type: 'image/png'
535
+ * }
536
+ * ]
537
+ * };
538
+ * const session = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...';
539
+ * // each doc: { docId, name, areaId, type, signedUrl }
540
+ * const { docs } = await api.user.document.signedUrls(params, session);
541
+ *
542
+ * @example
543
+ *
544
+ * const API = require('@docbrasil/api-systemmanager');
545
+ * const api = new API();
546
+ * const params - {
547
+ * methodType: 'get',
548
+ * docs: [
549
+ * { document: 'pinkandthebrain/5df7f19618430c89a41a19d2/5dadd01dc4af3941d42f8c5c/9dadd01dc4af3941d42f6dd4.pdf' }
550
+ * ],
551
+ * };
552
+ * const session = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...';
553
+ * const base64Data = await api.user.document.signedUrls(params, session);
554
+ */
555
+ async signedUrls(params, session) {
556
+ const self = this;
557
+
558
+ try {
559
+ Joi.assert(params, Joi.object().required());
560
+ Joi.assert(params.docs, Joi.array().required());
561
+ Joi.assert(params.orgId, Joi.string().required());
562
+ Joi.assert(session, Joi.string().required());
563
+
564
+ const {orgId, methodType = 'put', docs = []} = params;
565
+ const apiCall = self._client
566
+ .post(`/organizations/${orgId}/documents/getDocumentSignedUrl/${methodType}`, { docs }, self._setHeader(session));
567
+
568
+ return self._returnData(await apiCall);
569
+ } catch (ex) {
570
+ throw ex;
571
+ }
572
+ }
573
+
574
+ /**
575
+ * Uploads the file
576
+ * @param {object} params Params to upload document
577
+ * @param {buffer} params.content The content of the file (Buffer)
578
+ * @param {string} params.signedUrl The signed URL
579
+ * @param {string} params.type The file mime type
580
+ * @param {string} params.onUploadProgress A callback for the upload progress. It will return a progressEvent.
581
+ * @return {Promise<boolean>} True if success
582
+ *
583
+ * @public
584
+ * @async
585
+ * @example
586
+ *
587
+ * const FS = require('fs');
588
+ * const Path = require('path');
589
+ * const API = require('@docbrasil/api-systemmanager');
590
+ * const api = new API();
591
+ * const params - {
592
+ * content: FS.readFileSync(Path.join(__dirname, '.mypdf.pdf')),
593
+ * signedUrl: 'https://signedurl.com/token...',
594
+ * type: 'application/pdf'
595
+ * };
596
+ * const retData = await api.user.document.uploadSignedDocument(params);
597
+ *
598
+ * onUploadProgress return the progressEvent
599
+ * - lengthComputable: A Boolean that indicates whether or not the total number of bytes is known.
600
+ * - loaded: The number of bytes of the file that have been uploaded.
601
+ * - total: The total number of bytes in the file.
602
+ */
603
+ async uploadSignedDocument(params= {}) {
604
+ const { content, signedUrl, type } = params;
605
+ Joi.assert(params, Joi.object().required());
606
+ Joi.assert(params.content, Joi.required());
607
+ Joi.assert(params.signedUrl, Joi.string().required());
608
+ Joi.assert(params.type, Joi.string().required());
609
+
610
+ const self = this;
611
+ const reqOpts = {
612
+ headers: {
613
+ 'Content-Type': type
614
+ },
615
+ maxContentLength: Infinity,
616
+ maxBodyLength: Infinity
617
+ };
618
+
619
+ const onUploadProgress = params.onUploadProgress;
620
+
621
+ if(onUploadProgress) {
622
+ reqOpts.onUploadProgress = onUploadProgress;
623
+ }
624
+
625
+ const apiCall = self._client
626
+ .put(signedUrl, content, reqOpts);
627
+ self._returnData(await apiCall);
628
+ return true;
629
+ }
630
+
631
+ /**
632
+ * @author CloudBrasil <abernardo.br@gmail.com>
633
+ * Checks if a document can be added and it does not repeat its primary key
634
+ * @param params
635
+ * @param params.orgId {string} the organization id
636
+ * @param params.docTypeId {string} the id of the doc type
637
+ * @param params.docs {array<object>} an array of documents
638
+ * @param params.docs.id {string} an unique id representing the document
639
+ * @param params.docs.docTypeFields {object} thje docTypeFields of the document
640
+ * @param params.docs.docTypeFieldsData {object} thje docTypeFieldsData of the document
641
+ * @param session
642
+ * @return {Promise<array>} Return the array of the documents that are repeated. If not document is repeaded, then if returns an empty array.
643
+ * @return id {array<string>} the id of the repeated document
644
+ * @public
645
+ * @async
646
+ * @example
647
+ *
648
+ * const API = require('@docbrasil/api-systemmanager');
649
+ * const api = new API();
650
+ * const docTypeFields = [...]; // the doc type fields array
651
+ * const docTypeFieldsData = {...}; // the data of this fields
652
+ * const params - {
653
+ * docs: [{ id: '5dadd01dc4af3941d42f8c5c', docTypeFields, docTypeFieldsData }],
654
+ * orgId: '5df7f19618430c89a41a19d2',
655
+ * docTypeId: '5df7f19618430c89a41a19d5',
656
+ * };
657
+ * const session = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...';
658
+ * const retDocs = await api.user.document.checkPrimaryKeys(params, session);
659
+ *
660
+ */
661
+ async checkPrimaryKeys(params, session) {
662
+ Joi.assert(params, Joi.object().required().label('params'));
663
+ Joi.assert(params.orgId, Joi.string().required().label('orgId'));
664
+ Joi.assert(params.docTypeId, Joi.string().required().label('docTypeId'));
665
+ Joi.assert(params.docs, Joi.array().required().label('docs'));
666
+ Joi.assert(session, Joi.string().required().label('session'));
667
+
668
+ const { docs = [], orgId = '', docTypeId = '' } = params;
669
+
670
+ if(docs.length === 0) return;
671
+
672
+ try {
673
+ const self = this;
674
+ const payloadToSend = {
675
+ docs,
676
+ docTypeId
677
+ };
678
+ const apiCall = self._client.post(`/organizations/${orgId}/documents/can/add`, payloadToSend, self._setHeader(session));
679
+ return self._returnData(await apiCall);
680
+ } catch (ex) {
681
+ throw ex;
682
+ }
683
+ }
684
+
685
+ /**
686
+ * @author CloudBrasil <abernardo.br@gmail.com>
687
+ * @description Method to search documents for
688
+ * @param {object} params Params to search the documents
689
+ * @param {object} params.query Search documents query
690
+ * @param {object} params.orgId Organization id (_id database)
691
+ * @param {string} session Session, token JWT
692
+ * @returns {promise} returned data from the search
693
+ * @returns {number} count the count of items searched
694
+ * @returns {array<object>} items the items returned from search
695
+ * @returns {number} took the number of documents taken
696
+ * @returns {number} totalCount the total count of all documents
697
+ * @public
698
+ * @example
699
+ *
700
+ * const API = require('@docbrasil/api-systemmanager');
701
+ * const api = new API();
702
+ * const params = {
703
+ * query: {p: 20, i: 1, s: 'Mais recentes', as: '', m: 'w', ai: '57e6a3bd6be6b45210833fae'},
704
+ * orgId: '55e4a3bd6be6b45210833fae',
705
+ * };
706
+ * const session = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...';
707
+ * const retSearch = await api.user.document.searchDocuments(params, session);
708
+ */
709
+ async searchDocuments(params, session) {
710
+ const self = this;
711
+
712
+ try {
713
+ Joi.assert(params, Joi.object().required(), 'Params to search the documents');
714
+ Joi.assert(params.query, Joi.object().required(), 'The query for the search documents');
715
+ Joi.assert(params.orgId, Joi.string().required(), 'Organization id (_id database)');
716
+ Joi.assert(session, Joi.string().required(), 'Session token JWT');
717
+
718
+ const {query, orgId} = params;
719
+ const queryString = encodeURIComponent(JSON.stringify(query));
720
+ const apiCall = self._client
721
+ .get(`/organizations/${orgId}/documents/search?${queryString}`, self._setHeader(session));
722
+
723
+ return self._returnData(await apiCall);
724
+ } catch (ex) {
725
+ throw ex;
726
+ }
727
+ }
728
+
729
+ }
730
+
731
+ export default Documents;