Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- angular.module('smartform').controller('SummaryCtrl', [
- '$scope',
- '$http',
- '$q',
- '$parse',
- '$modal',
- '$location',
- '$anchorScroll',
- '$routeParams',
- 'sfOptions',
- '$window',
- '$log',
- '$filter',
- 'dataService',
- 'workspaceService',
- 'toaster', 'modalService', '$route', '$rootScope', 'Workflows', 'AuthToken', '$timeout', 'submissionsService',
- 'SUBMISSIONS_FOLDER_NAME',
- 'INSTITUTION_REVIEW_FOLDER_NAME',
- 'PREAPPROVAL_FOLDER_NAME',
- 'SUPPLEMENTARY_FILES_FOLDER_NAME',
- 'WORKFLOWS_DATE_FORMAT',
- 'WORKFLOWS_ACCESS_MESSAGE_TEXT', 'WORKFLOWS_EMAIL', 'SUBMISSIONS_PDF', 'fileService', 'PRE_APPROVAL_SMARTFORMS', 'ONQ_PORTAL_BASE_URL',
- function ($scope, $http, $q, $parse, $modal, $location, $anchorScroll, $routeParams,
- sfOptions, $window, $log, $filter, dataService, workspaceService, toaster, modalService,
- $route, $rootScope, Workflows, AuthToken, $timeout, submissionsService, SUBMISSIONS_FOLDER_NAME,
- INSTITUTION_REVIEW_FOLDER_NAME,
- PREAPPROVAL_FOLDER_NAME, SUPPLEMENTARY_FILES_FOLDER_NAME, WORKFLOWS_DATE_FORMAT, WORKFLOWS_ACCESS_MESSAGE_TEXT, WORKFLOWS_EMAIL, SUBMISSIONS_PDF, fileService, PRE_APPROVAL_SMARTFORMS, ONQ_PORTAL_BASE_URL) {
- $scope.data = dataService;
- $scope.sfKey;
- $scope.sortOrder = "section.sectionOrder";
- $scope.isWorkspacesLoading = true;
- $scope.submissionId = $routeParams.submissionId;
- $scope.portalRoot = ONQ_PORTAL_BASE_URL
- $scope.sectionId = $routeParams.sectionId;
- $scope.routingOptions = '';
- $scope.submitButtonText = 'Finalize Submission';
- if ($location.search().workspaceId) {
- $scope.workspaceId = $location.search().workspaceId;
- }
- if ($location.search().workspaceName) {
- $scope.workspaceName = $location.search().workspaceName;
- }
- if ($location.search().parentId) {
- $scope.parentId = $location.search().parentId;
- }
- var messageBody = '';
- /**
- $scope.smartFormName SIQ; // only happens when you process thru form without refreshing; TODO Figure out why
- $scope.currentSubmission @object
- attestationName
- columnOptionValues @string
- "[{"Name":"contactFirst","Value":"Test"},{"Name":"contactMiddle","Value":"Test"},{"Name":"contactLast","Value":"Test"},{"Name":"protocolNum","Value":"1141"},{"Name":"contactSuffix","Value":"TESt"},{"Name":"sponsor","Value":"at"}]"
- userSubmissionId: "ca9bd37d-019d-4e78-926d-03c935558188"
- userSubmissionIntId: 430
- columnOptions @array
- name: "contactLast"
- value: "afa"
- **/
- $scope.sponsor;
- $scope.firstName;
- $scope.lastName;
- var token = AuthToken.getToken(), User;
- var fetchWorkspaces = function () {
- $scope.isWorkspacesLoading = true;
- Workflows.getWorkspaces(token, 'qr')
- .then(function (res) {
- var workspaces = res.data.payload.workspaces || [], i;
- $scope.isWorkspacesLoading = false;
- // loop through workspaces so select dropdown can display both title and qr
- for (i = 0; i < workspaces.length; i += 1) {
- // Protocol, Sponsor, QR#, Workspace Name
- if (workspaces[i].qr) {
- workspaces[i].displayName = (workspaces[i].protocol) + ' / ' + (workspaces[i].sponsor) + ' / ' + (workspaces[i].qr) + '/ ' + workspaces[i].title;
- } else {
- // TODO: see if we should filter if there is no QR number
- workspaces[i].displayName = workspaces[i].title;
- }
- }
- $scope.workspaces = workspaces;
- }, function (err) {
- toaster.pop('error', 'Error', 'Oops, there was an error fetching workspaces. This was the error: ' + err.message);
- $scope.isWorkspacesLoading = false;
- });
- };
- $scope.isOwnerOrSponsor = function () {
- return ($scope.owner && $scope.owner.email == $scope.email) || ($scope.subscriber && $scope.subscriber.accountType == 'cro');
- };
- $scope.isOwner = function () {
- return ($scope.owner && $scope.owner.email == $scope.email);
- };
- //Finalize Submission
- //Send for Pre-Approval
- //Submit for Institution Review
- // watcher for Institution Review checkbox; this is where you'd do stuff if toggled "yes/no"
- $scope.onInstitutionChange = function () {
- $scope.calculateSubmitButtonText();
- };
- $scope.calculateSubmitButtonText = function () {
- if ($scope.currentSubmission.isInstitutionReview) {
- $scope.submitAction = 'institution';
- $scope.submitButtonText = 'Submit for Institution Review';
- $scope.currentSubmission.routingOptions = 'institution';
- } else if (!$scope.currentSubmission.isInstitutionReview && $scope.workspace && $scope.requiresPreApproval && !$scope.isOwnerOrSponsor()) {
- $scope.submitButtonText = 'Send for Pre-Approval';
- $scope.submitAction = 'pre-approval';
- $scope.currentSubmission.routingOptions = 'pre-approval';
- } else if (($scope.workspace && !$scope.requiresPreApproval) ||
- (!$scope.currentSubmission.isInstitutionReview && $scope.workspace && $scope.requiresPreApproval && $scope.isOwnerOrSponsor())) {
- $scope.submitButtonText = 'Submit to Quorum';
- $scope.submitAction = 'quorum';
- $scope.currentSubmission.routingOptions = 'quorumSubmit';
- $scope.requiresPreApproval = false; // reset to false
- } else {
- $scope.submitButtonText = 'Finalize Submission';
- $scope.submitAction = 'quorum';
- $scope.currentSubmission.routingOptions = '';
- $scope.requiresPreApproval = false; // reset to false
- }
- };
- // NOTE: For future Smart Forms that require pre-approval, add them in the Angular constants in app.js
- // There is a match if the SmartForm Name matches the key or value
- $scope.isSmartFormsAbleToRequirePreApproval = function () {
- return $scope.smartFormName && _.some(PRE_APPROVAL_SMARTFORMS, function (value, key, collection) {
- return $scope.sfKey = (value == $scope.smartFormName || key == $scope.smartFormName) ? key : false;
- });
- };
- $scope.onSiteSelected = function () {
- $scope.piName = $scope.currentSubmission.submissionSite.PI;
- /**
- if ($scope.currentSubmission.submissionSite) {
- for (var i = 0; i < $scope.workspaceSitesArray.length; i++) {
- if ($scope.workspaceSitesArray[i].Site_Suffix == $scope.currentSubmission.submissionSite) {
- $scope.piName = $scope.workspaceSitesArray[i].PI;
- }
- }
- } else {
- $scope.piName = null;
- } **/
- };
- $scope.onWorkspaceSelected = function () {
- $scope.requiresPreApproval = null;
- $scope.showSiteDropDown = false;
- $scope.piName = null;
- $scope.userIsViewer = null;
- $scope.currentSubmission.submissionSite = null;
- $scope.workspaceSitesArray = [];
- $scope.pendingWorkspacePreApprovalVerification = true;
- // one second delay so they can see pending message.
- if ($scope.currentSubmission.workspace) {
- $scope.workspace = true; // we set true here now, so we can hide stuff in HTML
- Workflows.getWorkspace($scope.currentSubmission.workspace._id, token)
- .then(function (res) {
- $scope.pendingWorkspacePreApprovalVerification = false;
- // if form is SIQ or SSR and matches workspace pre-approvals
- // SIQ should be mapped to Initial Site Submission (ISS).
- // SSR should be mapped to Site Periodic Review (SPR).
- // workspace.preapprovals: { "ISS" : true, "SI": true, etc. }
- $scope.workspace = res.data.payload.workspace;
- $scope.submissions.getUserSites();
- $scope.owner = _.find($scope.workspace.subscribers, { 'role': 'owner' });
- console.log('owner', $scope.owner);
- $scope.subscriber = _.find($scope.workspace.subscribers, { email: $scope.email });
- $scope.userIsViewer = $scope.subscriber.role == 'viewer';
- console.log('subscriber', $scope.subscriber);
- if ($scope.isSmartFormsAbleToRequirePreApproval()) {
- $scope.smartFormSubmissionType = $scope.sfKey; // e.g., SIQ, SSR
- }
- if ($scope.workspace && $scope.workspace.preapprovals.ISS && $scope.smartFormSubmissionType == 'SIQ') {
- $scope.submissionType = { 'value': 'ISS', 'text': 'Initial Site Submission', 'canRequirePreapproval': true };
- if (!$scope.isOwner()) {
- $scope.requiresPreApproval = true;
- } else {
- $scope.requiresPreApproval = false;
- }
- $scope.calculateSubmitButtonText();
- } else {
- $scope.submissionType = { 'value': $scope.smartFormName, 'text': $scope.smartFormName, 'canRequirePreapproval': false };
- $scope.requiresPreApproval = false;
- $scope.calculateSubmitButtonText();
- }
- }, function (err) {
- console.log('fetching workspace err', err);
- $scope.pendingWorkspacePreApprovalVerification = false;
- });
- } else {
- $scope.workspace = null;
- $scope.pendingWorkspacePreApprovalVerification = false;
- $scope.calculateSubmitButtonText();
- }
- };
- if (token) {
- Workflows.getUser(token)
- .then(function (res) {
- User = res.data.user;
- User.displayName = User.displayName || User.firstName + ' ' + User.lastName;
- $scope.email = User.email;
- });
- fetchWorkspaces();
- }
- $scope.resetRadio = function () {
- if (!$scope.requiresPreApproval) {
- $scope.currentSubmission.routingOptions = '';
- }
- };
- $scope.getModel = function (question, answers, option) {
- var value = null;
- var model = $filter('filter')(answers, { key: question.key })[0];
- if (model !== undefined && model != null) {
- var object;
- if (model != null) {
- question.hide = false;
- }
- if (question.type == "checkboxes") {
- var key = option["name"];
- object = JSON.parse(model.value);
- value = object[key];
- } else if (question.type == "select") {
- object = JSON.parse(model.value);
- value = object.value;
- }
- else if (question.type == "radio") {
- value = (model.value == option.name);
- } else if (question.type == "file") {
- value = JSON.parse(model.value);
- }
- else if (question.type == "date") {
- if (model.value != 'null')
- value = new Date(parseInt(model.value));
- }
- else {
- value = model.value;
- }
- }
- return value;
- };
- // save user submission is what saves the name
- dataService.getUserSubmission($scope.submissionId)
- .then(function (data) {
- $scope.currentSubmission = data || {};
- // we clear the form data
- // TODO: maybe we shouldn't and instead just save it with getUserSubmission, the new workflows data
- $scope.currentSubmission.jobTitle = '';
- $scope.currentSubmission.attestationFirstName = '';
- $scope.currentSubmission.attestationLastName = '';
- $scope.currentSubmission.workspace = null;
- $scope.currentSubmission.sponsor = '';
- $scope.currentSubmission.isTermsAccepted = false;
- // TODO: find out why getFormType does not work
- dataService.getFormType($scope.currentSubmission.userSubmissionId)
- .then(function (response) {
- $scope.formType = JSON.parse(response.data);
- console.log('$scope.formType', $scope.formType); // e.g., Site, Study, or null
- console.log('$scope.currentSubmission', $scope.currentSubmission);
- console.log('$scope.smartFormName', $scope.smartFormName); // e.g., SIQ
- if ($location.search().smartFormName) {
- $scope.smartFormName = $location.search().smartFormName;
- } else {
- if ($scope.smartFormName) {
- console.log('$scope.smartFormName', $scope.smartFormName); // e.g., SIQ
- $location.search('smartFormName', $scope.smartFormName);
- }
- }
- }, function (error) {
- toaster.pop('error', 'Error', 'Error retreiving form type.');
- });
- }, function (error) {
- toaster.pop('error', 'Error', 'Error grabbing UserSubmission.');
- $scope.currentSubmission = {};
- });
- dataService.getSummary()
- .then(function (result) {
- console.log('getSummary', result);
- dataService.userSections = result;
- }, function (error) {
- toaster.pop('error', 'Error', 'Error fetching data.');
- });
- $scope.getControlCSS = function (question) {
- return (question.isParent == true || question.isParent == null) ? 'parentControl' : 'childControl';
- };
- $scope.submissions = {
- getPR: function () {
- return {
- protocolNumber : $scope.workspace.protocol,
- qrNumber: $scope.workspace.qr,
- siteNumber: null
- }
- },
- addComment: function (inputs, property, data) {
- var comment = (property === 'comments') ? 'Comments:\t' + inputs[property].replace(/\n/g, '{NL}') : '*\t' + inputs[property];
- return data = data ? data + '\r\n' + comment : comment;
- },
- processMessageBody: function (formInputs, messageBody) {
- return messageBody || '';
- },
- processWorkflows: function () {
- var deferred = $q.defer();
- var submittedFolder,
- date = new moment().format(WORKFLOWS_DATE_FORMAT),
- folderName = '' + $scope.smartFormName + ' - ' + $scope.currentSubmission.sponsor + ' - ' + $scope.currentSubmission.attestationFirstName + ' ' + $scope.currentSubmission.attestationLastName + ' - ' + new moment().format(WORKFLOWS_DATE_FORMAT) + '',
- folderData = { workspaceId: $scope.workspace._id },
- subject,
- pr,
- data = {},
- statusObj = {
- submissionType: $scope.submissionType ? $scope.submissionType.text : null
- },
- formInputs; // TODO figure out
- // TODO: ADDED THIS, NEW STUFF, MAKE SURE IF RIGHT
- if ($scope.currentSubmission.isInstitutionReview) {
- $scope.submitAction = 'institution';
- } else if (!$scope.currentSubmission.isInstitutionReview && !$scope.requiresPreApproval && $scope.currentSubmission.routingOptions == "quorumSubmit") {
- $scope.submitAction = 'quorum';
- } else {
- $scope.submitAction = 'pre-approval';
- }
- folderData.sites = {};
- folderData.sites['*'] = true;
- if ($scope.currentSubmission.submissionSite && $scope.currentSubmission.submissionSite.Site_Suffix !== 'My site is not listed') {
- folderData.sites[$scope.currentSubmission.submissionSite.Site_Suffix] = true;
- }
- if ($scope.currentSubmission.submissionType) {
- folderData.submissionType = $scope.currentSubmission.submissionType;
- }
- folderData.folderName = folderName;
- folderData.status = $scope.submitAction;
- workspaceService.createFolder({
- workspaceId: $scope.workspace._id,
- folderName: folderName,
- sites: folderData.sites,
- requiresPreapproval: $scope.requiresPreapproval,
- submissionType: $scope.submissionType,
- submissionId: $scope.submissionId,
- status: $scope.submitAction,
- isForInstitutionReview: $scope.currentSubmission.isInstitutionReview
- }, token).then(function (response) {
- console.log('CREATE AOTHER FOLDER IN PROCESS WORKFLOWS', response);
- submittedFolder = response.data.payload || {};
- submittedFolder.workspace = $scope.workspace._id;
- submittedFolder.submissionId = $scope.submissionId;
- submittedFolder.isForInstitutionReview = $scope.currentSubmission.isInstitutionReview;
- // sumbit to quorum directly, move folders to workspace
- if ($scope.submitAction === 'quorum') {
- Workflows.moveToFolder(submittedFolder, SUBMISSIONS_FOLDER_NAME, $scope.email, token);
- // if institution review and workspace does not have preapproval
- } else if ($scope.submitAction === 'institution') {
- submittedFolder.status = $scope.submitAction;
- statusObj.status = $scope.submitAction;
- Workflows.moveToFolder(submittedFolder, INSTITUTION_REVIEW_FOLDER_NAME, $scope.email, token);
- // else workspace requires preapproval
- } else {
- console.log('PRE-APPROVAL MOVING TO FOLDER OCCURS', submittedFolder);
- Workflows.moveToFolder(submittedFolder, PREAPPROVAL_FOLDER_NAME, $scope.email, token);
- }
- if ($scope.email) {
- //set submission page name
- data.submissionPageName = $scope.submissionType ? $scope.submissionType.text : null;
- data.pi = $scope.piName;
- pr = $scope.submissions.getPR(); // TODO need to select protocolNumber
- // submit for quorum
- if ($scope.submitAction === 'quorum') {
- $scope.submissions.processSubmit({
- text: 'Submitted to Quorum',
- folderData: folderData,
- statusObj: statusObj,
- formInputs: formInputs,
- data: data,
- pr: pr,
- submittedFolder: submittedFolder
- }).then(function (res) {
- deferred.resolve(res);
- }).catch(function (err) {
- deferred.reject(err);
- });
- // submit for institution
- } else if ($scope.submitAction == 'institution') {
- $scope.submissions.processSubmit({
- text: 'Submitted for Institution Review',
- folderData: folderData,
- statusObj: statusObj,
- formInputs: formInputs,
- data: data,
- pr: pr,
- submittedFolder: submittedFolder
- }).then(function (res) {
- deferred.resolve(res);
- }).catch(function (err) {
- deferred.reject(err);
- });
- // submit for pre-approval
- } else {
- subject = $scope.submissionType.text + ' Document for Pre-approval';
- $scope.preApprovalCheck = true;
- for (i = 0, len = $scope.item.length; i < len; i += 1) {
- console.log('log and move file ' + i);
- $scope.item[i].workspace = $scope.workspace._id;
- $scope.item[i].isForInstitutionReview = $scope.currentSubmission.isInstitutionReview;
- $scope.submissions.logAndMoveFile($scope.item[i], folderData, 'submitted for pre-approval');
- }
- formInputs; // TODO
- messageBody = $scope.submissions.processMessageBody(formInputs, messageBody);
- messageBody += WORKFLOWS_ACCESS_MESSAGE_TEXT;
- // SENDS MESSAGE FOR FILES // TODO: MAKE SURE WORKS STILL
- deferred.resolve(true);
- $scope.submissions.sendMessagesForFiles(submittedFolder, statusObj, messageBody, subject)
- .then(function (res) {
- return $scope.submissions.processSubmit({
- text: 'Submitted for Pre-approval',
- folderData: folderData,
- statusObj: statusObj,
- formInputs: formInputs,
- data: data,
- pr: pr,
- submittedFolder: submittedFolder
- });
- }).then(function(res) {
- deferred.resolve(res);
- }).catch(function (err) {
- deferred.reject(err);
- });
- }
- }
- });
- return deferred.promise;
- },
- sendMessagesForFiles: function (submittedFolder, statusObj, messageBody, subject) {
- var deferred = $q.defer();
- var message = $scope.submissions.createMessage(submittedFolder, messageBody, subject);
- deferred.resolve(message);
- Workflows.sendMessage($scope.workspace._id, message, token)
- .then(function (response) {
- deferred.resolve(response);
- }).catch(function (err) {
- deferred.reject(err);
- });
- return deferred.promise;
- },
- getUserSites: function () {
- console.log('getting user sites');
- $scope.showSiteDropDown = false;
- Workflows.fetchUserSites($scope.workspace.qr, false).then(function (result) {
- console.log('got user sites');
- if (result && result.data) {
- $scope.workspaceSitesArray = result.data; // used to populate dropdown if length is more than 1. otherwise the 1 they have is the value of their submissions
- $scope.workspaceSitesArray = _.uniq($scope.workspaceSitesArray); // uniq so that the dropdown doesn't have duplicates (users can be associated to the same thing mulitple times)
- $scope.workspaceSites = {};
- for (var i = 0, len = $scope.workspaceSitesArray.length; i < len ; i++) {
- if ($scope.workspaceSitesArray[i].Site_Suffix === '*') { // if they have an '*' in the array, they have access to all sites, and need to have a dropdown for them all
- $scope.allWorkspaceSites = true;
- break;
- }
- }
- }
- // if they have access to all, or if they have more than one site,
- // we need to show them a drop down to select which sites should be allowed to see the submission
- if ($scope.allWorkspaceSites || $scope.workspaceSitesArray.length > 1) {
- if ($scope.allWorkspaceSites) {
- // get all sites for that QR, and set $scope.workspaceSitesArray to that
- Workflows.fetchAllQRSites($scope.workspace.qr).then(function (result) {
- if (result && result.data) {
- var sites = result.data;
- $scope.workspaceSitesArray = [];
- for (var b = 0, len = sites.length ; b < len ; b++) {
- $scope.workspaceSitesArray.push(sites[b]);
- }
- $scope.workspaceSitesArray.push({ Site_Suffix: 'My site is not listed' });
- $scope.workspaceSitesArray = _.unique($scope.workspaceSitesArray);
- $scope.showSiteDropDown = true;
- }
- });
- } else {
- // the drop down will be populated with $scope.workspaceSitesArray
- $scope.showSiteDropDown = true;
- }
- } else {
- if (!$scope.workspaceSitesArray || !$scope.workspaceSitesArray.length) {
- $scope.showSiteDropDown = true;
- console.log('the user had no sites. Not sure if that\'s supposed to be possible');
- } else if ($scope.workspaceSitesArray.length === 1) {
- $scope.showSiteDropDown = true;
- } else {
- toaster.pop('error', 'Error', 'Something very strange happened.');
- console.log('we did something wrong. This else should never happen. Counter should')
- }
- }
- console.log("pushing site is not listed");
- $scope.workspaceSitesArray.push({ Site_Suffix: 'My site is not listed' });
- $scope.workspaceSitesArray = _.unique($scope.workspaceSitesArray);
- console.log("$scope.workspaceSitesArray", $scope.workspaceSitesArray);
- });
- },
- createMessage: function (submittedFolder, messageBody, subject) {
- return {
- recipients: [{ name: $scope.owner.name, email: $scope.owner.email, recipient: true }],
- ccs: [{ name: User.name, email: User.email, cc: true }],
- subject: subject,
- notSendEmail: true,
- body: messageBody,
- fileFolderText: submittedFolder.name,
- workspaceName: $scope.workspace.title,
- workspaceId: $scope.workspace._id,
- fileFolderDocument: submittedFolder,
- fileOrFolderName: submittedFolder.name,
- fileFolderAssociation: submittedFolder._id
- };
- },
- submissionTypeSelection: function () {
- if (!$scope.submissionType) {
- return;
- }
- if ($scope.currentSubmission.isInstitutionReview) {
- $scope.submitAction = 'institution';
- $scope.submitButtonText = 'Submit for Institution Review';
- } else if ($scope.workspace.preapprovals[$scope.submissionType.value] && $scope.currUserRole !== 'owner') {
- $scope.submitButtonText = 'Send For Pre-Approval';
- $scope.submitAction = 'pre-approval';
- } else {
- $scope.submitButtonText = 'Send to Quorum';
- $scope.submitAction = "quorum";
- }
- },
- logAndMoveFile: function (item, folderData, text) {
- Workflows.logActivity(text, item, true, null, User, token);
- Workflows.copyToFolder(item, folderData.folderName, token);
- },
- transferProperties: function (data, pr) {
- console.log('$SCOPE.WORKSPACE', $scope.workspace);
- data = data || {};
- data.protocolNumber = pr ? pr.protocolNumber : null;
- data.qrNumber = $scope.workspace.qr || null;
- data.siteNumber = pr ? pr.siteNumber : null;
- data.name = User.displayName;
- data.emailAddress = User.email;
- data.sponsor = $scope.currentSubmission.sponsor;
- data.ids = [];
- data.files = [];
- var formInputs;
- //set PI
- data.pi = $scope.piName;
- return data;
- },
- submitFiles: function (item, data) {
- var deferred = $q.defer();
- var workspaceID = $scope.workspace._id;
- data.requiresPreapproval = $scope.requiresPreApproval;
- data.institutionName = $scope.currentSubmission.institutionName;
- data.isInstitutionReview = $scope.currentSubmission.isInstitutionReview || false;
- data.submissionSite = $scope.currentSubmission.submissionSite;
- submissionsService.workflowsSubmission(workspaceID, data)
- .then(function (res) {
- deferred.resolve(res);
- })
- .catch(function (err) {
- deferred.resolve(err);
- });
- return deferred.promise;
- },
- addStatusAndSubmissionTypeToItems: function () {
- var deferred = $q.defer(), pass = true;
- try {
- angular.forEach($scope.item, function (item) {
- item.status = $scope.submitAction;
- item.submissionType = $scope.submissionType.text;
- item.submitter = {
- id: User._id,
- email: User.email,
- displayName: User.displayName
- }
- });
- }
- catch (e) {
- deferred.reject(e);
- pass = false;
- }
- if (pass) {
- deferred.resolve($scope.item);
- }
- return deferred.promise;
- },
- setFileStatus: function (item, statusObj) {
- Workflows.setStatusAndSubType(item.workspace, item._id, statusObj, token);
- },
- processSubmit: function (args) {
- var deferred = $q.defer();
- var text = args.text,
- folderData = args.folderData,
- statusObj = args.statusObj,
- formInputs = args.formInputs,
- data = args.data,
- pr = args.pr,
- submittedFolder = args.submittedFolder;
- for (i = 0, len = $scope.item.length; i < len; i += 1) {
- $scope.item[i].workspace = $scope.workspace._id;
- $scope.item[i].isForInstitutionReview = $scope.currentSubmission.isInstitutionReview;
- if (!$scope.preApprovalCheck) {
- $scope.submissions.logAndMoveFile($scope.item[i], folderData, 'submitted to Quorum');
- }
- }
- statusObj.status = text;
- data = $scope.submissions.transferProperties(data, pr);
- data.comments = $scope.submissions.processMessageBody(formInputs, data.comments);
- data.submittedFolder = submittedFolder;
- for (i = 0, len = $scope.item.length; i < len; i += 1) {
- data.ids.push($scope.item[i]._id);
- }
- if ($scope.submitAction == 'pre-approval') {
- for (var i = 0, len = $scope.workspace.subscribers.length ; i < len ; i++) {
- if ($scope.workspace.subscribers[i].role == 'owner') {
- data.ownerEmail = $scope.workspace.subscribers[i].email;
- }
- }
- }
- $scope.submissions.submitFiles($scope.item, data)
- .then(function (res) {
- deferred.resolve(res);
- }).catch(function (err) {
- deferred.reject(err);
- });
- return deferred.promise;
- },
- };
- // TODO: in Portal, this will be under "Supplementary Files" in the workspace
- /**
- * processWorkflowsSubmission returns a promise.
- *
- * 1. Create Folder to record submission for User; folder resides under "Supplementary Files" in workspace
- * 2. Once created, we call createFiles method, which uploads the SmartForms PDF into the new directory
- * 3. This returns the newly generated meta data of the PDF in the workspace
- * 4.) We then add Status and Submissio Type to Items, this returns a promise
- * 5.) Finally, we execute the processWorkflows function
- */
- var processWorkflowsSubmission = function (pdf) {
- var deferred = $q.defer();
- var promises = [];
- $http.get('api/files/attachments/' + $routeParams.submissionId)
- .then(function (res) {
- var fileNames = res.data.result || [],
- processedResults = [];
- for (var i = 0; i < fileNames.length; i++) {
- processedResults.push({
- name: fileNames[i].name,
- data: fileNames[i].content,
- size: fileNames[i].size
- });
- }
- console.log('ITEMS RETURNED FROM SERVER PROCESSED RESULTS', processedResults);
- var returnedFolders;
- workspaceService.createFolder({
- folderName: $scope.smartFormName + '-' + $scope.currentSubmission.sponsor + ' - ' + $scope.currentSubmission.attestationFirstName + ' ' + $scope.currentSubmission.attestationLastName + ' - ' + new moment().format(WORKFLOWS_DATE_FORMAT),
- workspaceId: $scope.workspace._id,
- requiresPreapproval: $scope.requiresPreapproval,
- submissionType: $scope.submissionType,
- submissionId: $scope.submissionId,
- status: $scope.submitAction,
- isForInstitutionReview: $scope.currentSubmission.isInstitutionReview
- }, token)
- .then(function (returnedFolder) {
- $scope.parentId = returnedFolder.data.payload._id;
- console.log('returned Folder after FIRST CREATE', returnedFolder)
- returnedFolders = returnedFolder.data.payload;
- // TODO FIGURE OUT SIZE SO IT CAN TO WORKSPACE
- return workspaceService.createFiles({
- files: processedResults,
- workspaceId: $scope.workspace._id,
- parentId: returnedFolder.data.payload._id || null,
- isForInstitutionReview: $scope.currentSubmission.isInstitutionReview
- })
- }, token).then(function (returnedItems) {
- console.log('ITEMS RETURNED FROM SERVER AFTER CREATE FILES', returnedItems);
- var items = returnedItems.data.payload;
- $scope.item = items || [];
- return $scope.submissions.addStatusAndSubmissionTypeToItems();
- }).then(function (res) {
- returnedFolders.workspace = $scope.workspace._id;
- returnedFolders.submissionId = $scope.submissionId;
- returnedFolders.isForInstitutionReview = $scope.currentSubmission.isInstitutionReview;
- console.log('moving To Folder SUPPLEMENTARY_FILES_FOLDER_NAME', returnedFolders);
- return Workflows.moveToFolder(returnedFolders, SUPPLEMENTARY_FILES_FOLDER_NAME, $scope.email, token);
- }).then(function (res) {
- return $scope.submissions.processWorkflows();
- })
- .then(function (res) {
- deferred.resolve(res);
- }).catch(function (err) {
- console.log('err 2', err);
- return deferred.reject(err);
- });
- });
- return deferred.promise;
- };
- // Reset confirmation options, thus requiring the user to re-confirm the information is accurate
- // after returning from the summary page.
- $scope.returnToSummary = function() {
- $scope.currentSubmission.isTermsAccepted = false;
- $scope.currentSubmission.routingOptions = undefined;
- };
- $scope.finalizeSubmission = function () {
- if ($scope.pendingWorkspacePreApprovalVerification) {
- toaster.pop('error', 'Error', 'Cannot submit while verifying Pre-approval status for workspace');
- return false;
- }
- var generatePDF = function () {
- var deferred = $q.defer();
- dataService.generatePdf().then(function (res) {
- deferred.resolve(res); // resolve PDF buffer data
- }, function (err) {
- return deferred.reject(new Error('Error occurred while generating PDF. This was the error: ' + err.message));
- });
- return deferred.promise;
- };
- var sendEmails = function () {
- var deferred = $q.defer();
- data = { institutionReview: $scope.currentSubmission.isInstitutionReview, submissionSite: $scope.currentSubmission.submissionSite };
- if ($scope.currentSubmission.routingOptions !== 'downloadSubmit') {
- dataService.sendEmails(data).then(function (res) {
- deferred.resolve();
- }, function (err) {
- var message = err.data && err.data.message ? err.data.message : err.message;
- return deferred.reject(new Error('Error occurred while sending submission emails. This was the error: ' + message));
- });
- } else {
- deferred.resolve();
- }
- return deferred.promise;
- };
- var modalInstance = $modal.open({
- animation: false,
- templateUrl: '/app/partials/confirm.submission.modal.html',
- controller: ['$scope', '$modalInstance', 'data', function($scope, $modalInstance, data) {
- $scope.workspace = data.workspace;
- $scope.submitAction = data.submitAction || 'quorum';
- $scope.submissionType = data.submissionType;
- $scope.ok = function () {
- $modalInstance.close(true);
- };
- $scope.cancel = function () {
- $modalInstance.dismiss('cancel');
- };
- }],
- resolve: {
- data: function () {
- return {
- workspace: $scope.workspace,
- submissionType: $scope.smartFormName, // $scope.submissionType ? $scope.submissionType.text : $scope.smartFormName
- submitAction: $scope.currentSubmission.routingOptions == 'downloadSubmit' ? 'download' : $scope.submitAction
- }
- }
- }
- });
- modalInstance.result.then(function (value) {
- // TODO CURRENTSUBMISSION SUBMISSION STATUS
- $scope.currentSubmission.attestationName = $scope.currentSubmission.attestationFirstName + ' ' + $scope.currentSubmission.attestationLastName;
- var status = $scope.data.SubmissionStatusEnum;
- switch($scope.currentSubmission.routingOptions) {
- case 'quorumSubmit':
- $scope.currentSubmission.submissionStatus = status.Submitted
- break;
- case 'institution':
- $scope.currentSubmission.submissionStatus = status.SentForInstitutionReview;
- break;
- case 'pre-approval':
- $scope.currentSubmission.submissionStatus = status.SentForPreApproval;
- break;
- default:
- $scope.currentSubmission.submissionStatus = status.Downloaded
- }
- // first we save the form
- dataService.updateSubmission($scope.submissionId, $scope.currentSubmission)
- .then(function (res) {
- return generatePDF($scope.submissionId);
- }).then(function (res) {
- console.log('generated PDF', res);
- if ($scope.workspace) {
- return processWorkflowsSubmission(res.data); // pass pdf to be processed
- } else {
- // if institution review is checked, email is sent to institution review
- // otherwise, it is sent to regular Quorum's submission
- return sendEmails();
- }
- }).then(function (res) {
- var value, message;
- switch ($scope.currentSubmission.routingOptions) {
- case 'quorumSubmit':
- value = 'quorumSubmitted';
- message = 'A PDF of the submission has been generated and submitted to Quorum.';
- break;
- case 'institution':
- value = 'institutionSubmitted';
- message = 'A PDF of the submission has been generated and submitted for Institution Review.';
- break;
- case 'pre-approval':
- value = 'preApprovalSubmitted';
- message = 'A PDF of the submission has been generated and submitted for Pre-Approval.';
- break;
- default:
- value = 'userDownloaded';
- message = 'A PDF of the submission has been generated.';
- break;
- }
- if (value == 'quorumSubmitted' && $scope.workspace) {
- $location.path('/formViewer/' + $scope.submissionId + '/workspaceSubmitQuorum/' + $scope.sectionId).search({ 'workspaceId': $scope.workspace._id, workspaceName: $scope.workspace.title, parentId: $scope.parentId });
- } else if ($scope.workspace) {
- $location.path('/formViewer/' + $scope.submissionId + '/' + value + '/' + $scope.sectionId).search({'workspaceId': $scope.workspace._id, workspaceName: $scope.workspace.title, parentId: $scope.parentId});
- } else {
- $location.path('/formViewer/' + $scope.submissionId + '/' + value + '/' + $scope.sectionId);
- }
- toaster.pop('success', 'Successful', message);
- }).catch(function (err) {
- console.log('err', err);
- toaster.pop('error', 'Error', 'Error occured while updating submission. This was the error: ' + err.message);
- });
- });
- };
- $scope.saveAndExit = function () {
- dataService.updateSubmission($scope.submissionId, $scope.currentSubmission)
- .then(function (result) {
- $location.path('/');
- toaster.pop('success', 'Successful', 'The submission has been saved.');
- }, function (error) {
- toaster.pop('error', 'Error', 'Error fetching data');
- });
- };
- // for forms in the submissionType object...
- // get user's workspaces
- // find out if any of them have preapprovals
- // if at least one does, present a list of workspaces (with protocols) to the user
- // change radio button options accordingly
- // upon submission upload the PDF (assuming we have it) to Workspaces
- $scope.goToHost = function(submissionId, popupId) {
- dataService.getHostSection(popupId)
- .then(function (hostSection) {
- $location.url("/formViewer/" + submissionId + "/sections/" + hostSection.sectionId);
- },
- function (error) {
- toaster.pop('error', 'Error', 'Error retrieving section');
- });
- };
- $scope.gotoTop = function() {
- $location.hash('top');
- $anchorScroll();
- };
- }
- ]);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement