Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat/fix: FORMS-1483 queued file handling #1515

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
120 changes: 100 additions & 20 deletions app/frontend/src/components/designer/FormViewer.vue
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,8 @@ const json_csv = ref({
});
const loadingSubmission = ref(false);
const permissions = ref([]);
const queuedDeleteFiles = ref([]);
const queuedUploadFiles = ref([]);
const reRenderFormIo = ref(0);
const saveDraftDialog = ref(false);
const saveDraftState = ref(0);
Expand Down Expand Up @@ -796,7 +798,7 @@ async function saveDraft() {
try {
saving.value = true;

const response = await sendSubmission(true, submission.value);
const response = await sendSubmission(true);
if (properties.submissionId && properties.submissionId !== null) {
// Editing an existing draft
// Update this route with saved flag
Expand Down Expand Up @@ -831,15 +833,25 @@ async function saveDraft() {
}
}

async function sendSubmission(isDraft, sub) {
sub.data.lateEntry =
async function sendSubmission(isDraft) {
let err = await uploadQueuedFiles();
if (err) {
return;
}

err = await deleteQueuedFiles();
if (err) {
return;
}
jasonchung1871 marked this conversation as resolved.
Show resolved Hide resolved

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,
submission: submission.value,
};

let response;
Expand Down Expand Up @@ -931,14 +943,14 @@ async function onBeforeSubmit(submission, next) {

// FormIO submit event
// eslint-disable-next-line no-unused-vars
async function onSubmit(sub) {
async function onSubmit() {
if (properties.preview) {
alert(t('trans.formViewer.submissionsPreviewAlert'));
confirmSubmit.value = false;
return;
}

const errors = await doSubmit(sub);
const errors = await doSubmit();

// 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...
Expand All @@ -956,12 +968,12 @@ async function onSubmit(sub) {
}

// Not a formIO event, our saving routine to POST the submission to our API
async function doSubmit(sub) {
async function doSubmit() {
// 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 {
const response = await sendSubmission(false, sub);
const response = await sendSubmission(false);

if ([200, 201].includes(response.status)) {
// all is good, flag no errors and carry on...
Expand Down Expand Up @@ -1057,18 +1069,18 @@ function leaveThisPage() {
}
}

function yes() {
saveDraftFromModal(true);
async function yes() {
await saveDraftFromModal(true);
}

function no() {
saveDraftFromModal(false);
async function no() {
await saveDraftFromModal(false);
}

function saveDraftFromModal(event) {
async function saveDraftFromModal(event) {
doYouWantToSaveTheDraft.value = false;
if (event) {
saveDraftFromModalNow();
await saveDraftFromModalNow();
} else {
leaveThisPage();
}
Expand All @@ -1078,7 +1090,7 @@ function saveDraftFromModal(event) {
async function saveDraftFromModalNow() {
try {
saving.value = true;
await sendSubmission(true, submission.value);
await sendSubmission(true);
saving.value = false;
// Creating a new submission in draft state
// Go to the user form draft page
Expand Down Expand Up @@ -1106,9 +1118,11 @@ function beforeWindowUnload(e) {
}
}

async function deleteFile(file) {
const fileId = file?.data?.id ? file.data.id : file?.id ? file.id : undefined;
return fileService.deleteFile(fileId);
function deleteFile(file, cfg) {
queuedDeleteFiles.value.push({
file: file,
onSuccess: cfg.onSuccess,
});
}

async function getFile(fileId, options = {}) {
Expand Down Expand Up @@ -1148,8 +1162,74 @@ async function getFile(fileId, options = {}) {
}
}

async function uploadFile(file, config = {}) {
return fileService.uploadFile(file, config);
function uploadFile(file, cfg = {}) {
queuedUploadFiles.value.push({
file: file,
config: {
onUploadProgress: cfg.onUploadProgress,
headers: cfg.headers,
},
onUploaded: cfg.onUploaded,
onError: cfg.onError,
});
}

async function uploadQueuedFiles() {
let err = false;
for (let i = queuedUploadFiles.value.length - 1; i >= 0; i--) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just curious: is there a reason to upload them in reverse order? If I add file 0, 1, and 2, my submission shows file 2, 1, and 0. Might the users find this to be unexpected behaviour?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The reasoning for this was because it was uploading files from the array, and when successful, would remove those files from the array. That way when running the upload file function again, it would just run through the array until it is empty.

let response;
try {
response = await fileService.uploadFile(
queuedUploadFiles.value[i].file,
queuedUploadFiles.value[i].config
);
queuedUploadFiles.value[i].onUploaded(response);
queuedUploadFiles.value.splice(i, 1);
} catch (error) {
err = true;
queuedUploadFiles.value[i].onError(error);
notificationStore.addNotification({
text: t('trans.formViewer.errorSavingFile', {
fileName: queuedUploadFiles.value[i].file.originalName,
error: error,
}),
consoleError: t('trans.formViewer.errorSavingFile', {
fileName: queuedUploadFiles.value[i].file.originalName,
error: error,
}),
});
}
}
return err;
}

async function deleteQueuedFiles() {
let err = false;
for (let i = queuedDeleteFiles.value.length - 1; i >= 0; i--) {
const fileId = queuedDeleteFiles.value[i].file?.data?.id
? queuedDeleteFiles.value[i].file.data.id
: queuedDeleteFiles.value[i].file?.id
? queuedDeleteFiles.value[i].file.id
: undefined;
try {
await fileService.deleteFile(fileId);
queuedDeleteFiles.value[i].onSuccess();
queuedDeleteFiles.value.splice(i, 1);
} catch (error) {
err = true;
notificationStore.addNotification({
text: t('trans.formViewer.errorDeletingFile', {
fileName: queuedDeleteFiles.value[i].file.originalName,
error: error,
}),
consoleError: t('trans.formViewer.errorDeletingFile', {
fileName: queuedDeleteFiles.value[i].file.originalName,
error: error,
}),
});
}
}
return err;
}
</script>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -829,6 +829,7 @@
"failedResSubmissn": "فشل الرد من نقطة نهاية الإرسال. رمز الاستجابة: {status}",
"errSubmittingForm": "حدث خطأ أثناء إرسال هذا النموذج",
"errorSavingFile": "خطأ في حفظ الملفات. اسم الملف: {fileName}. خطأ: {error}",
"errorDeletingFile": "خطأ في حذف الملفات. اسم الملف: {fileName}. الخطأ: {error}",
"submittingDraftErrMsg": "حدث خطأ أثناء حفظ المسودة",
"submittingDraftConsErrMsg": "خطأ في حفظ المسودة. معرف التقديم: {submitId}. خطأ: {error}",
"formDraftAccessErrMsg": "تم إرسال طلب التقديم بالفعل ، مع إعادة التوجيه إلى صفحة العرض",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -830,6 +830,7 @@
"failedResSubmissn": "Fehlgeschlagene Antwort vom Übermittlungsendpunkt. Antwortcode: {status}",
"errSubmittingForm": "Beim Absenden dieses Formulars ist ein Fehler aufgetreten",
"errorSavingFile": "Fehler beim Speichern der Dateien. Dateiname: {fileName}. Fehler: {error}",
"errorDeletingFile": "Fehler beim Löschen der Dateien. Dateiname: {fileName}. Fehler: {error}",
"submittingDraftErrMsg": "Beim Speichern eines Entwurfs ist ein Fehler aufgetreten",
"submittingDraftConsErrMsg": "Fehler beim Speichern des Entwurfs. Einreichungs-ID: {submissionId}. Fehler: {error}",
"formDraftAccessErrMsg": "Die angeforderte Übermittlung wurde bereits übermittelt und wird zur Ansichtsseite weitergeleitet",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -882,6 +882,7 @@
"failedResSubmissn": "Failed response from submission endpoint. Response code: {status}",
"errSubmittingForm": "An error occurred submitting this form",
"errorSavingFile": "Error saving files. Filename: {fileName}. Error: {error}",
"errorDeletingFile": "Error deleting files. Filename: {fileName}. Error: {error}",
"submittingDraftErrMsg": "An error occurred while saving a draft",
"submittingDraftConsErrMsg": "Error saving draft. SubmissionId: {submissionId}. Error: {error}",
"formDraftAccessErrMsg": "Requested submission is already submitted, redirecting to View page",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -829,6 +829,7 @@
"failedResSubmissn": "Respuesta fallida desde el punto final de envío. Código de respuesta: {status}",
"errSubmittingForm": "Ocurrió un error al enviar este formulario",
"errorSavingFile": "Error al guardar archivos. Nombre de archivo: {fileName}. Error: {error}",
"errorDeletingFile": "Error al eliminar archivos. Nombre de archivo: {fileName}. Error: {error}",
"submittingDraftErrMsg": "Se produjo un error al guardar un borrador",
"submittingDraftConsErrMsg": "Error al guardar el borrador. Id de envío: {submissionId}. Error: {error}",
"formDraftAccessErrMsg": "El envío solicitado ya se envió, redirigiendo a la página Ver",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -829,6 +829,7 @@
"failedResSubmissn": "پاسخ ناموفق از نقطه پایان ارسال. کد پاسخ: {status}",
"errSubmittingForm": "هنگام ارسال این فرم خطایی روی داد",
"errorSavingFile": "خطا در ذخیره فایل ها. نام فایل: {fileName}. خطا: {error}",
"errorDeletingFile": "خطا در حذف فایل ها نام فایل: {fileName}. خطا: {خطا}",
"submittingDraftErrMsg": "هنگام ذخیره پیش نویس خطایی روی داد",
"submittingDraftConsErrMsg": "خطا در ذخیره پیش نویس. SubmissionId: {submissionId}. خطا: {error}",
"formDraftAccessErrMsg": "ارسال درخواستی قبلا ارسال شده است، به صفحه مشاهده هدایت می شود",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -829,6 +829,7 @@
"failedResSubmissn": "Échec de la réponse du point de terminaison de soumission. Code de réponse : {status}",
"errSubmittingForm": "Une erreur s'est produite lors de la soumission de ce formulaire",
"errorSavingFile": "Erreur lors de l'enregistrement des fichiers. Nom de fichier : {fileName}. Erreur : {error}",
"errorDeletingFile": "Erreur lors de la suppression des fichiers. Nom de fichier : {fileName}. Erreur : {error}",
"submittingDraftErrMsg": "Une erreur s'est produite lors de l'enregistrement d'un brouillon",
"submittingDraftConsErrMsg": "Erreur lors de l'enregistrement du brouillon. ID de soumission : {submissionId}. Erreur : {error}",
"formDraftAccessErrMsg": "La soumission demandée est déjà soumise, redirigeant vers la page Afficher",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -829,6 +829,7 @@
"failedResSubmissn": "सबमिशन समापन बिंदु से विफल प्रतिक्रिया। प्रतिक्रिया कोड: {status}",
"errSubmittingForm": "इस फ़ॉर्म को सबमिट करते समय एक त्रुटि हुई",
"errorSavingFile": "फ़ाइलें सहेजने में त्रुटि. फ़ाइल का नाम: {fileName}. त्रुटि: {error}",
"errorDeletingFile": "फ़ाइलें हटाने में त्रुटि. फ़ाइल नाम: {fileName}. त्रुटि: {error}",
"submittingDraftErrMsg": "ड्राफ्ट सहेजते समय एक त्रुटि उत्पन्न हुई",
"submittingDraftConsErrMsg": "ड्राफ्ट सहेजने में त्रुटि. सबमिशनआईडी: {submissionId}। त्रुटि: {error}",
"formDraftAccessErrMsg": "अनुरोधित सबमिशन पहले ही सबमिट किया जा चुका है, व्यू पेज पर रीडायरेक्ट किया जा रहा है",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -829,6 +829,7 @@
"failedResSubmissn": "Risposta non riuscita dall'endpoint di invio. Codice di risposta: {status}",
"errSubmittingForm": "Si è verificato un errore durante l'invio di questo modulo",
"errorSavingFile": "Errore durante il salvataggio dei file. nome file: {fileName}. Errore: {error}",
"errorDeletingFile": "Errore durante l'eliminazione dei file. Nome file: {fileName}. Errore: {error}",
"submittingDraftErrMsg": "Si è verificato un errore durante il salvataggio di una bozza",
"submittingDraftConsErrMsg": "Errore durante il salvataggio della bozza. SubmissionId: {submissionId}. Errore: {error}",
"formDraftAccessErrMsg": "L'invio richiesto è già stato inviato, reindirizzamento alla pagina Visualizza",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -829,6 +829,7 @@
"failedResSubmissn": "送信エンドポイントからの応答が失敗しました。レスポンスコード: {status}",
"errSubmittingForm": "このフォームの送信中にエラーが発生しました",
"errorSavingFile": "ファイルの保存中にエラーが発生しました。ファイル名: {fileName}。エラー: {error}",
"errorDeletingFile": "ファイルの削除中にエラーが発生しました。ファイル名: {fileName}。エラー: {error}",
"submittingDraftErrMsg": "下書きの保存中にエラーが発生しました",
"submittingDraftConsErrMsg": "下書きの保存中にエラーが発生しました。送信 ID: {submissionId}。エラー: {error}",
"formDraftAccessErrMsg": "リクエストされた送信はすでに送信されており、[表示] ページにリダイレクトされます。",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -829,6 +829,7 @@
"failedResSubmissn": "제출 끝점에서 실패한 응답입니다. 응답 코드: {status}",
"errSubmittingForm": "이 양식을 제출하는 중에 오류가 발생했습니다.",
"errorSavingFile": "파일을 저장하는 중에 오류가 발생했습니다. 파일 이름: {fileName}. 오류: {error}",
"errorDeletingFile": "파일 삭제 오류. 파일 이름: {fileName}. 오류: {error}",
"submittingDraftErrMsg": "초안을 저장하는 중에 오류가 발생했습니다.",
"submittingDraftConsErrMsg": "초안을 저장하는 중에 오류가 발생했습니다. 제출 ID: {submissionId}. 오류: {error}",
"formDraftAccessErrMsg": "요청한 제출이 이미 제출되었으며 보기 페이지로 리디렉션됩니다.",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -829,6 +829,7 @@
"failedResSubmissn": "ਸਪੁਰਦਗੀ ਅੰਤਮ ਬਿੰਦੂ ਤੋਂ ਅਸਫਲ ਜਵਾਬ। ਜਵਾਬ ਕੋਡ: {status}",
"errSubmittingForm": "ਇਸ ਫਾਰਮ ਨੂੰ ਸਪੁਰਦ ਕਰਨ ਵਿੱਚ ਇੱਕ ਤਰੁੱਟੀ ਉਤਪੰਨ ਹੋਈ",
"errorSavingFile": "ਫ਼ਾਈਲਾਂ ਨੂੰ ਰੱਖਿਅਤ ਕਰਨ ਵਿੱਚ ਗੜਬੜ ਹੋਈ। ਫ਼ਾਈਲ ਦਾ ਨਾਮ: {fileName}। ਗਲਤੀ: {error}",
"errorDeletingFile": "ਫ਼ਾਈਲਾਂ ਨੂੰ ਮਿਟਾਉਣ ਵਿੱਚ ਗੜਬੜ ਹੋਈ। ਫ਼ਾਈਲ ਦਾ ਨਾਮ: {fileName}। ਗਲਤੀ: {error}",
"submittingDraftErrMsg": "ਡਰਾਫਟ ਨੂੰ ਸੁਰੱਖਿਅਤ ਕਰਨ ਦੌਰਾਨ ਇੱਕ ਤਰੁੱਟੀ ਉਤਪੰਨ ਹੋਈ",
"submittingDraftConsErrMsg": "ਡਰਾਫਟ ਸੁਰੱਖਿਅਤ ਕਰਨ ਵਿੱਚ ਤਰੁੱਟੀ। SubmissionId: {submissionId}। ਗਲਤੀ: {error}",
"formDraftAccessErrMsg": "ਬੇਨਤੀ ਕੀਤੀ ਸਪੁਰਦਗੀ ਪਹਿਲਾਂ ਹੀ ਸਪੁਰਦ ਕੀਤੀ ਗਈ ਹੈ, ਵੇਖੋ ਪੰਨੇ 'ਤੇ ਰੀਡਾਇਰੈਕਟ ਕੀਤਾ ਜਾ ਰਿਹਾ ਹੈ",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -829,6 +829,7 @@
"failedResSubmissn": "Falha na resposta do endpoint de envio. Código de resposta: {status}",
"errSubmittingForm": "Ocorreu um erro ao enviar este formulário",
"errorSavingFile": "Erro ao salvar arquivos. Nome do arquivo: {fileName}. Erro: {error}",
"errorDeletingFile": "Erro ao excluir arquivos. Nome do arquivo: {fileName}. Erro: {error}",
"submittingDraftErrMsg": "Ocorreu um erro ao salvar um rascunho",
"submittingDraftConsErrMsg": "Erro ao salvar rascunho. SubmissãoId: {submissionId}. Erro: {error}",
"formDraftAccessErrMsg": "O envio solicitado já foi enviado, redirecionando para a página Exibir",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -829,6 +829,7 @@
"failedResSubmissn": "Неудачный ответ от конечной точки отправки. Код ответа: {status}",
"errSubmittingForm": "При отправке этой формы произошла ошибка",
"errorSavingFile": "Ошибка сохранения файлов. Имя файла: {fileName}. Ошибка: {error}",
"errorDeletingFile": "Ошибка удаления файлов. Имя файла: {fileName}. Ошибка: {error}",
"submittingDraftErrMsg": "Произошла ошибка при сохранении черновика",
"submittingDraftConsErrMsg": "Не удалось сохранить черновик. Идентификатор записи: {submissionId}. Ошибка: {error}",
"formDraftAccessErrMsg": "Запрошенная отправка уже отправлена, перенаправление на страницу просмотра",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -829,6 +829,7 @@
"failedResSubmissn": "Nabigong tugon mula sa endpoint ng pagsusumite. Code ng tugon: {status}",
"errSubmittingForm": "Nagkaroon ng error sa pagsusumite ng form na ito",
"errorSavingFile": "Error sa pag-save ng mga file. Filename: {fileName}. Error: {error}",
"errorDeletingFile": "Error sa pagtanggal ng mga file. Filename: {fileName}. Error: {error}",
"submittingDraftErrMsg": "Nagkaroon ng error habang nagse-save ng draft",
"submittingDraftConsErrMsg": "Error sa pag-save ng draft. SubmissionId: {submissionId}. Error: {error}",
"formDraftAccessErrMsg": "Ang hiniling na pagsusumite ay naisumite na, nagre-redirect sa View page",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -828,6 +828,7 @@
"failedResSubmissn": "Помилка відповіді від кінцевої точки надсилання. Код відповіді: {status}",
"errSubmittingForm": "Під час надсилання цієї форми сталася помилка",
"errorSavingFile": "Помилка збереження файлів. Ім'я файлу: {fileName}. Помилка: {error}",
"errorDeletingFile": "Error sa pagtanggal ng mga file. Filename: {fileName}. Error: {error}",
"submittingDraftErrMsg": "Під час збереження чернетки сталася помилка",
"submittingDraftConsErrMsg": "Помилка збереження чернетки. SubmissionId: {submissionId}. Помилка: {error}",
"formDraftAccessErrMsg": "Запитане подання вже подано, переспрямовує на сторінку перегляду",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -829,6 +829,7 @@
"failedResSubmissn": "Phản hồi không thành công từ điểm cuối gửi. Mã phản hồi: {status}",
"errSubmittingForm": "Đã xảy ra lỗi khi gửi biểu mẫu này",
"errorSavingFile": "Lỗi khi lưu tệp. Tên tệp: {fileName}. Lỗi: {error}",
"errorDeletingFile": "Lỗi khi xóa tệp. Tên tệp: {fileName}. Lỗi: {error}",
"submittingDraftErrMsg": "Đã xảy ra lỗi khi lưu bản nháp",
"submittingDraftConsErrMsg": "Lỗi khi lưu bản nháp. Đệ trìnhId: {submissionId}. Lỗi: {error}",
"formDraftAccessErrMsg": "Yêu cầu gửi đã được gửi, chuyển hướng đến Xem trang",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -829,6 +829,7 @@
"failedResSubmissn": "提交端点响应失败。响应代码:{status}",
"errSubmittingForm": "提交此表单时出错",
"errorSavingFile": "保存文件时出错。文件名:{fileName}。错误:{error}",
"errorDeletingFile": "删除文件时出错。文件名:{fileName}。错误:{error}",
"submittingDraftErrMsg": "保存草稿时出错",
"submittingDraftConsErrMsg": "保存草稿时出错。提交 ID:{submissionId}。错误:{error}",
"formDraftAccessErrMsg": "请求的提交已提交,正在重定向到查看页面",
Expand Down
Loading