Commit f2544089 by Owen Ryan Ang

Submit integration

parent d5ad37b7
......@@ -2,4 +2,8 @@ export function imageCapture(key) {
// Call Android function via javaScript interface
window.ImageCaptureInterface.captureImage(key);
}
\ No newline at end of file
export function selfieCapture(key) {
// Call Android function via javaScript interface
window.ImageCaptureInterface.captureSelfie(key);
}
\ No newline at end of file
......@@ -28,7 +28,7 @@ export function processCapture(key) {
// Set the hidden inputs when a file is selected
hiddenFnameInput.value = filenameString;
hiddenFnameInput.display = '';
hiddenFileContentInput.value = img.value; // This will store the base64-encoded content of the file
hiddenFileContentInput.value = img.src; // This will store the base64-encoded content of the file
hiddenFileContentInput.display = '';
document.getElementById('buttonsContainer-video').style.display = 'none';
......
......@@ -6,7 +6,7 @@ import { showError } from "./showError.js";
import { submitForm } from "../Submit/submit.js";
import { BPO_OBJECT } from "../globalVariable.js";
import { fetchOptionsDB } from "./DBLookup/DBLookup.js";
import { imageCapture } from "./AndroidInterface/androidInterface.js";
import { imageCapture, selfieCapture } from "./AndroidInterface/androidInterface.js";
import { processCapture } from "./ImageCapture/captureImage.js";
let newOption;
......@@ -481,6 +481,20 @@ const inputVideoUpload = (key, validation) => {
input.addEventListener('change', (event) => {
const file = event.target.files[0];
if (file) {
// Create hidden inputs for fname and file content
const hiddenFnameInput = document.createElement('input');
hiddenFnameInput.setAttribute('id', `${key}`);
hiddenFnameInput.setAttribute('type', 'hidden');
hiddenFnameInput.setAttribute('name', 'hidden_fname');
container2.appendChild(hiddenFnameInput);
const hiddenFileContentInput = document.createElement('input');
hiddenFileContentInput.setAttribute('id', `${key}`);
hiddenFileContentInput.setAttribute('type', 'hidden');
hiddenFileContentInput.setAttribute('name', 'hidden_file_content');
container2.appendChild(hiddenFileContentInput);
const img = document.getElementById('zz');
const thumb = document.getElementById('thumbnail');
const x = document.getElementsByClassName('x')[0];
......@@ -512,10 +526,8 @@ const inputVideoUpload = (key, validation) => {
document.getElementById('buttonsContainer-video').style.display = 'flex';
// Clear the hidden fields
hiddenFnameInput.display = 'none';
hiddenFnameInput.value = '';
hiddenFileContentInput.display = 'none';
hiddenFileContentInput.value = '';
container2.removeChild(hiddenFnameInput);
container2.removeChild(hiddenFileContentInput);
});
};
reader.readAsDataURL(file);
......@@ -549,10 +561,8 @@ const inputVideoUpload = (key, validation) => {
input.value = ''
// Clear the hidden fields
hiddenFnameInput.display = 'none';
hiddenFnameInput.value = '';
hiddenFileContentInput.display = 'none';
hiddenFileContentInput.value = '';
container2.removeChild(hiddenFnameInput);
container2.removeChild(hiddenFileContentInput);
});
}
}
......@@ -584,7 +594,7 @@ const inputVideoUpload = (key, validation) => {
input2.setAttribute('id', `${key}`);
input2.setAttribute('name', `${key}`);
input2.setAttribute('type', 'button');
input2.setAttribute('value', 'Record Video');
input2.setAttribute('value', 'Capture Photo');
input2.addEventListener('click', () => {
imageCapture(key);
});
......@@ -604,18 +614,95 @@ const inputVideoUpload = (key, validation) => {
filename.setAttribute('type','text');
filename.setAttribute('style', 'display: none; font-size: inherit;');
// Create hidden inputs for fname and file content
const hiddenFnameInput = document.createElement('input');
hiddenFnameInput.setAttribute('id', `${key}`);
hiddenFnameInput.setAttribute('type', 'hidden');
hiddenFnameInput.setAttribute('name', 'hidden_fname');
container2.appendChild(hiddenFnameInput);
const hiddenFileContentInput = document.createElement('input');
hiddenFileContentInput.setAttribute('id', `${key}`);
hiddenFileContentInput.setAttribute('type', 'hidden');
hiddenFileContentInput.setAttribute('name', 'hidden_file_content');
container2.appendChild(hiddenFileContentInput);
// Append all elements to the container
const container3 = document.createElement('div');
container2.appendChild(x);
container3.setAttribute('id', 'buttonsContainer-video')
container3.setAttribute('class', 'buttonsContainer');
container3.appendChild(input);
// container3.appendChild(input1);
// container3.appendChild(dash);
container3.appendChild(input2);
container2.appendChild(container3)
container2.appendChild(img);
container2.appendChild(thumbnail);
container2.appendChild(filename);
mandatory ? input.setAttribute('required', 'true') : null
return container
} catch (err) {
throw err
}
}
/**
*
* @param {*} key
* will serve as id of input field
* @param {*} validation
* validation of field from schema
* @returns
* created input field element
*/
const inputSelfieCapture = (key, validation) => {
try {
const {
mandatory,
fieldLength
} = validation
const container = document.createElement('div');
const container2 = document.createElement('div');
container.appendChild(container2);
container2.classList.add('image-capture');
const input = document.createElement('input');
input.setAttribute('id', `attachedMedia`);
input.setAttribute('name', `${key}`);
input.setAttribute('type', 'file');
input.setAttribute('style', 'display: none');
// input.setAttribute('accept', 'all/*');
const capturedImage = document.createElement('input');
capturedImage.setAttribute('id', 'capturedImageData');
capturedImage.setAttribute('name', `${key}`);
capturedImage.setAttribute('type', 'hidden');
capturedImage.setAttribute('style', 'display: none');
const x = document.createElement('span')
x.setAttribute('class', 'x');
x.setAttribute('style', 'display: none')
x.textContent = 'x';
const dash = document.createElement('label');
dash.setAttribute('class', 'dash');
dash.innerHTML = ' or ';
const input2 = document.createElement('input');
input2.setAttribute('id', `${key}`);
input2.setAttribute('name', `${key}`);
input2.setAttribute('type', 'button');
input2.setAttribute('value', 'Capture Photo');
input2.addEventListener('click', () => {
selfieCapture(key);
});
window.processCapture = processCapture
const img = document.createElement('img');
const thumbnail = document.createElement('video');
thumbnail.setAttribute('style', 'display: none');
thumbnail.setAttribute('id', 'thumbnail');
img.setAttribute('id', 'zz');
img.setAttribute('style', 'display: none');
const filename = document.createElement('span');
filename.setAttribute('id', 'fname');
filename.setAttribute('name', `${key}`);
filename.setAttribute('type','text');
filename.setAttribute('style', 'display: none; font-size: inherit;');
// Append all elements to the container
const container3 = document.createElement('div');
......@@ -623,8 +710,8 @@ const inputVideoUpload = (key, validation) => {
container3.setAttribute('id', 'buttonsContainer-video')
container3.setAttribute('class', 'buttonsContainer');
container3.appendChild(input);
container3.appendChild(input1);
container3.appendChild(dash);
// container3.appendChild(input1);
// container3.appendChild(dash);
container3.appendChild(input2);
container2.appendChild(container3)
container2.appendChild(img);
......@@ -1057,6 +1144,9 @@ const deconstruct = async (section, container, classAttribute) => {
case 'video-upload':
input = inputVideoUpload(key, validation)
break
case 'selfie-capture':
input = inputSelfieCapture(key, validation)
break
case 'audio-upload':
input = inputAudioUpload(key, validation)
break
......@@ -1402,6 +1492,9 @@ export function clearForm() {
// Clear the form by resetting its fields
formElement.reset();
// Programatically click media close button
document.getElementsByClassName('x')[0].click();
// Set the selected 'doctype' back
const options = docTypeField.options;
const { elements } = formElement
......
import { GFS_URL } from "../config.js";
export const urlFileUpload = GFS_URL + "/upload-file";
export const uploadDirectory = "C:\\Users\\oang\\Desktop\\Mobile GDE\\test for upload"
export const uploadDirectory = "/home/mobilegde-elements"
import { uploadDirectory, urlFileUpload } from "./config.js";
export const uploadFile = async (file, projectCode) => {
const fileNameInput = generateFormattedString(projectCode);
const directoryInput = uploadDirectory;
const fileName = fileNameInput.trim();
const directory = directoryInput.trim();
export const uploadFile = async (file, fileName, directory) => {
if (fileName === '' || directory === '') {
console.log("Please enter a valid file name and directory.");
return;
}
const formData = new FormData();
formData.append('file', file);
formData.append('fileName', fileName);
formData.append('directory', directory);
let base64Data = file.split(',')[1];
const requestData = {
base64Data: base64Data,
fileName: fileName,
directory: directory
};
fetch(urlFileUpload, {
method: 'POST',
body: formData
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(requestData)
})
.then(response => response.json())
.then(data => {
console.log('File uploaded successfully:', data);
return true;
})
.catch(error => {
console.error('Error uploading file:', error);
......
import { GDE_URL } from "../config";
import { GDE_URL } from "../config.js";
export let urlGetIfExisting = GDE_URL + "/" + "get-if-existing";
export let urlGetXml = GDE_URL + "/" + "get-xml";
......@@ -6,4 +6,5 @@ export let urlWriteXml = GDE_URL + "/" + "write-xml";
export let urlUpdateEob = GDE_URL + "/" + "update-eob";
export let urlUpdateException = GDE_URL + "/" + "update-exception";
export let urlWriteMetrics = GDE_URL + "/" + "write-metrics";
export let urlGetFields = GDE_URL + "/" + "get-fields";
\ No newline at end of file
export let urlGetFields = GDE_URL + "/" + "get-fields";
export let urlGetFile = GDE_URL + "/" + "get-file";
\ No newline at end of file
......@@ -3,7 +3,7 @@ import { SCHEMA_FILE_PATH } from "../../DataInputWidget/config.js";
import { schema } from "../../DataInputWidget/generateFields.js";
import { IS_RETRIEVE_FROM_BPO } from "../../config.js";
import { createInfoModal } from "../../genericPopup/genericPopup.js";
import { PROJECT_CODE, ENCODING_PASS } from "../config.js";
import { PROJECT_CODE, ENCODING_PASS, TEMPORARY_FOLDER } from "../config.js";
import { completeToNextNode } from "../submit.js";
export async function WriteForm(e,metrics,doctype,section) {
......@@ -12,19 +12,20 @@ export async function WriteForm(e,metrics,doctype,section) {
var Nodes=Frm.elements;
const myArray = Object.values(metrics);
const lookup = schema[doctype][section]
localStorage.setItem("submit", "1");
// localStorage.setItem("submit", "1");
if (IS_RETRIEVE_FROM_BPO == "Y") {
let fields = {};
let fields = {};
for (var i=0;i<Nodes.length;i++) {
if (Nodes[i].style.display === 'none') continue
let fid = Nodes[i].id;
if (fid == 'DocType' || fid == 'Section' || fid == '' || fid == "submitButton") continue
// Skip elements of type "button", "submit", and files
if (Nodes[i].type === 'button' || Nodes[i].type === 'submit' || Nodes[i].name === 'hidden_file_content') continue;
fields[Object.keys(lookup[fid]).includes('aka') ? lookup[fid].aka.replace("field", "") : fid] = Nodes[i].value;
}
await createOutputXml(fields, myArray, doctype, section);
}
let response = await createOutputXml(fields, myArray, doctype, section);
return response;
}
catch(Err) {
createInfoModal(null, 'OK', "Error: " + Err.description +" while writing form.");
......@@ -33,8 +34,75 @@ export async function WriteForm(e,metrics,doctype,section) {
}
async function createOutputXml(fields, metrics, doctype, section) {
let elementId = sessionStorage.getItem("element_id");
let response = null;
if (IS_RETRIEVE_FROM_BPO == "Y") {
response = await createBPOXML(fields, metrics, doctype, section);
} else{
response = await createNonBPOXML(fields, metrics, doctype, section);
}
return response;
}
async function createNonBPOXML(fields, metrics, doctype, section){
let fileExt = "";
switch(ENCODING_PASS){
case "PASS1":
fileExt = ".DTA"
break;
case "PASS2":
fileExt = ".DTB"
break;
default:
fileExt = ".xml"
break;
}
let userID = sessionStorage.getItem("user_id");
let fileName = userID + "_" + Date.now() + "_" + PROJECT_CODE + fileExt;
let fileNameOnly = userID + "_" + Date.now() + "_" + PROJECT_CODE;
sessionStorage.setItem("recentlySavedFileNameOnly", fileNameOnly);
sessionStorage.setItem("recentlySavedFileName", fileName);
let xmlData = {
"projCode": PROJECT_CODE,
"userId": userID,
"elementId": "",
"schema": SCHEMA_FILE_PATH,
"totalRec":"0",
"maxRec": "1",
"totalKeystroke": metrics[0],
"procTime": "",
"procDuration": metrics[1],
"eob": "",
"exceptionRemark": "",
"recordNo": "0",
"totalSubRec": "1",
"maxSubRec": "1",
"imageName": "",
"subRecordNo": "1",
"eor": "N",
"fields": fields,
"outputDir": TEMPORARY_FOLDER + "/" + fileNameOnly + "/" + fileName,
"doctype": doctype,
"section": section
}
let response = await fetch(urlWriteXml, {
method: "POST",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(xmlData)
});
return response;
}
async function createBPOXML(fields, metrics, doctype, section){
let elementId = sessionStorage.getItem("element_id");
let filePaths = JSON.parse(sessionStorage.getItem("dir_files"));
let xmlData = {
......@@ -42,7 +110,6 @@ async function createOutputXml(fields, metrics, doctype, section) {
"userId": sessionStorage.getItem("user_id"),
"elementId": elementId,
"schema": SCHEMA_FILE_PATH,
// "totalRec": 0,
"totalRec":filePaths.length,
"maxRec": "1",
"totalKeystroke": metrics[0],
......@@ -53,10 +120,9 @@ async function createOutputXml(fields, metrics, doctype, section) {
"recordNo": parseInt(sessionStorage.getItem("display_counter")) + 1,
"totalSubRec": "1",
"maxSubRec": "1",
//"imageName": "test",
"imageName": filePaths[parseInt(sessionStorage.getItem("display_counter"))],
"subRecordNo": "1",
"eor": "Y",
"eor": "N",
"fields": fields,
"outputDir": sessionStorage.getItem("element_file_loc") + "/" + (ENCODING_PASS == "PASS1" ? elementId + ".DTA" : elementId + ".DTB"),
"doctype": doctype,
......@@ -71,28 +137,10 @@ async function createOutputXml(fields, metrics, doctype, section) {
body: JSON.stringify(xmlData)
});
if (completenessCheck(await response.text())) {
let response = await fetch(urlUpdateEob, {
method: "POST",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(xmlData)
});
await completeToNextNode(elementId);
sessionStorage.setItem("isElementComplete", true);
}else{
sessionStorage.removeItem("isElementComplete");
}
}
function completenessCheck(xml) {
let lst = JSON.parse(sessionStorage.getItem("dir_files"));
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xml, "text/xml");
let files = [...xmlDoc.getElementsByTagName("imagename")].map((name) => name.childNodes[0].nodeValue)
return response;
return lst.every(file => files.includes(file));
}
export const PROJECT_CODE = "PROJCODE01";
export const ENCODING_PASS = "PASS1";
export const GDE_URL = "http://localhost:8080" + "/WebGde/svc/gfs-rest";
\ No newline at end of file
export const GDE_URL = "http://18.208.163.99:8080" + "/WebGde/svc/gfs-rest";
export const GFS_URL = "http://107.20.193.188/gfs-explorer-ws/svc/gfs-rest/";
export const TEMPORARY_FOLDER = "C:\\Users\\oang\\Desktop\\Mobile GDE\\test for upload\\Elements";
export const GFS_ROOT_FOLDER = "/Users";
\ No newline at end of file
......@@ -5,8 +5,9 @@ import { uploadFile } from "../FileUpload/fileUpload.js";
import { global_end_time, saveMetrics, stopMetricCapture, setGlobalEndTime, interval } from "../captureMetrics/captureMetrics.js";
import { createInfoModal } from "../genericPopup/genericPopup.js";
import { Settings } from "./XMLWriter/Global.js";
import { urlGetFile } from "./XMLWriter/WebServices.js";
import { WriteForm } from "./XMLWriter/XML_Saver.js";
import { PROJECT_CODE } from "./config.js";
import { PROJECT_CODE, TEMPORARY_FOLDER } from "./config.js";
export const submitForm = async (e) => {
try {
......@@ -21,21 +22,12 @@ export const submitForm = async (e) => {
// Validate all elements again
for (let element of elements) {
if (element.style.display === 'none') continue
const { id, value, type } = element
const { valid } = validateInput(id, value)
// Skip submit button
const { id, value, type } = element
// Skip submit, buttons, and files
if (type === 'button') continue
if (type === 'submit') continue
// Handle file uploads
if (type === 'file') {
const fileInput = element;
const files = fileInput.files;
if (files.length > 0) {
const file = files[0];
uploadFile(file, PROJECT_CODE);
}
}
if (type === 'file') continue
if (type === 'hidden') continue
if (id === 'DocType') {
doctype = element.options[element.selectedIndex].text;
continue;
......@@ -45,6 +37,8 @@ export const submitForm = async (e) => {
continue;
}
const { valid } = validateInput(id, value)
var { isValidValue, errMsg } = checkValidValues(id, value);
if (typeof errMsg !== "undefined") {
......@@ -53,6 +47,7 @@ export const submitForm = async (e) => {
// Update display of input field if input is not valid
if (!valid) {
console.log(element);
error = true
if (type === 'select-one') {
continue
......@@ -88,8 +83,25 @@ export const submitForm = async (e) => {
return false
}
else {
const metrics = stopMetricCapture();
await WriteForm(e, metrics, doctype, section);
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);
let getFile = await fetch(urlGetFile, {
method: "POST",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(filePath)
});
// await uploadTOGFS(await getFile.text(), sessionStorage.getItem("recentlySavedFileName"));
}
saveForm(sessionStorage.getItem("display_counter"));
}
return true
......@@ -119,3 +131,26 @@ export async function completeToNextNode(elementId) {
return response;
}
export async function batchUpload(Form){
let Nodes = Form.elements;
let file;
let fileName;
let folderName = sessionStorage.getItem("recentlySavedFileNameOnly");
let directory = TEMPORARY_FOLDER + "/" + folderName
for (var i=0;i<Nodes.length;i++){
if (Nodes[i].name === 'hidden_file_content'){
var fileId = Nodes[i].id; // Get the ID of the current node
file = Nodes[i].value
if(file){
for (var j = 0; j < Nodes.length; j++) {
// Get file name from other node
if (Nodes[j].name === 'hidden_fname' && Nodes[j].id === fileId) {
fileName = Nodes[j].value;
await uploadFile(file, fileName, directory);
}
}
}
}
}
}
......@@ -38,9 +38,9 @@ export const HIGH_LIGHT_SCHEMA = "./WebGde-Widgets/sample_schema/dbSchema_anno.
export const ROOT_FOLDER = "/WebGde-Widgets";
//this determines if the images will be retrieved from the gfs
export const DOMAIN = "http://3.84.219.51:8080"
export const DOMAIN = "http://18.208.163.99:8080"
export const CONTEXTROOT = "gfs-explorer-ws"
export const GFS_URL = "http://3.84.219.51:8080" + "/MobileGde/svc/gfs-rest"
export const GFS_URL = "http://18.208.163.99:8080" + "/WebGde/svc/gfs-rest"
export const FOLDER_URL = DOMAIN + "/" + CONTEXTROOT + "/svc/gfs-rest/get-folder?parentPath=/Users/"
export const DOWNLOAD_URL = DOMAIN + "/" + CONTEXTROOT + "/svc/gfs-rest/get-download-link"
export const IS_RETRIEVE_FROM_GFS = "N"
......@@ -48,10 +48,10 @@ export const IS_RETRIEVE_FROM_GFS = "N"
export const INVALID_KEYS = "F1,F2,F3,F4,F5,F6,F7,F8,F9,F10,F11,F12,PrintScreen,ScrollLock,Pause,PageUp,PageDown,Insert,Delete,Control"
//BPO CONFIG
export const IS_RETRIEVE_FROM_BPO = "Y"
export const IS_RETRIEVE_FROM_BPO = "N"
// export const BPO_URL = "http://35.171.20.94:8080/bpo-sqa/"
// export const CURRENT_NODE = "Web GDE"
export const BPO_URL = "http://3.84.219.51:8080/bpo/"
export const BPO_URL = "http://18.208.163.99:8080/bpo/"
export const CURRENT_NODE = "Mobile_GDE_DEV"
export const ENCODING_PASS = "PASS1"
export const NEXT_NODE = "Complete"
......
import { createLoadingScreen, displayNextRecord, removeLoadingScreen, resetGDE } from '../../script.js';
import { createRejectWindow } from '../BPO/rejectElement.js';
import { createReturnWindow, returnElementBPO } from '../BPO/returnElement.js';
import { completeToNextNode, submitForm } from '../Submit/submit.js';
import { interval, pauseMetricCapture, saveMetrics, stopMetricCapture } from '../captureMetrics/captureMetrics.js';
import { REASON_LIST, ROOT_FOLDER } from '../config.js';
import { submitForm } from '../Submit/submit.js';
import { ROOT_FOLDER } from '../config.js';
import { BPO_OBJECT, DISPLAY_FIELD_OBJECT, DOCUMENT_CONTROL_OBJECT, IMAGE_VIEWER_OBJECT, INDEXED_DB_STORAGE } from '../globalVariable.js';
export class DocumentControlWidget {
global = {
container: null,
// refreshBtn: null,
// pauseBtn: null,
submitBtn: null,
returnBtn: null,
rejectBtn: null
}
constructor() {
......@@ -25,41 +17,7 @@ export class DocumentControlWidget {
this.global.container = document.createElement("div");
this.global.container.id = "TiffButtonRight";
this.global.container.classList.add("ctrl-buttons")
//temporary
// this.global.refreshBtn = document.createElement("div");
// this.global.refreshBtn.title = "Refresh";
// this.global.refreshBtn.classList.add("buttonRightClass");
// this.global.refreshBtn.classList.add("buttonRightClass");
// const refreshIcon = document.createElement("img");
// refreshIcon.classList.add("tiffViewerIcons");
// refreshIcon.src = "."+ROOT_FOLDER+"/documentControlWidget/assets/refresh_icon.png";
// refreshIcon.alt = "Refresh";
// refreshIcon.height = "32";
// refreshIcon.width = "32";
// this.global.pauseBtn = document.createElement("div");
// this.global.pauseBtn.title = "Pause";
// this.global.pauseBtn.classList.add("buttonRightClass");
// const pauseIcon = document.createElement("img");
// pauseIcon.classList.add("tiffViewerIcons");
// pauseIcon.src = "."+ROOT_FOLDER+"/documentControlWidget/assets/pause_icon.png";
// pauseIcon.alt = "Pause";
// pauseIcon.height = "32";
// pauseIcon.width = "32";
this.global.returnBtn = document.createElement("div");
this.global.returnBtn.title = "Return";
this.global.returnBtn.classList.add("buttonRightClass");
const returnIcon = document.createElement("img");
returnIcon.classList.add("tiffViewerIcons");
returnIcon.src = "." + ROOT_FOLDER + "/documentControlWidget/assets/return_icon.png";
returnIcon.alt = "Return";
returnIcon.height = "32";
returnIcon.width = "32";
this.global.submitBtn = document.createElement("div");
this.global.submitBtn.title = "Submit";
......@@ -71,155 +29,31 @@ export class DocumentControlWidget {
submitIcon.alt = "Submit";
submitIcon.height = "32";
submitIcon.width = "32";
this.global.rejectBtn = document.createElement("div");
this.global.rejectBtn.title = "Reject";
this.global.rejectBtn.classList.add("buttonRightClass");
const rejectIcon = document.createElement("img");
rejectIcon.classList.add("tiffViewerIcons");
rejectIcon.src = "." + ROOT_FOLDER + "/documentControlWidget/assets/reject_icon.png";
rejectIcon.alt = "Reject";
rejectIcon.height = "32";
rejectIcon.width = "32";
// this.global.refreshBtn.append(refreshIcon);
// this.global.pauseBtn.append(pauseIcon);
this.global.submitBtn.append(submitIcon);
this.global.returnBtn.append(returnIcon);
this.global.rejectBtn.append(rejectIcon);
// this.global.container.appendChild(this.global.refreshBtn);
// this.global.container.appendChild(this.global.pauseBtn);
this.global.container.appendChild(this.global.submitBtn);
this.global.container.appendChild(this.global.returnBtn);
this.global.container.appendChild(this.global.rejectBtn);
this.addEvenListeners();
}
addEvenListeners() {
// this.global.refreshBtn.onclick = async(e) => {
// document.getElementById("currentImage").remove();
// let urls = JSON.parse(sessionStorage.getItem("dir_files"));
// let currentDisplayIndex = parseInt(sessionStorage.getItem("display_counter"));
// const url = urls[currentDisplayIndex-1];
// let filename = url.split('/').pop();
// let imageBlob = await INDEXED_DB_STORAGE.getStoreFile("imageNum_"+ currentDisplayIndex);
// await IMAGE_VIEWER_OBJECT.createCurrentImage(filename.split(".").pop(), filename, imageBlob);
// }
// this.global.pauseBtn.onclick = (e) => {
// pauseMetricCapture();
// }
// this.global.pauseBtn.onkeydown = (e) => {
// if (event.key === 'Escape' || event.key === 'Esc') {
// pauseMetricCapture();
// }
// }
this.global.submitBtn.onclick = async (e) => {
let isSuccessful = await submitForm(e);
if (isSuccessful) {
let currentDisplay = parseInt(sessionStorage.getItem("display_counter"));
let totalRecord = JSON.parse(sessionStorage.getItem("dir_files")).length;
//if (currentDisplay + 1 === totalRecord) {
if(sessionStorage.getItem("isElementComplete")){
//move element then fetch new element
//let response = await completeToNextNode(sessionStorage.getItem("element_id"));
createLoadingScreen();
const metrics = stopMetricCapture();
let eoe_ts = new Date().toLocaleString();
await saveMetrics(metrics, eoe_ts);
// if (response.status == 200) {
if (await BPO_OBJECT.getRandomWaitingElement()) {
document.getElementById("counter").innerHTML = "";
clearTimeout(interval);
resetGDE();
};
// } else {
// removeLoadingScreen();
// alert(`Error ${response.status}: Completing element to next node, Check if Complete Node Exist`);
// }
} else {
// document.getElementById("nextRecordImage").click();
//DISPLAY_FIELD_OBJECT.generateFields();
DISPLAY_FIELD_OBJECT.clearForm();
displayNextRecord();
//document.getElementById("input-field-container").appendChild(DOCUMENT_CONTROL_OBJECT.getWidget());
// DISPLAY_FIELD_OBJECT.updateHeaderText(0, "User: " + sessionStorage.getItem("user_id"));
// DISPLAY_FIELD_OBJECT.updateHeaderText(1, "Element ID: " + sessionStorage.getItem("element_id"));
// DISPLAY_FIELD_OBJECT.updateHeaderText(2, "");
}
}
}
this.global.returnBtn.onclick = (e) => {
createReturnWindow();
//returnElementBPO(sessionStorage.getItem("element_id"));
// var fileName = sessionStorage.getItem("file_Name");
// if (fileName !== null && fileName !== undefined) {
// document.getElementById("controlsContainer").outerHTML="";
// } else {
// document.getElementById("TiffViewer_ButtonContainer").outerHTML="";
// }
}
this.global.returnBtn.onkeydown = (e) => {
if (e.altKey == true && e.keyCode == 85) {
returnElementBPO(sessionStorage.getItem("element_id"));
// var fileName = sessionStorage.getItem("file_Name");
// if (fileName !== null && fileName !== undefined) {
// document.getElementById("controlsContainer").outerHTML="";
// } else {
// document.getElementById("TiffViewer_ButtonContainer").outerHTML="";
// }
if (isSuccessful) {
DISPLAY_FIELD_OBJECT.clearForm();
}
}
this.global.rejectBtn.onclick = (e) => {
createRejectWindow();
e.target.disabled = true;
}
this.global.rejectBtn.onkeydown = (e) => {
if (e.ctrlKey == true && e.keyCode == 69) {
createRejectWindow();
e.target.disabled = true;
}
}
}
getWidget() {
return this.global.container;
}
getRefreshBtn() {
return this.global.refreshBtn;
}
getSubmitBtn(){
return this.global.submitBtn;
}
getPauseBtn() {
return this.global.pauseBtn;
}
getReturnBtn() {
return this.global.returnBtn;
}
getRejectBtn() {
return this.global.rejectBtn;
}
}
{
"TEXT FIELDS": {
"SECTION1": {
"First Name": {
"fieldLabel": "First Name",
"aka": "field7",
"validation": {
"fieldLength": 30,
"collection": "alphanumeric",
"invalidchar": "`~!@#&$%^*_={}[]:;/\"|\\<>",
"mandatory": false
}
},
"Middle Name": {
"fieldLabel": "Middle Name",
"aka": "field8",
"validation": {
"fieldLength": 30,
"collection": "alphanumeric",
"invalidchar": "`~!@#&$%^*_={}[]:;/\"|\\<>",
"mandatory": false
}
},
"Surname": {
"fieldLabel": "Surname",
"aka": "field9",
"validation": {
"fieldLength": 30,
"collection": "alphanumeric",
"invalidchar": "`~!@#&$%^*_={}[]:;/\"|\\<>",
"mandatory": false
}
},
"Address": {
"fieldLabel": "Address",
"aka": "field10",
"validation": {
"fieldLength": 100,
"collection": "alphanumeric",
"invalidchar": "`~!$%^*=_[]:\"|\\<>",
"mandatory": false
}
},
"Birthdate": {
"fieldLabel": "Birthate",
"aka": "field5",
"validation": {
"fieldLength": 20,
"collection": "datepicker",
"mandatory": false
}
},
"Civil_Status": {
"fieldLabel": "Civil Status",
"aka": "field28",
"source": "s",
"validation": {
"fieldLength": 15,
"collection": "dropdown",
"options": [
"Single",
"Married",
"Widowed"
],
"mandatory": true
}
},
"Mother's_Name": {
"fieldLabel": "Mother's Name",
"aka": "field31",
"source": "s",
"validation": {
"fieldLength": 30,
"collection": "alphanumeric",
"invalidchar": "`~!@#&$%^*={}[]:;/\"|\\<>",
"mandatory": true
},
"childof": "Civil_Status",
"parentvalue": [
"Single"
]
},
"Spouse_Name": {
"fieldLabel": "Spouse Name",
"aka": "field29",
"source": "s",
"validation": {
"fieldLength": 30,
"collection": "alphanumeric",
"invalidchar": "`~!@#&$%^*={}[]:;/\"|\\<>",
"mandatory": true
},
"childof": "Civil_Status",
"parentvalue": [
"Married",
"Widowed"
]
},
"Date_of_Marriage": {
"fieldLabel": "Date of Marriage",
"aka": "field30",
"source": "s",
"validation": {
"fieldLength": 30,
"collection": "alphanumeric",
"invalidchar": "`~!@#&$%^*={}[]:;/\"|\\<>",
"mandatory": true
},
"childof": "Civil_Status",
"parentvalue": [
"Married",
"Widowed"
]
}
},
"SECTIONNEXT": {
"Name": {
"fieldLabel": "Name",
"aka": "field7",
"validation": {
"fieldLength": 30,
"collection": "alphanumeric",
"invalidchar": "`~!@#&$%^*_={}[]:;/\"|\\<>",
"mandatory": false
}
},
"Subject": {
"fieldLabel": "Subject",
"aka": "field8",
"validation": {
"fieldLength": 30,
"collection": "alphanumeric",
"mandatory": false
}
},
"Document_No": {
"fieldLabel": "Document No",
"aka": "field6",
"validation": {
"fieldLength": 30,
"collection": "alphanumeric",
"invalidchar": "`~!@#&$%^*={}[]:;/\"|\\<>",
"mandatory": false
}
},
"Date": {
"fieldLabel": "Date",
"aka": "field5",
"validation": {
"fieldLength": 20,
"collection": "datepicker",
"mandatory": false
}
}
}
},
"DATA INPUT": {
"SECTION3": {
"PC Setup": {
"fieldLabel": "PC Setup",
"aka": "field7",
"validation": {
"collection": "image-upload",
"mandatory": false
}
},
"First Name": {
"fieldLabel": "First Name",
"aka": "field7",
"validation": {
"fieldLength": 30,
"collection": "alphanumeric",
"invalidchar": "`~!@#&$%^*_={}[]:;/\"|\\<>",
"mandatory": false
}
},
"Middle Name": {
"fieldLabel": "Middle Name",
"aka": "field8",
"validation": {
"fieldLength": 30,
"collection": "alphanumeric",
"invalidchar": "`~!@#&$%^*_={}[]:;/\"|\\<>",
"mandatory": false
}
},
"Surname": {
"fieldLabel": "Surname",
"aka": "field9",
"validation": {
"fieldLength": 30,
"collection": "alphanumeric",
"invalidchar": "`~!@#&$%^*_={}[]:;/\"|\\<>",
"mandatory": false
}
}
}
}
}
\ No newline at end of file
......@@ -44,7 +44,7 @@
}
},
"Upload Video": {
"fieldLabel": "Upload or Record Video",
"fieldLabel": "Capture Image",
"aka": "field7",
"validation": {
"collection": "video-upload",
......@@ -156,7 +156,7 @@
}
},
"Upload_Video": {
"fieldLabel": "Upload or Record Video",
"fieldLabel": "Capture Image",
"aka": "field7",
"validation": {
"collection": "video-upload",
......@@ -186,19 +186,19 @@
"HR FILES": {
"SECTION3": {
"Upload_Audio": {
"fieldLabel": "Upload Audio",
"aka": "field7",
"fieldLabel": "Capture Selfie",
"aka": "field12",
"validation": {
"collection": "audio-upload",
"mandatory": true
"collection": "selfie-capture",
"mandatory": false
}
},
"Upload_Video": {
"fieldLabel": "Upload Video",
"fieldLabel": "Capture Image",
"aka": "field7",
"validation": {
"collection": "video-upload",
"mandatory": true
"mandatory": false
}
},
"Name": {
......@@ -217,7 +217,7 @@
"validation": {
"fieldLength": 200,
"collection": "alphanumeric",
"mandatory": true
"mandatory": false
}
},
"Employee_No": {
......
import { displayField } from "./WebGde-Widgets/DataInputWidget/displayFieldClass.js";
import { fetchSchema } from "./WebGde-Widgets/DataInputWidget/fetchSchema.js";
import { schema } from "./WebGde-Widgets/DataInputWidget/generateFields.js";
import { DocumentControlWidget } from "./WebGde-Widgets/documentControlWidget/documentControlWidget.js";
// import { DocumentControlWidget } from "./WebGde-Widgets/documentControlWidget/documentControlWidget.js";
import { INDEXED_DB_STORAGE, HIGHLIGHT_OBJECT, IMAGE_VIEWER_OBJECT, INDEXED_DB_NAME, INDEXED_DB_TBL_NAME, setIndexedDBStorage, setHighlightObject, setImageViewerObject, setBPOObject, BPO_OBJECT, DISPLAY_FIELD_OBJECT, setDisplayFieldObject, activateGDE, setDocumentControlObject, DOCUMENT_CONTROL_OBJECT, IS_GDE_ACTIVATED } from "./WebGde-Widgets/globalVariable.js";
......@@ -18,6 +19,8 @@ async function initializeWebGDE(){
await createWebGdeInterface(null);
// setDocumentControlObject(new DocumentControlWidget());
// document.getElementById("input-field-container").appendChild(DOCUMENT_CONTROL_OBJECT.getWidget());
setDocumentControlObject(new DocumentControlWidget());
document.getElementById("input-field-container").appendChild(DOCUMENT_CONTROL_OBJECT.getWidget());
removeLoadingScreen();
}
......@@ -48,7 +51,7 @@ async function createInputForm() {
// Instantiate widget and assign it to a container
const displayFieldClass = new displayField(schema, containerId);
// Call Function to generate fields with given schema to provided container
// setDisplayFieldObject(displayFieldClass);
setDisplayFieldObject(displayFieldClass);
displayFieldClass.generateFields();
// displayFieldClass.editHeader(element-id)
// displayFieldClass.updateHeaderText(0, "User: " + sessionStorage.getItem("user_id"));
......@@ -127,7 +130,6 @@ function testFunction(){
var Nodes=Frm.elements;
// const myArray = Object.values(metrics);
const lookup = schema[doctype][section]
localStorage.setItem("submit", "1");
if (true) {
let fields = {};
......
package com.svi.webgde.restservice.object;
public class Base64UploadRequest {
private String base64Data;
private String fileName;
private String directory;
public String getBase64Data() {
return base64Data;
}
public void setBase64Data(String base64Data) {
this.base64Data = base64Data;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getDirectory() {
return directory;
}
public void setDirectory(String directory) {
this.directory = directory;
}
}
package com.svi.webgde.restservice.services;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileReader;
......@@ -11,6 +13,10 @@ import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import javax.json.JsonObject;
......@@ -18,6 +24,7 @@ import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
......@@ -29,6 +36,7 @@ import org.json.simple.JSONObject;
import com.opencsv.CSVReader;
import com.opencsv.CSVWriter;
import com.svi.webgde.restservice.object.Base64UploadRequest;
import com.svi.webgde.restservice.object.Request;
import com.svi.webgde.restservice.object.XMLContents;
import com.svi.webgde.restservice.utils.DBUtil;
......@@ -36,23 +44,60 @@ import com.svi.webgde.restservice.utils.XMLUtil;
@Path("/gfs-rest")
public class GDEWebServices {
private String statusFilePath = "C:\\Users\\oang\\Desktop\\WebGde\\temp\\status.txt";
@GET
@Path("/check-status/{userId}")
public boolean checkStatus(@PathParam("userId") String id) {
Set<String> idsWithTrueStatus = readStatusFile();
if (!idsWithTrueStatus.contains(id)) {
idsWithTrueStatus.add(id);
writeStatusFile(idsWithTrueStatus);
return true;
} else {
return false;
}
}
@GET
@Path("/reset-status/{userId}")
public boolean resetStatus(@PathParam("userId") String id) {
Set<String> idsWithTrueStatus = readStatusFile();
idsWithTrueStatus.remove(id);
writeStatusFile(idsWithTrueStatus);
return true;
}
@GET
@Path("/get-list")
public Response getList() {
JSONObject json = new JSONObject();
Set<String> idsWithTrueStatus = readStatusFile();
for (String string : idsWithTrueStatus) {
json.put(string, true);
}
return Response.ok(json.toString()).build();
}
@GET
@Path("/test-upload")
public Response testWebservice() {
return Response.ok("test webservice").build();
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@Path("/db-lookup")
public Response dbLookup(JsonObject jsonObject) {
JSONObject json = new JSONObject();
String string = jsonObject.getString("dbLookup");
json = DBUtil.dbLookup(string);
return Response.ok(json.toString()).build();
}
......@@ -138,13 +183,30 @@ public class GDEWebServices {
public Response writeXML(XMLContents xml) {
String response = "";
try {
File file = new File(xml.getOutputDir());
String filePath = xml.getOutputDir();
int lastSeparatorIndex = filePath.lastIndexOf("/");
if (lastSeparatorIndex == -1) {
lastSeparatorIndex = filePath.lastIndexOf("\\"); // For Windows paths
}
if (lastSeparatorIndex != -1) {
String directoryPath = filePath.substring(0, lastSeparatorIndex);
File directoryFolder = new File(directoryPath);
if (!directoryFolder.exists()) {
directoryFolder.mkdirs();
}
}
File file = new File(filePath);
if (!file.exists()) {
System.out.println("creating output directory");
response = XMLUtil.generateXML(xml);
} else {
response = XMLUtil.udpateXML(xml);
}
} catch (Exception e) {
e.printStackTrace();
return Response.status(500).entity("Fail").build();
}
return Response.ok(response).build();
......@@ -271,35 +333,38 @@ public class GDEWebServices {
}
return Response.ok("Success").build();
}
@POST
@Path("/fetch-local")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response getFile(Request request) {
// extract file path from file:// URL format
// extract file path from file:// URL format
String filePath = request.getDir().substring("file://".length());
// read file from local file system
File file = new File(filePath);
if (!file.exists()) {
return Response.status(Response.Status.NOT_FOUND).build();
}
// read file from local file system
File file = new File(filePath);
if (!file.exists()) {
return Response.status(Response.Status.NOT_FOUND).build();
}
// return file contents in blob format with filename in content-disposition header
ResponseBuilder response = Response.ok(file);
response.header("content-disposition", String.format("attachment; filename=\"%s\"", file.getName()));
return response.build();
// return file contents in blob format with filename in content-disposition
// header
ResponseBuilder response = Response.ok(file);
response.header("content-disposition", String.format("attachment; filename=\"%s\"", file.getName()));
return response.build();
}
@POST
@Path("/upload-file")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
public Response uploadFile(@FormDataParam("file") InputStream fileInputStream,
@FormDataParam("fileName") String fileName,
@FormDataParam("directory") String directory) {
// Sanitize the file name and directory path
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response uploadFile(Base64UploadRequest request) {
String base64Data = request.getBase64Data();
String fileName = request.getFileName();
String directory = request.getDirectory();
// Sanitize the file name and directory path
String sanitizedFileName = sanitizeFileName(fileName);
String sanitizedDirectory = sanitizeDirectory(directory);
......@@ -313,8 +378,10 @@ public class GDEWebServices {
directoryFile.mkdirs();
}
// Save the file in the specified directory
Files.copy(fileInputStream, Paths.get(finalDirectory, sanitizedFileName));
// Decode base64 data and save the file in the specified directory
byte[] fileBytes = java.util.Base64.getDecoder().decode(base64Data);
ByteArrayInputStream inputStream = new ByteArrayInputStream(fileBytes);
Files.copy(inputStream, Paths.get(finalDirectory, sanitizedFileName));
JSONObject responseJson = new JSONObject();
responseJson.put("status", 200);
......@@ -323,7 +390,7 @@ public class GDEWebServices {
e.printStackTrace();
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
}
private String sanitizeDirectory(String directory) {
// Remove directory traversal sequences
......@@ -332,6 +399,30 @@ public class GDEWebServices {
private String sanitizeFileName(String fileName) {
// Remove special characters, spaces, and directory separators
return fileName.replaceAll("[^a-zA-Z0-9.-]", "_");
return fileName.replaceAll("[^a-zA-Z0-9.-]", "_");
}
private Set<String> readStatusFile() {
try (BufferedReader reader = new BufferedReader(new FileReader(statusFilePath))) {
Set<String> idsWithTrueStatus = new HashSet<>();
String line;
while ((line = reader.readLine()) != null) {
idsWithTrueStatus.add(line);
}
return idsWithTrueStatus;
} catch (IOException e) {
return new HashSet<>();
}
}
private void writeStatusFile(Set<String> idsWithTrueStatus) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(statusFilePath))) {
for (String id : idsWithTrueStatus) {
writer.write(id);
writer.newLine();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
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