Advertisement
Guest User

Untitled

a guest
Mar 15th, 2016
187
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 48.92 KB | None | 0 0
  1. angular.module('smartform').controller('SummaryCtrl', [
  2. '$scope',
  3. '$http',
  4. '$q',
  5. '$parse',
  6. '$modal',
  7. '$location',
  8. '$anchorScroll',
  9. '$routeParams',
  10. 'sfOptions',
  11. '$window',
  12. '$log',
  13. '$filter',
  14. 'dataService',
  15. 'workspaceService',
  16. 'toaster', 'modalService', '$route', '$rootScope', 'Workflows', 'AuthToken', '$timeout', 'submissionsService',
  17. 'SUBMISSIONS_FOLDER_NAME',
  18. 'INSTITUTION_REVIEW_FOLDER_NAME',
  19. 'PREAPPROVAL_FOLDER_NAME',
  20. 'SUPPLEMENTARY_FILES_FOLDER_NAME',
  21. 'WORKFLOWS_DATE_FORMAT',
  22. 'WORKFLOWS_ACCESS_MESSAGE_TEXT', 'WORKFLOWS_EMAIL', 'SUBMISSIONS_PDF', 'fileService', 'PRE_APPROVAL_SMARTFORMS', 'ONQ_PORTAL_BASE_URL',
  23. function ($scope, $http, $q, $parse, $modal, $location, $anchorScroll, $routeParams,
  24. sfOptions, $window, $log, $filter, dataService, workspaceService, toaster, modalService,
  25. $route, $rootScope, Workflows, AuthToken, $timeout, submissionsService, SUBMISSIONS_FOLDER_NAME,
  26. INSTITUTION_REVIEW_FOLDER_NAME,
  27. 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) {
  28.  
  29. $scope.data = dataService;
  30. $scope.sfKey;
  31. $scope.sortOrder = "section.sectionOrder";
  32. $scope.isWorkspacesLoading = true;
  33. $scope.submissionId = $routeParams.submissionId;
  34. $scope.portalRoot = ONQ_PORTAL_BASE_URL
  35. $scope.sectionId = $routeParams.sectionId;
  36. $scope.routingOptions = '';
  37. $scope.submitButtonText = 'Finalize Submission';
  38.  
  39. if ($location.search().workspaceId) {
  40. $scope.workspaceId = $location.search().workspaceId;
  41. }
  42.  
  43. if ($location.search().workspaceName) {
  44. $scope.workspaceName = $location.search().workspaceName;
  45. }
  46.  
  47. if ($location.search().parentId) {
  48. $scope.parentId = $location.search().parentId;
  49. }
  50.  
  51.  
  52. var messageBody = '';
  53.  
  54. /**
  55. $scope.smartFormName SIQ; // only happens when you process thru form without refreshing; TODO Figure out why
  56.  
  57. $scope.currentSubmission @object
  58.  
  59. attestationName
  60. columnOptionValues @string
  61. "[{"Name":"contactFirst","Value":"Test"},{"Name":"contactMiddle","Value":"Test"},{"Name":"contactLast","Value":"Test"},{"Name":"protocolNum","Value":"1141"},{"Name":"contactSuffix","Value":"TESt"},{"Name":"sponsor","Value":"at"}]"
  62. userSubmissionId: "ca9bd37d-019d-4e78-926d-03c935558188"
  63. userSubmissionIntId: 430
  64.  
  65. columnOptions @array
  66. name: "contactLast"
  67. value: "afa"
  68. **/
  69.  
  70. $scope.sponsor;
  71. $scope.firstName;
  72. $scope.lastName;
  73.  
  74. var token = AuthToken.getToken(), User;
  75.  
  76. var fetchWorkspaces = function () {
  77.  
  78. $scope.isWorkspacesLoading = true;
  79.  
  80. Workflows.getWorkspaces(token, 'qr')
  81. .then(function (res) {
  82.  
  83. var workspaces = res.data.payload.workspaces || [], i;
  84. $scope.isWorkspacesLoading = false;
  85.  
  86. // loop through workspaces so select dropdown can display both title and qr
  87. for (i = 0; i < workspaces.length; i += 1) {
  88. // Protocol, Sponsor, QR#, Workspace Name
  89.  
  90. if (workspaces[i].qr) {
  91. workspaces[i].displayName = (workspaces[i].protocol) + ' / ' + (workspaces[i].sponsor) + ' / ' + (workspaces[i].qr) + '/ ' + workspaces[i].title;
  92. } else {
  93. // TODO: see if we should filter if there is no QR number
  94. workspaces[i].displayName = workspaces[i].title;
  95. }
  96. }
  97.  
  98. $scope.workspaces = workspaces;
  99.  
  100. }, function (err) {
  101. toaster.pop('error', 'Error', 'Oops, there was an error fetching workspaces. This was the error: ' + err.message);
  102. $scope.isWorkspacesLoading = false;
  103. });
  104. };
  105.  
  106. $scope.isOwnerOrSponsor = function () {
  107. return ($scope.owner && $scope.owner.email == $scope.email) || ($scope.subscriber && $scope.subscriber.accountType == 'cro');
  108. };
  109.  
  110. $scope.isOwner = function () {
  111. return ($scope.owner && $scope.owner.email == $scope.email);
  112. };
  113.  
  114.  
  115. //Finalize Submission
  116. //Send for Pre-Approval
  117. //Submit for Institution Review
  118. // watcher for Institution Review checkbox; this is where you'd do stuff if toggled "yes/no"
  119. $scope.onInstitutionChange = function () {
  120. $scope.calculateSubmitButtonText();
  121. };
  122.  
  123. $scope.calculateSubmitButtonText = function () {
  124. if ($scope.currentSubmission.isInstitutionReview) {
  125. $scope.submitAction = 'institution';
  126. $scope.submitButtonText = 'Submit for Institution Review';
  127. $scope.currentSubmission.routingOptions = 'institution';
  128. } else if (!$scope.currentSubmission.isInstitutionReview && $scope.workspace && $scope.requiresPreApproval && !$scope.isOwnerOrSponsor()) {
  129. $scope.submitButtonText = 'Send for Pre-Approval';
  130. $scope.submitAction = 'pre-approval';
  131. $scope.currentSubmission.routingOptions = 'pre-approval';
  132. } else if (($scope.workspace && !$scope.requiresPreApproval) ||
  133. (!$scope.currentSubmission.isInstitutionReview && $scope.workspace && $scope.requiresPreApproval && $scope.isOwnerOrSponsor())) {
  134. $scope.submitButtonText = 'Submit to Quorum';
  135. $scope.submitAction = 'quorum';
  136. $scope.currentSubmission.routingOptions = 'quorumSubmit';
  137. $scope.requiresPreApproval = false; // reset to false
  138. } else {
  139. $scope.submitButtonText = 'Finalize Submission';
  140. $scope.submitAction = 'quorum';
  141. $scope.currentSubmission.routingOptions = '';
  142. $scope.requiresPreApproval = false; // reset to false
  143. }
  144. };
  145.  
  146.  
  147. // NOTE: For future Smart Forms that require pre-approval, add them in the Angular constants in app.js
  148. // There is a match if the SmartForm Name matches the key or value
  149. $scope.isSmartFormsAbleToRequirePreApproval = function () {
  150. return $scope.smartFormName && _.some(PRE_APPROVAL_SMARTFORMS, function (value, key, collection) {
  151. return $scope.sfKey = (value == $scope.smartFormName || key == $scope.smartFormName) ? key : false;
  152. });
  153. };
  154.  
  155. $scope.onSiteSelected = function () {
  156.  
  157.  
  158.  
  159. $scope.piName = $scope.currentSubmission.submissionSite.PI;
  160. /**
  161. if ($scope.currentSubmission.submissionSite) {
  162. for (var i = 0; i < $scope.workspaceSitesArray.length; i++) {
  163. if ($scope.workspaceSitesArray[i].Site_Suffix == $scope.currentSubmission.submissionSite) {
  164. $scope.piName = $scope.workspaceSitesArray[i].PI;
  165. }
  166. }
  167. } else {
  168. $scope.piName = null;
  169. } **/
  170.  
  171. };
  172.  
  173. $scope.onWorkspaceSelected = function () {
  174. $scope.requiresPreApproval = null;
  175. $scope.showSiteDropDown = false;
  176. $scope.piName = null;
  177. $scope.userIsViewer = null;
  178. $scope.currentSubmission.submissionSite = null;
  179. $scope.workspaceSitesArray = [];
  180.  
  181. $scope.pendingWorkspacePreApprovalVerification = true;
  182. // one second delay so they can see pending message.
  183. if ($scope.currentSubmission.workspace) {
  184. $scope.workspace = true; // we set true here now, so we can hide stuff in HTML
  185.  
  186. Workflows.getWorkspace($scope.currentSubmission.workspace._id, token)
  187. .then(function (res) {
  188.  
  189. $scope.pendingWorkspacePreApprovalVerification = false;
  190.  
  191. // if form is SIQ or SSR and matches workspace pre-approvals
  192. // SIQ should be mapped to Initial Site Submission (ISS).
  193. // SSR should be mapped to Site Periodic Review (SPR).
  194. // workspace.preapprovals: { "ISS" : true, "SI": true, etc. }
  195.  
  196. $scope.workspace = res.data.payload.workspace;
  197.  
  198.  
  199. $scope.submissions.getUserSites();
  200.  
  201. $scope.owner = _.find($scope.workspace.subscribers, { 'role': 'owner' });
  202.  
  203. console.log('owner', $scope.owner);
  204. $scope.subscriber = _.find($scope.workspace.subscribers, { email: $scope.email });
  205.  
  206. $scope.userIsViewer = $scope.subscriber.role == 'viewer';
  207.  
  208. console.log('subscriber', $scope.subscriber);
  209.  
  210.  
  211. if ($scope.isSmartFormsAbleToRequirePreApproval()) {
  212. $scope.smartFormSubmissionType = $scope.sfKey; // e.g., SIQ, SSR
  213. }
  214.  
  215. if ($scope.workspace && $scope.workspace.preapprovals.ISS && $scope.smartFormSubmissionType == 'SIQ') {
  216. $scope.submissionType = { 'value': 'ISS', 'text': 'Initial Site Submission', 'canRequirePreapproval': true };
  217. if (!$scope.isOwner()) {
  218. $scope.requiresPreApproval = true;
  219. } else {
  220. $scope.requiresPreApproval = false;
  221. }
  222. $scope.calculateSubmitButtonText();
  223. } else {
  224. $scope.submissionType = { 'value': $scope.smartFormName, 'text': $scope.smartFormName, 'canRequirePreapproval': false };
  225. $scope.requiresPreApproval = false;
  226. $scope.calculateSubmitButtonText();
  227. }
  228. }, function (err) {
  229. console.log('fetching workspace err', err);
  230. $scope.pendingWorkspacePreApprovalVerification = false;
  231. });
  232.  
  233.  
  234. } else {
  235. $scope.workspace = null;
  236. $scope.pendingWorkspacePreApprovalVerification = false;
  237. $scope.calculateSubmitButtonText();
  238. }
  239. };
  240.  
  241. if (token) {
  242. Workflows.getUser(token)
  243. .then(function (res) {
  244. User = res.data.user;
  245. User.displayName = User.displayName || User.firstName + ' ' + User.lastName;
  246. $scope.email = User.email;
  247. });
  248.  
  249. fetchWorkspaces();
  250. }
  251.  
  252. $scope.resetRadio = function () {
  253. if (!$scope.requiresPreApproval) {
  254. $scope.currentSubmission.routingOptions = '';
  255. }
  256. };
  257.  
  258. $scope.getModel = function (question, answers, option) {
  259. var value = null;
  260. var model = $filter('filter')(answers, { key: question.key })[0];
  261.  
  262. if (model !== undefined && model != null) {
  263. var object;
  264. if (model != null) {
  265. question.hide = false;
  266. }
  267. if (question.type == "checkboxes") {
  268. var key = option["name"];
  269. object = JSON.parse(model.value);
  270. value = object[key];
  271. } else if (question.type == "select") {
  272. object = JSON.parse(model.value);
  273. value = object.value;
  274. }
  275. else if (question.type == "radio") {
  276. value = (model.value == option.name);
  277. } else if (question.type == "file") {
  278. value = JSON.parse(model.value);
  279. }
  280. else if (question.type == "date") {
  281. if (model.value != 'null')
  282. value = new Date(parseInt(model.value));
  283. }
  284. else {
  285. value = model.value;
  286. }
  287. }
  288. return value;
  289. };
  290.  
  291. // save user submission is what saves the name
  292. dataService.getUserSubmission($scope.submissionId)
  293. .then(function (data) {
  294. $scope.currentSubmission = data || {};
  295.  
  296. // we clear the form data
  297. // TODO: maybe we shouldn't and instead just save it with getUserSubmission, the new workflows data
  298. $scope.currentSubmission.jobTitle = '';
  299. $scope.currentSubmission.attestationFirstName = '';
  300. $scope.currentSubmission.attestationLastName = '';
  301. $scope.currentSubmission.workspace = null;
  302. $scope.currentSubmission.sponsor = '';
  303. $scope.currentSubmission.isTermsAccepted = false;
  304.  
  305. // TODO: find out why getFormType does not work
  306. dataService.getFormType($scope.currentSubmission.userSubmissionId)
  307. .then(function (response) {
  308. $scope.formType = JSON.parse(response.data);
  309.  
  310. console.log('$scope.formType', $scope.formType); // e.g., Site, Study, or null
  311. console.log('$scope.currentSubmission', $scope.currentSubmission);
  312. console.log('$scope.smartFormName', $scope.smartFormName); // e.g., SIQ
  313.  
  314. if ($location.search().smartFormName) {
  315. $scope.smartFormName = $location.search().smartFormName;
  316. } else {
  317. if ($scope.smartFormName) {
  318. console.log('$scope.smartFormName', $scope.smartFormName); // e.g., SIQ
  319. $location.search('smartFormName', $scope.smartFormName);
  320. }
  321.  
  322. }
  323. }, function (error) {
  324. toaster.pop('error', 'Error', 'Error retreiving form type.');
  325. });
  326. }, function (error) {
  327. toaster.pop('error', 'Error', 'Error grabbing UserSubmission.');
  328. $scope.currentSubmission = {};
  329. });
  330.  
  331. dataService.getSummary()
  332. .then(function (result) {
  333. console.log('getSummary', result);
  334. dataService.userSections = result;
  335. }, function (error) {
  336. toaster.pop('error', 'Error', 'Error fetching data.');
  337. });
  338.  
  339.  
  340. $scope.getControlCSS = function (question) {
  341. return (question.isParent == true || question.isParent == null) ? 'parentControl' : 'childControl';
  342. };
  343.  
  344.  
  345. $scope.submissions = {
  346. getPR: function () {
  347. return {
  348. protocolNumber : $scope.workspace.protocol,
  349. qrNumber: $scope.workspace.qr,
  350. siteNumber: null
  351. }
  352. },
  353. addComment: function (inputs, property, data) {
  354. var comment = (property === 'comments') ? 'Comments:\t' + inputs[property].replace(/\n/g, '{NL}') : '*\t' + inputs[property];
  355. return data = data ? data + '\r\n' + comment : comment;
  356. },
  357. processMessageBody: function (formInputs, messageBody) {
  358. return messageBody || '';
  359. },
  360. processWorkflows: function () {
  361.  
  362. var deferred = $q.defer();
  363.  
  364. var submittedFolder,
  365. date = new moment().format(WORKFLOWS_DATE_FORMAT),
  366. folderName = '' + $scope.smartFormName + ' - ' + $scope.currentSubmission.sponsor + ' - ' + $scope.currentSubmission.attestationFirstName + ' ' + $scope.currentSubmission.attestationLastName + ' - ' + new moment().format(WORKFLOWS_DATE_FORMAT) + '',
  367. folderData = { workspaceId: $scope.workspace._id },
  368. subject,
  369. pr,
  370. data = {},
  371. statusObj = {
  372. submissionType: $scope.submissionType ? $scope.submissionType.text : null
  373. },
  374. formInputs; // TODO figure out
  375.  
  376.  
  377. // TODO: ADDED THIS, NEW STUFF, MAKE SURE IF RIGHT
  378. if ($scope.currentSubmission.isInstitutionReview) {
  379. $scope.submitAction = 'institution';
  380. } else if (!$scope.currentSubmission.isInstitutionReview && !$scope.requiresPreApproval && $scope.currentSubmission.routingOptions == "quorumSubmit") {
  381. $scope.submitAction = 'quorum';
  382. } else {
  383. $scope.submitAction = 'pre-approval';
  384. }
  385.  
  386. folderData.sites = {};
  387.  
  388. folderData.sites['*'] = true;
  389.  
  390. if ($scope.currentSubmission.submissionSite && $scope.currentSubmission.submissionSite.Site_Suffix !== 'My site is not listed') {
  391. folderData.sites[$scope.currentSubmission.submissionSite.Site_Suffix] = true;
  392. }
  393.  
  394. if ($scope.currentSubmission.submissionType) {
  395. folderData.submissionType = $scope.currentSubmission.submissionType;
  396. }
  397.  
  398. folderData.folderName = folderName;
  399. folderData.status = $scope.submitAction;
  400.  
  401. workspaceService.createFolder({
  402. workspaceId: $scope.workspace._id,
  403. folderName: folderName,
  404. sites: folderData.sites,
  405. requiresPreapproval: $scope.requiresPreapproval,
  406. submissionType: $scope.submissionType,
  407. submissionId: $scope.submissionId,
  408. status: $scope.submitAction,
  409. isForInstitutionReview: $scope.currentSubmission.isInstitutionReview
  410. }, token).then(function (response) {
  411.  
  412. console.log('CREATE AOTHER FOLDER IN PROCESS WORKFLOWS', response);
  413.  
  414. submittedFolder = response.data.payload || {};
  415. submittedFolder.workspace = $scope.workspace._id;
  416. submittedFolder.submissionId = $scope.submissionId;
  417. submittedFolder.isForInstitutionReview = $scope.currentSubmission.isInstitutionReview;
  418.  
  419. // sumbit to quorum directly, move folders to workspace
  420. if ($scope.submitAction === 'quorum') {
  421. Workflows.moveToFolder(submittedFolder, SUBMISSIONS_FOLDER_NAME, $scope.email, token);
  422. // if institution review and workspace does not have preapproval
  423. } else if ($scope.submitAction === 'institution') {
  424. submittedFolder.status = $scope.submitAction;
  425. statusObj.status = $scope.submitAction;
  426. Workflows.moveToFolder(submittedFolder, INSTITUTION_REVIEW_FOLDER_NAME, $scope.email, token);
  427. // else workspace requires preapproval
  428. } else {
  429. console.log('PRE-APPROVAL MOVING TO FOLDER OCCURS', submittedFolder);
  430. Workflows.moveToFolder(submittedFolder, PREAPPROVAL_FOLDER_NAME, $scope.email, token);
  431. }
  432.  
  433.  
  434. if ($scope.email) {
  435.  
  436. //set submission page name
  437. data.submissionPageName = $scope.submissionType ? $scope.submissionType.text : null;
  438. data.pi = $scope.piName;
  439. pr = $scope.submissions.getPR(); // TODO need to select protocolNumber
  440.  
  441. // submit for quorum
  442. if ($scope.submitAction === 'quorum') {
  443. $scope.submissions.processSubmit({
  444. text: 'Submitted to Quorum',
  445. folderData: folderData,
  446. statusObj: statusObj,
  447. formInputs: formInputs,
  448. data: data,
  449. pr: pr,
  450. submittedFolder: submittedFolder
  451. }).then(function (res) {
  452. deferred.resolve(res);
  453. }).catch(function (err) {
  454. deferred.reject(err);
  455. });
  456. // submit for institution
  457. } else if ($scope.submitAction == 'institution') {
  458. $scope.submissions.processSubmit({
  459. text: 'Submitted for Institution Review',
  460. folderData: folderData,
  461. statusObj: statusObj,
  462. formInputs: formInputs,
  463. data: data,
  464. pr: pr,
  465. submittedFolder: submittedFolder
  466. }).then(function (res) {
  467. deferred.resolve(res);
  468. }).catch(function (err) {
  469. deferred.reject(err);
  470. });
  471. // submit for pre-approval
  472. } else {
  473. subject = $scope.submissionType.text + ' Document for Pre-approval';
  474.  
  475. $scope.preApprovalCheck = true;
  476.  
  477. for (i = 0, len = $scope.item.length; i < len; i += 1) {
  478. console.log('log and move file ' + i);
  479. $scope.item[i].workspace = $scope.workspace._id;
  480. $scope.item[i].isForInstitutionReview = $scope.currentSubmission.isInstitutionReview;
  481. $scope.submissions.logAndMoveFile($scope.item[i], folderData, 'submitted for pre-approval');
  482. }
  483.  
  484. formInputs; // TODO
  485. messageBody = $scope.submissions.processMessageBody(formInputs, messageBody);
  486.  
  487. messageBody += WORKFLOWS_ACCESS_MESSAGE_TEXT;
  488.  
  489. // SENDS MESSAGE FOR FILES // TODO: MAKE SURE WORKS STILL
  490. deferred.resolve(true);
  491.  
  492. $scope.submissions.sendMessagesForFiles(submittedFolder, statusObj, messageBody, subject)
  493. .then(function (res) {
  494. return $scope.submissions.processSubmit({
  495. text: 'Submitted for Pre-approval',
  496. folderData: folderData,
  497. statusObj: statusObj,
  498. formInputs: formInputs,
  499. data: data,
  500. pr: pr,
  501. submittedFolder: submittedFolder
  502. });
  503. }).then(function(res) {
  504. deferred.resolve(res);
  505. }).catch(function (err) {
  506. deferred.reject(err);
  507. });
  508. }
  509. }
  510. });
  511.  
  512. return deferred.promise;
  513. },
  514. sendMessagesForFiles: function (submittedFolder, statusObj, messageBody, subject) {
  515.  
  516. var deferred = $q.defer();
  517.  
  518. var message = $scope.submissions.createMessage(submittedFolder, messageBody, subject);
  519.  
  520. deferred.resolve(message);
  521.  
  522. Workflows.sendMessage($scope.workspace._id, message, token)
  523. .then(function (response) {
  524. deferred.resolve(response);
  525. }).catch(function (err) {
  526. deferred.reject(err);
  527. });
  528.  
  529. return deferred.promise;
  530. },
  531. getUserSites: function () {
  532. console.log('getting user sites');
  533. $scope.showSiteDropDown = false;
  534. Workflows.fetchUserSites($scope.workspace.qr, false).then(function (result) {
  535. console.log('got user sites');
  536. if (result && result.data) {
  537. $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
  538. $scope.workspaceSitesArray = _.uniq($scope.workspaceSitesArray); // uniq so that the dropdown doesn't have duplicates (users can be associated to the same thing mulitple times)
  539. $scope.workspaceSites = {};
  540. for (var i = 0, len = $scope.workspaceSitesArray.length; i < len ; i++) {
  541. 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
  542. $scope.allWorkspaceSites = true;
  543. break;
  544. }
  545. }
  546. }
  547. // if they have access to all, or if they have more than one site,
  548. // we need to show them a drop down to select which sites should be allowed to see the submission
  549. if ($scope.allWorkspaceSites || $scope.workspaceSitesArray.length > 1) {
  550. if ($scope.allWorkspaceSites) {
  551. // get all sites for that QR, and set $scope.workspaceSitesArray to that
  552. Workflows.fetchAllQRSites($scope.workspace.qr).then(function (result) {
  553. if (result && result.data) {
  554. var sites = result.data;
  555. $scope.workspaceSitesArray = [];
  556. for (var b = 0, len = sites.length ; b < len ; b++) {
  557. $scope.workspaceSitesArray.push(sites[b]);
  558. }
  559.  
  560. $scope.workspaceSitesArray.push({ Site_Suffix: 'My site is not listed' });
  561.  
  562. $scope.workspaceSitesArray = _.unique($scope.workspaceSitesArray);
  563. $scope.showSiteDropDown = true;
  564. }
  565. });
  566. } else {
  567. // the drop down will be populated with $scope.workspaceSitesArray
  568. $scope.showSiteDropDown = true;
  569. }
  570. } else {
  571. if (!$scope.workspaceSitesArray || !$scope.workspaceSitesArray.length) {
  572. $scope.showSiteDropDown = true;
  573. console.log('the user had no sites. Not sure if that\'s supposed to be possible');
  574. } else if ($scope.workspaceSitesArray.length === 1) {
  575. $scope.showSiteDropDown = true;
  576. } else {
  577. toaster.pop('error', 'Error', 'Something very strange happened.');
  578. console.log('we did something wrong. This else should never happen. Counter should')
  579. }
  580. }
  581.  
  582. console.log("pushing site is not listed");
  583.  
  584. $scope.workspaceSitesArray.push({ Site_Suffix: 'My site is not listed' });
  585. $scope.workspaceSitesArray = _.unique($scope.workspaceSitesArray);
  586.  
  587. console.log("$scope.workspaceSitesArray", $scope.workspaceSitesArray);
  588. });
  589. },
  590. createMessage: function (submittedFolder, messageBody, subject) {
  591.  
  592. return {
  593. recipients: [{ name: $scope.owner.name, email: $scope.owner.email, recipient: true }],
  594. ccs: [{ name: User.name, email: User.email, cc: true }],
  595. subject: subject,
  596. notSendEmail: true,
  597. body: messageBody,
  598. fileFolderText: submittedFolder.name,
  599. workspaceName: $scope.workspace.title,
  600. workspaceId: $scope.workspace._id,
  601. fileFolderDocument: submittedFolder,
  602. fileOrFolderName: submittedFolder.name,
  603. fileFolderAssociation: submittedFolder._id
  604. };
  605.  
  606. },
  607. submissionTypeSelection: function () {
  608.  
  609. if (!$scope.submissionType) {
  610. return;
  611. }
  612.  
  613. if ($scope.currentSubmission.isInstitutionReview) {
  614. $scope.submitAction = 'institution';
  615. $scope.submitButtonText = 'Submit for Institution Review';
  616. } else if ($scope.workspace.preapprovals[$scope.submissionType.value] && $scope.currUserRole !== 'owner') {
  617. $scope.submitButtonText = 'Send For Pre-Approval';
  618. $scope.submitAction = 'pre-approval';
  619. } else {
  620. $scope.submitButtonText = 'Send to Quorum';
  621. $scope.submitAction = "quorum";
  622. }
  623. },
  624. logAndMoveFile: function (item, folderData, text) {
  625. Workflows.logActivity(text, item, true, null, User, token);
  626. Workflows.copyToFolder(item, folderData.folderName, token);
  627. },
  628. transferProperties: function (data, pr) {
  629. console.log('$SCOPE.WORKSPACE', $scope.workspace);
  630. data = data || {};
  631. data.protocolNumber = pr ? pr.protocolNumber : null;
  632. data.qrNumber = $scope.workspace.qr || null;
  633. data.siteNumber = pr ? pr.siteNumber : null;
  634. data.name = User.displayName;
  635. data.emailAddress = User.email;
  636. data.sponsor = $scope.currentSubmission.sponsor;
  637. data.ids = [];
  638. data.files = [];
  639.  
  640. var formInputs;
  641.  
  642. //set PI
  643. data.pi = $scope.piName;
  644.  
  645. return data;
  646. },
  647. submitFiles: function (item, data) {
  648.  
  649. var deferred = $q.defer();
  650.  
  651. var workspaceID = $scope.workspace._id;
  652.  
  653. data.requiresPreapproval = $scope.requiresPreApproval;
  654. data.institutionName = $scope.currentSubmission.institutionName;
  655. data.isInstitutionReview = $scope.currentSubmission.isInstitutionReview || false;
  656. data.submissionSite = $scope.currentSubmission.submissionSite;
  657.  
  658. submissionsService.workflowsSubmission(workspaceID, data)
  659. .then(function (res) {
  660. deferred.resolve(res);
  661. })
  662. .catch(function (err) {
  663. deferred.resolve(err);
  664. });
  665.  
  666. return deferred.promise;
  667. },
  668. addStatusAndSubmissionTypeToItems: function () {
  669. var deferred = $q.defer(), pass = true;
  670.  
  671. try {
  672. angular.forEach($scope.item, function (item) {
  673. item.status = $scope.submitAction;
  674. item.submissionType = $scope.submissionType.text;
  675. item.submitter = {
  676. id: User._id,
  677. email: User.email,
  678. displayName: User.displayName
  679. }
  680. });
  681. }
  682. catch (e) {
  683. deferred.reject(e);
  684. pass = false;
  685. }
  686.  
  687. if (pass) {
  688. deferred.resolve($scope.item);
  689. }
  690.  
  691. return deferred.promise;
  692. },
  693. setFileStatus: function (item, statusObj) {
  694. Workflows.setStatusAndSubType(item.workspace, item._id, statusObj, token);
  695. },
  696. processSubmit: function (args) {
  697.  
  698. var deferred = $q.defer();
  699.  
  700. var text = args.text,
  701. folderData = args.folderData,
  702. statusObj = args.statusObj,
  703. formInputs = args.formInputs,
  704. data = args.data,
  705. pr = args.pr,
  706. submittedFolder = args.submittedFolder;
  707.  
  708. for (i = 0, len = $scope.item.length; i < len; i += 1) {
  709. $scope.item[i].workspace = $scope.workspace._id;
  710. $scope.item[i].isForInstitutionReview = $scope.currentSubmission.isInstitutionReview;
  711. if (!$scope.preApprovalCheck) {
  712. $scope.submissions.logAndMoveFile($scope.item[i], folderData, 'submitted to Quorum');
  713. }
  714. }
  715.  
  716. statusObj.status = text;
  717.  
  718.  
  719. data = $scope.submissions.transferProperties(data, pr);
  720. data.comments = $scope.submissions.processMessageBody(formInputs, data.comments);
  721. data.submittedFolder = submittedFolder;
  722.  
  723. for (i = 0, len = $scope.item.length; i < len; i += 1) {
  724. data.ids.push($scope.item[i]._id);
  725. }
  726.  
  727. if ($scope.submitAction == 'pre-approval') {
  728. for (var i = 0, len = $scope.workspace.subscribers.length ; i < len ; i++) {
  729. if ($scope.workspace.subscribers[i].role == 'owner') {
  730. data.ownerEmail = $scope.workspace.subscribers[i].email;
  731. }
  732. }
  733. }
  734.  
  735. $scope.submissions.submitFiles($scope.item, data)
  736. .then(function (res) {
  737. deferred.resolve(res);
  738. }).catch(function (err) {
  739. deferred.reject(err);
  740. });
  741.  
  742. return deferred.promise;
  743. },
  744. };
  745.  
  746.  
  747. // TODO: in Portal, this will be under "Supplementary Files" in the workspace
  748.  
  749. /**
  750. * processWorkflowsSubmission returns a promise.
  751. *
  752. * 1. Create Folder to record submission for User; folder resides under "Supplementary Files" in workspace
  753. * 2. Once created, we call createFiles method, which uploads the SmartForms PDF into the new directory
  754. * 3. This returns the newly generated meta data of the PDF in the workspace
  755. * 4.) We then add Status and Submissio Type to Items, this returns a promise
  756. * 5.) Finally, we execute the processWorkflows function
  757. */
  758. var processWorkflowsSubmission = function (pdf) {
  759.  
  760. var deferred = $q.defer();
  761.  
  762. var promises = [];
  763.  
  764. $http.get('api/files/attachments/' + $routeParams.submissionId)
  765. .then(function (res) {
  766.  
  767. var fileNames = res.data.result || [],
  768. processedResults = [];
  769.  
  770. for (var i = 0; i < fileNames.length; i++) {
  771. processedResults.push({
  772. name: fileNames[i].name,
  773. data: fileNames[i].content,
  774. size: fileNames[i].size
  775. });
  776. }
  777.  
  778. console.log('ITEMS RETURNED FROM SERVER PROCESSED RESULTS', processedResults);
  779.  
  780. var returnedFolders;
  781.  
  782. workspaceService.createFolder({
  783. folderName: $scope.smartFormName + '-' + $scope.currentSubmission.sponsor + ' - ' + $scope.currentSubmission.attestationFirstName + ' ' + $scope.currentSubmission.attestationLastName + ' - ' + new moment().format(WORKFLOWS_DATE_FORMAT),
  784. workspaceId: $scope.workspace._id,
  785. requiresPreapproval: $scope.requiresPreapproval,
  786. submissionType: $scope.submissionType,
  787. submissionId: $scope.submissionId,
  788. status: $scope.submitAction,
  789. isForInstitutionReview: $scope.currentSubmission.isInstitutionReview
  790. }, token)
  791. .then(function (returnedFolder) {
  792.  
  793. $scope.parentId = returnedFolder.data.payload._id;
  794. console.log('returned Folder after FIRST CREATE', returnedFolder)
  795. returnedFolders = returnedFolder.data.payload;
  796.  
  797. // TODO FIGURE OUT SIZE SO IT CAN TO WORKSPACE
  798. return workspaceService.createFiles({
  799. files: processedResults,
  800. workspaceId: $scope.workspace._id,
  801. parentId: returnedFolder.data.payload._id || null,
  802. isForInstitutionReview: $scope.currentSubmission.isInstitutionReview
  803. })
  804. }, token).then(function (returnedItems) {
  805. console.log('ITEMS RETURNED FROM SERVER AFTER CREATE FILES', returnedItems);
  806. var items = returnedItems.data.payload;
  807. $scope.item = items || [];
  808. return $scope.submissions.addStatusAndSubmissionTypeToItems();
  809. }).then(function (res) {
  810. returnedFolders.workspace = $scope.workspace._id;
  811. returnedFolders.submissionId = $scope.submissionId;
  812. returnedFolders.isForInstitutionReview = $scope.currentSubmission.isInstitutionReview;
  813. console.log('moving To Folder SUPPLEMENTARY_FILES_FOLDER_NAME', returnedFolders);
  814. return Workflows.moveToFolder(returnedFolders, SUPPLEMENTARY_FILES_FOLDER_NAME, $scope.email, token);
  815. }).then(function (res) {
  816. return $scope.submissions.processWorkflows();
  817. })
  818. .then(function (res) {
  819. deferred.resolve(res);
  820. }).catch(function (err) {
  821. console.log('err 2', err);
  822. return deferred.reject(err);
  823. });
  824. });
  825.  
  826. return deferred.promise;
  827. };
  828.  
  829. // Reset confirmation options, thus requiring the user to re-confirm the information is accurate
  830. // after returning from the summary page.
  831. $scope.returnToSummary = function() {
  832. $scope.currentSubmission.isTermsAccepted = false;
  833. $scope.currentSubmission.routingOptions = undefined;
  834. };
  835.  
  836. $scope.finalizeSubmission = function () {
  837.  
  838. if ($scope.pendingWorkspacePreApprovalVerification) {
  839. toaster.pop('error', 'Error', 'Cannot submit while verifying Pre-approval status for workspace');
  840. return false;
  841. }
  842.  
  843.  
  844. var generatePDF = function () {
  845. var deferred = $q.defer();
  846. dataService.generatePdf().then(function (res) {
  847. deferred.resolve(res); // resolve PDF buffer data
  848. }, function (err) {
  849. return deferred.reject(new Error('Error occurred while generating PDF. This was the error: ' + err.message));
  850. });
  851. return deferred.promise;
  852. };
  853.  
  854. var sendEmails = function () {
  855.  
  856. var deferred = $q.defer();
  857.  
  858. data = { institutionReview: $scope.currentSubmission.isInstitutionReview, submissionSite: $scope.currentSubmission.submissionSite };
  859.  
  860. if ($scope.currentSubmission.routingOptions !== 'downloadSubmit') {
  861. dataService.sendEmails(data).then(function (res) {
  862. deferred.resolve();
  863. }, function (err) {
  864. var message = err.data && err.data.message ? err.data.message : err.message;
  865. return deferred.reject(new Error('Error occurred while sending submission emails. This was the error: ' + message));
  866. });
  867. } else {
  868. deferred.resolve();
  869. }
  870.  
  871. return deferred.promise;
  872. };
  873.  
  874.  
  875. var modalInstance = $modal.open({
  876. animation: false,
  877. templateUrl: '/app/partials/confirm.submission.modal.html',
  878. controller: ['$scope', '$modalInstance', 'data', function($scope, $modalInstance, data) {
  879.  
  880. $scope.workspace = data.workspace;
  881. $scope.submitAction = data.submitAction || 'quorum';
  882. $scope.submissionType = data.submissionType;
  883.  
  884. $scope.ok = function () {
  885. $modalInstance.close(true);
  886. };
  887.  
  888. $scope.cancel = function () {
  889. $modalInstance.dismiss('cancel');
  890. };
  891. }],
  892. resolve: {
  893. data: function () {
  894. return {
  895. workspace: $scope.workspace,
  896. submissionType: $scope.smartFormName, // $scope.submissionType ? $scope.submissionType.text : $scope.smartFormName
  897. submitAction: $scope.currentSubmission.routingOptions == 'downloadSubmit' ? 'download' : $scope.submitAction
  898. }
  899. }
  900. }
  901. });
  902.  
  903. modalInstance.result.then(function (value) {
  904. // TODO CURRENTSUBMISSION SUBMISSION STATUS
  905. $scope.currentSubmission.attestationName = $scope.currentSubmission.attestationFirstName + ' ' + $scope.currentSubmission.attestationLastName;
  906.  
  907. var status = $scope.data.SubmissionStatusEnum;
  908.  
  909. switch($scope.currentSubmission.routingOptions) {
  910. case 'quorumSubmit':
  911. $scope.currentSubmission.submissionStatus = status.Submitted
  912. break;
  913. case 'institution':
  914. $scope.currentSubmission.submissionStatus = status.SentForInstitutionReview;
  915. break;
  916. case 'pre-approval':
  917. $scope.currentSubmission.submissionStatus = status.SentForPreApproval;
  918. break;
  919. default:
  920. $scope.currentSubmission.submissionStatus = status.Downloaded
  921. }
  922.  
  923. // first we save the form
  924. dataService.updateSubmission($scope.submissionId, $scope.currentSubmission)
  925. .then(function (res) {
  926. return generatePDF($scope.submissionId);
  927. }).then(function (res) {
  928.  
  929. console.log('generated PDF', res);
  930.  
  931. if ($scope.workspace) {
  932. return processWorkflowsSubmission(res.data); // pass pdf to be processed
  933. } else {
  934. // if institution review is checked, email is sent to institution review
  935. // otherwise, it is sent to regular Quorum's submission
  936.  
  937. return sendEmails();
  938.  
  939. }
  940. }).then(function (res) {
  941.  
  942. var value, message;
  943.  
  944. switch ($scope.currentSubmission.routingOptions) {
  945. case 'quorumSubmit':
  946. value = 'quorumSubmitted';
  947. message = 'A PDF of the submission has been generated and submitted to Quorum.';
  948. break;
  949. case 'institution':
  950. value = 'institutionSubmitted';
  951. message = 'A PDF of the submission has been generated and submitted for Institution Review.';
  952. break;
  953. case 'pre-approval':
  954. value = 'preApprovalSubmitted';
  955. message = 'A PDF of the submission has been generated and submitted for Pre-Approval.';
  956. break;
  957. default:
  958. value = 'userDownloaded';
  959. message = 'A PDF of the submission has been generated.';
  960. break;
  961. }
  962.  
  963. if (value == 'quorumSubmitted' && $scope.workspace) {
  964. $location.path('/formViewer/' + $scope.submissionId + '/workspaceSubmitQuorum/' + $scope.sectionId).search({ 'workspaceId': $scope.workspace._id, workspaceName: $scope.workspace.title, parentId: $scope.parentId });
  965. } else if ($scope.workspace) {
  966. $location.path('/formViewer/' + $scope.submissionId + '/' + value + '/' + $scope.sectionId).search({'workspaceId': $scope.workspace._id, workspaceName: $scope.workspace.title, parentId: $scope.parentId});
  967. } else {
  968. $location.path('/formViewer/' + $scope.submissionId + '/' + value + '/' + $scope.sectionId);
  969. }
  970.  
  971. toaster.pop('success', 'Successful', message);
  972. }).catch(function (err) {
  973. console.log('err', err);
  974. toaster.pop('error', 'Error', 'Error occured while updating submission. This was the error: ' + err.message);
  975. });
  976. });
  977. };
  978.  
  979. $scope.saveAndExit = function () {
  980. dataService.updateSubmission($scope.submissionId, $scope.currentSubmission)
  981. .then(function (result) {
  982. $location.path('/');
  983. toaster.pop('success', 'Successful', 'The submission has been saved.');
  984. }, function (error) {
  985. toaster.pop('error', 'Error', 'Error fetching data');
  986. });
  987. };
  988.  
  989. // for forms in the submissionType object...
  990. // get user's workspaces
  991. // find out if any of them have preapprovals
  992. // if at least one does, present a list of workspaces (with protocols) to the user
  993. // change radio button options accordingly
  994. // upon submission upload the PDF (assuming we have it) to Workspaces
  995. $scope.goToHost = function(submissionId, popupId) {
  996. dataService.getHostSection(popupId)
  997. .then(function (hostSection) {
  998. $location.url("/formViewer/" + submissionId + "/sections/" + hostSection.sectionId);
  999. },
  1000. function (error) {
  1001. toaster.pop('error', 'Error', 'Error retrieving section');
  1002. });
  1003. };
  1004.  
  1005. $scope.gotoTop = function() {
  1006. $location.hash('top');
  1007. $anchorScroll();
  1008. };
  1009.  
  1010.  
  1011. }
  1012. ]);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement