-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathtask.vue
More file actions
1143 lines (1074 loc) · 37.3 KB
/
task.vue
File metadata and controls
1143 lines (1074 loc) · 37.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<template>
<div
id="tab-form"
role="tabpanel"
aria-labelledby="tab-form"
class="tab-pane active show h-100"
>
<template v-if="screen">
<b-overlay
:show="disabled || isSelfService"
id="overlay-background"
:variant="isSelfService ? 'white' : 'transparent'"
:blur="null"
cardStyles="pointer-events: none;pointer-events: none;inset: 1px"
rounded="sm"
>
<template #overlay>
<div class="text-center">
<p v-if="isSelfService">Please claim this task to continue.</p>
</div>
</template>
<div class="card card-body border-top-0 h-100" :class="screenTypeClass">
<div v-if="renderComponent === 'task-screen'">
<vue-form-renderer
ref="renderer"
v-model="requestData"
:class="{ loading: loadingTask || loadingListeners }"
:config="screen.config"
:computed="screen.computed"
:custom-css="screen.custom_css"
:watchers="screen.watchers"
:key="refreshScreen"
:loop-context="loopContext"
:taskdraft="this.task"
@update-page-task="pageUpdate"
@update="onUpdate"
@after-submit="afterSubmit"
@submit="submit"
/>
</div>
<div v-else>
<component
:is="renderComponent"
:process-id="processId"
:instance-id="requestId"
:token-id="taskId"
:screen="screen.config"
:csrf-token="csrfToken"
:computed="screen.computed"
:custom-css="screen.custom_css"
:watchers="screen.watchers"
:data="requestData"
:type="screen.type"
@update-page-task="pageUpdate"
@update="onUpdate"
@after-submit="afterSubmit"
@submit="submit"
/>
</div>
</div>
<div v-if="shouldAddSubmitButton" class="card-footer">
<button type="button" class="btn btn-primary" @click="submit(null)">
{{ $t('Complete Task') }}
</button>
</div>
</b-overlay>
</template>
<template v-if="showTaskIsCompleted">
<div class="card card-body text-center" v-cloak>
<h1>
{{ $t('Task Completed') }}
<i class="fas fa-clipboard-check" />
</h1>
</div>
</template>
</div>
</template>
<script>
import VueFormRenderer from './vue-form-renderer.vue';
import _ from 'lodash';
import simpleErrorMessage from './SimpleErrorMessage.vue';
const defaultBeforeLoadTask = () => {
return new Promise((resolve) => {
resolve();
});
};
export default {
components:{
simpleErrorMessage,
VueFormRenderer
},
props: {
initialTaskId: { type: Number, default: null },
initialScreenId: { type: Number, default: null },
initialRequestId: { type: Number, default: null },
initialProcessId: { type: Number, default: null },
initialNodeId: { type: String, default: null },
screenVersion: { type: Number, default: null },
userId: { type: Number, default: null },
csrfToken: { type: String, default: null },
value: { type: Object, default: () => {} },
beforeLoadTask: { type: Function, default: defaultBeforeLoadTask },
initialLoopContext: { type: String, default: "" },
taskPreview: { type: Boolean, default: false },
loading: { type: Number, default: null },
alwaysAllowEditing: { type: Boolean, default: false },
disableInterstitial: { type: Boolean, default: false },
waitLoadingListeners: { type: Boolean, default: false },
isWebEntry: { type: Boolean, default: false }
},
data() {
return {
task: null,
taskId: null,
request: null,
requestId: null,
screen: null,
screenId: null,
renderComponent: 'task-screen',
processId: null,
nodeId: null,
disabled: false,
socketListeners: [],
requestData: {},
hasErrors: false,
refreshScreen: 0,
redirecting: null,
loadingButton: false,
loadingTask: false,
loadingListeners: this.waitLoadingListeners,
isSelfService: false,
};
},
watch: {
initialScreenId: {
handler() {
this.screenId = this.initialScreenId;
},
},
initialRequestId: {
handler() {
this.requestId = this.initialRequestId;
},
},
initialProcessId: {
handler() {
this.processId = this.initialProcessId;
},
},
initialNodeId: {
handler() {
this.nodeId = this.initialNodeId;
},
},
screenId: {
handler() {
if (this.screenId) {
this.loadScreen(this.screenId);
}
},
},
requestId: {
handler() {
if (this.requestId) {
this.setMetaValue();
this.initSocketListeners();
} else {
this.unsubscribeSocketListeners();
}
},
},
value: {
handler() {
this.requestData = this.value;
},
},
screen: {
handler() {
if (!this.screen) {
return;
}
if (this.renderComponent === 'ConversationalForm') {
return;
}
if (this.screen.type === 'CONVERSATIONAL') {
this.renderComponent = 'ConversationalForm';
} else {
const isInterstitial = _.get(this.screen, '_interstitial', false);
let component = _.get(this, 'task.component', 'task-screen');
if (component === null || isInterstitial) {
component = 'task-screen';
}
this.renderComponent = component;
}
}
},
},
computed: {
shouldAddSubmitButton() {
if (!this.task) {
return false;
}
return this.task.bpmn_tag_name === 'manualTask' || (!this.task.screen && this.task.element_type !== 'startEvent');
},
showTaskIsCompleted() {
return (
this.task && this.task.advanceStatus === 'completed' && !this.screen
);
},
screenTypeClass() {
if (!this.screen) {
return;
}
const screenType = this.screen.type;
return screenType.toLowerCase() + '-screen';
},
parentRequest() {
return _.get(this.task, 'process_request.parent_request_id', null);
},
},
methods: {
disableForm(json) {
if (json instanceof Array) {
for (let item of json) {
if (item.component==='FormButton' && item.config.event==='submit') {
json.splice(json.indexOf(item), 1);
} else {
this.disableForm(item);
}
}
}
if (json.config !== undefined) {
json.config.disabled = true;
}
if (json.items !== undefined) {
this.disableForm(json.items);
}
return json;
},
showSimpleErrorMessage() {
// This triggers a re-render if it has already been displayed.
this.renderComponent = null;
setTimeout(() => {
this.renderComponent = 'simpleErrorMessage';
}, 0);
},
loadScreen(id) {
this.disabled = true;
let query = '?include=nested';
if (this.requestId) {
query += '&request_id=' + this.requestId;
}
this.$dataProvider.getScreen(id, query).then((response) => {
this.screen = response.data;
this.disabled = false;
});
},
reload() {
if (this.taskId) {
this.loadTask();
} else {
this.loadNextAssignedTask();
}
},
loadTask(mounting = false) {
if (!this.taskId) {
return;
}
let url = `/${this.taskId}?include=data,user,draft,requestor,processRequest,component,screen,requestData,loopContext,bpmnTagName,interstitial,definition,nested,userRequestPermission,elementDestination`;
if (this.screenVersion) {
url += `&screen_version=${this.screenVersion}`;
}
// For Vocabularies
if (window.ProcessMaker && window.ProcessMaker.packages && window.ProcessMaker.packages.includes('package-vocabularies')) {
window.ProcessMaker.VocabulariesSchemaUrl = `vocabularies/task_schema/${this.taskId}`;
}
return this.beforeLoadTask(this.taskId, this.nodeId).then(() => {
this.$dataProvider
.getTasks(url)
.then((response) => {
this.task = response.data;
this.setSelfService(this.task);
this.linkTask(mounting);
this.checkTaskStatus();
if (
window.PM4ConfigOverrides
&& window.PM4ConfigOverrides.getScreenEndpoint
&& window.PM4ConfigOverrides.getScreenEndpoint.includes('tasks/')
) {
const screenPath = window.PM4ConfigOverrides.getScreenEndpoint.split('/');
screenPath[1] = this.task.id;
window.PM4ConfigOverrides.getScreenEndpoint = screenPath.join('/');
}
})
.catch(() => {
this.hasErrors = true;
})
.finally(() => {
this.loadingTask = false;
});
});
},
linkTask(mounting) {
this.nodeId = this.task.element_id;
this.listenForParentChanges();
if (this.task.process_request.status === 'COMPLETED') {
if (!this.taskPreview) {
this.$emit('completed', this.task.process_request.id);
// When the process ends before the request is opened
if (mounting) {
// get end event element destination config
window.ProcessMaker.apiClient.get(`/requests/${this.requestId}/end-event-destination`)
.then((response) => {
if (!response.data?.data?.endEventDestination) {
// by default it goes to summary
window.location.href = `/requests/${this.requestId}`;
return;
}
// process the end event destination
this.processCompletedRedirect(response.data.data, this.userId, this.requestId);
});
}
}
}
if (this.taskPreview && this.task.status === "CLOSED") {
this.task.interstitial_screen['_interstitial'] = false;
if (!this.alwaysAllowEditing) {
this.task.screen.config = this.disableForm(this.task.screen.config);
}
this.screen = this.task.screen;
}
},
prepareTask() {
// If the immediate task status is completed and we are waiting with a loading button,
// do not reset the screen because that would stop displaying the loading spinner
// before the next task is ready.
if (!this.loadingButton || this.task.status === 'ACTIVE') {
this.resetScreenState();
this.requestData = _.get(this.task, 'request_data', {});
this.loopContext = _.get(this.task, "loop_context", "");
if (this.task.draft) {
this.requestData = this.restoreDraftData(
this.requestData,
this.task.draft.data
);
}
this.refreshScreen++;
}
this.$emit('task-updated', this.task);
if (this.task.process_request.status === 'ERROR') {
this.hasErrors = true;
this.$emit('error', this.requestId);
} else {
this.hasErrors = false;
}
},
restoreDraftData(requestData, draftData) {
const shouldMerge =
globalThis?.ProcessMaker?.screen?.mergeDraftOnRestore ?? true;
return shouldMerge
? _.merge({}, requestData, draftData)
: { ...requestData, ...draftData };
},
pageUpdate() {
this.$emit("updated-page-core");
},
resetScreenState() {
this.loadingButton = false;
this.disabled = false;
if (this.$refs.renderer && this.$refs.renderer.$children[0]) {
this.$refs.renderer.$children[0].currentPage = 0;
this.$refs.renderer.restartValidation();
}
},
checkTaskStatus() {
this.setSelfService(this.task);
if (
this.task.status == 'COMPLETED' ||
this.task.status == 'CLOSED' ||
this.task.status == 'TRIGGERED'
) {
this.closeTask();
} else {
this.screen = this.task.screen;
}
this.prepareTask();
},
resolveSelfService(task = this.task) {
if (task) {
return (
_.get(task, 'process_request.status') === 'ACTIVE'
&& Boolean(_.get(task, 'is_self_service', false))
);
}
return Boolean(_.get(window, 'ProcessMaker.isSelfService', false));
},
setSelfService(task = this.task) {
this.$nextTick(() => {
this.isSelfService = this.resolveSelfService(task);
});
},
/**
* Closes the current task and performs necessary actions based on task properties.
* @param {string|null} parentRequestId - The parent request ID.
*/
closeTask(parentRequestId = null) {
if (this.hasErrors) {
this.emitError();
}
if (this.shouldLoadNextTask()) {
this.loadNextAssignedTask(parentRequestId);
} else if (this.task.allow_interstitial) {
this.showInterstitial(parentRequestId);
} else if (!this.taskPreview) {
this.emitClosedEvent();
}
},
/**
* Checks if the next task should be loaded.
* @returns {boolean} - True if the next task should be loaded, otherwise false.
*/
shouldLoadNextTask() {
return (
this.task.process_request.status === "COMPLETED" || this.loadingButton
);
},
/**
* Shows the interstitial screen and loads the next assigned task.
* @param {string|null} parentRequestId - The parent request ID.
*/
showInterstitial(parentRequestId) {
// Show the interstitial screen
this.task.interstitial_screen['_interstitial'] = true;
this.screen = this.task.interstitial_screen;
// Load the next assigned task
this.loadNextAssignedTask(parentRequestId);
},
/**
* Emits an error event.
*/
emitError() {
this.$emit('error', this.requestId);
},
/**
* Emits a closed event.
*/
async emitClosedEvent() {
this.$emit("closed", this.task?.id, await this.getDestinationUrl());
},
/**
* Retrieves the destination URL for the closed event.
* @returns {string|null} - The destination URL.
*/
// eslint-disable-next-line consistent-return
async getDestinationUrl() {
const { elementDestination, allow_interstitial: allowInterstitial } = this.task || {};
if (!elementDestination) {
return null;
}
if (elementDestination.type === "taskSource") {
try {
const params = {
processRequestId: this.requestId,
status: "ACTIVE",
userId: this.userId,
};
const response = await this.retryApiCall(() => this.getTasks(params));
const firstTask = response.data.data[0];
if (allowInterstitial && firstTask?.user_id === this.userId) {
return `/tasks/${firstTask.id}/edit`;
}
return this.getSessionRedirectUrl();
} catch (error) {
return null;
}
}
const elementDestinationUrl = elementDestination.value;
if (elementDestinationUrl) {
// Save the referring URL to sessionStorage for future verification
sessionStorage.setItem('sessionUrlActionBlocker', document.referrer);
return elementDestinationUrl;
}
const sessionStorageUrl = sessionStorage.getItem("elementDestinationURL");
return sessionStorageUrl || null;
},
/**
* Retrieves the URL from the session storage or the document referrer.
*
* This method is used to determine the source of the redirection when the task is claimed.
* It retrieves the 'sessionUrlSelfService' value from sessionStorage, and if present, removes it.
* If the value is not found, it returns the document referrer.
*
* @returns {string|null} - The URL from the session storage or the document referrer.
*/
getSessionRedirectUrl() {
const urlSelfService = sessionStorage.getItem('sessionUrlSelfService');
if (urlSelfService) {
// Remove 'sessionUrlSelfService' from sessionStorage after retrieving its value
sessionStorage.removeItem('sessionUrlSelfService');
// Emit the source of the redirection
return urlSelfService;
}
// If the task has not an origin source it should re redirected top the tasks List as default.
return document.referrer || '/tasks';
},
loadNextAssignedTask(requestId = null) {
if (!requestId) {
requestId = this.requestId;
}
if (!this.userId) {
return;
}
const timestamp = !window.Cypress ? `&t=${Date.now()}` : "";
const url = `?user_id=${this.userId}&status=ACTIVE&process_request_id=${requestId}&include_sub_tasks=1${timestamp}`;
return this.$dataProvider
.getTasks(url).then((response) => {
this.$emit("load-data-task", response);
if (response.data.data.length > 0) {
let task = response.data.data[0];
if (task.process_request_id !== this.requestId) {
// Next task is in a subprocess, do a hard redirect
if (this.redirecting === task.process_request_id) {
return;
}
this.unsubscribeSocketListeners();
this.redirecting = task.process_request_id;
this.$emit('redirect', task.id, true);
return;
} else {
this.emitIfTaskCompleted(requestId);
}
this.taskId = task.id;
this.nodeId = task.element_id;
this.loadTask();
} else if (this.parentRequest && ['COMPLETED', 'CLOSED'].includes(this.task.process_request.status)) {
this.$emit('completed', this.getAllowedRequestId());
}
this.disabled = false;
});
},
emitIfTaskCompleted(requestId) {
// Only emit completed after getting the subprocess tasks and there are no tasks and process is completed
if (this.task
&& this.parentRequest
&& requestId == this.task.process_request_id
&& this.task.process_request.status === 'COMPLETED') {
this.$emit('completed', this.parentRequest);
}
},
classHeaderCard(status) {
let header = 'bg-success';
switch (status) {
case 'completed':
header = 'bg-secondary';
break;
case 'overdue':
header = 'bg-danger';
break;
}
return 'card-header text-capitalize text-white ' + header;
},
afterSubmit() {
this.$emit('after-submit', ...arguments);
},
submit(formData = null, loading = false, buttonInfo = null) {
//single click
if (this.disabled) {
return;
}
this.disabled = true;
// Ensure formData is always a valid object (never null, undefined, or false)
const safeFormData = (formData && typeof formData === 'object') ? formData : (this.requestData || {});
if (formData && typeof formData === 'object') {
this.onUpdate(Object.assign({}, this.requestData, formData));
}
if (loading) {
this.loadingButton = true;
} else {
this.loadingButton = false;
}
this.$emit('submit', this.task, safeFormData, loading, buttonInfo);
if (this.task?.allow_interstitial && !this.loadingButton && !this.disableInterstitial) {
this.task.interstitial_screen['_interstitial'] = true;
this.screen = this.task.interstitial_screen;
}
if (this.task?.bpmn_tag_name === 'manualTask') {
this.checkTaskStatus();
this.reload();
}
},
onUpdate(data) {
this.$emit('input', data);
this.setSelfService();
},
activityAssigned() {
// This may no longer be needed
},
processCompleted(data = null) {
let requestId;
if (this.parentRequest) {
requestId = this.getAllowedRequestId();
this.$emit('completed', requestId);
}
},
/**
* Makes an API call with retry logic.
* @param {Function} apiCall - The API call to be made.
* @param {number} retries - The number of retry attempts.
* @param {number} delay - The delay between retries in milliseconds.
* @returns {Promise} - The response from the API call.
*/
// eslint-disable-next-line consistent-return
async retryApiCall(apiCall, retries = 3, delay = 1000) {
for (let attempt = 0; attempt < retries; attempt++) {
try {
// eslint-disable-next-line no-await-in-loop
const response = await apiCall();
return response;
} catch (error) {
if (attempt === retries - 1) {
throw error;
}
// eslint-disable-next-line no-await-in-loop
await new Promise((resolve) => {
setTimeout(resolve, delay);
});
}
}
},
/**
* Gets the next request by posting to the specified endpoint.
* @param {string} processId - The process ID.
* @param {string} startEvent - The start event.
* @returns {Promise} - The response from the API call.
*/
getNextRequest(processId, startEvent) {
return window.ProcessMaker.apiClient.post(
`/process_events/${processId}?event=${startEvent}`,
{}
);
},
/**
* Gets the tasks for the specified process request ID.
* @param {object} params - The query params.
* @returns {Promise} - The response from the API call.
*/
getTasks(params) {
const queryParams = {
user_id: this.userId,
process_request_id: params.processRequestId,
page: params.page || 1,
per_page: params.perPage || 1,
status: params.status,
};
const queryString = new URLSearchParams(queryParams).toString();
return this.$dataProvider.getTasks(`?${queryString}`);
},
/**
* Parses a JSON string and returns the result.
* @param {string} jsonString - The JSON string to parse.
* @returns {object|null} - The parsed object or null if parsing fails.
*/
parseJsonSafely(jsonString) {
try {
return JSON.parse(jsonString);
} catch (error) {
console.error("Invalid JSON string:", error);
return null;
}
},
/**
* Handles redirection upon process completion, considering destination type and user task validation.
* @async
* @param {Object} data - Contains information about the end event destination.
* @param {number} userId - ID of the current user.
* @param {number} requestId - ID of the request to complete.
* @returns {Promise<void>}
*/
async processCompletedRedirect(data, userId, requestId) {
// Emit completion event if accessed through web entry.
if (this.isWebEntry) {
this.$emit("completed", requestId);
return;
}
try {
const destinationUrl = this.resolveDestinationUrl(data);
if (destinationUrl) {
window.location.href = destinationUrl;
return;
}
// Proceed to handle redirection to the next request if applicable.
await this.handleNextRequestRedirection(data, userId, requestId);
} catch (error) {
console.error("Error processing completed redirect:", error);
this.$emit("completed", requestId);
}
},
/**
* Resolves the URL to redirect to if the end event is not another process.
* @param {Object} data - Contains the end event destination data.
* @returns {string|null} - The URL for redirection, or null if proceeding to another process.
*/
resolveDestinationUrl(data) {
if (data.endEventDestination.type !== "anotherProcess") {
return data.endEventDestination.value || `/requests/${this.requestId}`;
}
return null;
},
/**
* Handles redirection logic to the next request's task or fallback to the request itself.
* @async
* @param {Object} data - Contains the end event destination.
* @param {number} userId - ID of the current user.
* @param {number} requestId - ID of the request to complete.
* @returns {Promise<void>}
*/
async handleNextRequestRedirection(data, userId, requestId) {
const nextRequest = await this.fetchNextRequest(data.endEventDestination);
const firstTask = await this.fetchFirstTask(nextRequest);
if (firstTask?.user_id === userId) {
this.redirectToTask(firstTask.id);
} else {
this.redirectToRequest(requestId);
}
},
/**
* Fetch the next request using retry logic.
* @async
* @param {Object} endEventDestination - The parsed end event destination object.
* @returns {Promise<Object>} - The next request data.
*/
async fetchNextRequest(endEventDestination) {
const destinationData = this.parseJsonSafely(endEventDestination.value);
return await this.retryApiCall(() =>
this.getNextRequest(destinationData.processId, destinationData.startEvent)
);
},
/**
* Fetch the first task from the next request using retry logic.
* @async
* @param {Object} nextRequest - The next request object.
* @returns {Promise<Object|null>} - The first task data, or null if no tasks found.
*/
async fetchFirstTask(nextRequest) {
const params = {
processRequestId: nextRequest.data.id,
status: "ACTIVE",
page: 1,
perPage: 1
};
const response = await this.retryApiCall(() => this.getTasks(params));
return response.data.data[0] || null;
},
getAllowedRequestId() {
const permissions = this.task.user_request_permission || [];
const permission = permissions.find(item => item.process_request_id === this.parentRequest)
const allowed = permission && permission.allowed;
return allowed ? this.parentRequest : this.requestId
},
redirectToTask(tokenId) {
this.$emit('redirect', tokenId);
},
redirectToRequest(requestId) {
window.location.href = `/requests/${requestId}`;
},
/**
* Initializes socket listeners for process updates and redirects.
* This method sets up listeners to handle specific events and reloads
* the task if necessary.
*/
initSocketListeners() {
this.addProcessUpdateListener();
this.addRedirectListener();
this.loadingListeners = false;
// Reload to check if there's a task waiting, in case an event was missed
if (!this.taskId) {
this.reload();
}
},
/**
* Adds a socket listener for process updates.
* Listens for specific events related to the process and triggers appropriate actions.
*/
addProcessUpdateListener() {
this.addSocketListener(
`updated-${this.requestId}`,
`ProcessMaker.Models.ProcessRequest.${this.requestId}`,
'.ProcessUpdated',
(data) => this.handleProcessUpdate(data)
);
},
/**
* Handles process update events.
* Emits an error if an activity exception event is detected.
*
* @param {Object} data - The event data received from the socket listener.
*/
handleProcessUpdate(data) {
if (!this.task) {
// reload the task if it is not found
this.reload();
return;
}
// get the event, element destination and token id from the data
const { event, elementDestination, tokenId } = data;
// If the activity is completed and there is an element destination, set the element destination to the task
if (
event === "ACTIVITY_COMPLETED" &&
this.task.id === tokenId &&
elementDestination
) {
this.task.elementDestination = elementDestination;
// update allow_interstitial based on the element destination change after the submit
this.task.allow_interstitial = elementDestination.type === "displayNextAssignedTask";
if (elementDestination?.type !== 'taskSource' && elementDestination?.value) {
// redirect to the element destination value
window.location.href = elementDestination.value;
return;
}
}
if (event === 'ACTIVITY_EXCEPTION') {
this.$emit('error', this.requestId);
window.location.href = `/requests/${this.requestId}`;
}
},
/**
* Adds a socket listener for redirect events.
* Listens for specific redirect actions and handles them according to the method provided.
*/
addRedirectListener() {
this.addSocketListener(
`redirect-${this.requestId}`,
`ProcessMaker.Models.ProcessRequest.${this.requestId}`,
'.RedirectTo',
(data) => this.handleRedirect(data)
);
},
/**
* Handles redirect events based on the method provided in the event data.
* Calls specific handlers for different redirect methods or falls back to a default redirect.
*
* @param {Object} data - The event data received from the socket listener.
*/
handleRedirect(data) {
// Validate if the task is still active before redirects
if (data.params?.activeTokens?.includes(this.taskId)) {
return;
}
switch (data.method) {
case 'redirectToTask':
this.handleRedirectToTask(data);
break;
case 'processUpdated':
this.handleProcessUpdated(data);
break;
case 'processCompletedRedirect':
this.processCompletedRedirect(
data.params[0],
this.userId,
this.requestId
);
break;
default:
this.handleDefaultRedirect(data);
}
},
/**
* Handles the 'redirectToTask' event by loading the specified task.
* Updates the current task ID and reloads the task data.
*
* @param {Object} data - The event data containing the tokenId of the task.
*/
async handleRedirectToTask(data) {
const tokenId = data?.params[0]?.tokenId;
const newTaskUserId = data?.params[0]?.userId; // User assigned to the new task (from the backend)
const nodeId = data?.params[0]?.nodeId;
// Current user: prop > window.ProcessMaker.user > task assignee (when viewing assigned task)
const currentUserId = this.userId ?? window.ProcessMaker?.user?.id ?? this.task?.user?.id;
const elementDestType = this.task?.elementDestination?.type;
const userCanClaim = data?.params?.[0]?.userCanClaim;
// Redirect if the new task is assigned to the current user, or if it is taskSource
const isNewTaskForCurrentUser = tokenId && (newTaskUserId === currentUserId || (newTaskUserId == null && (elementDestType === 'displayNextAssignedTask' || elementDestType === 'taskSource')));
const isTaskSource = elementDestType === 'taskSource';
// Redirect when task is unclaimed and user can claim it (pool tasks)
const isUnclaimedAndClaimable = newTaskUserId === null && userCanClaim === true;
const shouldHandle = isNewTaskForCurrentUser || isTaskSource || isUnclaimedAndClaimable;
if (shouldHandle) {
this.loadingTask = true;
// Check if interstitial tasks are allowed for this task.
if (this.task && !(this.task.allow_interstitial || this.isSameUser(data))) {
window.location.href = await this.getDestinationUrl();
return;
}
this.nodeId = nodeId;
this.taskId = tokenId;
// Force a redirect to ensure the correct task is loaded immediately for ConversationalForm.
if (this.renderComponent === "ConversationalForm") {
window.location.href = `/tasks/${this.taskId}/edit`;
}
this.reload();
}
},
/**
* Checks if the redirect applies to the current user.
* - userId of event = user assigned to the new task
* - It is considered a match if: new task assigned to the current user, or taskSource/displayNextAssignedTask with user null
*
* @param {Object} redirectData - The redirect data object.
*/
isSameUser(redirectData) {
const newTaskUserId = redirectData?.params?.[0]?.userId;
const currentUserId = this.userId ?? window.ProcessMaker?.user?.id ?? this.task?.user?.id;
const elementDestType = this.task?.elementDestination?.type;
const userIdMatch = newTaskUserId === currentUserId
|| (newTaskUserId == null && (elementDestType === 'displayNextAssignedTask' || elementDestType === 'taskSource'));
const typeMatch = elementDestType === null || elementDestType === 'taskSource' || elementDestType === 'displayNextAssignedTask';
return userIdMatch && typeMatch;
},
/**
* Handles the 'processUpdated' event by checking the event type and updating the task if necessary.
* Reloads the task data if the event is relevant.
*
* @param {Object} data - The event data containing the process update information.
*/
handleProcessUpdated(data) {
const elementDestinationValue = this.task.elementDestination?.value;
if (
elementDestinationValue &&
elementDestinationValue !== 'taskSource' &&
data?.params[0]?.tokenId === this.taskId &&
data?.params[0]?.requestStatus === 'ACTIVE'
) {
window.location.href = elementDestinationValue;
return;
}
if (
['ACTIVITY_ACTIVATED', 'ACTIVITY_COMPLETED'].includes(data.event)