/*jslint browser devel:true, for:true, es6:true */ /*global alert, confirm, console, prompt, jQuery, window, webapi, Promise, async */ (function (disrSharedUploadfile, $, undef) { 'use strict'; // Private Properties // Private Methods function getAttachments(formSection, disr_submissionid, disr_relatedtablename, disr_relatedtablerecordid) { console.log('Getting attachments:', formSection, disr_submissionid, disr_relatedtablename, disr_relatedtablerecordid); return new Promise(function (resolve, reject) { try { var url = `/attachments?disr_submission=${disr_submissionid}&disr_formsection=${formSection}`; if(disr_relatedtablename != null && disr_relatedtablerecordid != null){ url = `/attachments?disr_submission=${disr_submissionid}&disr_formsection=${formSection}&disr_relatedtablename=${disr_relatedtablename}&disr_relatedtablerecordid=${disr_relatedtablerecordid}`; } console.debug("url:", url); webapi.safeAjax({ type: "GET", url: url, contentType: "application/json", headers: { "Prefer": "odata.include-annotations=*" }, success: function (data, textStatus, xhr) { const results = JSON.parse(data); console.log("No of attachments found:", results.length); var attachments = [], i = 0, result = null; for (i = 0; i < results.length; i += 1) { result = results[i]; attachments.push({ disr_attachmentid: result.disr_attachmentid, disr_filename: result.disr_filename, disr_filesize: result.disr_filesize, formated_filesize: disrSharedUtils.formatFileSize(result.disr_filesize), disr_formsection: result.disr_formsection, disr_internalfilename: result.disr_internalfilename, disr_isvirusscanned: result.disr_isvirusscanned, disr_submission: result.disr_submission, disr_relatedtablename: result.disr_relatedtablename, disr_relatedtablerecordid: result.disr_relatedtablerecordid, disr_url: result.disr_url, createdon: result.createdon, modifiedon: result.modifiedon }); } console.log('attachments resolving', attachments); resolve(attachments); }, error: function (xhr, textStatus, errorThrown) { throw errorThrown; } }); } catch (error) { console.error('Error getting attachments:', error); throw error; } }); } async function createAttachment(file, formSection, internalFilename, disr_submissionid, blobUrl, relatedtablename, relatedtablerecordid) { console.log('Creating attachment:', file, formSection, internalFilename, disr_submissionid, relatedtablename, relatedtablerecordid, blobUrl); const record = { disr_filename: file.name, disr_filesize: file.size, disr_formsection: formSection, disr_internalfilename: internalFilename, disr_relatedtablename: relatedtablename, disr_relatedtablerecordid: relatedtablerecordid, disr_url: blobUrl, "disr_Submission@odata.bind" : `/disr_submissions(${disr_submissionid})` // Lookup }; console.log("Creating disr_attachment : record: " + JSON.stringify(record)); const url = `/_api/disr_attachments`; return await webapi.safeAjax({ type: "POST", contentType: "application/json", url: url, data: JSON.stringify(record), success: function (data, textStatus, xhr) { var newId = xhr.getResponseHeader("entityid"); console.log('newId', newId); return newId; }, error: function (xhr, textStatus, errorThrown) { console.log(xhr); return null; } }); console.log(`Complete createAttachment`); } // Upload file to shared industry BLOB using token async function uploadFile(file, blobUrl) { console.log('Uploading file:', file, blobUrl); const sasToken = (await getAzureBlobSASToken()).data; const blobUrlWithToken = `${blobUrl}?${sasToken}`; try { const response = await fetch(blobUrlWithToken, { method: 'PUT', headers: { 'x-ms-blob-type': 'BlockBlob', 'Content-Type': file.type }, body: file }); if (response.ok) { console.log('File uploaded successfully'); return true; } else { console.error('File upload failed', response.status, response.statusText); return false; } } catch (error) { console.error('Error uploading file:', error); return false; } } // Get Azure Blob SAS Token from ServerLogic, use data property to access the token value from the response async function getAzureBlobSASToken() { return webapi.safeAjax({ type: "POST", contentType: "application/json", url: "/_api/serverlogics/GetEvAzureBlobSASToken", success: function(response, status, xhr) { }, error: function(err, status, xhr) { console.error("[getAzureBlobSASToken] Request failed.", err); } }); } // Public Methods disrSharedUploadfile.refresh = function (submissionId, formSection, fileInput, viewModel, relatedtablename, relatedtablerecordid) { console.log("disrSharedUploadfile.refresh", submissionId, formSection, fileInput, viewModel, relatedtablename, relatedtablerecordid); try { return getAttachments(formSection, submissionId, relatedtablename, relatedtablerecordid) .then(function (attachments) { if (attachments === null) { throw new Error(`No attachments found`); } // Remove error class if file upload is successful if (fileInput) { fileInput.removeClass('is-invalid'); } console.log("Setting viewModel for formSection:", formSection); viewModel.set(`disr_${formSection}`, attachments); const count = attachments.length; console.log('in disrSharedUploadfile.refresh', 'attachments count', count); viewModel.set(`disr_${formSection}counthidden`, count === 0 ? '' : count); return true; }); } catch (error) { console.error('Error getting attachments:', error); throw error; } }; disrSharedUploadfile.upload = async function (fileHandle, accountName, containerName, viewModel, relatedtablename, relatedtablerecordid) { event.preventDefault(); const fileInput = $(fileHandle); const formSection = fileInput.data('type'); console.log('formSection:', formSection); var files = fileInput[0].files; // Get the filename and extension var fileName = files[0].name; var fileExtension = fileName.split('.').pop().toLowerCase(); console.log('Filename:', fileName, 'File extension:', fileExtension); if (files.length <= 0) { return new Error('There is no key to get!'); } // Validate file size (e.g., max 20MB) var maxSize = 20 * 1024 * 1024; // 20MB if (files[0].size > maxSize) { return new Error(`Error: The file you have just tried to attach has put your nomination over the acceptable 20 mb limit for attachments.`); } // Validate file basedon on extensions in accept attribute var accept = event.target.getAttribute('accept').split(','); var isValid = accept.some(function(extension) { return extension.trim().toLowerCase().replace('.', '') === fileExtension; }); if (!isValid) { return new Error(`Error: The file "${fileName}" is not a "${accept.join(', ')}" file type.`); } // Quit if more than 20 files are attached /* if (!isValid) { return new Error(`Error: You can only attach a maximum of 20 documents per nomination.`); } */ const internalFilename = `${disrSharedUtils.generateGUID()}.${fileExtension}`; const filePath = `${internalFilename}`; const blobUrl = `https://${accountName}.blob.core.windows.net/${containerName}/${filePath}`; $('button.disr-attachments-refresh[data-type="' + formSection + '"]').each(function(){ // Hide button and show spinner disrSharedUiUtils.showRefreshSpinner(this, true); }); const attachmentId = await createAttachment(files[0], formSection, internalFilename, submission.disr_submissionid, blobUrl, relatedtablename, relatedtablerecordid ); if (attachmentId === null) { $('button.disr-attachments-refresh[data-type="' + formSection + '"]').each(function(){ // Show button and hide spinner disrSharedUiUtils.showRefreshSpinner(this, false); }); // Show error return new Error(`Creation of attachment record failed.`); } const isFileUploaded = await uploadFile(files[0], blobUrl); if (!isFileUploaded) { $('button.disr-attachments-refresh[data-type="' + formSection + '"]').each(function(){ // Show button and hide spinner disrSharedUiUtils.showRefreshSpinner(this, false); }); // Show error return new Error(`File upload failed.`); } // refresh attachment table await disrSharedUploadfile.refresh(submission.disr_submissionid, formSection, fileInput, viewModel, relatedtablename, relatedtablerecordid) ; // Clear the input fileInput.val(''); $('button.disr-attachments-refresh[data-type="' + formSection + '"]').each(function(){ // Show button and hide spinner disrSharedUiUtils.showRefreshSpinner(this, false); }); }; disrSharedUploadfile.delete = async function (attachmentId, formSection, blobUrl, viewModel) { console.log('Deleting attachmentId:', attachmentId, 'formSection:', formSection, 'blobUrl:', blobUrl); const sasToken = (await getAzureBlobSASToken()).data; const blobUrlWithToken = `${blobUrl}?${sasToken}`; $('button.disr-attachments-refresh[data-type="' + formSection + '"]').each(function() { // Show button and hide spinner disrSharedUiUtils.showRefreshSpinner(this, true); }); try { const url = `/_api/disr_attachments(${attachmentId})`; console.log('in delete', 'url:', url); var record = { statecode : 1, // Inactive statuscode : 102220001 // Delete }; return webapi.safeAjax({ type: "PATCH", url: url, contentType: "application/json", data: JSON.stringify(record), success: async function (data, textStatus, xhr) { console.log('disr_attachments record status set to DELETE', xhr); await disrSharedUploadfile.refresh(submission.disr_submissionid, formSection, null, viewModel); $('button.disr-attachments-refresh[data-type="' + formSection + '"]').each(function(){ // Show button and hide spinner disrSharedUiUtils.showRefreshSpinner(this, false); }); }, error: function (xhr, textStatus, errorThrown) { console.log(xhr); throw new Error(`Error deleting attachment: ${errorThrown}`); } }); } catch (error) { console.error(error); $('button.disr-attachments-refresh[data-type="' + formSection + '"]').each(function(){ // Show button and hide spinner disrSharedUiUtils.showRefreshSpinner(this, false); }); return error; } }; disrSharedUploadfile.getUploadedFileData = function (viewModel) { // Get count of all files var count = viewModel.disr_graticularBlockfiles.length + viewModel.disr_shapefiles.length + viewModel.disr_mapfiles.length + viewModel.disr_supportingDocumentfiles.length; // Get total size of all files var totalSize = 0; viewModel.disr_graticularBlockfiles.forEach(function (file) { totalSize += file.disr_filesize; }); viewModel.disr_shapefiles.forEach(function (file) { totalSize += file.disr_filesize; }); viewModel.disr_mapfiles.forEach(function (file) { totalSize += file.disr_filesize; }); viewModel.disr_supportingDocumentfiles.forEach(function (file) { totalSize += file.disr_filesize; }); return { count: count, totalSize: totalSize }; } /** * Download PDF file from given entity record * @param {*} entityLogicalName * @param {*} recordId * @param {*} fileColumnName * @returns */ disrSharedUploadfile.downloadPdfFile = function(entityLogicalName, recordId, fileColumnName) { if (!entityLogicalName || !recordId || !fileColumnName) { console.error("Missing required parameters for PDF download."); return; } var downloadUrl = "/_api/" + entityLogicalName + "(" + recordId + ")/" + fileColumnName + "/$value"; window.location.href = downloadUrl; } }(window.disrSharedUploadfile = window.disrSharedUploadfile || {}, jQuery));