@apia/uploader-controller 5.0.0 → 5.0.1

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 (44) hide show
  1. package/dist/UploaderApi.d.ts +181 -0
  2. package/dist/UploaderApi.d.ts.map +1 -0
  3. package/dist/UploaderApi.js +1268 -0
  4. package/dist/UploaderApi.js.map +1 -0
  5. package/dist/UploaderModalController.d.ts +54 -0
  6. package/dist/UploaderModalController.d.ts.map +1 -0
  7. package/dist/UploaderModalController.js +269 -0
  8. package/dist/UploaderModalController.js.map +1 -0
  9. package/dist/directories/DirectoriesPicker.d.ts +29 -0
  10. package/dist/directories/DirectoriesPicker.d.ts.map +1 -0
  11. package/dist/directories/DirectoriesPicker.js +108 -0
  12. package/dist/directories/DirectoriesPicker.js.map +1 -0
  13. package/dist/directories/FilePicker.d.ts +14 -0
  14. package/dist/directories/FilePicker.d.ts.map +1 -0
  15. package/dist/directories/FilePicker.js +36 -0
  16. package/dist/directories/FilePicker.js.map +1 -0
  17. package/dist/directories/nodes/DirectoryPickerFolderNode.d.ts +16 -0
  18. package/dist/directories/nodes/DirectoryPickerFolderNode.d.ts.map +1 -0
  19. package/dist/directories/nodes/DirectoryPickerFolderNode.js +115 -0
  20. package/dist/directories/nodes/DirectoryPickerFolderNode.js.map +1 -0
  21. package/dist/directories/nodes/DocumentNode.d.ts +11 -0
  22. package/dist/directories/nodes/DocumentNode.d.ts.map +1 -0
  23. package/dist/directories/nodes/DocumentNode.js +16 -0
  24. package/dist/directories/nodes/DocumentNode.js.map +1 -0
  25. package/dist/directories/nodes/FilePickerFolderNode.d.ts +12 -0
  26. package/dist/directories/nodes/FilePickerFolderNode.d.ts.map +1 -0
  27. package/dist/directories/nodes/FilePickerFolderNode.js +91 -0
  28. package/dist/directories/nodes/FilePickerFolderNode.js.map +1 -0
  29. package/dist/directories/types.d.ts +57 -0
  30. package/dist/directories/types.d.ts.map +1 -0
  31. package/dist/directories/utils.d.ts +17 -0
  32. package/dist/directories/utils.d.ts.map +1 -0
  33. package/dist/directories/utils.js +17 -0
  34. package/dist/directories/utils.js.map +1 -0
  35. package/dist/index.d.ts +11 -616
  36. package/dist/index.js +9 -1868
  37. package/dist/index.js.map +1 -1
  38. package/dist/types.d.ts +285 -0
  39. package/dist/types.d.ts.map +1 -0
  40. package/dist/util.d.ts +6 -0
  41. package/dist/util.d.ts.map +1 -0
  42. package/dist/util.js +25 -0
  43. package/dist/util.js.map +1 -0
  44. package/package.json +6 -5
package/dist/index.js CHANGED
@@ -1,1869 +1,10 @@
1
- import { arrayOrArray, getLabel, toBoolean, EventEmitter, downloadUrl, addBoundary, formatMessage, parseAsSize } from '@apia/util';
2
- import { makeObservable, observable } from 'mobx';
3
- import { MobXTreeNode, MobXTree } from '@apia/tree2-controller';
4
- import { uniqueId } from 'lodash-es';
5
- import { ApiaApi } from '@apia/api2';
6
- import QueryString from 'qs';
7
-
8
- const DirectoryPickerActions = {
9
- ajaxUrl: (api) => api.context.URL_REQUEST_AJAX,
10
- loadFolderStructure: "loadFolderStructure",
11
- loadFilesForFolder: "loadFilesForFolder"
12
- };
13
- const FilePickerActions = {
14
- ajaxUrl: "apia.modals.FoldersAction.run",
15
- loadFileSystemStructureTree: "loadFileSystemStructureTree",
16
- loadFilesForFolder: "loadFilesForFolder",
17
- loadFolderStructure: "loadFolderStructure"
18
- };
19
- function makeId(str) {
20
- return str.replaceAll(/\W/g, "_");
21
- }
22
-
23
- class DocumentNode extends MobXTreeNode {
24
- constructor(parent, { parentId, id, ...props }) {
25
- const renderers = parent.tree.api.modalConfig.renderers;
26
- super(id ?? uniqueId("filepickertree"), parent, {
27
- icon: renderers.FileIconRenderer,
28
- isLeaf: true,
29
- ...props
30
- });
31
- }
32
- }
33
-
34
- var __defProp$3 = Object.defineProperty;
35
- var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
36
- var __publicField$3 = (obj, key, value) => {
37
- __defNormalProp$3(obj, typeof key !== "symbol" ? key + "" : key, value);
38
- return value;
39
- };
40
- class DirectoryPickerFolderNode extends MobXTreeNode {
41
- constructor(parent, { parentId, id, ...props }) {
42
- const renderers = parent.tree.api.props.modalConfig.renderers;
43
- super(id ?? uniqueId("filepickertree"), parent, {
44
- asyncNode: true,
45
- icon: props.nodeProps?.canWrite === false ? renderers.LockedFolderIconRenderer : renderers.FolderIconRenderer,
46
- isSelectable: props.nodeProps?.canWrite !== false,
47
- ...props
48
- });
49
- __publicField$3(this, "loadMoreDocsNode", null);
50
- __publicField$3(this, "isLoadingMore", false);
51
- makeObservable(this, {
52
- isLoadingMore: observable
53
- });
54
- }
55
- removeLoadMoreDocsNode() {
56
- this.loadMoreDocsNode?.remove();
57
- this.loadMoreDocsNode = null;
58
- }
59
- getTree() {
60
- return this.tree;
61
- }
62
- async loadMore(focus = true) {
63
- const res = await ApiaApi.post(
64
- this.getTree().api.context,
65
- {
66
- ajaxUrl: DirectoryPickerActions.ajaxUrl(this.getTree().api),
67
- action: DirectoryPickerActions.loadFolderStructure,
68
- preventAsXmlParameter: true,
69
- isAjax: true
70
- },
71
- {
72
- postData: {
73
- txtFld: this.state.nodeProps.id,
74
- loadFolders: true,
75
- until: this.id
76
- },
77
- postDataTreatement: "stringify",
78
- postDataStringifyOptions: {
79
- arrayFormat: "repeat"
80
- }
81
- }
82
- );
83
- if (res?.data) {
84
- this.removeLoadMoreDocsNode();
85
- const lastNode = this.getChildren()[this.getChildren().length - 1];
86
- arrayOrArray(res.data.folder).forEach((folder) => {
87
- if (!this.state.children.has(folder.id)) {
88
- this.getTree().createFolder({
89
- id: makeId(folder.id),
90
- label: folder.name,
91
- nodeProps: folder,
92
- parentId: this.id
93
- });
94
- }
95
- });
96
- arrayOrArray(res.data.documents?.document).forEach((document) => {
97
- if (!this.state.children.has(document.id)) {
98
- this.getTree().createDocument({
99
- id: makeId(document.id),
100
- label: document.name,
101
- nodeProps: document,
102
- parentId: this.id
103
- });
104
- }
105
- });
106
- if ((res?.data.documents?.documentInfo?.moreDocs ?? 0) > 0) {
107
- this.loadMoreDocsNode = this.getTree().createFolder({
108
- asyncNode: false,
109
- icon: void 0,
110
- isLeaf: true,
111
- label: getLabel("lblShwMoreEls").text,
112
- labelRenderer: this.getTree().renderers.LoadMoreRenderer,
113
- onClick: async () => {
114
- if (this.loadMoreDocsNode) {
115
- this.loadMoreDocsNode.state.nodeProps.isLoadingMore = true;
116
- }
117
- await this.loadMore();
118
- },
119
- parentId: this.id
120
- });
121
- if (focus) {
122
- this.tree.focusNode(this.loadMoreDocsNode);
123
- }
124
- } else {
125
- if (focus) {
126
- this.tree.focusNode(lastNode.getFollowingSibling() ?? lastNode);
127
- }
128
- }
129
- }
130
- }
131
- async refresh() {
132
- this.removeAllChildren();
133
- this.loadMoreDocsNode = null;
134
- const res = this.loadMore(false);
135
- this.tree.focusNode(this.getFirstChildren(true) ?? this);
136
- return res;
137
- }
138
- }
139
-
140
- var __defProp$2 = Object.defineProperty;
141
- var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
142
- var __publicField$2 = (obj, key, value) => {
143
- __defNormalProp$2(obj, typeof key !== "symbol" ? key + "" : key, value);
144
- return value;
145
- };
146
- class DirectoriesPicker extends MobXTree {
147
- constructor(api) {
148
- super({
149
- className: "FilePickerTree",
150
- isMultiple: false
151
- });
152
- this.api = api;
153
- __publicField$2(this, "isLoading", true);
154
- __publicField$2(this, "renderers");
155
- this.state.disableSelection = false;
156
- setTimeout(() => {
157
- this.initialLoad();
158
- }, 0);
159
- this.renderers = api.props.modalConfig.renderers;
160
- makeObservable(this, { isLoading: observable });
161
- }
162
- createDocument(nodeProps) {
163
- let parentNode = this.getNodeById(nodeProps.parentId);
164
- if (!parentNode) {
165
- console.warn("Cannot find parent node with id = ", nodeProps.parentId);
166
- parentNode = this;
167
- }
168
- const newNode = new DocumentNode(this, nodeProps);
169
- parentNode.append(newNode);
170
- return newNode;
171
- }
172
- createFolder(nodeProps) {
173
- let parentNode = this.getNodeById(nodeProps.parentId);
174
- if (!parentNode) {
175
- console.warn("Cannot find parent node with id = ", nodeProps.parentId);
176
- parentNode = this;
177
- }
178
- const newNode = this.getNodeHandler(nodeProps);
179
- parentNode.append(newNode);
180
- return newNode;
181
- }
182
- async initialLoad() {
183
- this.state.onLoadData = async (node) => {
184
- await node.refresh();
185
- };
186
- const res = await ApiaApi.post(
187
- this.api.context,
188
- this.getFolderStructureParams()
189
- );
190
- if (res?.data) {
191
- const foldersArray = this.parseStructureResponse(res);
192
- let selected = "";
193
- foldersArray?.forEach((folder) => {
194
- const newNode = this.createFolder({
195
- asyncNode: true,
196
- id: makeId(folder.id),
197
- label: folder.name,
198
- nodeProps: folder,
199
- parentId: folder.parent || "root"
200
- });
201
- if (folder.parent) {
202
- newNode.parent.expand();
203
- }
204
- if (folder.selectedFolder) {
205
- selected = makeId(folder.id);
206
- }
207
- if (String(this.api.props.modalConfig.defaultDirectory) === String(newNode.id)) {
208
- newNode.tree.setSelectedNodes(/* @__PURE__ */ new Set([newNode]));
209
- }
210
- });
211
- if (selected) {
212
- this.setSelectedNodes(/* @__PURE__ */ new Set([selected]));
213
- }
214
- }
215
- this.isLoading = false;
216
- }
217
- getFolderStructureParams() {
218
- return {
219
- ajaxUrl: DirectoryPickerActions.ajaxUrl(this.api),
220
- action: DirectoryPickerActions.loadFolderStructure,
221
- preventAsXmlParameter: true,
222
- isAjax: true,
223
- isXml: true,
224
- docId: this.api.state.versioningFile?.docId
225
- };
226
- }
227
- getNodeHandler(nodeProps) {
228
- return new DirectoryPickerFolderNode(this, nodeProps);
229
- }
230
- parseStructureResponse(res) {
231
- const castRes = res;
232
- if (castRes?.data?.folder)
233
- return arrayOrArray(castRes.data.folder);
234
- return null;
235
- }
236
- }
237
-
238
- var __defProp$1 = Object.defineProperty;
239
- var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
240
- var __publicField$1 = (obj, key, value) => {
241
- __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
242
- return value;
243
- };
244
- function getFileExtension(fileName) {
245
- const parts = fileName.split(".");
246
- return parts.length > 1 ? parts.pop().toLowerCase() : "";
247
- }
248
- const getInitialState = (context) => Object.freeze({
249
- metadata: {
250
- metadataArray: [],
251
- freeMetadataArray: [],
252
- isFreeMetadata: false
253
- },
254
- fromDirectoryFile: null,
255
- docFolder: void 0,
256
- docPath: void 0,
257
- docExpDate: void 0,
258
- description: "",
259
- isReadonly: false,
260
- permissions: {
261
- pools: [],
262
- users: context.ownerCanUpdate ? [
263
- {
264
- canUpdate: true,
265
- userId: context.currentUserLogin,
266
- userLogin: context.currentUserLogin
267
- }
268
- ] : [],
269
- allowAllType: context.everyoneCanUpdate !== false ? "M" : ""
270
- },
271
- fileReqError: false
272
- });
273
- class UploaderModalController {
274
- constructor(api, modalConfig, conf) {
275
- this.api = api;
276
- this.modalConfig = modalConfig;
277
- this.conf = conf;
278
- __publicField$1(this, "directories", null);
279
- __publicField$1(this, "state");
280
- makeObservable(this, {
281
- state: observable
282
- });
283
- this.state = getInitialState(api.props.context);
284
- if (modalConfig.showDirectoriesStructure) {
285
- if (!api.props.modalConfig.renderers) {
286
- throw new Error("If showDirectories is set, renderers are required");
287
- }
288
- this.directories = new DirectoriesPicker(this.api);
289
- }
290
- }
291
- get allMetadata() {
292
- return [
293
- ...this.state.metadata.metadataArray,
294
- ...this.state.metadata.freeMetadataArray
295
- ];
296
- }
297
- get allowAllType() {
298
- return this.state.permissions.allowAllType;
299
- }
300
- get description() {
301
- return this.state.description;
302
- }
303
- get docFolder() {
304
- return this.state.docFolder;
305
- }
306
- get docExpDate() {
307
- return this.state.docExpDate;
308
- }
309
- get docTypes() {
310
- return this.api.getDocTypes();
311
- }
312
- get freeMetadata() {
313
- return this.state.metadata.freeMetadataArray;
314
- }
315
- get exitingFiles() {
316
- return this.api.getExistingFiles();
317
- }
318
- get inProgressFiles() {
319
- return this.api.getInProgressFiles();
320
- }
321
- get hiddenFiles() {
322
- return this.api.getHiddenFiles();
323
- }
324
- get progress() {
325
- return this.api.getProgress();
326
- }
327
- get metadata() {
328
- return this.state.metadata.metadataArray;
329
- }
330
- get selectedDocTypeId() {
331
- return this.api.getCurrentDocTypeId();
332
- }
333
- get selectedDocType() {
334
- return this.api.getCurrentDocType();
335
- }
336
- addMetadata() {
337
- this.state.metadata.freeMetadataArray.push({
338
- free: "Y",
339
- id: String(Math.random()),
340
- name: "",
341
- required: "Y",
342
- title: "",
343
- type: "S",
344
- value: "",
345
- errorMessage: "",
346
- labelErrorMessage: ""
347
- });
348
- }
349
- addFiles(files) {
350
- this.state.fileReqError = false;
351
- this.state.isReadonly = false;
352
- this.api.saveDroppedFiles(files, this.conf);
353
- }
354
- addDirectoryFile(file) {
355
- this.state.fileReqError = false;
356
- this.api.state.inProgressFiles = [];
357
- this.state.fromDirectoryFile = file;
358
- }
359
- async changeDocType(docTypeId) {
360
- this.resetMetadata();
361
- this.api.setCurrentDocTypeId(docTypeId);
362
- this.onChangeExtension();
363
- this.api.reloadMetadata({ docTypeId });
364
- }
365
- clearDirectoryFile() {
366
- this.state.fromDirectoryFile = null;
367
- this.state.isReadonly = false;
368
- }
369
- clearFile(name) {
370
- this.api.clearFile(name);
371
- }
372
- clearFiles() {
373
- this.api.clearFiles();
374
- }
375
- clearState() {
376
- this.state = getInitialState(this.api.props.context);
377
- this.api.clearState();
378
- }
379
- clearPartialState() {
380
- if (this.api.state.inProgressFiles.length === 0) {
381
- this.state = getInitialState(this.api.props.context);
382
- }
383
- }
384
- onCloseModal() {
385
- this.clearState();
386
- }
387
- async confirm() {
388
- let isValid = this.validate();
389
- if (isValid)
390
- isValid = await this.api.confirmDropModal(this.conf);
391
- return isValid;
392
- }
393
- deleteMetadata(indices) {
394
- const deleteSet = new Set(indices);
395
- const offset = this.state.metadata.metadataArray.length;
396
- this.state.metadata.freeMetadataArray = this.state.metadata.freeMetadataArray.filter(
397
- (_, localIndex) => (
398
- // conservamos sólo los que NO estén en deleteSet
399
- !deleteSet.has(localIndex + offset)
400
- )
401
- );
402
- }
403
- deletePermission(item) {
404
- if (item && "userId" in item) {
405
- this.state.permissions.users = this.state.permissions.users.filter(
406
- (c) => c.userId !== item.userId
407
- );
408
- } else {
409
- this.state.permissions.pools = this.state.permissions.pools.filter(
410
- (c) => c.poolId !== item.poolId
411
- );
412
- }
413
- }
414
- onChangeExtension() {
415
- const rawDocExts = this.api.getCurrentDocType()?.docExts || "";
416
- let hideFileNames = "";
417
- const allowedExtensions = rawDocExts.split(";").map((ext) => ext.trim()).filter((ext) => ext !== "");
418
- if (rawDocExts === "") {
419
- const allFiles = [...this.inProgressFiles, ...this.hiddenFiles];
420
- const dedupedFiles = Array.from(
421
- new Map(allFiles.map((file) => [file.name, file])).values()
422
- );
423
- this.api.state.inProgressFiles = dedupedFiles;
424
- this.api.state.hiddenFiles = [];
425
- return;
426
- }
427
- const allowedInProgress = [];
428
- const toHide = [];
429
- this.inProgressFiles.forEach((file) => {
430
- const ext = getFileExtension(file.name);
431
- if (allowedExtensions.includes(ext)) {
432
- allowedInProgress.push(file);
433
- } else {
434
- toHide.push(file);
435
- hideFileNames += ` ${file.name} `;
436
- }
437
- });
438
- const allowedHidden = [];
439
- const stillHidden = [];
440
- this.api.state.hiddenFiles.forEach((file) => {
441
- const ext = getFileExtension(file.name);
442
- if (allowedExtensions.includes(ext)) {
443
- allowedHidden.push(file);
444
- } else {
445
- stillHidden.push(file);
446
- }
447
- });
448
- const combinedInProgress = [...allowedInProgress, ...allowedHidden];
449
- const dedupedInProgress = Array.from(
450
- new Map(
451
- combinedInProgress.map((file) => [file.name, file])
452
- ).values()
453
- );
454
- const combinedHidden = [...toHide, ...stillHidden];
455
- const dedupedHidden = Array.from(
456
- new Map(combinedHidden.map((file) => [file.name, file])).values()
457
- );
458
- this.api.state.inProgressFiles = dedupedInProgress;
459
- this.api.state.hiddenFiles = dedupedHidden;
460
- if (hideFileNames)
461
- this.api.notify({
462
- title: getLabel("msgFileWrngExt").text,
463
- message: hideFileNames,
464
- type: "warning"
465
- });
466
- }
467
- setDescription(desc) {
468
- this.state.description = desc;
469
- }
470
- async resetMetadata() {
471
- this.state.metadata = {
472
- freeMetadataArray: [],
473
- metadataArray: [],
474
- isFreeMetadata: false
475
- };
476
- }
477
- validate() {
478
- let isValid = true;
479
- this.state.fileReqError = false;
480
- if (this.api.getInProgressFiles().length === 0 && !this.state.fromDirectoryFile) {
481
- this.state.fileReqError = true;
482
- isValid = false;
483
- }
484
- this.allMetadata.forEach((c) => {
485
- if (c.free === "Y") {
486
- if (c.title.trim() === "") {
487
- c.labelErrorMessage = getLabel("msgReqField").text;
488
- isValid = false;
489
- }
490
- if (c.value.trim() === "") {
491
- if (!c.errorMessage)
492
- c.errorMessage = getLabel("msgReqField").text;
493
- isValid = false;
494
- }
495
- }
496
- });
497
- return isValid;
498
- }
499
- }
500
-
501
- const parseFileDefinition = (context, fileDefinition, isSignRequired) => {
502
- const { lock, isLocked, lockedBy, userLocking, ...file } = fileDefinition;
503
- return {
504
- ...file,
505
- isLocked: isLocked === "true" || isLocked === true || toBoolean(lock) || file.locked === true,
506
- isLockedByMe: (lockedBy || userLocking) === context.currentUserLogin,
507
- isMarkedToSign: file.markedToSign || toBoolean(file.sign) || isSignRequired,
508
- isVirtual: file.virtualDoc ?? false,
509
- lockingUser: lockedBy || userLocking
510
- };
511
- };
512
-
513
- var __defProp = Object.defineProperty;
514
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
515
- var __publicField = (obj, key, value) => {
516
- __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
517
- return value;
518
- };
519
- class UploaderApi extends EventEmitter {
520
- constructor(props) {
521
- super();
522
- this.props = props;
523
- __publicField(this, "maxFiles", Infinity);
524
- __publicField(this, "modalController", null);
525
- __publicField(this, "langs");
526
- __publicField(this, "currentConfiguration");
527
- __publicField(this, "state", {
528
- progress: 0,
529
- allowedTypes: [],
530
- selectedDocTypeId: "1",
531
- versioningFile: null,
532
- inProgressFiles: [],
533
- files: {},
534
- selectedFiles: [],
535
- hiddenFiles: [],
536
- translatedFiles: /* @__PURE__ */ new Map(),
537
- hasAllDocTypes: false
538
- });
539
- __publicField(this, "getConfirmDropModalMetadataString", ({
540
- metadata
541
- }) => {
542
- return metadata?.filter?.((current) => !!current.value).map((current) => `${current.id}~${current.type}~${current.value}`).join(";") ?? [];
543
- });
544
- __publicField(this, "getConfirmDropModalPermissionsString", ({
545
- poolsPermissions,
546
- usersPermissions
547
- }) => {
548
- let returnString = "";
549
- poolsPermissions.forEach(
550
- (current) => returnString = `${returnString}${returnString.length > 0 ? "&" : ""}docPoolId=${current.poolId}&docPoolName=${current.poolName}&docPermType${current.poolId}=${String(current.canUpdate)}`
551
- );
552
- usersPermissions.forEach(
553
- (current) => returnString = `${returnString}${returnString.length > 0 ? "&" : ""}docUserId=${current.userId}&docUsrLogin=${current.userLogin}&docPermType${current.userId}=${String(current.canUpdate)}`
554
- );
555
- return returnString;
556
- });
557
- __publicField(this, "getConfirmDropModalAdditionalMetadataString", (additionalMetadata) => {
558
- return Object.values(additionalMetadata).filter((current) => !!current?.value).map((current) => `${current.name}~${current.value}`).join(";");
559
- });
560
- __publicField(this, "parseFileDefinition", (file) => {
561
- return {
562
- ...parseFileDefinition(this.props.context, file, false),
563
- canEdit: file.canEdit || file.canWrite,
564
- canRead: file.canRead
565
- };
566
- });
567
- makeObservable(this, {
568
- state: observable
569
- });
570
- this.langs = this.props.context.docLangs;
571
- }
572
- get filesArray() {
573
- return Object.values(this.state.files);
574
- }
575
- get id() {
576
- return this.props.id;
577
- }
578
- get modalConfig() {
579
- return this.props.modalConfig;
580
- }
581
- get context() {
582
- return this.props.context;
583
- }
584
- async init() {
585
- await this.ajaxUploadStart();
586
- await this.reloadMetadata({
587
- docTypeId: this.state.selectedDocTypeId
588
- });
589
- await this.loadCurrentDocuments();
590
- }
591
- buildModalController(conf) {
592
- return new UploaderModalController(this, this.props.modalConfig, conf);
593
- }
594
- async onStartUpload(files) {
595
- if (this.props.modalConfig.oneClickUpload) {
596
- await this.saveDroppedFiles(files ?? []);
597
- } else {
598
- if (files) {
599
- const result = await this.saveDroppedFiles(files ?? []);
600
- if (!result)
601
- return;
602
- }
603
- this.modalController = this.buildModalController();
604
- this.context.openModal();
605
- }
606
- }
607
- async onTranslateUpload(conf, files) {
608
- if (this.props.modalConfig.oneClickUpload) {
609
- await this.saveDroppedFiles(files ?? [], conf);
610
- } else {
611
- await this.init();
612
- let mustOpen = true;
613
- if (files) {
614
- const res = await this.saveDroppedFiles(files ?? [], conf);
615
- if (!res) {
616
- mustOpen = false;
617
- }
618
- }
619
- if (mustOpen) {
620
- this.modalController = this.buildModalController(conf);
621
- this.context.openModal();
622
- }
623
- }
624
- }
625
- async onVersionUpload(file, conf = { newFiles: [] }) {
626
- this.version(file, conf);
627
- }
628
- async autoLock() {
629
- return new Promise((resolve) => {
630
- resolve(false);
631
- });
632
- }
633
- notify(notification) {
634
- this.props.context.notify(notification);
635
- }
636
- getAjaxUrl() {
637
- return this.props.context.URL_REQUEST_AJAX;
638
- }
639
- getDocTypes() {
640
- return this.state.allowedTypes;
641
- }
642
- getCurrentDocTypeId() {
643
- return this.state.selectedDocTypeId;
644
- }
645
- getCurrentDocType() {
646
- return this.state.allowedTypes.find(
647
- (c) => c.id === this.state.selectedDocTypeId
648
- );
649
- }
650
- getInProgressFiles() {
651
- return this.state.inProgressFiles;
652
- }
653
- getHiddenFiles() {
654
- return this.state.hiddenFiles;
655
- }
656
- getExistingFiles() {
657
- return this.state.files;
658
- }
659
- getProgress() {
660
- return this.state.progress;
661
- }
662
- getHasAllDocTypes() {
663
- return this.state.hasAllDocTypes;
664
- }
665
- async getDocumentInfo({
666
- docId: apiId,
667
- downloadDocId: docId
668
- }, newElem) {
669
- const id = apiId ? this.getDocument(apiId).docId : docId;
670
- const result = await ApiaApi.post(
671
- this.context,
672
- this.getDocumentInfoParameters({
673
- action: "getDocumentInfo",
674
- isAjax: true,
675
- docId: id,
676
- newElem,
677
- ajaxUrl: this.getAjaxUrl()
678
- })
679
- );
680
- if (result?.data) {
681
- return result.data;
682
- }
683
- return null;
684
- }
685
- /**
686
- * This method searches for the provided id in several places:
687
- *
688
- * If it's found in the current files, returns it.
689
- * If not, it searches the provided docId in the translations map of each uploaded file.
690
- */
691
- getDocument(docId) {
692
- if (this.state.files[docId]) {
693
- return this.state.files[docId];
694
- } else {
695
- for (const map of this.state.translatedFiles.values()) {
696
- for (const file of map.values()) {
697
- if (file.docId === docId) {
698
- return file;
699
- }
700
- }
701
- }
702
- }
703
- return void 0;
704
- }
705
- updateDocument(docId, newValue) {
706
- if (this.state.files[docId]) {
707
- this.state.files[docId] = { ...this.getDocument(docId), ...newValue };
708
- } else {
709
- this.state.translatedFiles.forEach((innerMap) => {
710
- innerMap.forEach((doc, langKey) => {
711
- if (doc.docId === docId) {
712
- innerMap.set(langKey, { ...doc, ...newValue });
713
- }
714
- });
715
- });
716
- }
717
- }
718
- deleteDocument(docId) {
719
- if (this.state.files[docId]) {
720
- delete this.state.files[docId];
721
- } else {
722
- this.state.translatedFiles.forEach((innerMap) => {
723
- innerMap.forEach((doc, langKey) => {
724
- if (doc.docId === docId) {
725
- innerMap.delete(langKey);
726
- }
727
- });
728
- });
729
- }
730
- }
731
- clearFile(name) {
732
- if (this.modalController) {
733
- this.modalController.state.isReadonly = false;
734
- }
735
- this.state.inProgressFiles = this.state.inProgressFiles.filter(
736
- (c) => c.name !== name
737
- );
738
- }
739
- clearFiles() {
740
- if (this.modalController) {
741
- this.modalController.state.isReadonly = false;
742
- }
743
- this.state.inProgressFiles = [];
744
- this.state.versioningFile = null;
745
- this.state.hiddenFiles = [];
746
- }
747
- clearState() {
748
- if (this.modalController) {
749
- this.modalController.state.isReadonly = false;
750
- }
751
- this.state.selectedDocTypeId = this.getDocTypes().find(
752
- (c) => String(c.id) === "1"
753
- ) ? "1" : this.getDocTypes()[0]?.id;
754
- this.state.inProgressFiles = [];
755
- this.state.versioningFile = null;
756
- }
757
- async checkLockDocument(id, shouldNotifyUnlocked = true) {
758
- if (this.props.context.IN_MONITOR) {
759
- return false;
760
- }
761
- if (Number(id) < 0)
762
- return true;
763
- const file = this.getDocument(id);
764
- const result = await ApiaApi.post(
765
- this.context,
766
- this.getCheckLockDocumentParameters({
767
- action: "checkLockDocument",
768
- docId: file.docId,
769
- ajaxUrl: this.getAjaxUrl()
770
- })
771
- );
772
- const isLocked = result?.data?.success === "ok";
773
- if (!isLocked && result?.data?.usr && result.data.usr !== this.props.context.currentUserLogin) {
774
- this.notify({
775
- message: `${getLabel("msgDocLockedByUsr", {}, this.props.context).text.split(".")[0]}: ${result.data.usr}.`,
776
- type: "warning"
777
- });
778
- return result.data.usr;
779
- }
780
- if (!isLocked && shouldNotifyUnlocked && !await this.autoLock())
781
- this.notify({
782
- message: getLabel("msgDocMustBeLocked", {}, this.props.context).text,
783
- type: "warning"
784
- });
785
- return isLocked;
786
- }
787
- setCurrentDocTypeId(docTypeId) {
788
- this.state.selectedDocTypeId = docTypeId;
789
- }
790
- async ajaxUploadStart(newFiles = []) {
791
- if (this.props.context.IN_MONITOR) {
792
- return;
793
- }
794
- const versioningFile = this.state.versioningFile;
795
- const res = await ApiaApi.post(
796
- this.context,
797
- this.getAjaxUploadStartParameters({
798
- action: "ajaxUploadStart",
799
- isAjax: true,
800
- docId: versioningFile?.docId,
801
- docTypeId: newFiles.length === 1 ? versioningFile?.docTypeId || "1" : "1",
802
- newDoc: !versioningFile,
803
- useDocTypePermitted: false,
804
- ajaxUrl: this.getAjaxUrl()
805
- })
806
- );
807
- if (res?.data) {
808
- const docTypes = arrayOrArray(res?.data?.function?.docTypes?.docType);
809
- const hasGeneric = !!docTypes.find((c) => String(c.id) === "1");
810
- this.state.allowedTypes = docTypes;
811
- this.state.selectedDocTypeId = hasGeneric ? "1" : docTypes[0].id;
812
- if (newFiles.length > 0) {
813
- await this.saveDroppedFiles(newFiles);
814
- }
815
- return res?.data?.function.name === "fncDocumentLoadInformation" ? true : false;
816
- } else {
817
- throw new Error("No files data");
818
- }
819
- }
820
- async reloadMetadata(props, additionalProps) {
821
- if (!this.modalController)
822
- return;
823
- const res = await ApiaApi.post(
824
- this.context,
825
- this.getReloadMetadataParameters({
826
- ajaxUrl: this.getAjaxUrl(),
827
- action: "reloadMetadata",
828
- isAjax: true,
829
- docId: props?.docId,
830
- docTypeId: props?.docTypeId,
831
- metadata: this.getConfirmDropModalMetadataString({
832
- metadata: this.modalController?.allMetadata
833
- }),
834
- ...additionalProps
835
- })
836
- );
837
- if (res?.data && props?.docTypeId) {
838
- const isFreeMetadata = this.state.allowedTypes.find(
839
- (current) => current.id === props.docTypeId
840
- )?.free ?? false;
841
- this.modalController.state.metadata.freeMetadataArray = [];
842
- this.modalController.state.metadata.metadataArray = [];
843
- arrayOrArray(res.data.metadata).forEach((c) => {
844
- if (c.free === "Y") {
845
- this.modalController.state.metadata.freeMetadataArray.push(c);
846
- } else {
847
- this.modalController.state.metadata.metadataArray.push(c);
848
- }
849
- });
850
- this.modalController.state.metadata.isFreeMetadata = isFreeMetadata;
851
- }
852
- }
853
- async saveDroppedFiles(unprocessedFiles, conf) {
854
- if (this.props.context.IN_MONITOR) {
855
- return false;
856
- }
857
- const {
858
- langId,
859
- strictMode: isConfStrictMode = false,
860
- translatingFile
861
- } = conf ?? {};
862
- const isStrictMode = isConfStrictMode || !!this.state.versioningFile || !!this.modalController?.state.fromDirectoryFile;
863
- const docType = this.getCurrentDocTypeId();
864
- if (!isStrictMode && !docType) {
865
- this.notify({
866
- message: `${getLabel("lblDropFileDeleted", {}, this.props.context).text}: ${unprocessedFiles.map((current) => current.name).join(", ")}.`,
867
- type: "warning"
868
- });
869
- return false;
870
- }
871
- const allowedFiles = this.filterAlreadyUploadedFiles(
872
- this.filterByFilesAmountLimit(
873
- this.filterAcceptedFiles(
874
- this.filterExistingFiles(
875
- this.filterVersioningFiles(unprocessedFiles, conf),
876
- conf
877
- ),
878
- true,
879
- docType
880
- )
881
- ),
882
- conf
883
- );
884
- if (allowedFiles.length > 0) {
885
- const formData = new FormData();
886
- allowedFiles.forEach(
887
- (file) => formData.append("fileRepository", file, file.name)
888
- );
889
- await ApiaApi.post(
890
- this.context,
891
- this.getSaveDroppedFilesParameters({
892
- action: "saveDroppedFiles",
893
- docId: this.state.versioningFile?.docId,
894
- ajaxUrl: this.getAjaxUrl(),
895
- frmOut: !this.modalController,
896
- docTypeId: this.state.selectedDocTypeId,
897
- langId
898
- }),
899
- {
900
- postData: formData,
901
- axiosConfig: {
902
- onUploadProgress: (ev) => this.state.progress = ev.loaded * 100 / ((ev.total ?? ev.loaded) * 2)
903
- }
904
- }
905
- );
906
- const ajaxUploadFileStatusParameters = this.getAjaxUploadFileStatusParameters({
907
- action: "ajaxUploadFileStatus",
908
- ajaxUrl: this.getAjaxUrl(),
909
- delayForDrop: true,
910
- isAjax: true
911
- });
912
- let tries = 0;
913
- const checkUploadResult = async () => {
914
- return new Promise(async (resolve) => {
915
- tries += 1;
916
- if (tries === 10) {
917
- this.notify({
918
- message: "Error while checking for uploadFileStatus, too many tries",
919
- type: "error"
920
- });
921
- resolve(false);
922
- return;
923
- }
924
- const response = await ApiaApi.post(
925
- this.context,
926
- ajaxUploadFileStatusParameters
927
- );
928
- if (response && response.data) {
929
- const hasMessages = arrayOrArray(
930
- response.data?.sysMessages?.message ?? response.data?.sysExceptions?.exception ?? response.data?.exceptions?.exception ?? response.data.function.messages?.message
931
- ).length > 0 || !!response.data.function.dropLastMessage;
932
- const uploadMessage = arrayOrArray(
933
- response.data.function.messages?.message
934
- ).find((current) => current.name === "message");
935
- if (uploadMessage)
936
- this.notify({ message: uploadMessage.label, type: "warning" });
937
- const method = response.data?.function.name;
938
- this.state.progress = 44;
939
- if (hasMessages) {
940
- resolve(false);
941
- return;
942
- }
943
- if (method === "fncProceedDocumentProcessing") {
944
- resolve(true);
945
- return;
946
- }
947
- if (tries === 10) {
948
- resolve(method === "fncProceedDocumentProcessing");
949
- }
950
- setTimeout(() => {
951
- checkUploadResult().then(resolve).catch(() => resolve(false));
952
- }, 100);
953
- } else {
954
- resolve(false);
955
- }
956
- });
957
- };
958
- const hasUploadedCorrectly = await checkUploadResult();
959
- this.state.progress = 66;
960
- if (hasUploadedCorrectly) {
961
- const shown = (this.state.inProgressFiles ?? []).map(
962
- (file) => file.name
963
- );
964
- const postData = QueryString.stringify(
965
- this.getProcessDroppedFilesPostdata({
966
- useDocTypePermitted: true,
967
- dropped: allowedFiles.map((file) => file.name).concat(shown),
968
- shown
969
- }),
970
- { arrayFormat: "repeat" }
971
- );
972
- const secondResult = await ApiaApi.post(
973
- this.context,
974
- this.getProcessDroppedFilesParameters({
975
- action: "processDroppedFiles",
976
- docId: this.state.versioningFile?.docId,
977
- frmOut: !this.modalController,
978
- ajaxUrl: this.getAjaxUrl()
979
- }),
980
- {
981
- postData: postData.toString()
982
- }
983
- );
984
- this.state.progress = 83;
985
- if (secondResult?.data?.function?.principal?.docInfo) {
986
- const acceptedByServerFiles = arrayOrArray(
987
- secondResult.data.function?.principal?.docInfo
988
- );
989
- this.state.inProgressFiles = [
990
- ...this.state.inProgressFiles ?? [],
991
- ...acceptedByServerFiles.map(
992
- (current) => [...this.state.inProgressFiles, ...unprocessedFiles].find(
993
- (search) => search.name === current.docInfoName
994
- )
995
- ).filter((current) => !!current)
996
- ];
997
- this.state.progress = 100;
998
- if (this.modalController)
999
- this.modalController.state.fromDirectoryFile = null;
1000
- this.notify({
1001
- type: "success",
1002
- message: getLabel(
1003
- "lblFileUploadedSuccessfully",
1004
- {},
1005
- this.props.context
1006
- ).text
1007
- });
1008
- if (this.props.modalConfig.oneClickUpload) {
1009
- if (langId && translatingFile)
1010
- void this.confirmDropModal({ langId, translatingFile });
1011
- else
1012
- void this.confirmDropModal();
1013
- }
1014
- }
1015
- }
1016
- this.state.progress = 100;
1017
- return true;
1018
- } else {
1019
- return false;
1020
- }
1021
- }
1022
- async checkWebDavLock(docId) {
1023
- if (this.props.context.IN_MONITOR) {
1024
- return false;
1025
- }
1026
- if (Number.parseInt(docId) < 0) {
1027
- return true;
1028
- }
1029
- return new Promise((resolve) => {
1030
- let tries = 10;
1031
- const checkLockAction = async () => {
1032
- const isLocked = await ApiaApi.post(
1033
- this.context,
1034
- this.getCheckWebDavLockParameters({
1035
- action: "isWebDavDocumentLocked",
1036
- docId,
1037
- ajaxUrl: this.props.context.URL_REQUEST_AJAX
1038
- })
1039
- );
1040
- if (isLocked?.data?.locked === true || isLocked?.data?.locked === void 0) {
1041
- if (--tries > 0) {
1042
- setTimeout(() => void checkLockAction(), 1e3);
1043
- } else {
1044
- this.notify({
1045
- message: getLabel("msgFailSyncDocument", {}, this.props.context).text
1046
- });
1047
- resolve(false);
1048
- }
1049
- } else {
1050
- resolve(true);
1051
- }
1052
- };
1053
- void checkLockAction();
1054
- });
1055
- }
1056
- async checkSignature(file) {
1057
- let res = null;
1058
- if (Number(file.docId) >= 0)
1059
- res = await ApiaApi.get(
1060
- this.context,
1061
- this.getCheckSignatureParameters({
1062
- action: "viewDocSigns",
1063
- docId: file.docId,
1064
- lock: false,
1065
- isAjax: true,
1066
- react: true
1067
- })
1068
- );
1069
- return res;
1070
- }
1071
- async editDocument(id) {
1072
- if (this.props.context.IN_MONITOR) {
1073
- return;
1074
- }
1075
- const file = this.getDocument(id);
1076
- if (await this.checkLockDocument(file.docId) === true) {
1077
- const result = await ApiaApi.post(
1078
- this.context,
1079
- this.getEditDocumentParameters({
1080
- action: "updateWebDavDocument",
1081
- docId: file.docId,
1082
- isAjax: true
1083
- })
1084
- );
1085
- if (result?.data?.folderId) {
1086
- const sDocumentUrl = `${this.props.context.WEBDAV_SERVER}${result?.data?.folderId}/${file.docId}/${file.name || file.docName || ""}`;
1087
- const ProtocolInstallMessage = () => {
1088
- this.notify({
1089
- type: "warning",
1090
- message: getLabel("msgNoDocEditProtocol", {}, this.props.context).text,
1091
- title: getLabel("lblEdit", {}, this.props.context).text
1092
- });
1093
- };
1094
- this.props.context.ITHit.WebDAV.Client.DavConstants.ProtocolTimeoutMs = 1e4;
1095
- await this.props.context.ITHit.WebDAV.Client.DocManager.DavProtocolEditDocument(
1096
- sDocumentUrl,
1097
- this.props.context.WEBDAV_SERVER,
1098
- ProtocolInstallMessage,
1099
- null,
1100
- "Current",
1101
- "ApiaWebDavCookie",
1102
- // Cookie(s) to copy.
1103
- "",
1104
- // URL to navigate to if any cookie from the list is not found.
1105
- "Edit"
1106
- );
1107
- }
1108
- }
1109
- }
1110
- async downloadVersion(fileId, version) {
1111
- const file = this.getDocument(fileId);
1112
- if (!file)
1113
- return;
1114
- if (Number.parseInt(fileId) < 0 || this.props.context.IN_MONITOR || await this.checkWebDavLock(file.docId))
1115
- await downloadUrl(
1116
- ApiaApi.makeUrl(this.context, {
1117
- action: "downloadDocument",
1118
- docId: file.downloadDocId,
1119
- version
1120
- })
1121
- );
1122
- }
1123
- async downloadDocument(id, version) {
1124
- const file = this.getDocument(id);
1125
- if (Number.parseInt(id) < 0 || this.props.context.IN_MONITOR || await this.checkWebDavLock(file.docId)) {
1126
- await downloadUrl(
1127
- ApiaApi.makeUrl(this.context, {
1128
- action: "downloadDocument",
1129
- docId: file.downloadDocId,
1130
- ajaxUrl: this.getAjaxUrl(),
1131
- version
1132
- })
1133
- );
1134
- }
1135
- }
1136
- async ajaxDeleteDocument(id, langId) {
1137
- const file = this.getDocument(id);
1138
- const isLocked = await this.checkLockDocument(file.docId);
1139
- if (isLocked === true) {
1140
- const result = await ApiaApi.post(
1141
- this.context,
1142
- this.getDeleteDocumentParameters({
1143
- action: "ajaxRemoveDocument",
1144
- docId: file.docId,
1145
- isAjax: true,
1146
- ajaxUrl: this.getAjaxUrl(),
1147
- langId
1148
- })
1149
- );
1150
- if (this.evaluateDeleteDocumentResult(result?.data))
1151
- this.deleteDocument(id);
1152
- }
1153
- }
1154
- async version(file, conf = { newFiles: [] }) {
1155
- const checkLock = await this.checkLockDocument(file.docId, true);
1156
- const isLocked = await this.checkWebDavLock(file.docId);
1157
- if (!(checkLock === true && isLocked))
1158
- return;
1159
- this.state.versioningFile = file;
1160
- const openVersionModal = () => {
1161
- if (!this.props.modalConfig.oneClickUpload) {
1162
- this.modalController = this.buildModalController({
1163
- versionFile: file
1164
- });
1165
- this.context.openModal();
1166
- }
1167
- };
1168
- if (!conf.newFiles || conf.newFiles.length === 0) {
1169
- openVersionModal();
1170
- }
1171
- await this.ajaxUploadStart();
1172
- if (file.docTypeId)
1173
- this.state.selectedDocTypeId = file.docTypeId;
1174
- await this.versionFileInfo(file);
1175
- const hasNewFiles = !!(conf.newFiles && conf.newFiles.length > 0);
1176
- if (hasNewFiles) {
1177
- const res = await this.saveDroppedFiles(conf.newFiles, {
1178
- langId: conf.langId,
1179
- translatingFile: conf.translatingFile,
1180
- shouldReset: false,
1181
- strictMode: true
1182
- });
1183
- if (res) {
1184
- openVersionModal();
1185
- }
1186
- } else {
1187
- await this.reloadMetadata({
1188
- docId: file.docId,
1189
- docTypeId: file.docTypeId
1190
- });
1191
- }
1192
- }
1193
- async versionFileInfo(file) {
1194
- const documentInfo = await this.getDocumentInfo({ docId: file.docId });
1195
- if (documentInfo?.function) {
1196
- const {
1197
- data: { general },
1198
- metadatas
1199
- } = documentInfo.function;
1200
- const isFreeMetadata = this.state.allowedTypes.find((current) => current.id === file.docTypeId)?.free ?? false;
1201
- if (this.modalController) {
1202
- this.modalController.state = {
1203
- description: general.docDesc,
1204
- docFolder: general.docFolder === "" ? void 0 : Number(general.docFolder),
1205
- docPath: general.docFolderPath,
1206
- permissions: {
1207
- allowAllType: general.docAllPoolPerm,
1208
- users: arrayOrArray(
1209
- documentInfo.function.data.permissions?.user
1210
- ).map((current) => {
1211
- const returnObject = {
1212
- canUpdate: current.permType === "M",
1213
- userId: current.id,
1214
- userLogin: current.name
1215
- };
1216
- return returnObject;
1217
- }),
1218
- pools: arrayOrArray(
1219
- documentInfo.function.data.permissions?.pool
1220
- ).map((current) => {
1221
- const returnObject = {
1222
- canUpdate: current.permType === "M",
1223
- poolId: current.id,
1224
- poolName: current.name
1225
- };
1226
- return returnObject;
1227
- })
1228
- },
1229
- docExpDate: general.docExpDate,
1230
- fileReqError: false,
1231
- fromDirectoryFile: null,
1232
- metadata: {
1233
- metadataArray: arrayOrArray(metadatas?.metadata),
1234
- freeMetadataArray: [],
1235
- isFreeMetadata
1236
- }
1237
- };
1238
- }
1239
- }
1240
- }
1241
- async pickFileById(id) {
1242
- const documentInfo = await this.getDocumentInfo(
1243
- { downloadDocId: id },
1244
- true
1245
- );
1246
- if (documentInfo) {
1247
- const document = documentInfo.function.data.general;
1248
- const { permissions } = documentInfo.function.data;
1249
- if (this.modalController) {
1250
- this.setCurrentDocTypeId(document.docTypeId);
1251
- this.modalController.addDirectoryFile(document);
1252
- this.modalController.state.description = document.docDesc;
1253
- this.modalController.state.docExpDate = document.docExpDate;
1254
- this.modalController.state.permissions = {
1255
- pools: arrayOrArray(permissions?.pool).map((c) => {
1256
- return {
1257
- poolId: c.id,
1258
- poolName: c.name,
1259
- canUpdate: c.permType === "M"
1260
- };
1261
- }),
1262
- users: [
1263
- ...arrayOrArray(permissions?.user).map((c) => {
1264
- return {
1265
- userId: c.id,
1266
- userLogin: c.name,
1267
- canUpdate: c.permType === "M"
1268
- };
1269
- })
1270
- ],
1271
- allowAllType: document.docAllPoolPerm
1272
- };
1273
- this.modalController.changeDocType(document.docTypeId);
1274
- this.modalController.state.isReadonly = !documentInfo.function.currentUsrPems.usrCanModify;
1275
- }
1276
- void this.reloadMetadata(
1277
- { docId: document.docId, docTypeId: document.docTypeId },
1278
- {
1279
- docReuse: true
1280
- }
1281
- );
1282
- }
1283
- }
1284
- async markFileToSign(id, langId) {
1285
- if (this.props.context.IN_MONITOR) {
1286
- return;
1287
- }
1288
- const file = this.getDocument(id);
1289
- if (await this.checkLockDocument(file.docId) === true) {
1290
- const marked = await ApiaApi.post(
1291
- this.context,
1292
- this.getMarkFileToSignParameters({
1293
- action: "markDocTosign",
1294
- docId: file.docId,
1295
- isAjax: true,
1296
- ajaxUrl: this.getAjaxUrl(),
1297
- langId
1298
- })
1299
- );
1300
- if (marked?.data?.markedToSign !== void 0) {
1301
- if (this.state.files[id]) {
1302
- this.state.files[id].markedToSign = marked.data.markedToSign;
1303
- } else {
1304
- this.state.translatedFiles.forEach((innerMap) => {
1305
- innerMap.forEach((doc, langKey) => {
1306
- if (doc.docId === id) {
1307
- innerMap.set(langKey, {
1308
- ...doc,
1309
- markedToSign: marked?.data?.markedToSign ?? false
1310
- });
1311
- }
1312
- });
1313
- });
1314
- }
1315
- }
1316
- }
1317
- }
1318
- /**
1319
- * Por el momento realiza la descarga de todos los archivos
1320
- * que estén subidos.
1321
- */
1322
- downloadMultipleDocuments() {
1323
- const files = this.filesArray;
1324
- if (files.length === 0)
1325
- return;
1326
- const docIds = this.state.selectedFiles;
1327
- const selectedFiles = files.filter(
1328
- (current) => docIds.find((search) => search === current.docId)
1329
- );
1330
- const ids = (selectedFiles.length > 0 ? selectedFiles : files).map((current) => current.downloadDocId).join("-");
1331
- void downloadUrl(
1332
- ApiaApi.makeUrl(
1333
- this.context,
1334
- this.getDownloadMultipleDocumentsParameters({
1335
- action: "multipleDownload",
1336
- docId: ids
1337
- })
1338
- ),
1339
- "documents.zip"
1340
- );
1341
- }
1342
- async confirmDropModal(conf) {
1343
- if (this.props.context.IN_MONITOR) {
1344
- return false;
1345
- }
1346
- const { langId, translatingFile } = conf ?? {};
1347
- const cmbDocType = this.state.selectedDocTypeId;
1348
- const fromDirectoryFile = this.modalController?.state.fromDirectoryFile;
1349
- const docDesc = this.modalController?.description ?? "";
1350
- const docAllowAllType = this.props.modalConfig.oneClickUpload ? "M" : this.modalController?.allowAllType ?? "";
1351
- const docFolder = this.modalController?.docFolder;
1352
- const docExpDate = this.modalController?.docExpDate;
1353
- const metadata = this.modalController?.metadata ?? [];
1354
- const freeMetadata = this.modalController?.freeMetadata ?? [];
1355
- const poolsPermissions = this.modalController?.state.permissions.pools ?? [];
1356
- const usersPermissions = this.modalController?.state.permissions.users ?? [];
1357
- let postData = QueryString.stringify(
1358
- this.getConfirmDropModalPostdata({
1359
- cmbDocType,
1360
- docDesc,
1361
- docAllowAllType,
1362
- dropped: this.state.inProgressFiles.map((file) => file.name),
1363
- txtLangId: langId,
1364
- txtLangGroup: translatingFile?.docLangGroup,
1365
- docFolder
1366
- }),
1367
- { arrayFormat: "repeat" }
1368
- );
1369
- postData = `${postData}${postData.length > 0 ? "&" : ""}${this.getConfirmDropModalPermissionsString({
1370
- poolsPermissions,
1371
- usersPermissions
1372
- })}&txtFreeMetadata=${this.getConfirmDropModalAdditionalMetadataString(
1373
- freeMetadata
1374
- )}&txtMetadata=${this.getConfirmDropModalMetadataString({
1375
- metadata: Object.values(metadata || {})
1376
- })}&docExpDate=${docExpDate ?? ""}`;
1377
- const result = await ApiaApi.post(
1378
- this.context,
1379
- this.getConfirmDropModalParameters({
1380
- ajaxUrl: this.getAjaxUrl(),
1381
- docId: fromDirectoryFile ? fromDirectoryFile.docId : this.state.versioningFile?.docId,
1382
- action: fromDirectoryFile ? "associateExistingFile" : "confirmDropModal",
1383
- fromForm: true,
1384
- ...fromDirectoryFile ? {
1385
- docId: fromDirectoryFile.docId,
1386
- fromReuse: true,
1387
- uploadDocument: false
1388
- } : null
1389
- }),
1390
- {
1391
- postData: postData.toString()
1392
- }
1393
- );
1394
- if (result?.data?.function) {
1395
- const currentFiles = { ...this.state.files };
1396
- const versioningFile = this.state.versioningFile;
1397
- if (versioningFile && versioningFile.name) {
1398
- delete currentFiles[versioningFile.name];
1399
- }
1400
- const newFiles = arrayOrArray(
1401
- result.data.function.general
1402
- ).map(
1403
- (current) => this.parseFileDefinition({
1404
- ...current,
1405
- canWrite: true,
1406
- canRead: true,
1407
- canEdit: true
1408
- })
1409
- ).filter((current) => !currentFiles[current.docId]).reduce((acc, current) => ({ ...acc, [current.docId]: current }), {});
1410
- if (langId && translatingFile) {
1411
- const firstFile = Object.values(newFiles)[0];
1412
- this.setTranslationFile(firstFile, translatingFile.docId, langId);
1413
- } else {
1414
- this.state.files = { ...currentFiles, ...newFiles };
1415
- }
1416
- this.clearFiles();
1417
- this.emit("fileUploaded", null);
1418
- return true;
1419
- }
1420
- return false;
1421
- }
1422
- getLoadCurrentDocumentsParameters(params) {
1423
- return params;
1424
- }
1425
- async loadCurrentDocuments() {
1426
- const result = await ApiaApi.post(
1427
- this.context,
1428
- this.getLoadCurrentDocumentsParameters({
1429
- ajaxUrl: this.getAjaxUrl(),
1430
- action: "ajaxLoadCurrent",
1431
- isAjax: true,
1432
- readOnly: this.props.context.readonly,
1433
- allowLock: true,
1434
- allowSign: true,
1435
- allowMultiple: true
1436
- }),
1437
- {}
1438
- );
1439
- if (result && result.data) {
1440
- const currentConfiguration = arrayOrArray(result.data.function.messages.message).reduce(
1441
- (prev, { name, label }) => ({ ...prev, [name]: Boolean(label) }),
1442
- {}
1443
- );
1444
- const currentFiles = result.data.function.general ? arrayOrArray(result.data.function.general).map(
1445
- this.parseFileDefinition
1446
- ) : [];
1447
- this.currentConfiguration = currentConfiguration;
1448
- const nonTranslationFiles = [];
1449
- const translationFiles = [];
1450
- currentFiles.forEach((current) => {
1451
- if (current.docLang === void 0)
1452
- nonTranslationFiles.push(current);
1453
- else
1454
- translationFiles.push(current);
1455
- });
1456
- nonTranslationFiles.forEach((c) => {
1457
- this.state.files[c.docId] = c;
1458
- });
1459
- translationFiles.forEach((current) => {
1460
- const originalFile = nonTranslationFiles.find(
1461
- (search) => search.docLangGroup === current.docLangGroup
1462
- );
1463
- if (originalFile && current.docLang !== void 0) {
1464
- this.setTranslationFile(
1465
- current,
1466
- originalFile.docId,
1467
- Number(current.docLang)
1468
- );
1469
- } else
1470
- console.warn(
1471
- `The following file is translated but has no orignal file`,
1472
- current,
1473
- nonTranslationFiles
1474
- );
1475
- });
1476
- }
1477
- }
1478
- async lockDocument(id) {
1479
- if (this.props.context.IN_MONITOR) {
1480
- return;
1481
- }
1482
- const file = this.getDocument(id);
1483
- if (file.markedToSign) {
1484
- this.notify({
1485
- message: getLabel("lblCantUnlockMarkedToSign", {}, this.props.context).text,
1486
- type: "warning"
1487
- });
1488
- return;
1489
- }
1490
- if (!file.isLocked || !file.isLockedByMe) {
1491
- const isLocked = await this.checkLockDocument(file.docId, false);
1492
- this.updateDocument(
1493
- id,
1494
- typeof isLocked === "string" ? this.parseFileDefinition({
1495
- ...file,
1496
- userLocking: isLocked,
1497
- lock: true,
1498
- isLocked: true,
1499
- lockedBy: isLocked
1500
- }) : { ...file, isLocked }
1501
- );
1502
- }
1503
- const result = await ApiaApi.post(
1504
- this.context,
1505
- this.getLockDocumentParameters({
1506
- action: "lockDocument",
1507
- ajaxUrl: this.getAjaxUrl(),
1508
- docId: file.docId,
1509
- lock: file.isLocked || file.locked,
1510
- isAjax: true
1511
- })
1512
- );
1513
- if (result?.data) {
1514
- const resultFile = result.data.function?.data?.general;
1515
- if (resultFile)
1516
- this.updateDocument(
1517
- resultFile.docId,
1518
- this.parseFileDefinition({
1519
- ...file,
1520
- ...resultFile,
1521
- isLocked: resultFile.locked
1522
- })
1523
- );
1524
- }
1525
- }
1526
- evaluateDeleteDocumentResult(result) {
1527
- return result?.function?.name === "fncDocumentRemove";
1528
- }
1529
- setTranslationFile(file, docId, langId) {
1530
- if (!this.state.translatedFiles.has(docId)) {
1531
- this.state.translatedFiles.set(docId, /* @__PURE__ */ new Map());
1532
- }
1533
- this.state.translatedFiles.get(docId)?.set(langId, file);
1534
- }
1535
- getCheckSignatureParameters(props) {
1536
- return props;
1537
- }
1538
- getAjaxUploadFileStatusParameters(props) {
1539
- return props;
1540
- }
1541
- getAjaxUploadStartParameters(props) {
1542
- return props;
1543
- }
1544
- getConfirmDropModalParameters(props) {
1545
- return props;
1546
- }
1547
- getCheckLockDocumentParameters(props) {
1548
- return props;
1549
- }
1550
- getCheckWebDavLockParameters(props) {
1551
- return props;
1552
- }
1553
- getConfirmDropModalPostdata(props) {
1554
- return props;
1555
- }
1556
- getDeleteDocumentParameters(props) {
1557
- return props;
1558
- }
1559
- getClearTempFilesParameters(props) {
1560
- return props;
1561
- }
1562
- getDocumentInfoParameters(props) {
1563
- return props;
1564
- }
1565
- getDownloadMultipleDocumentsParameters(props) {
1566
- return props;
1567
- }
1568
- getEditDocumentParameters(props) {
1569
- return props;
1570
- }
1571
- getLockDocumentParameters(props) {
1572
- return props;
1573
- }
1574
- getMarkFileToSignParameters(props) {
1575
- return props;
1576
- }
1577
- getProcessDroppedFilesParameters(props) {
1578
- return props;
1579
- }
1580
- getProcessDroppedFilesPostdata(props) {
1581
- return props;
1582
- }
1583
- getReloadMetadataParameters(props) {
1584
- return props;
1585
- }
1586
- getSaveDroppedFilesParameters(props) {
1587
- return props;
1588
- }
1589
- filterAlreadyUploadedFiles(files, conf) {
1590
- const versioningFile = this.state.versioningFile;
1591
- if (versioningFile)
1592
- return files;
1593
- const uploadedFiles = Object.values(this.state.files).filter(
1594
- (file) => Number(file.docId) > 0
1595
- );
1596
- const existingFiles = [];
1597
- const nonExistingFiles = [];
1598
- if (conf?.langId) {
1599
- const docId = conf.translatingFile?.docId ?? Infinity;
1600
- const translationsMap = this.state.translatedFiles.get(String(docId));
1601
- const alreadyUploadedToTranslationsFile = translationsMap ? Array.from(translationsMap.values()).find(
1602
- (current) => (current.docName || current.name) === files[0]?.name
1603
- ) : void 0;
1604
- if (alreadyUploadedToTranslationsFile)
1605
- existingFiles.push(files[0]);
1606
- } else
1607
- files.forEach((file) => {
1608
- if (uploadedFiles.find((search) => search.docName === file.name)) {
1609
- existingFiles.push(file);
1610
- } else
1611
- nonExistingFiles.push(file);
1612
- });
1613
- if (existingFiles.length > 0) {
1614
- void this.notify({
1615
- message: `${getLabel("lblDropFileRepeated", {}, this.props.context).text}: ${existingFiles.map((current) => current.name).join(", ")}`,
1616
- type: "warning"
1617
- });
1618
- return nonExistingFiles;
1619
- }
1620
- return files;
1621
- }
1622
- filterByFilesAmountLimit(files) {
1623
- return files.slice(
1624
- 0,
1625
- addBoundary(this.maxFiles - (this.state.inProgressFiles?.length ?? 0), 0)
1626
- );
1627
- }
1628
- filterAcceptedFiles(files, shouldNotify = true, docTypeId) {
1629
- const docTypes = docTypeId !== void 0 ? this.state.allowedTypes.filter((c) => {
1630
- return typeof docTypeId === "string" ? c.id === docTypeId : c.id === docTypeId.id;
1631
- }) : this.state.allowedTypes;
1632
- if (!docTypes.find((c) => c.docExts === "")) {
1633
- const notAllowedFilesBecauseOfExtension = [];
1634
- const notAllowedFilesBecauseOfSize = [];
1635
- let maxSize = Infinity;
1636
- const allowedFiles = files.filter((currentFile) => {
1637
- const extension = (currentFile.name.match(/\.(\w+)$/) ?? [])[1];
1638
- let isAllowed = true;
1639
- if (!docTypes.find((currentDocType) => {
1640
- if (!currentDocType.docExts.split(";").map((current) => current.toLowerCase()).includes(extension.toLowerCase())) {
1641
- return false;
1642
- }
1643
- return true;
1644
- })) {
1645
- isAllowed = false;
1646
- notAllowedFilesBecauseOfExtension.push(currentFile);
1647
- }
1648
- if (isAllowed && !docTypes.find((currentDocType) => {
1649
- if (Number(currentDocType.maxSize) < currentFile.size) {
1650
- maxSize = Number(currentDocType.maxSize);
1651
- return false;
1652
- }
1653
- return true;
1654
- })) {
1655
- notAllowedFilesBecauseOfSize.push(currentFile);
1656
- isAllowed = false;
1657
- }
1658
- if (!isAllowed)
1659
- return false;
1660
- return true;
1661
- });
1662
- if (shouldNotify) {
1663
- let errorMessage = "";
1664
- if (notAllowedFilesBecauseOfExtension.length > 0) {
1665
- const filesNames = notAllowedFilesBecauseOfExtension.reduce(
1666
- (accumulated, current) => {
1667
- if (accumulated.length === 0)
1668
- return current.name;
1669
- return `${accumulated}, ${current.name}`;
1670
- },
1671
- ""
1672
- );
1673
- errorMessage = `<strong>${getLabel("lblFilesWrongExt", {}, this.props.context).text}</strong><br />${filesNames}`;
1674
- }
1675
- if (notAllowedFilesBecauseOfSize.length > 0) {
1676
- const filesNames = notAllowedFilesBecauseOfSize.reduce(
1677
- (accumulated, current) => {
1678
- if (accumulated.length === 0)
1679
- return current.name;
1680
- return `${accumulated}, ${current.name}`;
1681
- },
1682
- ""
1683
- );
1684
- if (errorMessage.length > 0)
1685
- errorMessage = `${errorMessage} <br /><br />`;
1686
- errorMessage = `${errorMessage}${formatMessage(
1687
- getLabel("lblFilesTooBig", {}, this.props.context).text,
1688
- {
1689
- TOK1: `<br />${filesNames}`,
1690
- TOK2: `${parseAsSize(maxSize)}`
1691
- }
1692
- )}`;
1693
- }
1694
- if (errorMessage.length > 0)
1695
- this.notify({
1696
- message: errorMessage,
1697
- type: "warning"
1698
- });
1699
- }
1700
- return allowedFiles;
1701
- }
1702
- return files;
1703
- }
1704
- filterExistingFiles(files, conf) {
1705
- if (conf?.langId)
1706
- return files;
1707
- const currentFiles = this.state.inProgressFiles;
1708
- const alreadyUploadedFiles = Object.values(this.state.files).filter(
1709
- (current) => Number(current.docId) < 0
1710
- );
1711
- let alreadyIncludedFileNames = "";
1712
- const filteredFiles = files.filter((current) => {
1713
- const isIncluded = currentFiles.findIndex((search) => search.name === current.name) !== -1 || alreadyUploadedFiles.findIndex(
1714
- (search) => search.docName === current.name
1715
- ) !== -1;
1716
- if (isIncluded)
1717
- alreadyIncludedFileNames = `${alreadyIncludedFileNames}${alreadyIncludedFileNames.length > 0 ? ", " : ""}${current.name}`;
1718
- return !isIncluded;
1719
- });
1720
- if (alreadyIncludedFileNames.length > 0)
1721
- this.notify({
1722
- message: `${getLabel("lblDropFileRepeated", {}, this.props.context).text}: ${alreadyIncludedFileNames}`,
1723
- type: "warning"
1724
- });
1725
- return filteredFiles;
1726
- }
1727
- filterVersioningFiles(files, conf) {
1728
- const versioningFile = this.state.versioningFile;
1729
- if (versioningFile) {
1730
- const newFiles = files.filter(
1731
- (current) => current.name === versioningFile.docName || current.name === versioningFile.name
1732
- );
1733
- if (newFiles.length === 0) {
1734
- this.notify({
1735
- type: "warning",
1736
- message: getLabel("lblDropFileNamesNotMatch", {}, this.props.context).text
1737
- });
1738
- }
1739
- return newFiles;
1740
- }
1741
- return files;
1742
- }
1743
- getLoadFileSystemStructureTree() {
1744
- return {
1745
- useDocTypePermitted: true
1746
- };
1747
- }
1748
- getLoadFilesForFolderParameters() {
1749
- return {
1750
- useDocTypePermitted: true
1751
- };
1752
- }
1753
- }
1754
-
1755
- class FilePickerFolderNode extends DirectoryPickerFolderNode {
1756
- constructor(parent, props, params = {}) {
1757
- super(parent, props);
1758
- this.params = params;
1759
- this.state.isSelectable = false;
1760
- }
1761
- async loadMore(focus = true) {
1762
- const res = await ApiaApi.post(
1763
- this.getTree().api.context,
1764
- {
1765
- ajaxUrl: FilePickerActions.ajaxUrl,
1766
- action: FilePickerActions.loadFilesForFolder,
1767
- preventAsXmlParameter: true,
1768
- isAjax: true
1769
- },
1770
- {
1771
- postData: {
1772
- txtFld: this.state.nodeProps.id,
1773
- loadFolders: true,
1774
- txtCantDoc: this.getChildren().length,
1775
- offset: this.getChildren().length,
1776
- docTypePermittedObjId: this.params.docTypePermittedObjId,
1777
- docTypePermittedObjType: this.params.docTypePermittedObjType,
1778
- useDocTypePermitted: this.params.useDocTypePermitted,
1779
- docTypeForcedId: this.params.docTypeForcedId,
1780
- ...this.params
1781
- },
1782
- postDataTreatement: "stringify",
1783
- postDataStringifyOptions: {
1784
- arrayFormat: "repeat"
1785
- }
1786
- }
1787
- );
1788
- if (res?.data) {
1789
- const lastNode = this.getChildren()[this.getChildren().length - 1];
1790
- arrayOrArray(res.data.folders?.folder).forEach((folder) => {
1791
- if (!this.state.children.has(makeId(folder.id))) {
1792
- this.getTree().createFolder({
1793
- id: makeId(folder.id),
1794
- label: folder.name,
1795
- nodeProps: folder,
1796
- parentId: this.id
1797
- });
1798
- }
1799
- });
1800
- arrayOrArray(res.data.documents?.document).forEach((document) => {
1801
- if (!this.state.children.has(makeId(document.id))) {
1802
- this.getTree().createDocument({
1803
- id: makeId(document.id),
1804
- label: document.name,
1805
- nodeProps: document,
1806
- parentId: this.id
1807
- });
1808
- }
1809
- });
1810
- if ((res?.data.documents?.documentInfo?.moreDocs ?? 0) > 0) {
1811
- this.removeLoadMoreDocsNode();
1812
- this.loadMoreDocsNode = this.getTree().createFolder({
1813
- asyncNode: false,
1814
- icon: void 0,
1815
- isLeaf: true,
1816
- label: getLabel("lblShwMoreEls").text,
1817
- labelRenderer: this.getTree().renderers.LoadMoreRenderer,
1818
- onClick: async () => {
1819
- if (this.loadMoreDocsNode) {
1820
- this.loadMoreDocsNode.state.nodeProps.isLoadingMore = true;
1821
- }
1822
- await this.loadMore();
1823
- },
1824
- parentId: this.id
1825
- });
1826
- if (focus) {
1827
- this.tree.focusNode(this.loadMoreDocsNode);
1828
- }
1829
- } else {
1830
- this.removeLoadMoreDocsNode();
1831
- if (focus) {
1832
- this.tree.focusNode(lastNode.getFollowingSibling() ?? lastNode);
1833
- }
1834
- }
1835
- }
1836
- }
1837
- }
1838
-
1839
- class FilePicker extends DirectoriesPicker {
1840
- constructor(api) {
1841
- super(api);
1842
- }
1843
- getNodeHandler(nodeProps) {
1844
- return new FilePickerFolderNode(
1845
- this,
1846
- nodeProps,
1847
- this.api.getLoadFilesForFolderParameters()
1848
- );
1849
- }
1850
- getFolderStructureParams() {
1851
- return {
1852
- ajaxUrl: FilePickerActions.ajaxUrl,
1853
- action: FilePickerActions.loadFileSystemStructureTree,
1854
- preventAsXmlParameter: true,
1855
- isAjax: true,
1856
- isXml: true,
1857
- txtFld: this.api.modalConfig.rootFolder
1858
- };
1859
- }
1860
- parseStructureResponse(res) {
1861
- const castRes = res;
1862
- if (castRes.data?.folders.folder)
1863
- return arrayOrArray(castRes.data?.folders.folder);
1864
- return null;
1865
- }
1866
- }
1867
-
1868
- export { DirectoriesPicker, DirectoryPickerActions, DirectoryPickerFolderNode, DocumentNode, FilePicker, FilePickerActions, FilePickerFolderNode, UploaderApi, UploaderModalController, makeId, parseFileDefinition };
1
+ export { UploaderApi } from './UploaderApi.js';
2
+ export { UploaderModalController } from './UploaderModalController.js';
3
+ export { parseFileDefinition } from './util.js';
4
+ export { DirectoriesPicker } from './directories/DirectoriesPicker.js';
5
+ export { FilePicker } from './directories/FilePicker.js';
6
+ export { DirectoryPickerFolderNode } from './directories/nodes/DirectoryPickerFolderNode.js';
7
+ export { DocumentNode } from './directories/nodes/DocumentNode.js';
8
+ export { FilePickerFolderNode } from './directories/nodes/FilePickerFolderNode.js';
9
+ export { DirectoryPickerActions, FilePickerActions, makeId } from './directories/utils.js';
1869
10
  //# sourceMappingURL=index.js.map