-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathFormViewer.vue
More file actions
1123 lines (1039 loc) · 33.2 KB
/
Copy pathFormViewer.vue
File metadata and controls
1123 lines (1039 loc) · 33.2 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
<script setup>
import { Form } from '@formio/vue';
import _ from 'lodash';
import { storeToRefs } from 'pinia';
import {
computed,
onBeforeUpdate,
onBeforeUnmount,
onMounted,
ref,
watch,
} from 'vue';
import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';
import BaseDialog from '~/components/base/BaseDialog.vue';
import FormViewerActions from '~/components/designer/FormViewerActions.vue';
import FormViewerMultiUpload from '~/components/designer/FormViewerMultiUpload.vue';
import templateExtensions from '~/plugins/templateExtensions';
import { fileService, formService, rbacService } from '~/services';
import { useAppStore } from '~/store/app';
import { useAuthStore } from '~/store/auth';
import { useFormStore } from '~/store/form';
import { useNotificationStore } from '~/store/notification';
import { isFormPublic } from '~/utils/permissionUtils';
import {
attachAttributesToLinks,
getDisposition,
} from '~/utils/transformUtils';
import { FormPermissions, NotificationTypes } from '~/utils/constants';
const { t, locale } = useI18n({ useScope: 'global' });
const router = useRouter();
const emit = defineEmits(['submission-updated']);
const properties = defineProps({
displayTitle: {
type: Boolean,
default: false,
},
draftId: {
type: String,
default: null,
},
formId: {
type: String,
default: null,
},
readOnly: {
type: Boolean,
default: false,
},
preview: Boolean,
staffEditMode: {
type: Boolean,
default: false,
},
saved: {
type: Boolean,
default: false,
},
submissionId: {
type: String,
default: null,
},
versionId: {
type: String,
default: null,
},
isDuplicate: {
type: Boolean,
default: false,
},
});
const block = ref(false);
const bulkFile = ref(false);
const chefForm = ref(null);
const confirmSubmit = ref(false);
const currentForm = ref({});
const downloadTimeout = ref(null);
const doYouWantToSaveTheDraft = ref(false);
const forceNewTabLinks = ref(true);
const form = ref({});
const formDataEntered = ref(false);
const formElement = ref(undefined);
const formSchema = ref({});
const isFormScheduleExpired = ref(false);
const isLateSubmissionAllowed = ref(false);
const isLoading = ref(false);
const json_csv = ref({
data: [],
file_name: String,
});
const loadingSubmission = ref(false);
const permissions = ref([]);
const reRenderFormIo = ref(0);
const saveDraftDialog = ref(false);
const saveDraftState = ref(0);
const saving = ref(false);
const showModal = ref(false);
const showSubmitConfirmDialog = ref(false);
const submission = ref({ data: { lateEntry: false } });
const submissionRecord = ref({});
const version = ref(0);
const versionIdToSubmitTo = ref(properties.versionId);
const isAuthorized = ref(true);
const appStore = useAppStore();
const authStore = useAuthStore();
const formStore = useFormStore();
const notificationStore = useNotificationStore();
const { config } = storeToRefs(appStore);
const { authenticated, keycloak, tokenParsed, user } = storeToRefs(authStore);
const { downloadedFile, isRTL } = storeToRefs(formStore);
const formScheduleExpireMessage = computed(() =>
form?.value?.schedule?.message
? form.value.schedule.message
: t('trans.formViewer.formScheduleExpireMessage')
);
const formUnauthorizedMessage = computed(() =>
t('trans.formViewer.formUnauthorizedMessage')
);
const NOTIFICATIONS_TYPES = computed(() => NotificationTypes);
const shouldDisableFileDownloads = computed(() => {
// To disable file downloads for Public forms
if (!form.value || !properties.readOnly) {
return false;
}
return (
properties.readOnly && isFormPublic(form.value) && !authenticated.value
);
});
const viewerOptions = computed(() => {
// Force recomputation of viewerOptions after rerendered formio to prevent duplicate submission update calls
reRenderFormIo.value;
const evalContextUser = getEvalContextUser();
return {
sanitizeConfig: {
addTags: ['iframe'],
ALLOWED_TAGS: ['iframe'],
},
templates: templateExtensions,
readOnly: properties.readOnly,
hooks: {
beforeSubmit: onBeforeSubmit,
},
// pass in options for custom components to use
componentOptions: {
simplefile: {
config: config.value,
chefsToken: getCurrentAuthHeader,
deleteFile: deleteFile,
getFile: getFile,
uploadFile: uploadFile,
},
},
evalContext: {
token: tokenParsed.value,
user: evalContextUser,
},
};
});
function getEvalContextUser() {
// New submission (no submissionId), use current logged in user
if (!properties.submissionId) {
return user.value;
}
// Reviewer viewing in read-only mode, use submitter
if (properties.readOnly && submissionRecord.value?.createdBy) {
return {
id: submissionRecord.value.createdBy,
username: submissionRecord.value.createdBy,
fullName:
submissionRecord.value.createdByUsername ||
submissionRecord.value.createdBy,
email: submissionRecord.value.createdByEmail || '',
};
}
// Submitter editing their own submission, use submitter
if (
!properties.staffEditMode &&
submissionRecord.value?.createdBy &&
submissionRecord.value.createdBy === user.value?.usernameIdp
) {
return {
id: submissionRecord.value.createdBy,
username: submissionRecord.value.createdBy,
fullName:
submissionRecord.value.createdByUsername ||
submissionRecord.value.createdBy,
email: submissionRecord.value.createdByEmail || '',
};
}
// Reviewer editing a submission, use current logged in user
return user.value;
}
const canSaveDraft = computed(
() =>
!properties.readOnly &&
permissions.value.includes(FormPermissions.SUBMISSION_UPDATE)
);
watch(locale, () => {
reRenderFormIo.value += 1;
});
onMounted(async () => {
// load up headers for any External API calls
// from components.
await setProxyHeaders();
if (properties.submissionId && properties.isDuplicate) {
// Run when make new submission from existing one called. Get the
// published version of form, and then get the submission data.
await getFormSchema();
await getFormData();
} else if (properties.submissionId && !properties.isDuplicate) {
await getFormData();
} else {
showModal.value = true;
await getFormSchema();
}
window.addEventListener('beforeunload', beforeWindowUnload);
reRenderFormIo.value += 1;
});
onBeforeUnmount(() => {
window.removeEventListener('beforeunload', beforeWindowUnload);
clearTimeout(downloadTimeout.value);
});
onBeforeUpdate(() => {
if (forceNewTabLinks.value) {
attachAttributesToLinks(formSchema.value.components);
}
});
function getCurrentAuthHeader() {
return `Bearer ${keycloak.value.token}`;
}
async function getFormData() {
// When the form contains a Data Grid there will be an array that needs to be
// checked, and an array of properties to be unset.
function iterateArray(array, stack, fields, propNeeded) {
const fieldsArray = [];
for (let i = 0; i < array.length; i++) {
const next = iterate(array[i], stack + '[' + i + ']', fields, propNeeded);
if (next) {
fieldsArray.push(...(Array.isArray(next) ? next : [next]));
}
}
return fieldsArray;
}
function iterate(obj, stack, fields, propNeeded) {
//Get property path from nested object
for (let property in obj) {
const innerObject = obj[property];
const path = stack + '.' + property;
if (propNeeded === property) {
return (fields + path).replace(/^\./, '');
} else if (Array.isArray(innerObject)) {
const fieldsArray = iterateArray(innerObject, path, fields, propNeeded);
if (fieldsArray.length > 0) {
return fieldsArray;
}
} else if (typeof innerObject === 'object' && innerObject !== null) {
return iterate(innerObject, path, fields, propNeeded);
}
}
}
function deleteFieldData(fieldcomponent, submission) {
if (Object.prototype.hasOwnProperty.call(fieldcomponent, 'columns')) {
// It's a layout component that has columns.
fieldcomponent.columns.map((subComponent) => {
deleteFieldData(subComponent, submission);
});
} else if (
Object.prototype.hasOwnProperty.call(fieldcomponent, 'components')
) {
// It's a layout component that has subcomponents, such as a panel.
fieldcomponent.components.map((subComponent) => {
deleteFieldData(subComponent, submission);
});
} else if (fieldcomponent?.validate?.isUseForCopy === false) {
const fieldPath = iterate(submission, '', '', fieldcomponent.key);
if (Array.isArray(fieldPath)) {
for (let path of fieldPath) {
_.unset(submission, path);
}
} else if (fieldPath) {
_.unset(submission, fieldPath);
}
}
}
try {
loadingSubmission.value = true;
const response = await formService.getSubmission(properties.submissionId);
submissionRecord.value = Object.assign({}, response.data.submission);
submission.value = submissionRecord.value.submission;
showModal.value =
submission.value.data.submit ||
submission.value.data.state == 'submitted' ||
!submissionRecord.value.draft ||
properties.readOnly
? false
: true;
form.value = response.data.form;
// Schedule status is already processed by backend (checkIsFormExpired)
// Set flags directly from the form schedule data
if (form.value.schedule && form.value.schedule.expire !== undefined) {
isFormScheduleExpired.value = form.value.schedule.expire === true;
isLateSubmissionAllowed.value =
form.value.schedule.allowLateSubmissions === true;
} else {
// Explicitly reset flags if no schedule
isFormScheduleExpired.value = false;
isLateSubmissionAllowed.value = false;
}
versionIdToSubmitTo.value = versionIdToSubmitTo.value
? versionIdToSubmitTo.value
: response.data?.version?.id;
if (!properties.isDuplicate) {
//As we know this is a Submission from existing one so we will wait for the latest version to be set on the getFormSchema
formSchema.value = response.data.version.schema;
version.value = response.data.version.version;
} else {
if (
response.data?.version?.schema?.components &&
response.data?.version?.schema?.components.length
) {
response.data.version.schema.components.map((component) => {
deleteFieldData(component, submission.value); //Delete all the fields data that are not enabled for duplication
});
}
}
// Get permissions
if (!properties.staffEditMode && !isFormPublic(form.value)) {
const permRes = await rbacService.getUserSubmissions({
formSubmissionId: properties.submissionId,
});
permissions.value = permRes.data[0] ? permRes.data[0].permissions : [];
}
} catch (error) {
notificationStore.addNotification({
text: t('trans.formViewer.getUsersSubmissionsErrMsg'),
consoleError: t('trans.formViewer.getUsersSubmissionsConsoleErrMsg', {
submissionId: properties.submissionId,
error: error,
}),
});
} finally {
loadingSubmission.value = false;
}
}
async function setProxyHeaders() {
try {
let response = await formService.getProxyHeaders({
formId: properties.formId,
versionId: properties.versionId,
submissionId: properties.submissionId,
});
// error checking for response
sessionStorage.setItem(
'X-CHEFS-PROXY-DATA',
response.data['X-CHEFS-PROXY-DATA']
);
} catch (error) {
// need error handling
}
}
// Get the form definition/schema
async function getFormSchema() {
try {
let response = undefined;
if (properties.versionId) {
versionIdToSubmitTo.value = properties.versionId;
// If getting for a specific older version of the form
response = await formService.readVersion(
properties.formId,
properties.versionId
);
if (!response.data || !response.data.schema) {
throw new Error(
t('trans.formViewer.readVersionErrMsg', {
versionId: properties.versionId,
})
);
}
form.value = response.data;
version.value = response.data.version;
formSchema.value = response.data.schema;
} else if (properties.draftId) {
// If getting for a specific draft version of the form for preview
response = await formService.readDraft(
properties.formId,
properties.draftId
);
if (!response.data || !response.data.schema) {
throw new Error(
t('trans.formViewer.readDraftErrMsg', {
draftId: properties.draftId,
})
);
}
form.value = response.data;
formSchema.value = response.data.schema;
} else {
// If getting the HEAD form version (IE making a new submission)
response = await formService.readPublished(properties.formId);
if (
!response ||
!response.data ||
!response.data.versions ||
!response.data.versions[0]
) {
router.push({
name: 'Alert',
query: {
text: t('trans.formViewer.alertRouteMsg'),
type: 'info',
},
});
return;
}
form.value = response.data;
version.value = response.data.versions[0].version;
versionIdToSubmitTo.value = response.data.versions[0].id;
formSchema.value = response.data.versions[0].schema;
if (response.data.schedule && response.data.schedule.expire) {
let formScheduleStatus = response.data.schedule;
isFormScheduleExpired.value = formScheduleStatus.expire;
isLateSubmissionAllowed.value = formScheduleStatus.allowLateSubmissions;
}
}
} catch (error) {
if (authenticated.value) {
// if 401 error, the user is not authorized to view the form
if (error.response && error.response.status === 401) {
isAuthorized.value = false;
} else {
// throw a generic error message
notificationStore.addNotification({
text: t('trans.formViewer.fecthingFormErrMsg'),
consoleError: t('trans.formViewer.fecthingFormConsoleErrMsg', {
versionId: properties.versionId,
error: error,
}),
});
}
}
}
}
function isProcessingMultiUpload(e) {
block.value = e;
}
function formChange(e) {
// if draft check validation on render
if (submissionRecord.value.draft) {
chefForm.value.formio.checkValidity(null, true, null, false);
}
if (e.changed != undefined && !e.changed.flags.fromSubmission) {
formDataEntered.value = true;
}
// Seems to be the only place the form changes on load
jsonManager();
}
function jsonManager() {
json_csv.value.file_name = 'template_' + form.value.name + '_' + Date.now();
if (chefForm.value?.formio) {
formElement.value = chefForm.value.formio;
json_csv.value.data = [
JSON.parse(JSON.stringify(formElement.value._data)),
JSON.parse(JSON.stringify(formElement.value._data)),
];
}
}
async function saveDraft() {
try {
saving.value = true;
const response = await sendSubmission(true, submission.value);
if (
properties.submissionId &&
properties.submissionId !== null &&
!properties.isDuplicate
) {
// Editing an existing draft
// Update this route with saved flag
if (!properties.saved) {
await router.replace({
name: 'UserFormDraftEdit',
query: { ...router.currentRoute.value.query, sv: true },
});
}
saving.value = false;
} else {
// Creating a new submission in draft state (fresh form or copied submission)
// Go to the user form draft page with the new draft's ID
await router.push({
name: 'UserFormDraftEdit',
query: {
s: response.data.id,
sv: true,
},
});
}
showSubmitConfirmDialog.value = false;
saveDraftDialog.value = false;
} catch (error) {
notificationStore.addNotification({
text: t('trans.formViewer.savingDraftErrMsg'),
consoleError: t('trans.formViewer.fecthingFormConsoleErrMsg', {
submissionId: properties.submissionId,
error: error,
}),
});
}
}
async function sendSubmission(isDraft, sub) {
submission.value.data.lateEntry =
form.value?.schedule?.expire !== undefined &&
form.value.schedule.expire === true
? form.value.schedule.allowLateSubmissions
: false;
const body = {
draft: isDraft,
submission: sub,
};
let response;
//let's check if this is a submission from existing one, If isDuplicate then create new submission if now isDuplicate then update the submission
if (properties.submissionId && !properties.isDuplicate) {
// Updating an existing submission
response = await formService.updateSubmission(
properties.submissionId,
body
);
} else {
// Adding a new submission
response = await formService.createSubmission(
properties.formId,
versionIdToSubmitTo.value,
body
);
}
return response;
}
function onFormRender() {
if (isLoading.value) isLoading.value = false;
}
// -----------------------------------------------------------------------------------------
// FormIO Events
// -----------------------------------------------------------------------------------------
// https://help.form.io/developers/form-renderer#form-events
// event order is:
// onSubmitButton
// onBeforeSubmit
// if no errors: onSubmit -> onSubmitDone
// else onSubmitError
function onSubmitButton(event) {
if (properties.preview) {
alert(t('trans.formViewer.submissionsPreviewAlert'));
return;
}
// this is our first event in the submission chain.
// most important thing here is ensuring that the formio form does not have an action, or else it POSTs to that action.
// console.info('onSubmitButton()') ; // eslint-disable-line no-console
currentForm.value = event.instance.parent.root;
currentForm.value.form.action = undefined;
// if form has drafts enabled in form settings, show 'confirm submit?' dialog
if (form.value.enableSubmitterDraft) {
showSubmitConfirmDialog.value = true;
}
}
// If the confirm modal pops up on drafts
function continueSubmit() {
confirmSubmit.value = true;
showSubmitConfirmDialog.value = false;
}
// formIO hook, prior to a submission occurring
// We can cancel a formIO submission event here, or go on
async function onBeforeSubmit(submission, next) {
// dont do anything if previewing the form
if (properties.preview) {
// Force re-render form.io to reset submit button state
reRenderFormIo.value += 1;
return;
}
// if form has drafts enabled in form setttings,
if (form.value.enableSubmitterDraft) {
let timeout;
// while 'confirm submit?' dialog is open..
while (showSubmitConfirmDialog.value) {
// await a promise that never resolves to block this thread
await new Promise((resolve) => (timeout = setTimeout(resolve, 500)));
}
if (confirmSubmit.value) {
confirmSubmit.value = false; // clear for next attempt
clearTimeout(timeout);
next();
} else {
// Force re-render form.io to reset submit button state
reRenderFormIo.value += 1;
}
} else {
next();
}
}
// FormIO submit event
// eslint-disable-next-line no-unused-vars
async function onSubmit(sub) {
if (properties.preview) {
alert(t('trans.formViewer.submissionsPreviewAlert'));
confirmSubmit.value = false;
return;
}
const errors = await doSubmit(sub);
// if we are here, the submission has been saved to our db
// the passed in submission is the formio submission, not our db persisted submission record...
// fire off the submitDone event.
if (errors) {
notificationStore.addNotification({
text: errors,
consoleError: t('trans.formViewer.submissionsSubmitErrMsg', {
errors: errors,
}),
});
// On error: reset button state without triggering navigation
// Force re-render form.io to reset submit button state
reRenderFormIo.value += 1;
} else if (currentForm.value?.events) {
// On success: emit submitDone to reset button AND trigger navigation via onSubmitDone handler
currentForm.value.events.emit('formio.submitDone');
}
}
// Helper function to extract submission data from response
function extractSubmissionData(response) {
if (properties.submissionId && properties.isDuplicate) {
return response.data;
}
if (properties.submissionId && !properties.isDuplicate) {
return response.data.submission;
}
return response.data;
}
// Helper function to extract error message from error object
function extractErrorMessage(error) {
if (error.response?.status === 403) {
// Backend returns schedule expiration message
return (
error.response.data?.detail ||
error.response.data?.message ||
formScheduleExpireMessage.value
);
}
if (error.response?.data?.detail) {
return error.response.data.detail;
}
if (error.response?.data?.message) {
return error.response.data.message;
}
return t('trans.formViewer.errMsg');
}
// Not a formIO event, our saving routine to POST the submission to our API
async function doSubmit(sub) {
// since we are not using formio api
// we should do the actual submit here, and return any error that occurrs to handle in the submit event
let errMsg = undefined;
try {
// Validate schedule before submission
if (isFormScheduleExpired.value && !isLateSubmissionAllowed.value) {
const errorMsg = formScheduleExpireMessage.value;
notificationStore.addNotification({
text: errorMsg,
consoleError: `Submission blocked: ${errorMsg}`,
});
return errorMsg; // This will be caught and handled by onSubmit
}
const response = await sendSubmission(false, sub);
if ([200, 201].includes(response.status)) {
// all is good, flag no errors and carry on...
// store our submission result...
submissionRecord.value = { ...extractSubmissionData(response) };
} else {
throw new Error(
t('trans.formViewer.sendSubmissionErrMsg', {
status: response.status,
})
);
}
} catch (error) {
errMsg = extractErrorMessage(error);
} finally {
confirmSubmit.value = false;
}
return errMsg;
}
async function onSubmitDone() {
// huzzah!
// really nothing to do, the formio button has consumed the event and updated its display
// is there anything here for us to do?
// console.info('onSubmitDone()') ; // eslint-disable-line no-console
// Note: This handler is only called on successful submission (when formio.submitDone is emitted)
// On errors, we use reRenderFormIo to reset button without triggering this handler
if (properties.staffEditMode) {
// updating an existing submission on the staff side
emit('submission-updated');
} else {
// User created new submission
router.push({
name: 'FormSuccess',
query: {
s: submissionRecord.value.id,
},
});
}
}
// Custom Event triggered from buttons with Action type "Event"
function onCustomEvent(event) {
alert(t('trans.formViewer.customEventAlert', { event: event.type }));
}
function switchView() {
if (!bulkFile.value) {
showdoYouWantToSaveTheDraftModalForSwitch();
return;
}
bulkFile.value = !bulkFile.value;
}
function showdoYouWantToSaveTheDraftModalForSwitch() {
saveDraftState.value = 1;
if (formDataEntered.value && showModal.value) {
doYouWantToSaveTheDraft.value = true;
} else {
leaveThisPage();
}
}
function showdoYouWantToSaveTheDraftModal() {
if (!bulkFile.value) {
saveDraftState.value = 0;
if (
(properties.submissionId == undefined || formDataEntered.value) &&
showModal.value &&
form.value.enableSubmitterDraft
) {
doYouWantToSaveTheDraft.value = true;
} else leaveThisPage();
} else {
leaveThisPage();
}
}
function leaveThisPage() {
if (saveDraftState.value == 0 || bulkFile.value) {
router.push({
name: 'UserSubmissions',
query: { f: form.value.id },
});
} else {
bulkFile.value = !bulkFile.value;
}
}
async function yes() {
await saveDraftFromModal(true);
}
async function no() {
await saveDraftFromModal(false);
}
async function saveDraftFromModal(event) {
doYouWantToSaveTheDraft.value = false;
if (event) {
await saveDraftFromModalNow();
} else {
leaveThisPage();
}
}
// Custom Event triggered from buttons with Action type "Event"
async function saveDraftFromModalNow() {
try {
saving.value = true;
await sendSubmission(true, submission.value);
saving.value = false;
// Creating a new submission in draft state
// Go to the user form draft page
leaveThisPage();
showSubmitConfirmDialog.value = false;
} catch (error) {
notificationStore.addNotification({
text: t('trans.formViewer.submittingDraftErrMsg'),
consoleError: t('trans.formViewer.submittingDraftConsErrMsg', {
submissionId: properties.submissionId,
error: error,
}),
});
}
}
function closeBulkYesOrNo() {
doYouWantToSaveTheDraft.value = false;
}
function beforeWindowUnload(e) {
if (!properties.preview && !properties.readOnly) {
e.preventDefault();
e.returnValue = '';
}
}
async function deleteFile(file) {
let fileId;
if (file?.data?.id) {
fileId = file.data.id;
} else if (file?.id) {
fileId = file.id;
} else {
fileId = undefined;
}
return fileService.deleteFile(fileId);
}
async function getFile(fileId, options = {}) {
await formStore.downloadFile(fileId, options);
if (downloadedFile.value?.data && downloadedFile.value?.headers) {
const blob = downloadedFile.value.data;
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = getDisposition(
downloadedFile.value.headers['content-disposition']
);
a.style.display = 'none';
a.classList.add('hiddenDownloadTextElement');
document.body.appendChild(a);
a.click();
downloadTimeout.value = setTimeout(() => {
document.body.removeChild(a);
URL.revokeObjectURL(url);
});
}
}
async function uploadFile(file, config = {}) {
const uploadConfig = {
...config,
formId: properties.formId,
};
return fileService.uploadFile(file, uploadConfig);
}
</script>
<template>
<v-skeleton-loader :loading="loadingSubmission" type="article, actions">
<v-container fluid>
<div v-if="!isAuthorized">
<v-alert
:text="formUnauthorizedMessage"
prominent
type="error"
:class="{ 'dir-rtl': isRTL }"
:lang="locale"
>
</v-alert>
</div>
<div v-else-if="isFormScheduleExpired && !properties.readOnly">
<v-alert
:text="
isLateSubmissionAllowed
? $t('trans.formViewer.lateFormSubmissions')
: formScheduleExpireMessage
"
prominent
type="info"
:class="{ 'dir-rtl': isRTL }"
:lang="locale"
>
</v-alert>
<div v-if="isLateSubmissionAllowed">
<v-col cols="12" md="6">
<v-btn
color="primary"
:class="{ 'dir-rtl': isRTL }"
:title="$t('trans.formViewer.createLateSubmission')"
@click="isFormScheduleExpired = false"
>
<span :lang="locale">{{
$t('trans.formViewer.createLateSubmission')
}}</span>
</v-btn>
</v-col>
</div>
</div>
<div v-else>
<div v-if="displayTitle">
<FormViewerActions
:allow-submitter-to-upload-file="form.allowSubmitterToUploadFile"
:block="block"
:bulk-file="bulkFile"
:copy-existing-submission="form.enableCopyExistingSubmission"
:draft-enabled="form.enableSubmitterDraft"
:form-id="form.id"
:is-draft="submissionRecord.draft"
:permissions="permissions"
:read-only="readOnly"
:submission="submission"
:submission-id="submissionId"
:wide-form-layout="form.wideFormLayout"
:public-form="isFormPublic(form)"
class="d-print-none"
@showdoYouWantToSaveTheDraftModal="showdoYouWantToSaveTheDraftModal"
@save-draft="saveDraft"
@switchView="switchView"
/>
<h1 class="my-6 text-center">{{ form.name }}</h1>
</div>
<div
class="form-wrapper"
:class="{ 'disable-file-downloads': shouldDisableFileDownloads }"
>
<v-alert
v-if="saved || saving"
:class="
saving
? NOTIFICATIONS_TYPES.INFO.class
: NOTIFICATIONS_TYPES.SUCCESS.class
"
:icon="
saving
? NOTIFICATIONS_TYPES.INFO.icon
: NOTIFICATIONS_TYPES.SUCCESS.icon
"
>
<div v-if="saving" :class="{ 'mr-2': isRTL }">
<v-progress-linear indeterminate :lang="locale" />
{{ $t('trans.formViewer.saving') }}
</div>
<div v-else :class="{ 'mr-2': isRTL }" :lang="locale">
{{ $t('trans.formViewer.draftSaved') }}
</div>
</v-alert>
<slot name="alert" :form="form" :class="{ 'dir-rtl': isRTL }" />