Commit 957b4dca by Jhunel Adam Calub

return element bugs fix commit

parent 77429298
...@@ -24,7 +24,7 @@ ...@@ -24,7 +24,7 @@
<attribute name="maven.pomderived" value="true"/> <attribute name="maven.pomderived" value="true"/>
</attributes> </attributes>
</classpathentry> </classpathentry>
<classpathentry kind="con" path="org.eclipse.payara.tools.lib.system"> <classpathentry kind="con" path="fish.payara.eclipse.tools.server.lib.system">
<attributes> <attributes>
<attribute name="owner.project.facets" value="jst.web"/> <attribute name="owner.project.facets" value="jst.web"/>
</attributes> </attributes>
......
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<faceted-project> <faceted-project>
<runtime name="Payara Server 5 (5.2022.5)"/> <runtime name="Payara"/>
<fixed facet="jst.web"/> <fixed facet="jst.web"/>
<fixed facet="java"/> <fixed facet="java"/>
<fixed facet="wst.jsdt.web"/> <fixed facet="wst.jsdt.web"/>
......
...@@ -24,4 +24,5 @@ USERNAME=root ...@@ -24,4 +24,5 @@ USERNAME=root
PASSWORD=p455w0rd PASSWORD=p455w0rd
[SSO CONFIG] [SSO CONFIG]
PUBKEY = C:/Users/oang/git/web-ui-mobile2/WebGde/WebContent/WEB-INF/config/sso/pubkey.pem
\ No newline at end of file PUBKEY = C:/Users/jcalub/git/web-ui-479/WebGde/WebContent/WEB-INF/config/sso/pubkey.pem
\ No newline at end of file
...@@ -7,117 +7,157 @@ import { interval } from "../captureMetrics/captureMetrics.js"; ...@@ -7,117 +7,157 @@ import { interval } from "../captureMetrics/captureMetrics.js";
import { createConfirmationModal, createInfoModal, createModal } from "../genericPopup/genericPopup.js"; import { createConfirmationModal, createInfoModal, createModal } from "../genericPopup/genericPopup.js";
import { BPO_OBJECT, IMAGE_VIEWER_OBJECT, INDEXED_DB_STORAGE } from "../globalVariable.js"; import { BPO_OBJECT, IMAGE_VIEWER_OBJECT, INDEXED_DB_STORAGE } from "../globalVariable.js";
import { getUrlReturnElement } from "./bpoService.js"; import { getUrlReturnElement } from "./bpoService.js";
import { returnForm } from "../Submit/submit.js";
export async function returnElementBPO(elementId) { export async function returnElementBPO(elementId) {
try { try {
let response = await fetch(getUrlReturnElement(elementId), { method: "POST" });
let response = await fetch(getUrlReturnElement(elementId), { method: "POST" });
if (response.ok) {
// If the response status is 200 if (response.ok) {
return { success: true, data: await response.json() }; // If the response status is 200
} else { console.log("RETURNED")
// If the response status is not 200
return { success: false, error: `Error: ${response.status}` }; return { success: true, data: await response.json() };
} } else {
} catch (error) { // If the response status is not 200
// Handle connection errors or other issues return { success: false, error: `Error: ${response.status}` };
console.error('Error:', error); }
return { success: false, error: 'Connection error' }; } catch (error) {
} // Handle connection errors or other issues
console.error('Error:', error);
return { success: false, error: 'Connection error' };
}
} }
async function returnElementLogout(elementId) { async function returnElementLogout(elementId) {
let response = await fetch(getUrlReturnElement(elementId), {method: "POST"}); let response = await fetch(getUrlReturnElement(elementId), { method: "POST" });
if (response.status == 200) { if (response.status == 200) {
console.log('Element Returned'); console.log('Element Returned');
} }
// else{ // else{
// //PROMPT.createInfoPrompt(`Error ${response.status}: Returning element`); // //PROMPT.createInfoPrompt(`Error ${response.status}: Returning element`);
// logoutKeycloak(); // logoutKeycloak();
// } // }
return response.status; return response.status;
} }
function returnSaveXML(){ function returnSaveXML() {
var elementId = sessionStorage.getItem("element_id"); var elementId = sessionStorage.getItem("element_id");
let doctype; let doctype;
let section; let section;
// Validate all elements again // Validate all elements again
for(let element of document.getElementById("fields").elements) { for (let element of document.getElementById("fields").elements) {
if (element.style.display === 'none') continue if (element.style.display === 'none') continue
const { id, value,type } = element const { id, value, type } = element
const { valid } = validateInput(id, value) const { valid } = validateInput(id, value)
// Skip submit button // Skip submit button
if(type==='submit') continue if (type === 'submit') continue
if(id==='DocType') { if (id === 'DocType') {
doctype = element.options[element.selectedIndex].text; doctype = element.options[element.selectedIndex].text;
continue; continue;
} }
if(id==='Section') { if (id === 'Section') {
section = element.options[element.selectedIndex].text; section = element.options[element.selectedIndex].text;
continue; continue;
} }
} }
let filePaths = JSON.parse(sessionStorage.getItem("dir_files")); let filePaths = JSON.parse(sessionStorage.getItem("dir_files"));
let xmlData = { let xmlData = {
"projCode": PROJECT_CODE, "projCode": PROJECT_CODE,
"userId": sessionStorage.getItem("user_id"), "userId": sessionStorage.getItem("user_id"),
"elementId": elementId, "elementId": elementId,
"schema": SCHEMA_FILE_PATH, "schema": SCHEMA_FILE_PATH,
"totalRec":"1", "totalRec": "1",
"maxRec": "1", "maxRec": "1",
"totalKeystroke": "", "totalKeystroke": "",
"procTime": "", "procTime": "",
"procDuration": "", "procDuration": "",
"eob": "", "eob": "",
"exceptionRemark": "", "exceptionRemark": "",
"recordNo": "1", "recordNo": "1",
"totalSubRec": "1", "totalSubRec": "1",
"maxSubRec": "1", "maxSubRec": "1",
"imageName": "", "imageName": "",
"subRecordNo": "1", "subRecordNo": "1",
"eor": "N", "eor": "N",
"fields": fields, "fields": fields,
"outputDir": sessionStorage.getItem("element_file_loc") + "/" + (ENCODING_PASS == "PASS1" ? elementId + ".DTA" : elementId + ".DTB"), "outputDir": sessionStorage.getItem("element_file_loc") + "/" + (ENCODING_PASS == "PASS1" ? elementId + ".DTA" : elementId + ".DTB"),
"doctype": doctype, "doctype": doctype,
"section": section "section": section
} }
updateXMLException(xmlData); updateXMLException(xmlData);
return false; return false;
} }
/*export function createReturnWindow() {
async function returnButtonFunction() {
createLoadingModal("Returning Element", "Returning Element", null, null, null);
let response = await returnElementBPO(sessionStorage.getItem("element_id"));
if (response.success) {
let submitStatus;
submitStatus = await submitForm(e)
if (submitStatus) {
console.log("SUBMITTED")
sessionStorage.removeItem("section");
sessionStorage.removeItem("doctype");
removeLoadingModal();
goBackToElementListViewer();
} else {
console.log("LOL")
}
} else {
function errorReturn() {
removeLoadingModal();
}
createInfoModal(errorReturn, 'Error', `${response.error} while returning the element.`);
}
}
createConfirmationModal(returnButtonFunction, "Return to Item List Menu?", "Any unsubmitted inputs and items will be lost.");
}*/
export function createReturnWindow() { export function createReturnWindow() {
async function returnButtonFunction() { async function returnButtonFunction(e) {
createLoadingModal("Returning Element", "Returning Element", null, null, null); createLoadingModal("Returning Element", "Returning Element", null, null, null);
let response = await returnElementBPO(sessionStorage.getItem("element_id")); let response = await returnElementBPO(sessionStorage.getItem("element_id"));
if (response.success) { if (response.success) {
sessionStorage.removeItem("section"); let submitStatus;
sessionStorage.removeItem("doctype"); submitStatus = await returnForm(e);
removeLoadingModal(); if (submitStatus) {
goBackToElementListViewer(); sessionStorage.removeItem("section");
sessionStorage.removeItem("doctype");
}else{ removeLoadingModal();
function errorReturn(){ goBackToElementListViewer();
removeLoadingModal(); } else {
} sessionStorage.removeItem("section");
createInfoModal(errorReturn, 'Error', `${response.error} while returning the element.`); sessionStorage.removeItem("doctype");
} removeLoadingModal();
} }
} else {
createConfirmationModal(returnButtonFunction, "Return to Item List Menu?", "Any unsubmitted inputs and items will be lost."); function errorReturn() {
removeLoadingModal();
}
createInfoModal(errorReturn, 'Error', `${response.error} while returning the element.`);
}
}
createConfirmationModal(returnButtonFunction, "Return to Item List Menu?", null);
} }
function createButtonElem(className, buttonName, icon) { function createButtonElem(className, buttonName, icon) {
/* let buttonElem = document.createElement("button"); */ /* let buttonElem = document.createElement("button"); */
let buttonElem; let buttonElem;
......
...@@ -17,10 +17,10 @@ let newOption; ...@@ -17,10 +17,10 @@ let newOption;
export let schema; export let schema;
export async function generateFields(inputSchema, containerId) { export async function generateFields(inputSchema, containerId) {
if(IS_RETRIEVE_FROM_BPO){ if (IS_RETRIEVE_FROM_BPO) {
let elementId = sessionStorage.getItem("element_id"); let elementId = sessionStorage.getItem("element_id");
window.addEventListener('beforeunload', function (event) { window.addEventListener('beforeunload', function(event) {
returnElementBPO(elementId); returnElementBPO(elementId);
}); });
} }
...@@ -166,32 +166,32 @@ export async function generateFields(inputSchema, containerId) { ...@@ -166,32 +166,32 @@ export async function generateFields(inputSchema, containerId) {
// add handler event handler for dropdown // add handler event handler for dropdown
// separate handler is used to fit with the library used 'select2' // separate handler is used to fit with the library used 'select2'
$(document.body).ready(function () { $(document.body).ready(function() {
// Initialize Select2 // Initialize Select2
const dropdowns = $('.dropdown-input').select2({ const dropdowns = $('.dropdown-input').select2({
focus: false focus: false
}); });
// Remove the first two elements from the dropdowns array // Remove the first two elements from the dropdowns array
dropdowns.splice(0, 2); dropdowns.splice(0, 2);
// Attach event handlers // Attach event handlers
$('.dropdown-input').select2().on('select2:open', () => { $('.dropdown-input').select2().on('select2:open', () => {
// Focus on the search field when the dropdown is opened // Focus on the search field when the dropdown is opened
// document.querySelector('.select2-search__field').focus(); // document.querySelector('.select2-search__field').focus();
// Set the background color to yellow // Set the background color to yellow
document.querySelector('.select2-container--open').firstChild.firstChild.style.backgroundColor = 'yellow'; document.querySelector('.select2-container--open').firstChild.firstChild.style.backgroundColor = 'yellow';
}); });
$('.dropdown-input').select2().on('select2:close', () => { $('.dropdown-input').select2().on('select2:close', () => {
// Reset the background color when the dropdown is closed // Reset the background color when the dropdown is closed
if (document.querySelector('.select2-container--focus') !== null) { if (document.querySelector('.select2-container--focus') !== null) {
document.querySelector('.select2-container--focus').firstChild.firstChild.style.backgroundColor = ''; document.querySelector('.select2-container--focus').firstChild.firstChild.style.backgroundColor = '';
} }
}); });
// Attach event handler to the remaining dropdowns // Attach event handler to the remaining dropdowns
dropdowns.on('select2:close', handleDropdown); dropdowns.on('select2:close', handleDropdown);
...@@ -245,19 +245,19 @@ const noValidation = (key) => { ...@@ -245,19 +245,19 @@ const noValidation = (key) => {
*/ */
const inputHidden = (key, validation) => { const inputHidden = (key, validation) => {
try { try {
const input = document.createElement('textarea'); const input = document.createElement('textarea');
input.setAttribute('rows', 5); input.setAttribute('rows', 5);
input.setAttribute('id', key); input.setAttribute('id', key);
input.setAttribute('name', key); input.setAttribute('name', key);
input.setAttribute('cols', 30); input.setAttribute('cols', 30);
input.setAttribute('autocomplete', 'off'); input.setAttribute('autocomplete', 'off');
input.setAttribute('inputMode', validation.collection === 'email' ? 'email' : 'text'); input.setAttribute('inputMode', validation.collection === 'email' ? 'email' : 'text');
input.addEventListener('focusout', handleInput); input.addEventListener('focusout', handleInput);
return input; return input;
} catch (err) { } catch (err) {
throw err; throw err;
} }
} }
/** /**
...@@ -521,7 +521,7 @@ const inputImageCapture = (key, validation) => { ...@@ -521,7 +521,7 @@ const inputImageCapture = (key, validation) => {
if (event.target.files.length > 0) { if (event.target.files.length > 0) {
container2.classList.remove('input-invalid'); container2.classList.remove('input-invalid');
container2.classList.add('input-valid'); container2.classList.add('input-valid');
} }
}); });
const capturedImage = document.createElement('input'); const capturedImage = document.createElement('input');
...@@ -611,7 +611,7 @@ const inputVideoCapture = (key, validation) => { ...@@ -611,7 +611,7 @@ const inputVideoCapture = (key, validation) => {
if (event.target.files.length > 0) { if (event.target.files.length > 0) {
container2.classList.remove('input-invalid'); container2.classList.remove('input-invalid');
container2.classList.add('input-valid'); container2.classList.add('input-valid');
} }
}); });
const capturedImage = document.createElement('input'); const capturedImage = document.createElement('input');
...@@ -824,7 +824,7 @@ const inputFingerprintCapture = (key, validation) => { ...@@ -824,7 +824,7 @@ const inputFingerprintCapture = (key, validation) => {
if (event.target.files.length > 0) { if (event.target.files.length > 0) {
container2.classList.remove('input-invalid'); container2.classList.remove('input-invalid');
container2.classList.add('input-valid'); container2.classList.add('input-valid');
} }
}); });
const capturedImage = document.createElement('input'); const capturedImage = document.createElement('input');
...@@ -1113,7 +1113,7 @@ const inputFileUpload = (key, validation) => { ...@@ -1113,7 +1113,7 @@ const inputFileUpload = (key, validation) => {
container2.classList.toggle('input-invalid', !hasFiles); container2.classList.toggle('input-invalid', !hasFiles);
}); });
} }
const capturedImage = document.createElement('input'); const capturedImage = document.createElement('input');
capturedImage.setAttribute('id', `${key}_capturedImageData`); capturedImage.setAttribute('id', `${key}_capturedImageData`);
capturedImage.setAttribute('name', `${key}`); capturedImage.setAttribute('name', `${key}`);
...@@ -1331,15 +1331,15 @@ const inputChecklist = (key, validation) => { ...@@ -1331,15 +1331,15 @@ const inputChecklist = (key, validation) => {
dropdown1.classList.add('dropdown'); dropdown1.classList.add('dropdown');
var dropdownContent = document.createElement('div'); var dropdownContent = document.createElement('div');
dropdownContent.classList.add('dropdown-content'); dropdownContent.classList.add('dropdown-content');
dropdownContent.setAttribute('id',`checklistContainer_${key}`); dropdownContent.setAttribute('id', `checklistContainer_${key}`);
dropdown1.appendChild(dropdownContent); dropdown1.appendChild(dropdownContent);
var isOther = false; var isOther = false;
// Create the checkboxes for each item // Create the checkboxes for each item
items.forEach(function (item, index) { items.forEach(function(item, index) {
if (item.toLowerCase() === "other" || item.toLowerCase() === "others"){ if (item.toLowerCase() === "other" || item.toLowerCase() === "others") {
isOther = true; isOther = true;
}else{ } else {
var div = document.createElement('div'); var div = document.createElement('div');
div.classList.add('checkbox'); div.classList.add('checkbox');
...@@ -1352,15 +1352,15 @@ const inputChecklist = (key, validation) => { ...@@ -1352,15 +1352,15 @@ const inputChecklist = (key, validation) => {
checkbox.classList.add("checkboxFirst"); checkbox.classList.add("checkboxFirst");
checkbox.setAttribute('id', `${key}`); checkbox.setAttribute('id', `${key}`);
} }
div.appendChild(checkbox); div.appendChild(checkbox);
var label = document.createTextNode(item); var label = document.createTextNode(item);
div.appendChild(label); div.appendChild(label);
dropdownContent.appendChild(div) dropdownContent.appendChild(div)
} }
}) })
if(isOther){ if (isOther) {
// Create the checkbox dependent on an input text value // Create the checkbox dependent on an input text value
var dependentDiv = document.createElement('div'); var dependentDiv = document.createElement('div');
dependentDiv.classList.add('checkbox'); dependentDiv.classList.add('checkbox');
...@@ -1374,7 +1374,7 @@ const inputChecklist = (key, validation) => { ...@@ -1374,7 +1374,7 @@ const inputChecklist = (key, validation) => {
var dependentLabel = document.createTextNode('other'); var dependentLabel = document.createTextNode('other');
dependentDiv.appendChild(dependentLabel); dependentDiv.appendChild(dependentLabel);
dropdownContent.appendChild(dependentDiv); dropdownContent.appendChild(dependentDiv);
// Initially hide the input text box // Initially hide the input text box
var inputTextBox = document.createElement('input'); var inputTextBox = document.createElement('input');
inputTextBox.type = 'text'; inputTextBox.type = 'text';
...@@ -1384,7 +1384,7 @@ const inputChecklist = (key, validation) => { ...@@ -1384,7 +1384,7 @@ const inputChecklist = (key, validation) => {
dropdownContent.appendChild(inputTextBox); dropdownContent.appendChild(inputTextBox);
// Add event listener to the "other" checkbox // Add event listener to the "other" checkbox
dropdownContent.addEventListener('change', function () { dropdownContent.addEventListener('change', function() {
if (dependentCheckbox.checked) { if (dependentCheckbox.checked) {
inputTextBox.style.display = 'inline-block'; inputTextBox.style.display = 'inline-block';
} else { } else {
...@@ -1399,15 +1399,15 @@ const inputChecklist = (key, validation) => { ...@@ -1399,15 +1399,15 @@ const inputChecklist = (key, validation) => {
}); });
} }
dropdownContent.addEventListener('change', function () { dropdownContent.addEventListener('change', function() {
const checkboxButtons = document.getElementsByName(`checkboxChoices_${key}`); const checkboxButtons = document.getElementsByName(`checkboxChoices_${key}`);
checkboxButtons.forEach(checkbox => { checkboxButtons.forEach(checkbox => {
if (checkbox.checked) { if (checkbox.checked) {
dropdownContent.classList.remove('input-invalid'); dropdownContent.classList.remove('input-invalid');
dropdownContent.classList.add('input-valid'); dropdownContent.classList.add('input-valid');
errorDiv.innerHTML = ''; errorDiv.innerHTML = '';
} }
}); });
}); });
return dropdown1; return dropdown1;
...@@ -1435,15 +1435,15 @@ const inputRadiolist = (key, validation) => { ...@@ -1435,15 +1435,15 @@ const inputRadiolist = (key, validation) => {
dropdown1.classList.add('dropdown'); dropdown1.classList.add('dropdown');
var dropdownContent = document.createElement('div'); var dropdownContent = document.createElement('div');
dropdownContent.classList.add('dropdown-content'); dropdownContent.classList.add('dropdown-content');
dropdownContent.setAttribute('id',`dropdownContainer_${key}`); dropdownContent.setAttribute('id', `dropdownContainer_${key}`);
dropdown1.appendChild(dropdownContent); dropdown1.appendChild(dropdownContent);
var isOther = false; var isOther = false;
// Create radio buttons for each item // Create radio buttons for each item
items.forEach((item, index) => { items.forEach((item, index) => {
if (item.toLowerCase() === "other" || item.toLowerCase() === "others"){ if (item.toLowerCase() === "other" || item.toLowerCase() === "others") {
isOther = true; isOther = true;
}else{ } else {
var radioDiv = document.createElement('div'); var radioDiv = document.createElement('div');
radioDiv.classList.add('radio-like-checkbox'); radioDiv.classList.add('radio-like-checkbox');
...@@ -1463,7 +1463,7 @@ const inputRadiolist = (key, validation) => { ...@@ -1463,7 +1463,7 @@ const inputRadiolist = (key, validation) => {
dropdownContent.appendChild(radioDiv); dropdownContent.appendChild(radioDiv);
} }
}); });
if (isOther){ if (isOther) {
// Create the radio button dependent on an input text value // Create the radio button dependent on an input text value
var dependentDiv = document.createElement('div'); var dependentDiv = document.createElement('div');
dependentDiv.classList.add('radio-like-checkbox'); dependentDiv.classList.add('radio-like-checkbox');
...@@ -1486,31 +1486,31 @@ const inputRadiolist = (key, validation) => { ...@@ -1486,31 +1486,31 @@ const inputRadiolist = (key, validation) => {
dropdownContent.appendChild(inputTextBox); dropdownContent.appendChild(inputTextBox);
// Add event listener to the "other" radio button // Add event listener to the "other" radio button
dropdownContent.addEventListener('change', function () { dropdownContent.addEventListener('change', function() {
if (dependentRadio.checked) { if (dependentRadio.checked) {
inputTextBox.style.display = 'inline-block'; inputTextBox.style.display = 'inline-block';
} else { } else {
inputTextBox.style.display = 'none'; // Hide the input text box when "other" radio button is unchecked inputTextBox.style.display = 'none'; // Hide the input text box when "other" radio button is unchecked
} }
}); });
inputTextBox.addEventListener('change', event => { inputTextBox.addEventListener('change', event => {
if (dependentRadio.checked) { if (dependentRadio.checked) {
dependentRadio.value = event.target.value; dependentRadio.value = event.target.value;
} }
}); });
} }
dropdownContent.addEventListener('change', function () { dropdownContent.addEventListener('change', function() {
const radioButtons = document.getElementsByName(`radioChoices_${key}`); const radioButtons = document.getElementsByName(`radioChoices_${key}`);
radioButtons.forEach(radio => { radioButtons.forEach(radio => {
if (radio.checked) { if (radio.checked) {
dropdownContent.classList.remove('input-invalid'); dropdownContent.classList.remove('input-invalid');
dropdownContent.classList.add('input-valid'); dropdownContent.classList.add('input-valid');
errorDiv.innerHTML = ''; errorDiv.innerHTML = '';
} }
}); });
}); });
return dropdown1; return dropdown1;
...@@ -1570,46 +1570,46 @@ const inputGeoTag = (key, validation) => { ...@@ -1570,46 +1570,46 @@ const inputGeoTag = (key, validation) => {
*/ */
const inputDropdown = (key, validation) => { const inputDropdown = (key, validation) => {
try { try {
const { mandatory, options } = validation; const { mandatory, options } = validation;
const input = document.createElement('select'); const input = document.createElement('select');
const errorDiv = document.getElementById(`${key}_error`); const errorDiv = document.getElementById(`${key}_error`);
input.setAttribute('id', `${key}`); input.setAttribute('id', `${key}`);
input.setAttribute('name', `${key}`); input.setAttribute('name', `${key}`);
input.classList.add('dropdown-input'); input.classList.add('dropdown-input');
$(input).select2(); $(input).select2();
$(input).on('select2:select', function (e) { $(input).on('select2:select', function(e) {
// Get the selected value // Get the selected value
var selectedValue = e.params.data.id; var selectedValue = e.params.data.id;
// Your custom logic when an option is selected // Your custom logic when an option is selected
console.log('Selected option: ' + selectedValue); console.log('Selected option: ' + selectedValue);
}); });
if (options && options.length > 0) { if (options && options.length > 0) {
// Add a placeholder option // Add a placeholder option
const newOption = new Option('Choose an option', null, false, false); const newOption = new Option('Choose an option', null, false, false);
input.add(newOption); input.add(newOption);
// Add other options // Add other options
for (const option of options) { for (const option of options) {
const newOption = new Option(option, option, false, false); const newOption = new Option(option, option, false, false);
input.add(newOption); input.add(newOption);
}
} else {
// Add a disabled option if no options are available
const newOption = new Option('No option available', null, false, true);
input.add(newOption);
input.setAttribute('disabled', 'false');
} }
} else {
// Add a disabled option if no options are available return input;
const newOption = new Option('No option available', null, false, true);
input.add(newOption);
input.setAttribute('disabled', 'false');
}
return input;
} catch (err) { } catch (err) {
throw err; throw err;
} }
}; };
const inputDbLookup = async (key, validation) => { const inputDbLookup = async (key, validation) => {
try { try {
...@@ -1747,7 +1747,7 @@ const deconstruct = async (section, container, classAttribute) => { ...@@ -1747,7 +1747,7 @@ const deconstruct = async (section, container, classAttribute) => {
const validation = getValidation(key, schema) const validation = getValidation(key, schema)
const { mandatory } = validation; const { mandatory } = validation;
if (hidden) { if (hidden) {
const hiddenField = document.createElement('div') // will contain input field and label const hiddenField = document.createElement('div') // will contain input field and label
hiddenField.setAttribute('class', 'fieldContainer ' + classAttribute) hiddenField.setAttribute('class', 'fieldContainer ' + classAttribute)
...@@ -1774,7 +1774,7 @@ const deconstruct = async (section, container, classAttribute) => { ...@@ -1774,7 +1774,7 @@ const deconstruct = async (section, container, classAttribute) => {
hiddenInputGeo.setAttribute('class', classAttribute); hiddenInputGeo.setAttribute('class', classAttribute);
inputContainer.appendChild(hiddenInputGeo); inputContainer.appendChild(hiddenInputGeo);
break; break;
default: default:
const hiddenInputDefault = inputHidden(key, validation); const hiddenInputDefault = inputHidden(key, validation);
hiddenInputDefault.setAttribute('class', classAttribute); hiddenInputDefault.setAttribute('class', classAttribute);
...@@ -1805,7 +1805,7 @@ const deconstruct = async (section, container, classAttribute) => { ...@@ -1805,7 +1805,7 @@ const deconstruct = async (section, container, classAttribute) => {
mandatoryMarker.classList.add('asterisk'); mandatoryMarker.classList.add('asterisk');
mandatoryMarker.textContent = "*"; mandatoryMarker.textContent = "*";
if(mandatory){ if (mandatory) {
labelContainer.appendChild(mandatoryMarker) labelContainer.appendChild(mandatoryMarker)
}; };
...@@ -1882,7 +1882,7 @@ const deconstruct = async (section, container, classAttribute) => { ...@@ -1882,7 +1882,7 @@ const deconstruct = async (section, container, classAttribute) => {
input.classList.add(classAttribute) input.classList.add(classAttribute)
inputContainer.appendChild(input) inputContainer.appendChild(input)
if (hidden && ["geotag", "altitude", "direction"].includes(validation.collection)){ if (hidden && ["geotag", "altitude", "direction"].includes(validation.collection)) {
newField.style.display = 'none'; // Hide the input newField.style.display = 'none'; // Hide the input
newField.classList.add('hidden'); // Add 'hidden' class newField.classList.add('hidden'); // Add 'hidden' class
} }
...@@ -1917,7 +1917,7 @@ const deconstruct = async (section, container, classAttribute) => { ...@@ -1917,7 +1917,7 @@ const deconstruct = async (section, container, classAttribute) => {
const parentValues = section[element]["parentvalue"]; const parentValues = section[element]["parentvalue"];
const childOf = section[element]["childof"]; const childOf = section[element]["childof"];
if(childOf === selectId){ if (childOf === selectId) {
if (parentValues.includes(selectedValue)) { if (parentValues.includes(selectedValue)) {
grandParentInput.style.display = "flex"; grandParentInput.style.display = "flex";
childInput.setAttribute("required", "required"); childInput.setAttribute("required", "required");
...@@ -1933,13 +1933,13 @@ const deconstruct = async (section, container, classAttribute) => { ...@@ -1933,13 +1933,13 @@ const deconstruct = async (section, container, classAttribute) => {
//logic for show hide //logic for show hide
// get id of element that triggered select // get id of element that triggered select
selectElementId.on('select2:select', function (event) { selectElementId.on('select2:select', function(event) {
selectId = $(this).attr('id'); selectId = $(this).attr('id');
console.log('select Id:' + selectId); console.log('select Id:' + selectId);
}); });
// get value of selected option // get value of selected option
selectElement.on('select2:select', function (event) { selectElement.on('select2:select', function(event) {
selectedValue = event.params.data.id; selectedValue = event.params.data.id;
console.log('selected value: ' + selectedValue); console.log('selected value: ' + selectedValue);
showHideElements(section); showHideElements(section);
}); });
...@@ -1955,7 +1955,7 @@ const deconstruct = async (section, container, classAttribute) => { ...@@ -1955,7 +1955,7 @@ const deconstruct = async (section, container, classAttribute) => {
childInput.removeAttribute("required"); childInput.removeAttribute("required");
childInput.style.display = "none"; childInput.style.display = "none";
} }
return container return container
} catch (err) { } catch (err) {
...@@ -2161,8 +2161,8 @@ export async function populateFields() { ...@@ -2161,8 +2161,8 @@ export async function populateFields() {
document.querySelector('#DocType').value = doctype; document.querySelector('#DocType').value = doctype;
sessionStorage.setItem("doctype", doctype); sessionStorage.setItem("doctype", doctype);
const docType = $("#DocType"); const docType = $("#DocType");
if(docType[0]){ if (docType[0]) {
for (let i = 0; i < docType[0].options.length; i++) { for (let i = 0; i < docType[0].options.length; i++) {
if (docType[0].options[i].value == doctype) { if (docType[0].options[i].value == doctype) {
docType[0].options[i].selected = "selected" docType[0].options[i].selected = "selected"
...@@ -2173,11 +2173,11 @@ export async function populateFields() { ...@@ -2173,11 +2173,11 @@ export async function populateFields() {
sessionStorage.setItem("section", section); sessionStorage.setItem("section", section);
document.querySelector('#Section').value = section; document.querySelector('#Section').value = section;
const sectionElem =$("Section"); const sectionElem = $("Section");
for (let i = 0; i < document.getElementById("Section").options.length; i++) { for (let i = 0; i < document.getElementById("Section").options.length; i++) {
if (document.getElementById("Section").options[i].value == section) { if (document.getElementById("Section").options[i].value == section) {
document.getElementById("Section").options[i].selected = "selected"; document.getElementById("Section").options[i].selected = "selected";
if(sectionElem[0]){ if (sectionElem[0]) {
sectionElem.trigger('change'); sectionElem.trigger('change');
} }
} }
...@@ -2210,79 +2210,177 @@ export async function populateFields() { ...@@ -2210,79 +2210,177 @@ export async function populateFields() {
for (let [k, v] of Object.entries(fieldsobj)) { for (let [k, v] of Object.entries(fieldsobj)) {
for (let key of Object.keys(schema[doctype][section])) { for (let key of Object.keys(schema[doctype][section])) {
if (schema[doctype][section][key].aka == "field" + k) { if (schema[doctype][section][key].aka == "field" + k) {
console.log("key = " + key + +", value ="+v); console.log("key = " + key + ", value =" + v);
//console.log("validation: " + schema[doctype][section][key].validation.collection); //console.log("validation: " + schema[doctype][section][key].validation.collection);
fields["field" + k] = v; fields["field" + k] = v;
if (schema[doctype][section][key].hidden){ if (schema[doctype][section][key].hidden) {
document.getElementById(key).value = v; document.getElementById(key).value = v;
continue; continue;
} }
if(schema[doctype][section][key].validation.collection === 'radiolist'){ if (schema[doctype][section][key].validation.collection === 'radiolist') {
//retrieve the radio button value from the XML //retrieve the radio button value from the XML
const radioButton = document.querySelector(`#dropdownContainer_${key} input[value="${v}"]`); const radioButton = document.querySelector(`#dropdownContainer_${key} input[value="${v}"]`);
if(radioButton){ if (radioButton) {
radioButton.checked = true; radioButton.checked = true;
} else { } else {
const radOther1 = document.querySelector(`#dropdownContainer_${key} input[value="other"]`); const radOther1 = document.querySelector(`#dropdownContainer_${key} input[value="other"]`);
if(radOther1){ if (radOther1) {
radOther1.checked = true; radOther1.checked = true;
} }
const radOther2 = document.querySelector(`#dropdownContainer_${key} input[value="others"]`); const radOther2 = document.querySelector(`#dropdownContainer_${key} input[value="others"]`);
if(radOther2){ if (radOther2) {
radOther2.checked = true; radOther2.checked = true;
} }
document.getElementById(`dependentTB_${key}`).value = v; document.getElementById(`dependentTB_${key}`).value = v;
document.getElementById(`dependentTB_${key}`).style.display = 'inline-block'; document.getElementById(`dependentTB_${key}`).style.display = 'inline-block';
} }
} else if(schema[doctype][section][key].validation.collection === 'checklist') { } else if (schema[doctype][section][key].validation.collection === 'checklist') {
const checklistArrayValues = v.split(","); const checklistArrayValues = v.split(",");
let otherValues = ""; let otherValues = "";
let isFirstCheckboxOtherValue = true; let isFirstCheckboxOtherValue = true;
let checkboxOtherValue = ""; let checkboxOtherValue = "";
for(let checklistValue of checklistArrayValues){ for (let checklistValue of checklistArrayValues) {
console.log("Array Values: " + checklistValue); console.log("Array Values: " + checklistValue);
const checklistbox = document.querySelector(`#checklistContainer_${key} input[value="${checklistValue}"]`); const checklistbox = document.querySelector(`#checklistContainer_${key} input[value="${checklistValue}"]`);
if(checklistbox){ if (checklistbox) {
checklistbox.checked = true; checklistbox.checked = true;
if(checklistValue === "other" || checklistValue === "others"){ if (checklistValue === "other" || checklistValue === "others") {
checkboxOtherValue = checklistValue; checkboxOtherValue = checklistValue;
document.getElementById(`dependentTB_${key}`).value = checkboxOtherValue; document.getElementById(`dependentTB_${key}`).value = checkboxOtherValue;
document.getElementById(`dependentTB_${key}`).style.display = 'inline-block'; document.getElementById(`dependentTB_${key}`).style.display = 'inline-block';
isFirstCheckboxOtherValue = false; isFirstCheckboxOtherValue = false;
} }
} else { } else {
if(isFirstCheckboxOtherValue){ if (isFirstCheckboxOtherValue) {
checkboxOtherValue = checklistValue; checkboxOtherValue = checklistValue;
isFirstCheckboxOtherValue = false; isFirstCheckboxOtherValue = false;
} else{ } else {
checkboxOtherValue = checkboxOtherValue + "," + checklistValue; checkboxOtherValue = checkboxOtherValue + "," + checklistValue;
} }
const checkOther1 = document.querySelector(`#checklistContainer_${key} input[value="other"]`); const checkOther1 = document.querySelector(`#checklistContainer_${key} input[value="other"]`);
if(checkOther1){ if (checkOther1) {
console.log("checkOther1 checked"); console.log("checkOther1 checked");
checkOther1.checked = true; checkOther1.checked = true;
} }
const checkOther2 = document.querySelector(`#checklistContainer_${key} input[value="others"]`); const checkOther2 = document.querySelector(`#checklistContainer_${key} input[value="others"]`);
if(checkOther2){ if (checkOther2) {
console.log("checkOther2 checked"); console.log("checkOther2 checked");
checkOther2.checked = true; checkOther2.checked = true;
} }
document.getElementById(`dependentTB_${key}`).value = checkboxOtherValue; document.getElementById(`dependentTB_${key}`).value = checkboxOtherValue;
document.getElementById(`dependentTB_${key}`).style.display = 'inline-block'; document.getElementById(`dependentTB_${key}`).style.display = 'inline-block';
} }
} }
} else{ } else if (schema[doctype][section][key].validation.collection === 'image-capture') {
let fileSizeStr;
const endpointUrl = sessionStorage.getItem('gde_domain') + "svc/gfs-rest/fetch-local";
const elementFileLoc = sessionStorage.getItem('element_file_loc');
const filePath = `file://${elementFileLoc}/${v}`;
// JSON payload
const payload = {
"dir": filePath
};
// Bearer token from sessionStorage
const token = sessionStorage.getItem('token');
// Headers
const headers = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
};
// Fetch options
const options = {
method: 'POST',
headers: headers,
body: JSON.stringify(payload)
};
// Make the fetch request
fetch(endpointUrl, options)
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const contentDisposition = response.headers.get('content-disposition');
const fileSizeMatch = /size="([^"]+)"/.exec(contentDisposition);
fileSizeStr = fileSizeMatch ? fileSizeMatch[1] : null;
return response.blob();
})
.then(blobData => {
let blobUrl = URL.createObjectURL(blobData);
var img = document.getElementById(key + '_zz');
img.src = blobUrl;
processCapture(key, v, fileSizeStr);
})
.catch(error => {
console.error('Fetch error:', error);
});
} else if (schema[doctype][section][key].validation.collection === 'fingerprint') {
const endpointUrl = sessionStorage.getItem('gde_domain') + "svc/gfs-rest/fetch-local";
const elementFileLoc = sessionStorage.getItem('element_file_loc');
const filePath = `file://${elementFileLoc}/${v}`;
// JSON payload
const payload = {
"dir": filePath
};
// Bearer token from sessionStorage
const token = sessionStorage.getItem('token');
// Headers
const headers = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
};
// Fetch options
const options = {
method: 'POST',
headers: headers,
body: JSON.stringify(payload)
};
// Make the fetch request
fetch(endpointUrl, options)
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.blob();
})
.then(blobData => {
let blobUrl = URL.createObjectURL(blobData);
var img = document.getElementById(key + '_zz');
img.src = blobUrl;
processFingerprint(key, v);
})
.catch(error => {
console.error('Fetch error:', error);
});
} else {
document.getElementById(key).value = v; document.getElementById(key).value = v;
} }
continue; continue;
......
...@@ -13,55 +13,107 @@ import { schema } from "./generateFields.js"; ...@@ -13,55 +13,107 @@ import { schema } from "./generateFields.js";
* errors - list of errors found during validation * errors - list of errors found during validation
*/ */
export const validateInput = (fieldID, value) => { export const validateInput = (fieldID, value) => {
try { try {
const { valid, error } = validateSchema() const { valid, error } = validateSchema()
if(!valid) return { valid: false, error: [`${error}`]} if (!valid) return { valid: false, error: [`${error}`] }
const validation = getValidation(fieldID) const validation = getValidation(fieldID)
if(!validation) return { valid: false, error: [`FieldName: '${fieldID}' not in schema`] } if (!validation) return { valid: false, error: [`FieldName: '${fieldID}' not in schema`] }
// Skip validation for hidden fields // Skip validation for hidden fields
if (isFieldHidden(fieldID)){ if (isFieldHidden(fieldID)) {
return { valid: true }; return { valid: true };
} }
switch(validation.collection) { switch (validation.collection) {
case 'email': case 'email':
return validateEmail(validation, value) return validateEmail(validation, value)
case 'alphanumeric': case 'alphanumeric':
return validateAlphanumeric(validation, value) return validateAlphanumeric(validation, value)
case 'alphabet': case 'alphabet':
return validateAlphabet(validation, value) return validateAlphabet(validation, value)
case 'specific': case 'specific':
case 'dropdown': case 'dropdown':
return validateSpecific(validation, value) return validateSpecific(validation, value)
case 'numeric': case 'numeric':
return validateNumeric(validation, value) return validateNumeric(validation, value)
case 'timepicker': case 'timepicker':
return validateTime(validation, value) return validateTime(validation, value)
case 'daterange': case 'daterange':
return validateDateRange(validation, value) return validateDateRange(validation, value)
case 'datepicker': case 'datepicker':
case 'date': case 'date':
// console.log('date') // console.log('date')
return validateDate(validation, value) return validateDate(validation, value)
case 'image-capture': case 'image-capture':
case 'video-capture': case 'video-capture':
case 'fingerprint': case 'fingerprint':
case 'file-upload': case 'file-upload':
return validateMedia(validation, fieldID); return validateMedia(validation, fieldID);
case 'radiolist': case 'radiolist':
return validateRadio(validation, fieldID); return validateRadio(validation, fieldID);
case 'checklist': case 'checklist':
return validateChecklist(validation, fieldID); return validateChecklist(validation, fieldID);
default: default:
return { valid: false, error: [`Collection of allowed values for field: ${fieldID} not found`]} return { valid: false, error: [`Collection of allowed values for field: ${fieldID} not found`] }
} }
} catch(err) { } catch (err) {
return { valid: false, error: [err]} return { valid: false, error: [err] }
} }
} }
export const validateReturnInput = (fieldID, value) => {
try {
const { valid, error } = validateSchema()
if (!valid) return { valid: false, error: [`${error}`] }
const validation = getValidation(fieldID)
if (!validation) return { valid: false, error: [`FieldName: '${fieldID}' not in schema`] }
// Skip validation for hidden fields
if (isFieldHidden(fieldID)) {
return { valid: true };
}
console.log(validation.collection)
switch (validation.collection) {
case 'email':
return validateReturnEmail(validation, value)
case 'alphanumeric':
return validateReturnAlphanumeric(validation, value)
case 'alphabet':
return validateReturnAlphabet(validation, value)
case 'specific':
case 'dropdown':
return validateReturnSpecific(validation, value)
case 'numeric':
return validateReturnNumeric(validation, value)
case 'timepicker':
case 'daterange':
case 'datepicker':
case 'date':
// console.log('date')
return validateReturnDate(validation, value)
case 'image-capture':
case 'video-capture':
case 'fingerprint':
case 'file-upload':
return validateReturnMedia(validation, fieldID);
case 'radiolist':
return validateReturnRadio(validation, fieldID);
case 'checklist':
return validateReturnChecklist(validation, fieldID);
default:
return { valid: false, error: [`Collection of allowed values for field: ${fieldID} not found`] }
}
} catch (err) {
return { valid: false, error: [err] }
}
}
/** /**
* *
* @param {*} fieldID * @param {*} fieldID
...@@ -70,18 +122,34 @@ export const validateInput = (fieldID, value) => { ...@@ -70,18 +122,34 @@ export const validateInput = (fieldID, value) => {
* validation of given key in schema * validation of given key in schema
*/ */
const validateEmail = (validation, value) => { const validateEmail = (validation, value) => {
const PATTERN_EMAIL = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ const PATTERN_EMAIL = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
let errors = [] let errors = []
const { mandatory, fieldLength } = validation const { mandatory, fieldLength } = validation
if(!mandatory && value.length===0) return { valid: true, errors: ['Field is required'] } if (!mandatory && value.length === 0) return { valid: true, errors: ['Field is required'] }
if(mandatory && (value.length===0 || !value.match(/\S/g))) return { valid: false, errors: ['Field is required.'] } if (mandatory && (value.length === 0 || !value.match(/\S/g))) return { valid: false, errors: ['Field is required.'] }
if(fieldLength && value.length>fieldLength) errors = [...errors, 'Input exceed maximum characters.'] if (fieldLength && value.length > fieldLength) errors = [...errors, 'Input exceed maximum characters.']
if(!value.match(PATTERN_EMAIL)) errors = [...errors, 'Please input valid email address.'] if (!value.match(PATTERN_EMAIL)) errors = [...errors, 'Please input valid email address.']
return { return {
valid: errors.length===0, valid: errors.length === 0,
errors errors
} }
}
const validateReturnEmail = (validation, value) => {
const PATTERN_EMAIL = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
let errors = []
const { fieldLength } = validation
if (fieldLength && value.length > fieldLength) errors = [...errors, 'Input exceed maximum characters.']
if (value && !value.match(PATTERN_EMAIL)) {
errors = [...errors, 'Please input a valid email address.'];
}
return {
valid: errors.length === 0,
errors
}
} }
/** /**
* *
...@@ -91,17 +159,17 @@ const validateEmail = (validation, value) => { ...@@ -91,17 +159,17 @@ const validateEmail = (validation, value) => {
* validation of given key in schema * validation of given key in schema
*/ */
export const getValidation = (fieldID) => { export const getValidation = (fieldID) => {
// const { SECTION } = schema // const { SECTION } = schema
let section = schema[sessionStorage.getItem("currentDoctype").replaceAll("_"," ")][sessionStorage.getItem("currentSection").replaceAll("_"," ")]; let section = schema[sessionStorage.getItem("currentDoctype").replaceAll("_", " ")][sessionStorage.getItem("currentSection").replaceAll("_", " ")];
try{ try {
if (Object.keys(section).includes(fieldID)) return section[fieldID].validation; if (Object.keys(section).includes(fieldID)) return section[fieldID].validation;
return null; return null;
} catch(err) { } catch (err) {
return null return null
} }
} }
/** /**
...@@ -116,28 +184,52 @@ export const getValidation = (fieldID) => { ...@@ -116,28 +184,52 @@ export const getValidation = (fieldID) => {
* errors - list of errors found during validation * errors - list of errors found during validation
*/ */
const validateAlphanumeric = (validation, value) => { const validateAlphanumeric = (validation, value) => {
let errors = [] let errors = []
const { mandatory, fieldLength, invalidchar } = validation const { mandatory, fieldLength, invalidchar } = validation
try { try {
if(mandatory && (value.length===0 || !value.match(/\S/g))) return { valid: false, errors: ['Field is required.'] } if (mandatory && (value.length === 0 || !value.match(/\S/g))) return { valid: false, errors: ['Field is required.'] }
if(fieldLength && value.length>fieldLength) errors = [...errors, 'Input exceed maximum characters'] if (fieldLength && value.length > fieldLength) errors = [...errors, 'Input exceed maximum characters']
if(invalidchar) { if (invalidchar) {
// method for escaping characters // method for escaping characters
// source: https://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript // source: https://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
const escaped_pattern = invalidchar.replace(/[-[\]{}()*+!<=:?.\/\\^$|#\s,]/g, '\\$&') const escaped_pattern = invalidchar.replace(/[-[\]{}()*+!<=:?.\/\\^$|#\s,]/g, '\\$&')
const pattern = new RegExp(`[${escaped_pattern}]`) const pattern = new RegExp(`[${escaped_pattern}]`)
if(pattern.test(value)) errors = [...errors, 'Has invalid character(s).'] if (pattern.test(value)) errors = [...errors, 'Has invalid character(s).']
} }
return { return {
valid: errors.length===0, valid: errors.length === 0,
errors errors
} }
} catch(err) { } catch (err) {
throw err throw err
} }
}
const validateReturnAlphanumeric = (validation, value) => {
let errors = []
const { fieldLength, invalidchar } = validation
try {
if (fieldLength && value.length > fieldLength) errors = [...errors, 'Input exceed maximum characters']
if (invalidchar) {
// method for escaping characters
// source: https://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
const escaped_pattern = invalidchar.replace(/[-[\]{}()*+!<=:?.\/\\^$|#\s,]/g, '\\$&')
const pattern = new RegExp(`[${escaped_pattern}]`)
if (pattern.test(value)) errors = [...errors, 'Has invalid character(s).']
}
return {
valid: errors.length === 0,
errors
}
} catch (err) {
throw err
}
} }
/** /**
...@@ -152,17 +244,30 @@ const validateAlphanumeric = (validation, value) => { ...@@ -152,17 +244,30 @@ const validateAlphanumeric = (validation, value) => {
* errors - list of errors found during validation * errors - list of errors found during validation
*/ */
const validateAlphabet = (validation, value) => { const validateAlphabet = (validation, value) => {
const PATTERN_ALPHABET = /[^A-Za-z\s]/g const PATTERN_ALPHABET = /[^A-Za-z\s]/g
let errors = [] let errors = []
const { mandatory, fieldLength } = validation const { mandatory, fieldLength } = validation
if(mandatory && (value.length===0 || !value.match(/\S/g))) return { valid: false, errors: ['Field is required.'] } if (mandatory && (value.length === 0 || !value.match(/\S/g))) return { valid: false, errors: ['Field is required.'] }
if(fieldLength && value.length>fieldLength) errors = [...errors, 'Input exceed maximum characters.'] if (fieldLength && value.length > fieldLength) errors = [...errors, 'Input exceed maximum characters.']
if(PATTERN_ALPHABET.test(value)) errors = [...errors, 'Has invalid character(s).'] if (PATTERN_ALPHABET.test(value)) errors = [...errors, 'Has invalid character(s).']
return { return {
valid: errors.length===0, valid: errors.length === 0,
errors errors
} }
}
const validateReturnAlphabet = (validation, value) => {
const PATTERN_ALPHABET = /[^A-Za-z\s]/g
let errors = []
const { fieldLength } = validation
if (fieldLength && value.length > fieldLength) errors = [...errors, 'Input exceed maximum characters.']
if (PATTERN_ALPHABET.test(value)) errors = [...errors, 'Has invalid character(s).']
return {
valid: errors.length === 0,
errors
}
} }
/** /**
...@@ -177,22 +282,40 @@ const validateAlphabet = (validation, value) => { ...@@ -177,22 +282,40 @@ const validateAlphabet = (validation, value) => {
* errors - list of errors found during validation * errors - list of errors found during validation
*/ */
const validateNumeric = (validation, value) => { const validateNumeric = (validation, value) => {
const PATTERN_NUMERIC = /[^0-9/-]/g const PATTERN_NUMERIC = /[^0-9/-]/g
let errors = [] let errors = []
const { mandatory, fieldLength } = validation const { mandatory, fieldLength } = validation
try { try {
if(mandatory && (value.length===0 || !value.match(/\S/g))) return { valid: false, errors: ['Field is required.'] } if (mandatory && (value.length === 0 || !value.match(/\S/g))) return { valid: false, errors: ['Field is required.'] }
if(fieldLength && value.length>fieldLength) errors = [...errors, 'Input exceed maximum characters.'] if (fieldLength && value.length > fieldLength) errors = [...errors, 'Input exceed maximum characters.']
if(PATTERN_NUMERIC.test(value)) errors = [...errors, 'Has invalid character(s).'] if (PATTERN_NUMERIC.test(value)) errors = [...errors, 'Has invalid character(s).']
return { return {
valid: errors.length===0, valid: errors.length === 0,
errors errors
} }
} catch(err) { } catch (err) {
throw err throw err
} }
}
const validateReturnNumeric = (validation, value) => {
const PATTERN_NUMERIC = /[^0-9/-]/g
let errors = []
const { fieldLength } = validation
try {
if (fieldLength && value.length > fieldLength) errors = [...errors, 'Input exceed maximum characters.']
if (PATTERN_NUMERIC.test(value)) errors = [...errors, 'Has invalid character(s).']
return {
valid: errors.length === 0,
errors
}
} catch (err) {
throw err
}
} }
/** /**
...@@ -207,17 +330,30 @@ const validateNumeric = (validation, value) => { ...@@ -207,17 +330,30 @@ const validateNumeric = (validation, value) => {
* errors - list of errors found during validation * errors - list of errors found during validation
*/ */
const validateDateRange = (validation, value) => { const validateDateRange = (validation, value) => {
const { mandatory, regexformat } = validation const { mandatory, regexformat } = validation
try {
if (mandatory && (value.length === 0 || !value.match(/\S/g))) return { valid: false, errors: ['Field is required.'] }
return { valid: true }
} catch (err) {
throw err
}
}
try{ const validateReturnDateRange = (validation, value) => {
if(mandatory && (value.length===0 || !value.match(/\S/g))) return { valid: false, errors: ['Field is required.'] }
return { valid: true }
} catch(err) { try {
throw err if ((value.length === 0 || !value.match(/\S/g))) return { valid: false, errors: ['Does not match required format'] }
}
return { valid: true }
} catch (err) {
throw err
}
} }
/** /**
* *
* @param {*} validation * @param {*} validation
...@@ -230,53 +366,102 @@ const validateDateRange = (validation, value) => { ...@@ -230,53 +366,102 @@ const validateDateRange = (validation, value) => {
* errors - list of errors found during validation * errors - list of errors found during validation
*/ */
const validateDate = (validation, value) => { const validateDate = (validation, value) => {
const { mandatory, regexformat, validdate } = validation const { mandatory, regexformat, validdate } = validation
try{ try {
if(mandatory && (value.length===0 || !value.match(/\S/g))) return { valid: false, errors: ['Field is required.'] } if (mandatory && (value.length === 0 || !value.match(/\S/g))) return { valid: false, errors: ['Field is required.'] }
if(validdate!=""){ if (validdate != "") {
if (value.length === 0) { if (value.length === 0) {
return { valid: true }; return { valid: true };
} }
const enteredDateParts = value.split('-'); const enteredDateParts = value.split('-');
if (enteredDateParts.length !== 3) { if (enteredDateParts.length !== 3) {
return { valid: false, errors: ['Invalid date format.'] }; return { valid: false, errors: ['Invalid date format.'] };
}
const enteredYear = parseInt(enteredDateParts[0]);
const enteredMonth = parseInt(enteredDateParts[1]) - 1; // Months are 0-based
const enteredDay = parseInt(enteredDateParts[2]);
const enteredDate = new Date(enteredYear, enteredMonth, enteredDay);
const currentDate = new Date();
console.log(currentDate);
switch(validdate){
case "past":
if (enteredDate < currentDate) {
return { valid: true }; // The date is in the past
} else {
return { valid: false, errors: ['Only past dates are allowed.'] };
}
case "current":
if (enteredDate = currentDate) {
return { valid: true }; // The date is today
} else {
return { valid: false, errors: ['Only current date is allowed.'] };
}
case "future":
if (enteredDate > currentDate) {
return { valid: true }; // The date is in the future
} else {
return { valid: false, errors: ['Only future dates are allowed.'] };
}
}
} }
return { valid: true } const enteredYear = parseInt(enteredDateParts[0]);
} catch(err) { const enteredMonth = parseInt(enteredDateParts[1]) - 1; // Months are 0-based
throw err const enteredDay = parseInt(enteredDateParts[2]);
}
const enteredDate = new Date(enteredYear, enteredMonth, enteredDay);
const currentDate = new Date();
console.log(currentDate);
switch (validdate) {
case "past":
if (enteredDate < currentDate) {
return { valid: true }; // The date is in the past
} else {
return { valid: false, errors: ['Only past dates are allowed.'] };
}
case "current":
if (enteredDate = currentDate) {
return { valid: true }; // The date is today
} else {
return { valid: false, errors: ['Only current date is allowed.'] };
}
case "future":
if (enteredDate > currentDate) {
return { valid: true }; // The date is in the future
} else {
return { valid: false, errors: ['Only future dates are allowed.'] };
}
}
}
return { valid: true }
} catch (err) {
throw err
}
}
const validateReturnDate = (validation, value) => {
const { validdate } = validation
try {
if (validdate != "") {
if (value.length === 0) {
return { valid: true };
}
const enteredDateParts = value.split('-');
if (enteredDateParts.length !== 3) {
return { valid: false, errors: ['Invalid date format.'] };
}
const enteredYear = parseInt(enteredDateParts[0]);
const enteredMonth = parseInt(enteredDateParts[1]) - 1; // Months are 0-based
const enteredDay = parseInt(enteredDateParts[2]);
const enteredDate = new Date(enteredYear, enteredMonth, enteredDay);
const currentDate = new Date();
console.log(currentDate);
switch (validdate) {
case "past":
if (enteredDate < currentDate) {
return { valid: true }; // The date is in the past
} else {
return { valid: false, errors: ['Only past dates are allowed.'] };
}
case "current":
if (enteredDate = currentDate) {
return { valid: true }; // The date is today
} else {
return { valid: false, errors: ['Only current date is allowed.'] };
}
case "future":
if (enteredDate > currentDate) {
return { valid: true }; // The date is in the future
} else {
return { valid: false, errors: ['Only future dates are allowed.'] };
}
}
}
return { valid: true }
} catch (err) {
throw err
}
} }
/** /**
...@@ -291,15 +476,26 @@ const validateDate = (validation, value) => { ...@@ -291,15 +476,26 @@ const validateDate = (validation, value) => {
* errors - list of errors found during validation * errors - list of errors found during validation
*/ */
const validateTime = (validation, value) => { const validateTime = (validation, value) => {
const { mandatory, regexformat } = validation const { mandatory, regexformat } = validation
try {
if (mandatory && (value.length === 0 || !value.match(/\S/g))) return { valid: false, errors: ['Field is required.'] }
try{ return { valid: true }
if(mandatory && (value.length===0 || !value.match(/\S/g))) return { valid: false, errors: ['Field is required.'] } } catch (err) {
throw err
}
}
const validateReturnTime = (validation, value) => {
try {
if ((value.length === 0 || !value.match(/\S/g))) return { valid: false, errors: ['Does not match required format'] }
return { valid: true } return { valid: true }
} catch(err) { } catch (err) {
throw err throw err
} }
} }
...@@ -316,18 +512,26 @@ const validateTime = (validation, value) => { ...@@ -316,18 +512,26 @@ const validateTime = (validation, value) => {
* errors - list of errors found during validation * errors - list of errors found during validation
*/ */
const validateSpecific = (validation, value) => { const validateSpecific = (validation, value) => {
const { mandatory, validchars, options } = validation const { mandatory, validchars, options } = validation
try { try {
if(mandatory && (value.length===0 || !value.match(/\S/g))) return { valid: false, errors: ['Field is required'] } if (mandatory && (value.length === 0 || !value.match(/\S/g))) return { valid: false, errors: ['Field is required'] }
if(validchars && validchars.includes(value)) return { valid: true } if (validchars && validchars.includes(value)) return { valid: true }
if(options && options.includes(value)) return {valid: true } if (options && options.includes(value)) return { valid: true }
if(!mandatory) return { valid: true } if (!mandatory) return { valid: true }
return { valid: false, errors: ['No option selected.'] } return { valid: false, errors: ['No option selected.'] }
} catch(err) { } catch (err) {
throw err throw err
} }
}
const validateReturnSpecific = (validation, value) => {
let errors = [];
return {
valid: errors.length === 0,
errors
}
} }
/** /**
...@@ -342,27 +546,36 @@ const validateSpecific = (validation, value) => { ...@@ -342,27 +546,36 @@ const validateSpecific = (validation, value) => {
* errors - list of errors found during validation * errors - list of errors found during validation
*/ */
const validateMedia = (validation, fieldID) => { const validateMedia = (validation, fieldID) => {
let errors = []; let errors = [];
const { mandatory } = validation const { mandatory } = validation
const inputElement = document.getElementById(`${fieldID}_thumbnail`); const inputElement = document.getElementById(`${fieldID}_thumbnail`);
const inputFilename = document.getElementById(`${fieldID}_fname`); const inputFilename = document.getElementById(`${fieldID}_fname`);
// Check if both inputElement and inputFilename are null // Check if both inputElement and inputFilename are null
if (mandatory && (!inputElement || !inputFilename)) { if (mandatory && (!inputElement || !inputFilename)) {
return { return {
valid: false, valid: false,
errors: ['No file attached.'] errors: ['No file attached.']
}; };
} }
if (mandatory && !inputElement.src && inputElement.src.trim() === '' && inputFilename.textContent.trim() === '') { if (mandatory && !inputElement.src && inputElement.src.trim() === '' && inputFilename.textContent.trim() === '') {
errors = [...errors, 'No File Attached.'] errors = [...errors, 'No File Attached.']
} }
return { return {
valid: errors.length===0, valid: errors.length === 0,
errors errors
}; };
}
const validateReturnMedia = (validation, fieldID) => {
let errors = [];
return {
valid: errors.length === 0,
errors
};
} }
/** /**
...@@ -377,26 +590,35 @@ const validateMedia = (validation, fieldID) => { ...@@ -377,26 +590,35 @@ const validateMedia = (validation, fieldID) => {
* errors - list of errors found during validation * errors - list of errors found during validation
*/ */
const validateRadio = (validation, fieldID) => { const validateRadio = (validation, fieldID) => {
let errors = []; let errors = [];
const { mandatory } = validation const { mandatory } = validation
const radioButtons = document.getElementsByName(`radioChoices_${fieldID}`); const radioButtons = document.getElementsByName(`radioChoices_${fieldID}`);
if (mandatory){ if (mandatory) {
let isChecked; let isChecked;
radioButtons.forEach(radio => { radioButtons.forEach(radio => {
if (radio.checked) { if (radio.checked) {
isChecked = true; isChecked = true;
} }
}); });
if (!isChecked) { if (!isChecked) {
errors = [...errors, 'No option selected.']; errors = [...errors, 'No option selected.'];
} }
} }
return { return {
valid: errors.length===0, valid: errors.length === 0,
errors errors
}; };
}
const validateReturnRadio = (validation, fieldID) => {
let errors = [];
return {
valid: errors.length === 0,
errors
};
} }
/** /**
...@@ -411,58 +633,67 @@ const validateRadio = (validation, fieldID) => { ...@@ -411,58 +633,67 @@ const validateRadio = (validation, fieldID) => {
* errors - list of errors found during validation * errors - list of errors found during validation
*/ */
const validateChecklist = (validation, fieldID) => { const validateChecklist = (validation, fieldID) => {
let errors = []; let errors = [];
const { mandatory } = validation const { mandatory } = validation
const checkboxButtons = document.getElementsByName(`checkboxChoices_${fieldID}`); const checkboxButtons = document.getElementsByName(`checkboxChoices_${fieldID}`);
if (mandatory){ if (mandatory) {
let isChecked; let isChecked;
checkboxButtons.forEach(checkbox => { checkboxButtons.forEach(checkbox => {
if (checkbox.checked) { if (checkbox.checked) {
isChecked = true; isChecked = true;
} }
}); });
if (!isChecked) { if (!isChecked) {
errors = [...errors, 'No option selected.']; errors = [...errors, 'No option selected.'];
} }
} }
return { return {
valid: errors.length===0, valid: errors.length === 0,
errors errors
}; };
}
const validateReturnChecklist = (validation, fieldID) => {
let errors = [];
return {
valid: errors.length === 0,
errors
};
} }
export const checkValidValues = (fieldID, value) => { export const checkValidValues = (fieldID, value) => {
try { try {
const validation = getValidation(fieldID); const validation = getValidation(fieldID);
if(!validation) return { isValidValue: false, errMsg: [`FieldName: '${fieldID}' not in schema`] }; if (!validation) return { isValidValue: false, errMsg: [`FieldName: '${fieldID}' not in schema`] };
if(typeof validation.validvalues !== "undefined") { if (typeof validation.validvalues !== "undefined") {
let validValues = validation.validvalues; let validValues = validation.validvalues;
const result = validValues.findIndex(item => value.toUpperCase() === item.toUpperCase()); const result = validValues.findIndex(item => value.toUpperCase() === item.toUpperCase());
if (result !== -1) { if (result !== -1) {
return { isValidValue: true }; return { isValidValue: true };
} else { } else {
return { isValidValue: false, errMsg: [`'${value}' is not a valid value. Choose between ${validValues}`] }; return { isValidValue: false, errMsg: [`'${value}' is not a valid value. Choose between ${validValues}`] };
} }
} }
return { isValidValue: true }; return { isValidValue: true };
} catch(err) { } catch (err) {
return { isValidValue: false, errMsg: [err]} return { isValidValue: false, errMsg: [err] }
} }
} }
function isFieldHidden(key) { function isFieldHidden(key) {
for (const docType in schema) { for (const docType in schema) {
for (const section in schema[docType]) { for (const section in schema[docType]) {
if (schema[docType][section][key] && schema[docType][section][key].hidden) { if (schema[docType][section][key] && schema[docType][section][key].hidden) {
return true; return true;
} }
} }
} }
return false; return false;
} }
\ No newline at end of file \ No newline at end of file
...@@ -2,43 +2,44 @@ import { initializeWebpage } from "../../startup.js"; ...@@ -2,43 +2,44 @@ import { initializeWebpage } from "../../startup.js";
import { initializeConfig } from "../config.js"; import { initializeConfig } from "../config.js";
import { createInfoModal } from "../genericPopup/genericPopup.js"; import { createInfoModal } from "../genericPopup/genericPopup.js";
export function loginGde(token){ export function loginGde(token) {
sessionStorage.setItem("token", token); sessionStorage.setItem("token", token);
var decodedToken = parseJwt(token); var decodedToken = parseJwt(token);
// Check if the decodedToken contains the desired properties // Check if the decodedToken contains the desired properties
if (decodedToken) { if (decodedToken) {
const { preferred_username, gde_domain, gde_bpo_domain, gde_bpo_node } = decodedToken; const { preferred_username, gde_domain, gde_bpo_domain, gde_bpo_node } = decodedToken;
// Now you can use these variables as needed // Now you can use these variables as needed
console.log("Preferred Username:", preferred_username); console.log("Preferred Username:", preferred_username);
sessionStorage.setItem("user_id", preferred_username); sessionStorage.setItem("user_id", preferred_username);
console.log("Domain:", gde_domain); console.log("Domain:", gde_domain);
console.log("Bpo Domain:", gde_bpo_domain); sessionStorage.setItem("gde_domain", gde_domain);
console.log("Node:", gde_bpo_node); console.log("Bpo Domain:", gde_bpo_domain);
initializeConfig(gde_domain, gde_bpo_domain, gde_bpo_node); console.log("Node:", gde_bpo_node);
createInfoModal(null, "OK", "Success! Logged in as "&preferred_username); initializeConfig(gde_domain, gde_bpo_domain, gde_bpo_node);
initializeWebpage(); createInfoModal(null, "OK", "Success! Logged in as " & preferred_username);
initializeWebpage();
// You can return these values or perform any other actions with them here // You can return these values or perform any other actions with them here
} else { } else {
// Handle the case where the token couldn't be decoded or doesn't contain the expected properties // Handle the case where the token couldn't be decoded or doesn't contain the expected properties
console.error("Invalid token or missing properties."); console.error("Invalid token or missing properties.");
} }
} }
export function fallbackLogin(user_id, gde_domain, bpo_domain, node){ export function fallbackLogin(user_id, gde_domain, bpo_domain, node) {
sessionStorage.setItem("user_id", user_id); sessionStorage.setItem("user_id", user_id);
initializeConfig(gde_domain, bpo_domain, node); initializeConfig(gde_domain, bpo_domain, node);
initializeWebpage(); initializeWebpage();
} }
function parseJwt (token) { function parseJwt(token) {
var base64Url = token.split('.')[1]; var base64Url = token.split('.')[1];
var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/'); var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
var jsonPayload = decodeURIComponent(window.atob(base64).split('').map(function(c) { var jsonPayload = decodeURIComponent(window.atob(base64).split('').map(function(c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2); return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join('')); }).join(''));
return JSON.parse(jsonPayload); return JSON.parse(jsonPayload);
} }
\ No newline at end of file
import { getUrlCompleteToNextNode } from "../BPO/bpoService.js"; import { getUrlCompleteToNextNode } from "../BPO/bpoService.js";
import { saveForm } from "../DataInputWidget/generateFields.js"; import { saveForm } from "../DataInputWidget/generateFields.js";
import { checkValidValues, validateInput } from "../DataInputWidget/validateInput.js"; import { checkValidValues, validateInput, validateReturnInput } from "../DataInputWidget/validateInput.js";
import { goBackToElementListViewer } from "../ElementListWidget/ElementListWidget.js"; import { goBackToElementListViewer } from "../ElementListWidget/ElementListWidget.js";
import { uploadFile } from "../FileUpload/fileUpload.js"; import { uploadFile } from "../FileUpload/fileUpload.js";
import { createLoadingModal, removeLoadingModal } from "../LoadingModal/LoadingModal.js"; import { createLoadingModal, removeLoadingModal } from "../LoadingModal/LoadingModal.js";
...@@ -28,19 +28,19 @@ export const submitForm = async (e) => { ...@@ -28,19 +28,19 @@ export const submitForm = async (e) => {
for (let element of elements) { for (let element of elements) {
if (element.style.display === 'none' || element.classList.contains('hidden')) { if (element.style.display === 'none' || element.classList.contains('hidden')) {
continue; continue;
} }
const { id, value, type, name } = element const { id, value, type, name } = element
const errorContainer = document.getElementById(`${id}_error`); const errorContainer = document.getElementById(`${id}_error`);
// Skip submit, buttons, and files // Skip submit, buttons, and files
if (element.classList.contains('radioOther') || element.classList.contains('checkboxOther')) continue; if (element.classList.contains('radioOther') || element.classList.contains('checkboxOther')) continue;
if (element.classList.contains('geotag') || element.classList.contains('altitude') || element.classList.contains('direction')) { if (element.classList.contains('geotag') || element.classList.contains('altitude') || element.classList.contains('direction')) {
continue; continue;
} }
if (type === 'submit') continue if (type === 'submit') continue
if (type === 'file') continue if (type === 'file') continue
if (type === 'hidden') continue if (type === 'hidden') continue
if (element.classList.contains('radioOption') && id.length === 0) continue if (element.classList.contains('radioOption') && id.length === 0) continue
if (element.classList.contains('checkboxOption') && id.length === 0) continue if (element.classList.contains('checkboxOption') && id.length === 0) continue
if (id === 'DocType') { if (id === 'DocType') {
doctype = element.options[element.selectedIndex].text; doctype = element.options[element.selectedIndex].text;
continue; continue;
...@@ -53,6 +53,7 @@ export const submitForm = async (e) => { ...@@ -53,6 +53,7 @@ export const submitForm = async (e) => {
const { valid, errors } = validateInput(id, value) const { valid, errors } = validateInput(id, value)
var { isValidValue, errMsg } = checkValidValues(id, value); var { isValidValue, errMsg } = checkValidValues(id, value);
console.log(valid + " " + errors + " " + isValidValue + " " + errMsg)
if (typeof errMsg !== "undefined") { if (typeof errMsg !== "undefined") {
errorMsg = errMsg; errorMsg = errMsg;
...@@ -65,15 +66,15 @@ export const submitForm = async (e) => { ...@@ -65,15 +66,15 @@ export const submitForm = async (e) => {
if (type === 'select-one') { if (type === 'select-one') {
continue continue
} }
if (type === 'button'){ if (type === 'button') {
errorContainer.innerHTML = errors; errorContainer.innerHTML = errors;
continue continue
} }
if (type === 'radio'){ if (type === 'radio') {
errorContainer.innerHTML = errors; errorContainer.innerHTML = errors;
continue continue
} }
if (type === 'checkbox'){ if (type === 'checkbox') {
errorContainer.innerHTML = errors; errorContainer.innerHTML = errors;
continue continue
} }
...@@ -84,7 +85,7 @@ export const submitForm = async (e) => { ...@@ -84,7 +85,7 @@ export const submitForm = async (e) => {
if (!isValidValue) { if (!isValidValue) {
error = true error = true
const field = document.getElementById(id); const field = document.getElementById(id);
field.classList.remove('input-valid'); field.classList.remove('input-valid');
field.classList.add('input-invalid'); field.classList.add('input-invalid');
...@@ -94,7 +95,7 @@ export const submitForm = async (e) => { ...@@ -94,7 +95,7 @@ export const submitForm = async (e) => {
} }
// TO-DO Separate validation for attached media (Image, Video, File) // TO-DO Separate validation for attached media (Image, Video, File)
for (let key of keys){ for (let key of keys) {
const inputElement = document.getElementById(`${key}_attachedMedia`); const inputElement = document.getElementById(`${key}_attachedMedia`);
if (inputElement.files.length === 0) { if (inputElement.files.length === 0) {
console.log(key + " empty"); console.log(key + " empty");
...@@ -119,13 +120,13 @@ export const submitForm = async (e) => { ...@@ -119,13 +120,13 @@ export const submitForm = async (e) => {
return return
} }
else { else {
if(IS_RETRIEVE_FROM_BPO === "N"){ if (IS_RETRIEVE_FROM_BPO === "N") {
let response = await WriteForm(e, [], doctype, section); let response = await WriteForm(e, [], doctype, section);
await batchUpload(Form); await batchUpload(Form);
if (response !== false) { if (response !== false) {
let folderName = sessionStorage.getItem("recentlySavedFileNameOnly"); let folderName = sessionStorage.getItem("recentlySavedFileNameOnly");
let folderPath = TEMPORARY_FOLDER +"/"+ folderName let folderPath = TEMPORARY_FOLDER + "/" + folderName
let filePath = { "filePath": folderPath + "/" + sessionStorage.getItem("recentlySavedFileName") }; let filePath = { "filePath": folderPath + "/" + sessionStorage.getItem("recentlySavedFileName") };
console.log(filePath); console.log(filePath);
const authToken = sessionStorage.getItem('token'); const authToken = sessionStorage.getItem('token');
...@@ -143,12 +144,12 @@ export const submitForm = async (e) => { ...@@ -143,12 +144,12 @@ export const submitForm = async (e) => {
createInfoModal(null, 'OK', 'Error while generating output.'); createInfoModal(null, 'OK', 'Error while generating output.');
return false return false
} }
}else { } else {
let response = await WriteForm(e, [], doctype, section); let response = await WriteForm(e, [], doctype, section);
await batchUpload(Form); await batchUpload(Form);
if (response !== false) { if (response !== false) {
let folderName = sessionStorage.getItem("recentlySavedFileNameOnly"); let folderName = sessionStorage.getItem("recentlySavedFileNameOnly");
let folderPath = TEMPORARY_FOLDER +"/"+ folderName let folderPath = TEMPORARY_FOLDER + "/" + folderName
let filePath = { "filePath": sessionStorage.getItem("element_file_loc") }; let filePath = { "filePath": sessionStorage.getItem("element_file_loc") };
console.log(filePath); console.log(filePath);
const authToken = sessionStorage.getItem('token'); const authToken = sessionStorage.getItem('token');
...@@ -174,17 +175,179 @@ export const submitForm = async (e) => { ...@@ -174,17 +175,179 @@ export const submitForm = async (e) => {
} }
} }
export async function createSubmitWindow(e){ export const returnForm = async (e) => {
try {
setGlobalEndTime(new Date().toLocaleString());
const Form = document.getElementById("fields");
const { elements } = Form
let error = false;
let errorMsg = null;
let doctype;
let section;
let keys = [];
// Validate all elements again
for (let element of elements) {
if (element.style.display === 'none' || element.classList.contains('hidden')) {
continue;
}
const { id, value, type, name } = element
const errorContainer = document.getElementById(`${id}_error`);
// Skip submit, buttons, and files
if (element.classList.contains('radioOther') || element.classList.contains('checkboxOther')) continue;
if (element.classList.contains('geotag') || element.classList.contains('altitude') || element.classList.contains('direction')) {
continue;
}
if (type === 'submit') continue
if (type === 'file') continue
if (type === 'hidden') continue
if (element.classList.contains('radioOption') && id.length === 0) continue
if (element.classList.contains('checkboxOption') && id.length === 0) continue
if (id === 'DocType') {
doctype = element.options[element.selectedIndex].text;
continue;
}
if (id === 'Section') {
section = element.options[element.selectedIndex].text;
continue;
}
const { valid, errors } = validateReturnInput(id, value)
/* var { isValidValue, errMsg } = checkValidValues(id, value);*/
console.log(valid + " " + errors);
/* if (typeof errMsg !== "undefined") {
errorMsg = errMsg;
}
*/
// Update display of input field if input is not valid
if (!valid) {
console.log(element);
error = true
if (type === 'select-one') {
continue
}
if (type === 'button') {
errorContainer.innerHTML = errors;
continue
}
if (type === 'radio') {
errorContainer.innerHTML = errors;
continue
}
if (type === 'checkbox') {
errorContainer.innerHTML = errors;
continue
}
const field = document.getElementById(id)
const newEvent = new Event('focusout')
field.dispatchEvent(newEvent)
}
/* if (!isValidValue) {
error = true
const field = document.getElementById(id);
field.classList.remove('input-valid');
field.classList.add('input-invalid');
errorContainer.innerHTML = errors;
field.select();
}*/
}
// TO-DO Separate validation for attached media (Image, Video, File)
for (let key of keys) {
const inputElement = document.getElementById(`${key}_attachedMedia`);
if (inputElement.files.length === 0) {
console.log(key + " empty");
let emptyMedia = document.getElementsByClassName(key);
console.log(emptyMedia[0]);
}
}
// Update display of dropdown field if input is not valid
const dropdowns = $('.dropdown-input').select2();
for (let dropdown of dropdowns) {
const newEvent = new Event('select2:close')
dropdown.dispatchEvent(newEvent)
}
if (error) {
if (errorMsg !== null) {
createErrorModal(null, 'Return', errorMsg);
} else {
createErrorModal(null, 'Return', 'Invalid or Missing data on highlighted fields!');
}
return
}
else {
if (IS_RETRIEVE_FROM_BPO === "N") {
let response = await WriteForm(e, [], doctype, section);
await batchUpload(Form);
if (response !== false) {
let folderName = sessionStorage.getItem("recentlySavedFileNameOnly");
let folderPath = TEMPORARY_FOLDER + "/" + folderName
let filePath = { "filePath": folderPath + "/" + sessionStorage.getItem("recentlySavedFileName") };
console.log(filePath);
const authToken = sessionStorage.getItem('token');
let getFile = await fetch(urlGetFile, {
method: "POST",
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${authToken}`
},
body: JSON.stringify(filePath)
});
console.log(getFile.text());
// await uploadTOGFS(getFile.text(), sessionStorage.getItem("recentlySavedFileName"));
} else {
createInfoModal(null, 'OK', 'Error while generating output.');
return false
}
} else {
let response = await WriteForm(e, [], doctype, section);
await batchUpload(Form);
if (response !== false) {
let folderName = sessionStorage.getItem("recentlySavedFileNameOnly");
let folderPath = TEMPORARY_FOLDER + "/" + folderName
let filePath = { "filePath": sessionStorage.getItem("element_file_loc") };
console.log(filePath);
const authToken = sessionStorage.getItem('token');
let getFile = await fetch(urlGetFile, {
method: "POST",
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${authToken}`
},
body: JSON.stringify(filePath)
});
} else {
createInfoModal(null, 'OK', 'Error while generating output.');
return false
}
}
// saveForm(sessionStorage.getItem("display_counter"));
}
return true
} catch (err) {
console.log(err)
return false
}
}
export async function createSubmitWindow(e) {
let submitStatus; let submitStatus;
async function okButtonFunction() { async function okButtonFunction() {
createLoadingModal("Submitting Element", "Please wait...", null, null, null); createLoadingModal("Submitting Element", "Please wait...", null, null, null);
submitStatus = await submitForm(e); submitStatus = await submitForm(e);
if(submitStatus){ if (submitStatus) {
removeLoadingModal(); removeLoadingModal();
DISPLAY_FIELD_OBJECT.clearForm(); DISPLAY_FIELD_OBJECT.clearForm();
if (SHOW_ELEMENT_LIST_VIEWER === "Y") { if (SHOW_ELEMENT_LIST_VIEWER === "Y") {
console.log("PUMASOK DITO");
createInfoModal(goBackToElementListViewer, 'ok', 'Form Submitted.'); createInfoModal(goBackToElementListViewer, 'ok', 'Form Submitted.');
} else { } else {
createInfoModal(null, 'ok', 'Form Submitted.'); createInfoModal(null, 'ok', 'Form Submitted.');
...@@ -192,15 +355,15 @@ export async function createSubmitWindow(e){ ...@@ -192,15 +355,15 @@ export async function createSubmitWindow(e){
if (IS_RETRIEVE_FROM_BPO === "Y") { if (IS_RETRIEVE_FROM_BPO === "Y") {
let response = await completeToNextNode(sessionStorage.getItem("element_id")); let response = await completeToNextNode(sessionStorage.getItem("element_id"));
} }
} else{ } else {
removeLoadingModal(); removeLoadingModal();
} }
}; };
return createConfirmationModal(okButtonFunction, "Submit Element?"); return createConfirmationModal(okButtonFunction, "Submit Element?");
} }
function validateMedia(key){ function validateMedia(key) {
const inputElement = document.getElementById(`${key}_attachedMedia`); const inputElement = document.getElementById(`${key}_attachedMedia`);
if (inputElement.files.length === 0) { if (inputElement.files.length === 0) {
console.log(key + " empty"); console.log(key + " empty");
...@@ -230,23 +393,23 @@ export async function completeToNextNode(elementId) { ...@@ -230,23 +393,23 @@ export async function completeToNextNode(elementId) {
return response; return response;
} }
export async function batchUpload(Form){ export async function batchUpload(Form) {
let Nodes = Form.elements; let Nodes = Form.elements;
let file; let file;
let fileName; let fileName;
let folderName; let folderName;
let directory; let directory;
if(IS_RETRIEVE_FROM_BPO==="N"){ if (IS_RETRIEVE_FROM_BPO === "N") {
folderName = sessionStorage.getItem("recentlySavedFileNameOnly"); folderName = sessionStorage.getItem("recentlySavedFileNameOnly");
directory = TEMPORARY_FOLDER + "/" + folderName directory = TEMPORARY_FOLDER + "/" + folderName
} else{ } else {
directory = sessionStorage.getItem("element_file_loc") directory = sessionStorage.getItem("element_file_loc")
} }
for (var i=0;i<Nodes.length;i++){ for (var i = 0; i < Nodes.length; i++) {
if (Nodes[i].name === 'hidden_file_content'){ if (Nodes[i].name === 'hidden_file_content') {
var fileId = Nodes[i].id; // Get the ID of the current node var fileId = Nodes[i].id; // Get the ID of the current node
file = Nodes[i].value file = Nodes[i].value
if(file){ if (file) {
for (var j = 0; j < Nodes.length; j++) { for (var j = 0; j < Nodes.length; j++) {
// Get file name from other node // Get file name from other node
if (Nodes[j].name === 'hidden_fname' && Nodes[j].id === fileId) { if (Nodes[j].name === 'hidden_fname' && Nodes[j].id === fileId) {
...@@ -260,72 +423,72 @@ export async function batchUpload(Form){ ...@@ -260,72 +423,72 @@ export async function batchUpload(Form){
} }
async function uploadTOGFS(stream, filename){ async function uploadTOGFS(stream, filename) {
await checkIfFolderExists(GFS_ROOT_FOLDER+"/"+sessionStorage.getItem("user_id"), "uploads"); await checkIfFolderExists(GFS_ROOT_FOLDER + "/" + sessionStorage.getItem("user_id"), "uploads");
await checkIfFolderExists(GFS_ROOT_FOLDER+"/"+sessionStorage.getItem("user_id")+"/uploads", PROJECT_CODE); await checkIfFolderExists(GFS_ROOT_FOLDER + "/" + sessionStorage.getItem("user_id") + "/uploads", PROJECT_CODE);
let xml = new File([stream], filename, {type: "text/plain"}); let xml = new File([stream], filename, { type: "text/plain" });
let formData = new FormData(); let formData = new FormData();
formData.append("file", xml); formData.append("file", xml);
formData.append("parentPath", GFS_ROOT_FOLDER+"/"+sessionStorage.getItem("user_id")+ "/uploads/"+PROJECT_CODE); formData.append("parentPath", GFS_ROOT_FOLDER + "/" + sessionStorage.getItem("user_id") + "/uploads/" + PROJECT_CODE);
formData.append("extraData", "{}"); formData.append("extraData", "{}");
formData.append("remarks", "Non-BPO Upload"); formData.append("remarks", "Non-BPO Upload");
formData.append("description", ""); formData.append("description", "");
formData.append("isSudo", false); formData.append("isSudo", false);
formData.append("inheritFolderMetadata", ""); formData.append("inheritFolderMetadata", "");
formData.append("hash", ""); formData.append("hash", "");
formData.append("isSigned", ""); formData.append("isSigned", "");
let response = await fetch(GFS_URL + "add-file", { let response = await fetch(GFS_URL + "add-file", {
method: "PUT", method: "PUT",
headers: { headers: {
'Authorization': sessionStorage.getItem("token"), 'Authorization': sessionStorage.getItem("token"),
'Accept-Encoding': "gzip, deflate, utf-8", 'Accept-Encoding': "gzip, deflate, utf-8",
'Accept': "*/*" 'Accept': "*/*"
}, },
body: formData body: formData
}); });
console.log(response); console.log(response);
} }
async function checkIfFolderExists(parentPath, folderName ){ async function checkIfFolderExists(parentPath, folderName) {
let url = GFS_URL + "check-folder?" + new URLSearchParams({folderPath: parentPath+"/"+folderName , isSudo: false }); let url = GFS_URL + "check-folder?" + new URLSearchParams({ folderPath: parentPath + "/" + folderName, isSudo: false });
let response = await fetch(url, { let response = await fetch(url, {
method: "GET", method: "GET",
headers: { headers: {
'Authorization': sessionStorage.getItem("token"), 'Authorization': sessionStorage.getItem("token"),
}, },
}); });
let result = response.json; let result = response.json;
if(result !== null && result.isExists === false){ if (result !== null && result.isExists === false) {
let createObj = { let createObj = {
"folderName": folderName, "folderName": folderName,
"parentPath": parentPath, "parentPath": parentPath,
"extraData": "{}", "extraData": "{}",
"isSudo": false, "isSudo": false,
// "remarks": "Non-BPO Upload", // "remarks": "Non-BPO Upload",
// "description": "", // "description": "",
// "inheritFolderMetadata":"", // "inheritFolderMetadata":"",
// "hash":"", // "hash":"",
// "isSigned": "" // "isSigned": ""
} }
await createGFSFolder(createObj); await createGFSFolder(createObj);
} }
} }
async function createGFSFolder(jsonObj){ async function createGFSFolder(jsonObj) {
let response = await fetch(GFS_URL + "add-folder", { let response = await fetch(GFS_URL + "add-folder", {
method: "PUT", method: "PUT",
headers: { headers: {
'Authorization': sessionStorage.getItem("token"), 'Authorization': sessionStorage.getItem("token"),
}, },
body: jsonObj body: jsonObj
}); });
} }
function createButtonElem(className, buttonName, icon) { function createButtonElem(className, buttonName, icon) {
......
...@@ -10,6 +10,24 @@ ...@@ -10,6 +10,24 @@
"mandatory" : true "mandatory" : true
} }
}, },
"capture_location_clearance_photo" : {
"fieldLabel" : "Capture Locational Clearance Photo",
"aka" : "field75",
"validation" : {
"fieldLength" : 1.0,
"collection" : "image-capture",
"mandatory" : true
}
},
"fingerprint" : {
"fieldLabel" : "Fingerprint",
"aka" : "field76",
"validation" : {
"fieldLength" : 1.0,
"collection" : "fingerprint",
"mandatory" : true
}
},
"registered_owner" : { "registered_owner" : {
"fieldLabel" : "Registered Owner", "fieldLabel" : "Registered Owner",
"aka" : "field3", "aka" : "field3",
......
...@@ -52,10 +52,10 @@ import com.svi.webgde.restservice.utils.XMLUtil; ...@@ -52,10 +52,10 @@ import com.svi.webgde.restservice.utils.XMLUtil;
@Path("/gfs-rest") @Path("/gfs-rest")
public class GDEWebServices { public class GDEWebServices {
@Context @Context
private HttpHeaders httpHeaders; private HttpHeaders httpHeaders;
private String statusFilePath = "C:\\Users\\oang\\Desktop\\WebGde\\temp\\status.txt"; private String statusFilePath = "C:\\Users\\oang\\Desktop\\WebGde\\temp\\status.txt";
@GET @GET
...@@ -86,8 +86,8 @@ public class GDEWebServices { ...@@ -86,8 +86,8 @@ public class GDEWebServices {
@Authorized @Authorized
public Response getList() { public Response getList() {
if (!JWTUtils.isJwtValid(httpHeaders.getRequestHeader(JWTEnums.REQUEST_HEADER_AUTH.value()))) { if (!JWTUtils.isJwtValid(httpHeaders.getRequestHeader(JWTEnums.REQUEST_HEADER_AUTH.value()))) {
return Response.status(401).entity("Invalid Token").build(); return Response.status(401).entity("Invalid Token").build();
} }
JSONObject json = new JSONObject(); JSONObject json = new JSONObject();
Set<String> idsWithTrueStatus = readStatusFile(); Set<String> idsWithTrueStatus = readStatusFile();
...@@ -104,8 +104,8 @@ public class GDEWebServices { ...@@ -104,8 +104,8 @@ public class GDEWebServices {
@EnabledCORS @EnabledCORS
public Response testWebservice() { public Response testWebservice() {
if (!JWTUtils.isJwtValid(httpHeaders.getRequestHeader(JWTEnums.REQUEST_HEADER_AUTH.value()))) { if (!JWTUtils.isJwtValid(httpHeaders.getRequestHeader(JWTEnums.REQUEST_HEADER_AUTH.value()))) {
return Response.status(401).entity("Invalid Token").build(); return Response.status(401).entity("Invalid Token").build();
} }
return Response.ok("test webservice").build(); return Response.ok("test webservice").build();
} }
...@@ -116,8 +116,8 @@ public class GDEWebServices { ...@@ -116,8 +116,8 @@ public class GDEWebServices {
@Authorized @Authorized
public Response dbLookup(JsonObject jsonObject) { public Response dbLookup(JsonObject jsonObject) {
if (!JWTUtils.isJwtValid(httpHeaders.getRequestHeader(JWTEnums.REQUEST_HEADER_AUTH.value()))) { if (!JWTUtils.isJwtValid(httpHeaders.getRequestHeader(JWTEnums.REQUEST_HEADER_AUTH.value()))) {
return Response.status(401).entity("Invalid Token").build(); return Response.status(401).entity("Invalid Token").build();
} }
JSONObject json = new JSONObject(); JSONObject json = new JSONObject();
String string = jsonObject.getString("dbLookup"); String string = jsonObject.getString("dbLookup");
...@@ -133,8 +133,8 @@ public class GDEWebServices { ...@@ -133,8 +133,8 @@ public class GDEWebServices {
@Authorized @Authorized
public Response getFile(JsonObject jsonObject) { public Response getFile(JsonObject jsonObject) {
if (!JWTUtils.isJwtValid(httpHeaders.getRequestHeader(JWTEnums.REQUEST_HEADER_AUTH.value()))) { if (!JWTUtils.isJwtValid(httpHeaders.getRequestHeader(JWTEnums.REQUEST_HEADER_AUTH.value()))) {
return Response.status(401).entity("Invalid Token").build(); return Response.status(401).entity("Invalid Token").build();
} }
File file = new File(jsonObject.getString("filePath").trim()); File file = new File(jsonObject.getString("filePath").trim());
StreamingOutput stream = null; StreamingOutput stream = null;
...@@ -170,8 +170,8 @@ public class GDEWebServices { ...@@ -170,8 +170,8 @@ public class GDEWebServices {
@Authorized @Authorized
public Response getFileIfExisting(JsonObject jsonObject) { public Response getFileIfExisting(JsonObject jsonObject) {
if (!JWTUtils.isJwtValid(httpHeaders.getRequestHeader(JWTEnums.REQUEST_HEADER_AUTH.value()))) { if (!JWTUtils.isJwtValid(httpHeaders.getRequestHeader(JWTEnums.REQUEST_HEADER_AUTH.value()))) {
return Response.status(401).entity("Invalid Token").build(); return Response.status(401).entity("Invalid Token").build();
} }
boolean isExisting = false; boolean isExisting = false;
File file = new File(jsonObject.getString("filePath").trim()); File file = new File(jsonObject.getString("filePath").trim());
JSONObject json = new JSONObject(); JSONObject json = new JSONObject();
...@@ -196,8 +196,8 @@ public class GDEWebServices { ...@@ -196,8 +196,8 @@ public class GDEWebServices {
@Authorized @Authorized
public Response getXMLData(JsonObject jsonObject) { public Response getXMLData(JsonObject jsonObject) {
if (!JWTUtils.isJwtValid(httpHeaders.getRequestHeader(JWTEnums.REQUEST_HEADER_AUTH.value()))) { if (!JWTUtils.isJwtValid(httpHeaders.getRequestHeader(JWTEnums.REQUEST_HEADER_AUTH.value()))) {
return Response.status(401).entity("Invalid Token").build(); return Response.status(401).entity("Invalid Token").build();
} }
File file = new File(jsonObject.getString("filePath").trim()); File file = new File(jsonObject.getString("filePath").trim());
JSONObject json = new JSONObject(); JSONObject json = new JSONObject();
...@@ -220,26 +220,26 @@ public class GDEWebServices { ...@@ -220,26 +220,26 @@ public class GDEWebServices {
@Authorized @Authorized
public Response writeXML(XMLContents xml) { public Response writeXML(XMLContents xml) {
if (!JWTUtils.isJwtValid(httpHeaders.getRequestHeader(JWTEnums.REQUEST_HEADER_AUTH.value()))) { if (!JWTUtils.isJwtValid(httpHeaders.getRequestHeader(JWTEnums.REQUEST_HEADER_AUTH.value()))) {
return Response.status(401).entity("Invalid Token").build(); return Response.status(401).entity("Invalid Token").build();
} }
String response = ""; String response = "";
try { try {
String filePath = xml.getOutputDir(); String filePath = xml.getOutputDir();
int lastSeparatorIndex = filePath.lastIndexOf("/"); int lastSeparatorIndex = filePath.lastIndexOf("/");
if (lastSeparatorIndex == -1) { if (lastSeparatorIndex == -1) {
lastSeparatorIndex = filePath.lastIndexOf("\\"); // For Windows paths lastSeparatorIndex = filePath.lastIndexOf("\\"); // For Windows paths
} }
if (lastSeparatorIndex != -1) { if (lastSeparatorIndex != -1) {
String directoryPath = filePath.substring(0, lastSeparatorIndex); String directoryPath = filePath.substring(0, lastSeparatorIndex);
File directoryFolder = new File(directoryPath); File directoryFolder = new File(directoryPath);
if (!directoryFolder.exists()) { if (!directoryFolder.exists()) {
directoryFolder.mkdirs(); directoryFolder.mkdirs();
} }
} }
System.out.println("creating output directory"); System.out.println("creating output directory");
response = XMLUtil.generateXML(xml); response = XMLUtil.generateXML(xml);
// File file = new File(filePath); // File file = new File(filePath);
// if (!file.exists()) { // if (!file.exists()) {
...@@ -262,8 +262,8 @@ public class GDEWebServices { ...@@ -262,8 +262,8 @@ public class GDEWebServices {
@Authorized @Authorized
public Response writeCSVMetrics(JsonObject jsonObject) { public Response writeCSVMetrics(JsonObject jsonObject) {
if (!JWTUtils.isJwtValid(httpHeaders.getRequestHeader(JWTEnums.REQUEST_HEADER_AUTH.value()))) { if (!JWTUtils.isJwtValid(httpHeaders.getRequestHeader(JWTEnums.REQUEST_HEADER_AUTH.value()))) {
return Response.status(401).entity("Invalid Token").build(); return Response.status(401).entity("Invalid Token").build();
} }
SimpleDateFormat isoFormat = new SimpleDateFormat("MM-dd-yyyy"); SimpleDateFormat isoFormat = new SimpleDateFormat("MM-dd-yyyy");
isoFormat.setTimeZone(TimeZone.getTimeZone("Asia/Manila")); isoFormat.setTimeZone(TimeZone.getTimeZone("Asia/Manila"));
...@@ -340,8 +340,8 @@ public class GDEWebServices { ...@@ -340,8 +340,8 @@ public class GDEWebServices {
@Authorized @Authorized
public Response updateEOB(XMLContents xml) { public Response updateEOB(XMLContents xml) {
if (!JWTUtils.isJwtValid(httpHeaders.getRequestHeader(JWTEnums.REQUEST_HEADER_AUTH.value()))) { if (!JWTUtils.isJwtValid(httpHeaders.getRequestHeader(JWTEnums.REQUEST_HEADER_AUTH.value()))) {
return Response.status(401).entity("Invalid Token").build(); return Response.status(401).entity("Invalid Token").build();
} }
try { try {
XMLUtil.updateEOB(xml); XMLUtil.updateEOB(xml);
} catch (Exception e) { } catch (Exception e) {
...@@ -357,8 +357,8 @@ public class GDEWebServices { ...@@ -357,8 +357,8 @@ public class GDEWebServices {
@Authorized @Authorized
public Response getFields(XMLContents xml) { public Response getFields(XMLContents xml) {
if (!JWTUtils.isJwtValid(httpHeaders.getRequestHeader(JWTEnums.REQUEST_HEADER_AUTH.value()))) { if (!JWTUtils.isJwtValid(httpHeaders.getRequestHeader(JWTEnums.REQUEST_HEADER_AUTH.value()))) {
return Response.status(401).entity("Invalid Token").build(); return Response.status(401).entity("Invalid Token").build();
} }
try { try {
return Response.ok(XMLUtil.getFields(xml)).build(); return Response.ok(XMLUtil.getFields(xml)).build();
} catch (Exception e) { } catch (Exception e) {
...@@ -366,7 +366,7 @@ public class GDEWebServices { ...@@ -366,7 +366,7 @@ public class GDEWebServices {
} }
} }
@POST @POST
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
...@@ -374,15 +374,15 @@ public class GDEWebServices { ...@@ -374,15 +374,15 @@ public class GDEWebServices {
@Authorized @Authorized
public Response getMobileFields(XMLContents xml) { public Response getMobileFields(XMLContents xml) {
if (!JWTUtils.isJwtValid(httpHeaders.getRequestHeader(JWTEnums.REQUEST_HEADER_AUTH.value()))) { if (!JWTUtils.isJwtValid(httpHeaders.getRequestHeader(JWTEnums.REQUEST_HEADER_AUTH.value()))) {
return Response.status(401).entity("Invalid Token").build(); return Response.status(401).entity("Invalid Token").build();
} }
try { try {
return Response.ok(XMLUtil.getFieldsFromSingleRecord(xml)).build(); return Response.ok(XMLUtil.getFieldsFromSingleRecord(xml)).build();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
return Response.status(500).entity("Fail").build(); return Response.status(500).entity("Fail").build();
} }
} }
@POST @POST
...@@ -392,8 +392,8 @@ public class GDEWebServices { ...@@ -392,8 +392,8 @@ public class GDEWebServices {
@Authorized @Authorized
public Response updateException(XMLContents xml) { public Response updateException(XMLContents xml) {
if (!JWTUtils.isJwtValid(httpHeaders.getRequestHeader(JWTEnums.REQUEST_HEADER_AUTH.value()))) { if (!JWTUtils.isJwtValid(httpHeaders.getRequestHeader(JWTEnums.REQUEST_HEADER_AUTH.value()))) {
return Response.status(401).entity("Invalid Token").build(); return Response.status(401).entity("Invalid Token").build();
} }
try { try {
File file = new File(xml.getOutputDir()); File file = new File(xml.getOutputDir());
...@@ -418,8 +418,8 @@ public class GDEWebServices { ...@@ -418,8 +418,8 @@ public class GDEWebServices {
@Authorized @Authorized
public Response getFile(Request request) { public Response getFile(Request request) {
if (!JWTUtils.isJwtValid(httpHeaders.getRequestHeader(JWTEnums.REQUEST_HEADER_AUTH.value()))) { if (!JWTUtils.isJwtValid(httpHeaders.getRequestHeader(JWTEnums.REQUEST_HEADER_AUTH.value()))) {
return Response.status(401).entity("Invalid Token").build(); return Response.status(401).entity("Invalid Token").build();
} }
// extract file path from file:// URL format // extract file path from file:// URL format
String filePath = request.getDir().substring("file://".length()); String filePath = request.getDir().substring("file://".length());
...@@ -429,53 +429,68 @@ public class GDEWebServices { ...@@ -429,53 +429,68 @@ public class GDEWebServices {
return Response.status(Response.Status.NOT_FOUND).build(); return Response.status(Response.Status.NOT_FOUND).build();
} }
// return file contents in blob format with filename in content-disposition // Get file size
// header long size = file.length();
String[] units = { "B", "KB", "MB", "GB", "TB" };
int unitIndex = 0;
double fileSize = size;
while (fileSize > 1024 && unitIndex < units.length - 1) {
fileSize /= 1024;
unitIndex++;
}
String fileSizeStr = String.format("%.2f %s", fileSize, units[unitIndex]);
// return file contents in blob format with filename and filesize in
// content-disposition header
ResponseBuilder response = Response.ok(file); ResponseBuilder response = Response.ok(file);
response.header("content-disposition", String.format("attachment; filename=\"%s\"", file.getName())); response.header("content-disposition",
String.format("attachment; filename=\"%s\"; size=\"%s\"", file.getName(), fileSizeStr));
return response.build(); return response.build();
} }
@POST @POST
@Path("/upload-file") @Path("/upload-file")
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@Authorized @Authorized
public Response uploadFile(Base64UploadRequest request) { public Response uploadFile(Base64UploadRequest request) {
if (!JWTUtils.isJwtValid(httpHeaders.getRequestHeader(JWTEnums.REQUEST_HEADER_AUTH.value()))) { if (!JWTUtils.isJwtValid(httpHeaders.getRequestHeader(JWTEnums.REQUEST_HEADER_AUTH.value()))) {
return Response.status(401).entity("Invalid Token").build(); return Response.status(401).entity("Invalid Token").build();
} }
String base64Data = request.getBase64Data(); String base64Data = request.getBase64Data();
String fileName = request.getFileName(); String fileName = request.getFileName();
String directory = request.getDirectory(); String directory = request.getDirectory();
// Sanitize the file name and directory path // Sanitize the file name and directory path
String sanitizedFileName = sanitizeFileName(fileName); String sanitizedFileName = sanitizeFileName(fileName);
String sanitizedDirectory = sanitizeDirectory(directory); String sanitizedDirectory = sanitizeDirectory(directory);
// Create the final directory path // Create the final directory path
String finalDirectory = sanitizedDirectory; String finalDirectory = sanitizedDirectory;
try { try {
// Create the directory if it doesn't exist // Create the directory if it doesn't exist
File directoryFile = new File(finalDirectory); File directoryFile = new File(finalDirectory);
if (!directoryFile.exists()) { if (!directoryFile.exists()) {
directoryFile.mkdirs(); directoryFile.mkdirs();
} }
// Decode base64 data and save the file in the specified directory // Decode base64 data and save the file in the specified directory
byte[] fileBytes = java.util.Base64.getDecoder().decode(base64Data); byte[] fileBytes = java.util.Base64.getDecoder().decode(base64Data);
ByteArrayInputStream inputStream = new ByteArrayInputStream(fileBytes); ByteArrayInputStream inputStream = new ByteArrayInputStream(fileBytes);
Files.copy(inputStream, Paths.get(finalDirectory, sanitizedFileName)); Files.copy(inputStream, Paths.get(finalDirectory, sanitizedFileName));
JSONObject responseJson = new JSONObject(); JSONObject responseJson = new JSONObject();
responseJson.put("status", 200); responseJson.put("status", 200);
return Response.ok(responseJson.toString()).build(); return Response.ok(responseJson.toString()).build();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
} }
} }
private String sanitizeDirectory(String directory) { private String sanitizeDirectory(String directory) {
// Remove directory traversal sequences // Remove directory traversal sequences
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment