Best JavaScript code snippet using ng-mocks
edit.js
Source:edit.js
1(function () {2 'use strict';3 angular.module('app.membership')4 .controller('EditAppCtrl', EditAppCtrl);5 /** @ngInject */6 function EditAppCtrl($rootScope, $scope, $state, $sce, $q, toaster, appUtils, authService, memStateService, applicationMaps, memAppService, membershipMediaService, memberShipService, memAppHisService, memberShipPlansService, memberShipAddOnsService, $uibModal, $ngBootbox, $timeout, employeeService, $stateParams, permissionService, memberShipFacilitiesService, $http, memRegionService, memProcessQueueService, memAppVerifyService, memAppTimeLineService, memAppIndicatorService, firebaseDataRef, employeeLogService, personTitleService, DataUtils) {7 $rootScope.settings.layout.pageSidebarClosed = true;8 $scope.userPermission = $rootScope.storage.statePermission;9 //$rootScope.itemSelected = $stateParams.id;10 var currentUser = authService.getCurrentUser(); //$rootScope.storage.currentUser;11 var appSettings = $rootScope.storage.appSettings;12 var timestampStart = $stateParams.start ? $stateParams.start : '';13 var timestampEnd = $stateParams.end ? $stateParams.end : '';14 var clients = $stateParams.author || currentUser.repCode || currentUser.username || '';15 var alias = $stateParams.alias || currentUser.alias || '';16 var states = $stateParams.state || 'All';17 var plantypes = $stateParams.plantype || null;18 var reportBy = $stateParams.reportBy || 'timestampCreated';19 var sortBy = $stateParams.sortBy || 'asc';20 var countWatch = 0;21 var totalAmountTmp = 0,22 indicatorRef, editRef, physicalFilesRef = {},23 applicationId = angular.copy($stateParams.id),24 indicator = null;25 var initModel = false,26 indicatorCallback = appSettings.indicatorCallback || 5;27 $scope.userPermission.isAccessPermission = $rootScope.can('access', 'ViewApplicationImages');28 //Tracking history application variables=========================29 var modelsDirtied = {};30 var skipKeys = ['fields'];31 var isobject = function (x) {32 return Object.prototype.toString.call(x) === '[object Object]';33 };34 var getkeys = function (obj, prefix) {35 var keys = Object.keys(obj);36 prefix = prefix ? prefix + '.' : '';37 return keys.reduce(function (result, key) {38 if (isobject(obj[key]) && skipKeys.indexOf(key) != -1) {39 result = result.concat(getkeys(obj[key], prefix + key));40 } else {41 result.push(prefix + key);42 }43 return result;44 }, []);45 };46 var checkNested = function (obj, key) {47 var splitKey = key.split('.');48 return key.split(".").reduce(function (o, x) {49 if (({}.toString.apply(o[x]) === '[object Function]')) return undefined;50 return o[x];51 }, obj);52 };53 //End Tracking history application variables===================54 var applicationVm = this;55 applicationVm.model = {};56 applicationVm.model.$id = $stateParams.id ? $stateParams.id : '';57 applicationVm.isEnableSelectPlan = false;58 //common59 $scope.toggleImagePnl = false;60 applicationVm.activeFileUploadTab = false;61 applicationVm.currentFiles = null;62 applicationVm.isEnoughtCast = true;63 applicationVm.submitting = false;64 applicationVm.cashChange = 0;65 applicationVm.tabFileId = -1;66 applicationVm.statePlans = {};67 applicationVm.secPlanKey = '';68 applicationVm.planItems = [];69 applicationVm.planItemsIndex = {};70 applicationVm.addonItems = [];71 applicationVm.addonItemsIndex = {};72 applicationVm.employees = [];73 applicationVm.appStatelist = [];74 applicationVm.appFacilityItems = [];75 applicationVm.regionGroups = {};76 applicationVm.allStates = appUtils.getAllState();77 if (applicationVm.allStates && applicationVm.allStates.length > 0) {78 var usStates = _.map(applicationVm.allStates, function (s) {79 return s.value;80 });81 if (usStates && usStates.length > 0) {82 var stateStr = usStates.join('|');83 applicationVm.stateRegx = new RegExp('^(' + stateStr + ')$');84 }85 }86 applicationVm.appStatus = appUtils.appStatus;87 applicationVm.appNumAdultsList = appUtils.appNumAdults;88 applicationVm.appCycleList = appUtils.appCycles;89 applicationVm.appPaymentMethodList = appUtils.appPaymentMethods;90 applicationVm.prefixList = [];91 applicationVm.suffixList = [];92 //Load data93 // templay hide marker94 // $scope.appMaps = applicationMaps.getFrmSettings('FL');95 // $scope.markers = $scope.appMaps.markers;96 // $scope.mapping = $scope.appMaps.mapping;97 $scope.appMaps = {}; $scope.markers = {}; $scope.mapping = null;98 $scope.fieldsMap = applicationMaps.fieldsMap;99 //Form Variables100 applicationVm.showInvalid = true;101 applicationVm.numberRegx = /^\d+$/;102 applicationVm.year2Regx = /(1[6-9])|([2-9][0-9])/;103 applicationVm.monthRegx = /(0[1-9])|(1[012])/;104 applicationVm.yearRegx = /(20[1-9][9]|20[2-9][0-9]|2100)/;105 applicationVm.zipcodeRegx = /(^\d{5}$)|(^\d{5}-\d{4}$)/;106 applicationVm.nameRegx = /^(a-z|A-Z|0-9)*[^!#$%^&*()'"\/\\;:@=+,?\[\]\/]*$/;107 applicationVm.addressRegx = /^(a-z|A-Z|0-9)*[^!$%^&*()'"\/\\;:@=+,?\[\]]*$/;108 applicationVm.emailRegx = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;109 // applicationVm.emailRegx = '\\d+';110 applicationVm.currencyRegx = /^\$\d/;111 applicationVm.cvvRegx = /(^\d{3}$)|(^\d{4}$)|^\d+$/;112 applicationVm.memberIDRegx = /^[a-zA-Z0-9]+$/;113 applicationVm.formTitle = 'Add New Application';114 applicationVm.facilityTxt = '';115 applicationVm.eventTxt = '';116 applicationVm.initPopup = false;117 applicationVm.initSeclectEvent = false;118 applicationVm.keyword = '';119 //applicationVm.status = '-1';120 applicationVm.clients = clients;121 applicationVm.reportDate = reportBy;122 applicationVm.sortBy = sortBy;123 applicationVm.getState = getState;124 applicationVm.paging = {125 pageSize: 25,126 currentPage: 0,127 totalPage: 0,128 totalRecord: 0129 };130 applicationVm.selectedRegionSettings = {};131 var itemStatusMap = {132 'New': { icon: 'fa-file' },133 'Processing': { icon: 'fa-spinner' },134 'Verified': { icon: 'fa-check-square-o' },135 'Billing Pending': { icon: 'fa-hourglass-half' },136 'Billing Denied': { icon: 'fa-hourglass-half' },137 'Cancelled': { icon: 'fa fa-times' },138 'Error': { icon: 'fa fa-exclamation-triangle' },139 'Billing Approved': { icon: 'fa-user' },140 'Billing Required': { icon: 'fa-usd' },141 'Default': { icon: 'fa-file-o' }142 };143 //Google address Variables144 $scope.addressInvalid = true;145 $scope.addressVerification = {146 show: false,147 cls: 'gplace',148 content: $sce.trustAsHtml('<span class="fa fa-spinner font-grey-silver"></span>'),149 place: {150 address: '',151 city: '',152 state: '',153 zipCode: ''154 },155 getPlace: function (place) { }156 };157 //Dropzone Init158 applicationVm.dzOptions = {159 url: 'application/',160 firebaseStorage: true,161 parallelUploads: 10,162 // addRemoveLinks : true,163 // dictRemoveFile : 'Remove',164 // dictResponseError : 'Could not upload this file',165 acceptedFiles: '.png,.jpg,.jpeg, image/jpeg, images/jpg, image/png'166 };167 applicationVm.dzCallbacks = {168 'addedfile': function (file, response) {169 },170 'success': function (file, response) {171 appUtils.hideLoading();172 var snapshot = {};173 _.each(response, function (task, key) {174 snapshot[key] = task.snapshot;175 });176 var metadata = snapshot.ori.metadata,177 appId = angular.copy(applicationVm.model.$id);178 //Create employee log for upload application image179 var employeeLog = {180 action: appUtils.logEmployeeAction.uploadImage.value,181 status: 'Success',182 fileInfo: {183 fileName: metadata.name,184 originalName: file.name,185 fileSize: metadata.size,186 fileType: metadata.contentType,187 repCode: currentUser.username || currentUser.repCode,188 state: applicationVm.model.state,189 region: applicationVm.model.region || '',190 regionCode: applicationVm.model.regionCode || '',191 facility: applicationVm.facilityObj,192 applications: {}193 }194 };195 employeeLog.fileInfo.applications[applicationVm.model.$id] = {196 pageIndex: 1197 };198 var imgFile = {199 "alternativeText": "",200 "author": currentUser.email,201 "bucket": metadata.bucket,202 "caption": "",203 "description": "",204 "displayName": metadata.name,205 "downloadUrl": snapshot.ori.downloadURL,206 "fileName": metadata.name,207 "fileSize": metadata.size,208 "fileType": metadata.contentType,209 "fullPath": metadata.fullPath,210 "appId": appId,211 "storageLocation": 'gs://' + metadata.bucket + '/' + metadata.fullPath,212 "type": metadata.contentType,213 "originalName": file.name || ''214 };215 membershipMediaService.addFile(imgFile).then(function (res) {216 if (res.result) {217 employeeLog.fileInfo.mediaId = employeeLog.fileInfo.applications[applicationVm.model.$id].mediaId = res.fileKey;218 employeeLogService.create(currentUser.$id, employeeLog);219 _initFileModel(imgFile, res.fileKey);220 //Application tracking timeline obj221 var appTrackingObjUploadFile = {222 eventType: appUtils.logEvent.uploadFileApp,223 status: angular.copy(applicationVm.model.status),224 mediaId: res.fileKey225 };226 return memAppService.updatePhysicalFiles(applicationVm.model).then(function (rs) {227 if (rs.result) {228 appTrackingObjUploadFile.message = 'Upload application file success.';229 toaster.success('Upload file success!');230 return true;231 } else {232 appTrackingObjUploadFile.message = rs && rs.errorMsg || 'Upload application file has error.';233 toaster.error(rs.errorMsg);234 return false;235 }236 }).catch(function (err) {237 appTrackingObjUploadFile.message = err && err.message || 'Upload application file has error.';238 return false;239 }).then(function () {240 console.log('====Upload more version file do application tracking=====');241 //Create tracking application upload more version file242 memAppTimeLineService.create(appId, appTrackingObjUploadFile);243 });244 } else {245 toaster.error('upload new form has error.');246 }247 });248 },249 'error': function (file, err) {250 toaster.error('upload new form has error.');251 console.log(err);252 var employeeLog = {253 action: appUtils.logEmployeeAction.uploadImage.value,254 status: 'Failed',255 fileInfo: {256 fileName: file.name,257 originalName: file.name,258 fileSize: file.size,259 fileType: file.type,260 repCode: currentUser.username || currentUser.repCode,261 state: applicationVm.model.state,262 region: applicationVm.model.region || '',263 regionCode: applicationVm.model.regionCode || '',264 facility: applicationVm.facilityObj265 }266 };267 employeeLog.message = err && err.message || 'Upload has error.';268 employeeLogService.create(currentUser.$id, employeeLog);269 },270 'removedfile': function (file, response) {271 appUtils.hideLoading();272 toaster.error('File removed.');273 }274 };275 var verifyTimeout;276 $scope.selectFacility = function (item) {277 applicationVm.notBelongState = false;278 applicationVm.model.facilityId = item.$id;279 applicationVm.model.facilityCode = item.facility_promo_code || '';280 if (applicationVm.selectedRegionSettings.enable_promo_code === false) {281 applicationVm.model.facilityCode = '';282 }283 applicationVm.facilityTxt = item.address && $.trim(item.address) !== '' ? item.name + ' - ' + item.facility_promo_code + ' (' + item.address + ')' : item.name + ' - ' + item.facility_promo_code;284 applicationVm.facilityObj = item;285 applicationVm.facilityObj.id = item.$id;286 applicationVm.initSeclectEvent = false;287 if (item.state_code !== applicationVm.model.state) {288 applicationVm.notBelongState = true;289 }290 };291 $scope.filesFilter = function (item) {292 return !item.isDeleted || item.isDeleted === false;293 };294 $scope.$watch('applicationVm.model.numberOfAdults', function (val) {295 if (!initModel) {296 return;297 }298 _watchPlan();299 });300 $scope.$watch('applicationVm.model.cashInput', function (val) {301 if (!initModel) {302 return;303 }304 applicationVm.isEnoughtCast = parseFloat(val) >= parseFloat(applicationVm.model.total.totalAmount);305 applicationVm.cashChange = parseFloat(val - (applicationVm.model.total.totalAmount || 0));306 });307 $scope.$watch('applicationVm.model.total.totalAmount', function (val) {308 if (!initModel) {309 return;310 }311 applicationVm.isEnoughtCast = parseFloat(applicationVm.model.cashInput) >= parseFloat(val);312 applicationVm.cashChange = parseFloat(applicationVm.model.cashInput - (val || 0));313 });314 $scope.$watch('applicationVm.model.cycle', function (val) {315 if (!initModel) {316 return;317 }318 _watchPlan();319 });320 $scope.$watch('applicationVm.model.creditCard.month', function (val) {321 if (!initModel) {322 return;323 }324 var month = val,325 year = applicationVm.model.creditCard.year;326 if (month && year && applicationVm.model.signature && applicationVm.model.paymentMethod === '0') {327 var time = moment().utc().year(year).month(month - 1);328 applicationVm.expirationCard = _.clone(time).endOf('month').format('MM/DD/YYYY');329 } else {330 applicationVm.expirationCard = null;331 }332 });333 $scope.$watch('applicationVm.model.signature', function (val) {334 if (!initModel) {335 return;336 }337 var month = applicationVm.model.creditCard.month,338 year = applicationVm.model.creditCard.year;339 if (month && year && val && applicationVm.model.paymentMethod === '0') {340 var time = moment().utc().year(year).month(month - 1);341 applicationVm.expirationCard = _.clone(time).endOf('month').format('MM/DD/YYYY');342 } else {343 applicationVm.expirationCard = null;344 }345 });346 $scope.$watch('applicationVm.model.creditCard.year', function (val) {347 if (!initModel) {348 return;349 }350 var month = applicationVm.model.creditCard.month,351 year = val;352 if (month && year && applicationVm.model.signature && applicationVm.model.paymentMethod === '0') {353 var time = moment().utc().year(year).month(month - 1);354 applicationVm.expirationCard = _.clone(time).endOf('month').format('MM/DD/YYYY');355 } else {356 applicationVm.expirationCard = null;357 }358 });359 $scope.$watch('applicationVm.model.state', function (newValue, oldValue) {360 if (!initModel) {361 return;362 }363 if (_.trim(newValue) !== _.trim(oldValue)) {364 var autoSelect = applicationVm.regionGroups[newValue];365 if (autoSelect && autoSelect.length === 1) {366 applicationVm.model.region = autoSelect[0].id;367 applicationVm.model.regionCode = autoSelect[0].code;368 changeRegion();369 } else {370 applicationVm.model.region = applicationVm.model.regionCode = '';371 }372 }373 });374 $scope.indicatorMsgErr = '';375 $scope.$on('$destroy', function () {376 //on value membership-applications-indicator/377 if (indicatorRef) {378 indicatorRef.off('value', checkIndicator);379 }380 //on value membership-applications/381 if (editRef) {382 editRef.off('value', showMessageUpdateInfo);383 }384 if (physicalFilesRef) {385 _.forEach(physicalFilesRef, function (item, key) {386 physicalFilesRef[key].on('value', onValuePhysicalFiles);387 });388 }389 //clear interval update timestamp after 5 minutes390 if (indicator !== null) {391 clearInterval(indicator);392 }393 //$scope.$emit('indicatorsLoad', null);394 $scope.indicatorMsgErr = '';395 unCheckIndicator();396 $(window).off('scroll');397 });398 // Make sure DOM is loaded before get elems399 angular.element(document).ready(function () {400 $timeout(function () {401 var appFormEl = angular.element(document.querySelector('#application_form'));402 var appImageEl = angular.element(document.querySelector('#application_image'));403 // var bodyEl = angular.element( document.querySelector('body' ));404 $(window).on('resize', function (event) {405 $timeout(function () {406 applicationVm.formW = $('#application_form').width() || 420;407 }, 800);408 });409 applicationVm.scrolling = false;410 applicationVm.timeoutScrolling = null;411 $(window).on('scroll', function (event) {412 let windowScrollCount = $(this).scrollTop();413 let animationFrame = Math.round(windowScrollCount / 100);414 if (applicationVm.scrolling || animationFrame % 5 !== 0) {415 return;416 }417 clearTimeout(applicationVm.timeoutScrolling);418 applicationVm.timeoutScrolling = setTimeout(function () {419 applicationVm.scrolling = true;420 var element = $('#application_image'),421 originalY = $('#application-content').offset() ? $('#application-content').offset().top : 600,422 limit = $(document).height() - $(window).height();423 element.css('position', 'relative');424 var scrollTop = $(window).scrollTop(),425 topVal = 0;426 if (scrollTop < originalY) {427 topVal = 0;428 } else {429 topVal = scrollTop - originalY + 75;430 if ($('#application_image').offset() !== undefined) {431 var compare = $('#application_image').offset().top + $('#application_image').height();432 var compare2 = $('#application-content').offset().top + $('#application-content').height();433 if (compare > compare2) {434 topVal = $('#application-content').height() - $('#application_image').height();435 }436 } else {437 topVal = 0;438 }439 }440 $('#application_image').stop(false, false).animate({441 top: topVal442 }, { duration: 300, complete: function () { applicationVm.scrolling = false; } });443 }, 200);444 });445 // tempory hide focus446 // $scope.focusMe = function(mapName, isToggle) {447 // var map = $scope.mapping[mapName];448 // if (!map) {449 // return;450 // }451 // _clearSelected(); // Clear before show another one452 // map.selected = isToggle ? !map.selected : true;453 // };454 $scope.focusMe = angular.noop;455 }, 2000);456 });457 _initPage();458 //Functions459 //applicationVm.create = create;460 applicationVm.changeState = changeState;461 applicationVm.changeRegion = changeRegion;462 applicationVm.changePaymentMethod = changePaymentMethod;463 applicationVm.addressVerification = addressVerification;464 applicationVm.bankAddressVerification = bankAddressVerification;465 applicationVm.waivedSetupFee = waivedSetupFee;466 //467 applicationVm.getStaffName = getStaffName;468 applicationVm.clearUploadedFiles = clearUploadedFiles;469 applicationVm.viewMember = viewMember;470 applicationVm.getIconStatus = getIconStatus;471 applicationVm.getAppImage = getAppImage;472 applicationVm.refreshStatus = refreshStatus;473 applicationVm.getMemberName = getMemberName;474 applicationVm.activeFileTab = activeFileTab;475 applicationVm.activeUploadFileTab = activeUploadFileTab;476 applicationVm.checkPriAddon = checkPriAddon;477 applicationVm.popupChangeStatus = popupChangeStatus;478 applicationVm.getFileStatus = getFileStatus;479 applicationVm.getAppStatus = getAppStatus;480 applicationVm.processFile = processFile;481 applicationVm.selectFile = selectFile;482 applicationVm.recycleFile = recycleFile;483 applicationVm.process = process;484 applicationVm.verify = verify;485 applicationVm.justSave = justSave;486 applicationVm.unLock = unLock;487 applicationVm.submit = submit;488 applicationVm.cancel = cancel;489 applicationVm.membershipOverwrite = membershipOverwrite;490 applicationVm.getCashOptionTxt = getCashOptionTxt;491 applicationVm.cancelAccount = cancelAccount;492 //493 applicationVm.showPopupTrackingActivities = showPopupTrackingActivities;494 applicationVm.showPopupEmployeeList = showPopupEmployeeList;495 applicationVm.showPopupOriginalImage = showPopupOriginalImage;496 applicationVm.openPreviewModal = openPreviewModal;497 applicationVm.showPopupFacilityList = showPopupFacilityList;498 applicationVm.detechCardType = detechCardType;499 applicationVm.showPopupEventList = showPopupEventList;500 //501 applicationVm.activeEditApp = function () {502 $rootScope.isEditApp = true;503 };504 $scope.toggleImagePnlFunc = toggleImagePnlFunc;505 $scope.selectPriPlan = _selectPriPlan;506 //===================================================================================================================================507 function _initPage() {508 if (indicatorRef) {509 indicatorRef.off('value', checkIndicator);510 }511 if (editRef) {512 editRef.off('value', showMessageUpdateInfo);513 }514 appUtils.showLoading();515 var reqs = [];516 reqs.push(employeeService.getAll().then(function (rs) {517 applicationVm.employees = rs;518 }));519 reqs.push(memStateService.getAll().then(function (data) {520 applicationVm.appStatelist = data;521 }));522 reqs.push(memRegionService.getAll().then(function (regionGoups) {523 _.each(regionGoups, function (regionGroup, stateCode) {524 regionGoups[stateCode] = DataUtils.toAFArray(regionGroup);525 });526 applicationVm.regionGroups = regionGoups;527 // console.log(regionGoups);528 }));529 reqs.push(memberShipAddOnsService.getAll().then(function (data) {530 applicationVm.addonItems = data;531 // _.each(data, function (item) {532 // applicationVm.addonItemsIndex[item.$id] = item;533 // });534 _.each(data, function (item, stateCode) {535 var groupByRegion = {};536 _.each(item, function (addOn, addOnId) {537 if (!groupByRegion[addOn.region_id]) {538 // groupByRegion[plan.region_id] = [];539 groupByRegion[addOn.region_id] = {};540 }541 // addOn.key = addOnId;542 // groupByRegion[plan.region_id].push(plan);543 groupByRegion[addOn.region_id][addOnId] = addOn;544 });545 applicationVm.addonItemsIndex[stateCode] = groupByRegion;546 });547 // console.log(applicationVm.addonItemsIndex);548 }));549 reqs.push(memberShipFacilitiesService.itemsLoadOnce().then(function (data) {550 applicationVm.appFacilityItems = data;551 }));552 reqs.push(memberShipPlansService.getAll().then(function (data) {553 applicationVm.planItems = data;554 _.each(data, function (item, stateCode) {555 var groupByRegion = {};556 _.each(item, function (plan, planId) {557 if (!groupByRegion[plan.region_id]) {558 // groupByRegion[plan.region_id] = [];559 groupByRegion[plan.region_id] = {};560 }561 plan.key = planId;562 // groupByRegion[plan.region_id].push(plan);563 groupByRegion[plan.region_id][planId] = plan;564 });565 applicationVm.planItemsIndex[stateCode] = groupByRegion;566 });567 }));568 reqs.push(personTitleService.getPrefixs().then(function (data) {569 applicationVm.prefixList = data;570 }));571 reqs.push(personTitleService.getSuffixs().then(function (data) {572 applicationVm.suffixList = data;573 }));574 if (applicationId !== '') {575 //list update indicator576 indicatorRef = firebaseDataRef.child('membership-applications-indicator/' + applicationId);577 indicatorRef.on('value', checkIndicator);578 //listen update value application579 editRef = firebaseDataRef.child('membership-applications/' + applicationId);580 editRef.on('value', showMessageUpdateInfo);581 //call update timestamp indicator582 var intervalCallback = indicatorCallback * 60000;583 indicator = setInterval(function () {584 var currentTime = moment().valueOf();585 if (applicationId) {586 memAppIndicatorService.get(applicationId).then(function (data) {587 if (data && data.editingBy) {588 var uEdited = data.editingBy[currentUser.$id];589 if (uEdited !== undefined) {590 uEdited.timestampEdited = moment().valueOf();591 memAppIndicatorService.update(applicationId, data);592 }593 }594 });595 }596 }, intervalCallback);597 //init check Indicator598 reqs.push(checkIndicator());599 }600 $q.all(reqs).then(function () {601 _loadData().then(function () {602 _watchPlan();603 initModel = true;604 $timeout(function () {605 applicationVm.formW = $('#application_form').width() || 420;606 }, 800);607 });608 });609 }610 function _loadData() {611 if (!applicationVm.model.$id || applicationVm.model.$id === '') {612 return $q.when();613 }614 var request = memAppService.getWithLoad(applicationVm.model.$id).then(function (rs) {615 if (!rs) {616 // initModel = true;617 appUtils.hideLoading();618 return $q.when();619 }620 // default cycle & number of adults of security plan621 if (rs.regionCode == 'sec') {622 if (!rs.numberOfAdults) {623 rs.numberOfAdults = '1';624 }625 }626 var request_array = [];627 applicationVm.model = rs;628 applicationVm.errMsg = angular.copy(applicationVm.model.errorMessage || '');629 if (applicationVm.errMsg.length > 200) {630 applicationVm.errMsg = applicationVm.errMsg.substr(0, 200) + '...';631 }632 if (!applicationVm.model.saleRep) {633 applicationVm.model.saleRep = '';634 }635 if (!applicationVm.model.managers) {636 applicationVm.model.managers = [];637 }638 applicationVm.employeeId = '';639 if (applicationVm.model.representativeCode) {640 var repCodeInfo = _.find(applicationVm.employees, { repCode: applicationVm.model.representativeCode });641 if (repCodeInfo) {642 applicationVm.employeeId = repCodeInfo.$id || '';643 applicationVm.model.saleRep = repCodeInfo.firstName + ' ' + repCodeInfo.lastName;644 }645 }646 // if (!$scope.userPermission.isAccessPermission) {647 // $scope.userPermission.isAccessPermission = applicationVm.model.representativeCode === (currentUser.repCode || currentUser.username);648 // }649 // initModel = true;650 //load Membership651 _loadMembership(rs.membershipId);652 if (applicationVm.model.waivedSetupFee === undefined) {653 applicationVm.model.waivedSetupFee = false;654 }655 if (applicationVm.model.processPayment === undefined) {656 applicationVm.model.processPayment = true;657 }658 //Account Source659 _getAccountSource(applicationVm.model);660 if (!applicationVm.model.cashInput) {661 applicationVm.model.cashInput = angular.copy(applicationVm.model.cashAmount || 0);662 }663 //Files664 applicationVm.model.physicalFiles = _.filter(rs.physicalFiles, function (o) { return !o.isDeleted; });665 if (!applicationVm.model.physicalFiles || (applicationVm.model.physicalFiles && applicationVm.model.physicalFiles.length === 0)) {666 $scope.toggleImagePnl = true;667 } else {668 var fileData = _.find(rs.physicalFiles, function (file) {669 return file.isSelected === true;670 });671 applicationVm.currentFiles = fileData || null;672 }673 activeFileTab();674 //675 if (!applicationVm.model.signatureDate || $.trim(applicationVm.model.signatureDate) === '') {676 applicationVm.model.signatureDate = moment().format('MM/DD/YYYY');677 }678 totalAmountTmp = applicationVm.model.total.totalAmount;679 if (applicationVm.model.facilityId !== '') {680 var fR = memberShipFacilitiesService.get(applicationVm.model.facilityId).then(function (data) {681 var facilityTxt = data && data.address && $.trim(data.address) !== '' ? data.name + ' - ' + data.facility_promo_code + ' (' + data.address + ')' : data.name + ' - ' + data.facility_promo_code;682 applicationVm.facilityTxt = facilityTxt;683 applicationVm.facilityObj = data;684 applicationVm.facilityObj.id = data.$id || '';685 });686 request_array.push(fR);687 }688 if (!applicationVm.model.eventId) {689 applicationVm.model.eventId = '';690 }691 if (!applicationVm.model.eventName) {692 applicationVm.model.eventName = '';693 }694 applicationVm.eventTxt = applicationVm.model.eventName;695 // handle selectedRegion696 if (applicationVm.model.region) {697 var selectedRegion = _.find(applicationVm.regionGroups[applicationVm.model.state], { id: applicationVm.model.region });698 if (selectedRegion) {699 applicationVm.selectedRegionSettings = selectedRegion.settings || {};700 }701 }702 // need reverifyData on Review Screen703 // verify Data: for sure upload lastest info704 if (applicationVm.model.status == 2) {705 // core plan and add on706 if (applicationVm.model.state && applicationVm.model.selectedPlans) {707 // var planInfo = applicationVm.planItemsIndex[applicationVm.model.state] && applicationVm.planItemsIndex[applicationVm.model.state][applicationVm.model.selectedPlans.key];708 var planInfo = applicationVm.planItemsIndex[applicationVm.model.state] && applicationVm.planItemsIndex[applicationVm.model.state][applicationVm.model.region] && applicationVm.planItemsIndex[applicationVm.model.state][applicationVm.model.region][applicationVm.model.selectedPlans.key];709 // console.log('planInfo');710 // console.log(planInfo);711 if (planInfo) {712 applicationVm.model.selectedPlans = planInfo;713 } else {714 applicationVm.model.selectedPlans = null;715 applicationVm.model.selectedAddOns = null;716 }717 }718 if (applicationVm.model.selectedAddOns) {719 var stateAddOns = applicationVm.addonItemsIndex[applicationVm.model.state] && applicationVm.addonItemsIndex[applicationVm.model.state][applicationVm.model.region];720 if (stateAddOns) {721 _.each(applicationVm.model.selectedAddOns, function (sAddOn, id) {722 if (stateAddOns[id]) {723 applicationVm.model.selectedAddOns[id] = stateAddOns[id];724 } else {725 applicationVm.model.selectedAddOns[id] = null;726 }727 });728 }729 }730 // end verify data731 }732 //templay hide maker733 /*734 $scope.appMaps = applicationMaps.getFrmSettings(rs.state);735 if ($scope.appMaps) {736 $scope.markers = $scope.appMaps.markers;737 $scope.mapping = $scope.appMaps.mapping;738 }739 */740 //Payment Method741 if (!rs.paymentMethod || rs.paymentMethod === '') {742 applicationVm.model.paymentMethod = '0';743 }744 if (applicationVm.model.paymentMethod === '0') {745 var creditObj = {746 name: '',747 creditCardNumber: '',748 month: '',749 year: '',750 cvv: '',751 zipCode: ''752 };753 applicationVm.model.creditCard = angular.extend(creditObj, rs.creditCard);754 } else if (applicationVm.model.paymentMethod === '1') {755 if (!rs.cashOption || _.trim(rs.cashOption) === '') {756 applicationVm.model.cashOption = 'TakeCredit';757 }758 } else {759 var checkObj = {760 accountNumber: '',761 routingNumber: '',762 type: 'BusinessChecking',763 address: '',764 state: '',765 city: '',766 zipCode: '',767 name: '',768 fullName: ''769 };770 applicationVm.model.check = angular.extend(checkObj, rs.check);771 _initVerifyAddressPaymentCheck();772 }773 if (applicationVm.model.status.toString() === '4' || applicationVm.model.status.toString() === '8') {774 if (applicationVm.model.creditCard) {775 var cvv = applicationVm.model.creditCard.cvv;776 var cardNumber = applicationVm.model.creditCard.creditCardNumber;777 applicationVm.model.creditCard.cvv = cvv ? cvv.replace(/[^A-Z]/g, '*') : '';778 applicationVm.model.creditCard.creditCardNumber = cardNumber ? cardNumber.substring(0, cardNumber.length - 4).replace(/[^A-Z]/g, '*') + cardNumber.substring(cardNumber.length - 4, cardNumber.length) : '';779 }780 if (applicationVm.model.check) {781 var routingNumber = applicationVm.model.check.routingNumber;782 var accountNumber = applicationVm.model.check.accountNumber;783 applicationVm.model.check.routingNumber = routingNumber ? routingNumber.substring(0, routingNumber.length - 4).replace(/[^A-Z]/g, '*') + routingNumber.substring(routingNumber.length - 4, routingNumber.length) : '';784 applicationVm.model.check.accountNumber = accountNumber ? accountNumber.substring(0, accountNumber.length - 4).replace(/[^A-Z]/g, '*') + accountNumber.substring(accountNumber.length - 4, accountNumber.length) : '';785 }786 } else {787 //remove * character788 if (applicationVm.model.creditCard && applicationVm.model.creditCard.creditCardNumber !== '' &&789 applicationVm.model.creditCard.creditCardNumber.indexOf('*') != -1) {790 applicationVm.model.creditCard.creditCardNumber = '';791 }792 if (applicationVm.model.check && applicationVm.model.check.routingNumber !== '' &&793 applicationVm.model.check.routingNumber.indexOf('*') != -1) {794 applicationVm.model.check.routingNumber = '';795 }796 if (applicationVm.model.check && applicationVm.model.check.accountNumber !== '' &&797 applicationVm.model.check.accountNumber.indexOf('*') != -1) {798 applicationVm.model.check.accountNumber = '';799 }800 }801 // Init watching dirtied models Tracking history application802 var keys = getkeys(applicationVm.model);803 $timeout(function () {804 appUtils.hideLoading();805 _.forEach(keys, function (key, idx) {806 if (checkNested(applicationVm.model, key) !== undefined) {807 $scope.$watchCollection('applicationVm.model.' + key, function (newVal, oldVal) {808 if (modelsDirtied['applicationVm_model_' + key] === undefined && newVal !== oldVal) {809 modelsDirtied['applicationVm_model_' + key] = oldVal;810 modelsDirtied['applicationVm_model_new_' + key] = newVal;811 }812 });813 }814 });815 }, 2000);816 // End Init watching dirtied models817 if (request_array.length > 0) {818 return $q.all(request_array);819 }820 return $q.when();821 });822 // end request823 return request;824 }825 function _loadMembership(membershipId) {826 memberShipService.getWithLoad(membershipId).then(function (memberModel) {827 applicationVm.memberModel = memberModel;828 // Assign data for google verification address829 if (applicationVm.memberModel && applicationVm.memberModel.priMember) {830 $scope.addressVerification.place = applicationVm.memberModel.priMember.mailingAddress;831 _googleMapVerification(1);832 $scope.addressVerification.getPlace = function (addrComp) {833 var rs = {834 address: '',835 city: '',836 state: '',837 zipCode: ''838 };839 _.forEach(addrComp, function (comp) {840 if (comp.types[0] === "street_number") rs.address = comp.short_name + " ";841 if (comp.types[0] === "route") rs.address += comp.short_name;842 if (comp.types[0] === "locality") rs.city = comp.short_name;843 if (comp.types[0] === "administrative_area_level_1") rs.state = comp.short_name;844 if (comp.types[0] === "postal_code") rs.zipCode = comp.short_name;845 });846 $scope.$apply(function () {847 applicationVm.memberModel.priMember.mailingAddress = rs;848 $scope.addressInvalid = false;849 });850 };851 if (applicationVm.model.creditCard && (!applicationVm.model.creditCard.name || applicationVm.model.creditCard.name === '')) {852 // applicationVm.model.creditCard.name = applicationVm.memberModel.priMember.firstName + ' ' + applicationVm.memberModel.priMember.lastName;853 applicationVm.model.creditCard.name = (applicationVm.memberModel.priMember.firstName + ' ' + applicationVm.memberModel.priMember.lastName).trim();854 }855 }856 });857 }858 //Common Functions859 function activeFileTab(itemFile) {860 if (itemFile) {861 applicationVm.tabFileId = itemFile.id;862 applicationVm.activeFileUploadTab = false;863 } else {864 applicationVm.activeFileUploadTab = true;865 $('#application_image ul.nav-tabs li').removeClass('active');866 $('#application_image .tab-content .tab-pane').removeClass('active');867 $('#li-tab-upload-file').addClass('active');868 $('#tab_upload_file').addClass('in');869 $('#tab_upload_file').addClass('active');870 var selectedFiles = _.filter(applicationVm.model.physicalFiles, function (o) { return o.isSelected; });871 if (selectedFiles && selectedFiles.length > 0) {872 applicationVm.activeFileUploadTab = false;873 $('#li-tab-upload-file').removeClass('active');874 $('#tab_upload_file').removeClass('in');875 $('#tab_upload_file').removeClass('active');876 }877 }878 }879 function activeUploadFileTab() {880 applicationVm.activeFileUploadTab = true;881 applicationVm.tabFileId = -1;882 }883 function getMemberName(member) {884 if (member) {885 if (member.priMember) {886 return member.priMember.firstName + ' ' + member.priMember.lastName;887 } else if (member.secMember) {888 return member.secMember.firstName + ' ' + member.secMember.lastName;889 }890 }891 return ' ';892 }893 function toggleImagePnlFunc() {894 $scope.toggleImagePnl = !$scope.toggleImagePnl;895 $timeout(function () {896 applicationVm.formW = $('#application_form').width() || 420;897 }, 800);898 }899 function changeState() {900 // applicationVm.initPopup = false;901 // applicationVm.initSeclectEvent = false;902 // _watchPlan();903 // onChange State auto change Region904 }905 function changeRegion($event) {906 // console.log(applicationVm.selectedRegion);907 applicationVm.initPopup = false;908 applicationVm.initSeclectEvent = false;909 var selectedRegion = _.find(applicationVm.regionGroups[applicationVm.model.state], { id: applicationVm.model.region });910 // set region_code911 var regionCode = selectedRegion.code;912 applicationVm.model.regionCode = regionCode;913 if (selectedRegion) {914 applicationVm.selectedRegionSettings = selectedRegion.settings || {};915 }916 if (applicationVm.selectedRegionSettings) {917 if (applicationVm.selectedRegionSettings.enable_promo_code === false) {918 applicationVm.model.facilityCode = '';919 }920 if (applicationVm.selectedRegionSettings.enable_waived_setup_fee === false) {921 applicationVm.model.waivedSetupFee = false;922 }923 }924 if (regionCode !== 'leo') {925 Object.assign(applicationVm.model, {926 activeRetiredLEO: 'notLEO',927 officerCard: null,928 platinumPlus: null,929 enteredBy: null930 });931 }932 if (regionCode !== 'sec') {933 Object.assign(applicationVm.model, {934 moneyCollected: null,935 systemEntered: null,936 enteredDate: null937 });938 }939 if (regionCode !== 'nfa') {940 if (applicationVm.model.cycle == '3') {941 applicationVm.model.cycle = null;942 }943 }944 if (regionCode == 'nfa' /*|| regionCode =='sec'*/) {945 Object.assign(applicationVm.model, {946 cycle: "3",947 numberOfAdults: "1"948 });949 }950 if (regionCode == 'sec') {951 Object.assign(applicationVm.model, {952 numberOfAdults: "1"953 });954 }955 _watchPlan();956 }957 function changePaymentMethod() {958 applicationVm.model.processPayment = true;959 applicationVm.model.creditCard = {960 name: '',961 creditCardNumber: '',962 month: '',963 year: '',964 cvv: '',965 zipCode: ''966 };967 applicationVm.model.check = {968 accountNumber: '',969 routingNumber: '',970 type: 'BusinessChecking',971 address: '',972 state: '',973 city: '',974 zipCode: '',975 name: '',976 fullName: ''977 };978 applicationVm.model.cashAmount = applicationVm.model.cashInput = 0;979 if (applicationVm.model.paymentMethod === '1')980 applicationVm.model.cashOption = 'TakeCredit';981 else982 applicationVm.model.cashOption = '';983 //Assign data for google verification bank address 984 _initVerifyAddressPaymentCheck();985 }986 function getStaffName(item) {987 var keyword = item.authorName;988 if (item.authorModifier) {989 keyword = item.authorModifier;990 }991 var staff = _.find(applicationVm.employees, { email: keyword });992 if (staff) {993 return staff.email;994 }995 return 'Staff';996 }997 function getIconStatus(item) {998 if (item && item.status) {999 var statusObj = _.find(applicationVm.appStatus, { key: parseInt(item.status) });1000 if (statusObj) {1001 return itemStatusMap[statusObj.value].icon;1002 }1003 }1004 return itemStatusMap.Default.icon;1005 }1006 function getAppStatus(key) {1007 var rs = _.find(applicationVm.appStatus, { 'key': key });1008 return rs !== undefined && rs.value ? rs.value : '';1009 }1010 function getFileStatus(key, itemFile) {1011 var rs = _.find(appUtils.appFileStatus, { 'key': key });1012 return rs !== undefined && rs.value ? rs.value : '';1013 }1014 function viewMember() {1015 $rootScope.reProcessSideBar = true;1016 $state.go('membership.memberdetails', { id: applicationVm.model.membershipId });1017 }1018 function addressVerification() {1019 if (verifyTimeout) $timeout.cancel(verifyTimeout);1020 verifyTimeout = $timeout(function () {1021 _googleMapVerification(1);1022 }, 250);1023 }1024 function bankAddressVerification() {1025 if (verifyTimeout) $timeout.cancel(verifyTimeout);1026 verifyTimeout = $timeout(function () {1027 _googleMapVerification(2);1028 }, 250);1029 }1030 function cancel() {1031 window.location.reload();1032 }1033 function checkPriAddon(key) {1034 if (!applicationVm.model.selectedAddOns) return false;1035 var rs = _.find(applicationVm.model.selectedAddOns, { 'key': key.toString() });1036 return rs && rs != null;1037 }1038 //End Common Functions1039 //Files Functions1040 function loadCanvas(dataURL, index) {1041 $timeout(function () {1042 var canvas = document.getElementById('canvas-img-' + index);1043 var context = canvas.getContext('2d');1044 // load image from data url1045 var imageObj = new Image();1046 imageObj.onload = function () {1047 canvas.width = 1200;1048 canvas.height = 1600;1049 context.drawImage(imageObj, 0, 0, imageObj.width, imageObj.height, 0, 0, 1200, 1600);1050 window.URL.revokeObjectURL(dataURL);1051 };1052 imageObj.src = dataURL;1053 }, 800);1054 }1055 function downloadImg(url, index) {1056 $http.get(url, { responseType: "blob" }).then(function (res) {1057 var urlImg = window.URL.createObjectURL(res.data);1058 loadCanvas(urlImg, index);1059 }, function (error, status) {1060 console.log(error);1061 console.log(status);1062 });1063 }1064 function getAppImage(itemFile, index) {1065 if (itemFile && itemFile.processPath) {1066 var gsReference = firebase.storage().refFromURL(itemFile.processPath);1067 firebase.storage().ref().child(gsReference.fullPath).getDownloadURL().then(function (url) {1068 $timeout(function () {1069 downloadImg(url, index);1070 }, 1000);1071 }).catch(function (error) {1072 switch (error.code) {1073 case 'storage/object_not_found':1074 // File doesn't exist1075 console.log('File doesnt exist');1076 break;1077 case 'storage/unauthorized':1078 // User doesn't have permission to access the object1079 console.log('User doesnt have permission to access the object');1080 break;1081 case 'storage/canceled':1082 // User canceled the upload1083 console.log('User canceled the upload');1084 break;1085 case 'storage/unknown':1086 // Unknown error occurred, inspect the server response1087 console.log('Unknown error occurred, inspect the server response');1088 break;1089 }1090 return '';1091 });1092 } else {1093 $timeout(function () {1094 downloadImg(itemFile.path, index);1095 }, 1000);1096 }1097 }1098 function clearUploadedFiles() {1099 Dropzone.forElement("#tab_upload_file #form-dropzone").removeAllFiles(true);1100 }1101 function processFile(key, item) {1102 appUtils.showLoading();1103 if (item) {1104 var index = applicationVm.model.physicalFiles.indexOf(item);1105 if (index !== -1) {1106 var appId = applicationVm.model.$id;1107 item.status = 1;1108 applicationVm.model.physicalFiles[index] = item;1109 applicationVm.model.status = 1;1110 activeFileTab(item);1111 var updateFields = {1112 status: applicationVm.model.status,1113 physicalFiles: applicationVm.model.physicalFiles1114 };1115 //Application tracking timeline obj1116 var appTrackingObjProcesFile = {1117 eventType: appUtils.logEvent.processFileApp,1118 status: angular.copy(applicationVm.model.status)1119 };1120 //Application tracking timeline obj push OCR1121 var appTrackingObjPushORC = {1122 eventType: appUtils.logEvent.pushToOcrQueue,1123 status: angular.copy(applicationVm.model.status),1124 mediaId: item.mediaId || ''1125 };1126 return memAppService.updateProcessFile(appId, updateFields).then(function (rs) {1127 if (rs.result) {1128 toaster.success("Process success!");1129 appTrackingObjProcesFile.message = 'Start process application file.';1130 appTrackingObjPushORC.message = 'Push to OCR queue success.';1131 appUtils.hideLoading();1132 return memProcessQueueService.create(appId, key).then(function (createRs) {1133 if (!createRs.result) {1134 appTrackingObjPushORC.message = 'Push to OCR queue has error.';1135 toaster.error('Cannot create process queue!');1136 return false;1137 }1138 //listen update value application physicalFiles1139 physicalFilesRef[item.mediaId] = firebaseDataRef.child('membership-applications/' + applicationId + '/physicalFiles/' + key);1140 if (physicalFilesRef[item.mediaId]) {1141 physicalFilesRef[item.mediaId].on('value', onValuePhysicalFiles);1142 }1143 return true;1144 }).catch(function (err) {1145 appTrackingObjPushORC.message = 'Push to OCR queue has error.';1146 return false;1147 });1148 } else {1149 appTrackingObjProcesFile.message = rs && rs.errorMsg || 'Process application file has error.';1150 toaster.error(rs.errorMsg);1151 appUtils.hideLoading();1152 return false;1153 }1154 }).catch(function (err) {1155 appTrackingObjProcesFile.message = err && err.message || 'Process application file has error.';1156 return false;1157 }).then(function () {1158 //Create tracking application do process application file1159 memAppTimeLineService.create(appId, appTrackingObjProcesFile).then(function () {1160 console.log('=====create tracking push to ocr queue======');1161 //Create tracking application push to OCR1162 memAppTimeLineService.create(appId, appTrackingObjPushORC);1163 });1164 });1165 }1166 }1167 }1168 function selectFile(item) {1169 var index = applicationVm.model.physicalFiles.indexOf(item);1170 _.forEach(applicationVm.model.physicalFiles, function (fileItem, key) {1171 fileItem.isSelected = false;1172 });1173 if (index !== -1) {1174 item.isSelected = true;1175 applicationVm.model.physicalFiles[index] = item;1176 }1177 //Update data for application from fields of OCI1178 var appTrackingObj = {1179 eventType: appUtils.logEvent.editApp,1180 message: 'Select File - Updated application information.'1181 };1182 update("Select file success!", appTrackingObj).then(function () {1183 _reloadGoState();1184 });1185 }1186 function recycleFile(key, item) {1187 $ngBootbox.confirm('Are you sure want to delete version ' + (key + 1) + '?').then(function () {1188 appUtils.showLoading();1189 applicationVm.model.physicalFiles.splice(key, 1);1190 //init application tracking obj;1191 var appTrackingObjRemoveFile = {1192 eventType: appUtils.logEvent.removeFileApp,1193 status: angular.copy(applicationVm.model.status)1194 };1195 //end init1196 return memAppService.recycleFile(applicationVm.model.$id, applicationVm.model.physicalFiles).then(function (rs) {1197 appUtils.hideLoading();1198 if (rs.result) {1199 appTrackingObjRemoveFile.message = 'Remove application file success.';1200 toaster.success("Delete file success!");1201 return true;1202 //applicationVm.cancel();1203 } else {1204 appTrackingObjRemoveFile.message = rs && rs.errorMsg || 'Remove application file has error.';1205 toaster.error(rs.errorMsg);1206 return false;1207 }1208 }).catch(function (err) {1209 appTrackingObjRemoveFile.message = err && err.message || 'Remove application file has error.';1210 return false;1211 }).then(function () {1212 //create application tracking remove file1213 memAppTimeLineService.create(applicationVm.model.$id, appTrackingObjRemoveFile);1214 });1215 });1216 }1217 //End Files Functions1218 //Application Functions1219 function update(message, applicationTrackingObj) {1220 // console.log(message);1221 //Update an application1222 applicationVm.model.authorModifier = applicationVm.memberModel.authorModifier = currentUser.email;1223 var stateId = $('[name="appState"]:visible option:selected').attr('data-id');1224 applicationVm.model.stateId = !stateId ? '0' : stateId;1225 if ($.trim(applicationVm.model.representativeCode) === '') {1226 applicationVm.model.representativeCode = currentUser.username ? currentUser.username.toUpperCase() : '';1227 }1228 _setAccountSource(applicationVm.model);1229 //always get lastest promo code.1230 return memberShipFacilitiesService.get(applicationVm.model.facilityId).then(function (data) {1231 if (data && data.facility_promo_code) {1232 // applicationVm.model.facilityCode = data.facility_promo_code;1233 }1234 //1235 return _updateApplication(message, applicationTrackingObj);1236 }).catch(function () {1237 return _updateApplication(message, applicationTrackingObj);1238 });1239 }1240 function _updateApplication(message, applicationTrackingObj) {1241 var appId = applicationVm.model.$id;1242 return memAppService.update(applicationVm.model).then(function (rs) {1243 applicationTrackingObj.status = angular.copy(applicationVm.model.status);1244 if (rs.result) {1245 if (message && message !== '') {1246 toaster.success(message);1247 } else {1248 if (applicationTrackingObj && applicationTrackingObj.submitResult === 'Failed') {1249 toaster.error(applicationTrackingObj.message || 'TLS API: Submit failed');1250 }1251 }1252 var callVerify = false;1253 if (applicationVm.model.status === 4 || applicationVm.model.status === 8) {1254 applicationVm.memberModel.isActive = true;1255 //Create application-verify 1256 memAppVerifyService.create(appId);1257 callVerify = true;1258 }1259 var apps = applicationVm.memberModel.apps;1260 if (apps && apps.length > 0 && apps.indexOf(appId) === -1) {1261 apps.push(appId);1262 }1263 if (applicationVm.model.numberOfAdults == '1' && applicationVm.memberModel.secMember && applicationVm.memberModel.secMember.memberId) {1264 applicationVm.memberModel.secMember.memberId = '';1265 }1266 //Create tracking application updated1267 memAppTimeLineService.create(appId, applicationTrackingObj).then(function () {1268 if (callVerify) {1269 var appTrackingVerify = {1270 eventType: appUtils.logEvent.createMember,1271 status: applicationVm.model.status1272 };1273 //Create tracking application create member1274 memAppTimeLineService.create(appId, appTrackingVerify);1275 }1276 });1277 return memberShipService.update(applicationVm.memberModel).then(function (memRs) {1278 appUtils.hideLoading();1279 if (!memRs.result) {1280 toaster.error('Cannot save membership!');1281 }1282 $scope.itemSelected = applicationVm.model.$id;1283 });1284 } else {1285 applicationTrackingObj.message = rs && rs.errorMsg || 'Updated application information has error.';1286 //Create tracking application updated1287 memAppTimeLineService.create(appId, applicationTrackingObj);1288 appUtils.hideLoading();1289 toaster.error(rs.errorMsg);1290 }1291 });1292 }1293 function process() {1294 appUtils.showLoading();1295 _setAppPlans();1296 applicationVm.model.status = 1;1297 var appTrackingObjProcess = {1298 eventType: appUtils.logEvent.editApp,1299 message: 'Process - Updated application information.'1300 };1301 update("Process success!", appTrackingObjProcess).then(function () {1302 _reloadGoState();1303 });1304 }1305 function verify() {1306 appUtils.showLoading();1307 _setAppPlans();1308 applicationVm.model.isLocked = true;1309 applicationVm.model.isVerified = true;1310 applicationVm.model.timestampVerified = appUtils.getTimestamp();1311 applicationVm.model.status = 2;1312 var appTrackingObjVerify = {1313 eventType: appUtils.logEvent.verifyApp,1314 message: 'Verify - Updated application information.'1315 };1316 update("Verify success!", appTrackingObjVerify).then(function () {1317 memAppHisService.create(modelsDirtied);1318 _reloadGoState();1319 });1320 }1321 function justSave() {1322 _setAppPlans();1323 applicationVm.model.authorModifier = currentUser.email;1324 var stateId = $('[name="appState"]:visible option:selected').attr('data-id');1325 applicationVm.model.stateId = !stateId ? '0' : stateId;1326 //Application tracking timeline obj1327 var appTrackingObjSave = {1328 eventType: appUtils.logEvent.editApp,1329 status: angular.copy(applicationVm.model.status)1330 };1331 _setAccountSource(applicationVm.model);1332 //always get lastest promo code.1333 return memberShipFacilitiesService.get(applicationVm.model.facilityId).then(function (data) {1334 if (data && data.facility_promo_code) {1335 // applicationVm.model.facilityCode = data.facility_promo_code;1336 }1337 //1338 return memAppService.update(applicationVm.model).then(function (rs) {1339 if (rs && rs.result) {1340 appTrackingObjSave.message = 'Updated application information.';1341 toaster.success('Save Success!');1342 return memberShipService.update(applicationVm.memberModel);1343 } else {1344 appTrackingObjSave.message = rs && rs.errorMsg || 'Updated application information has error.';1345 return false;1346 }1347 }).catch(function (error) {1348 appTrackingObjSave.message = error && error.message || 'Updated application information has error.';1349 return false;1350 });1351 }).catch(function () {1352 return memAppService.update(applicationVm.model).then(function (rs) {1353 if (rs && rs.result) {1354 appTrackingObjSave.message = 'Updated application information.';1355 toaster.success('Save Success!');1356 return memberShipService.update(applicationVm.memberModel);1357 } else {1358 appTrackingObjSave.message = rs && rs.errorMsg || 'Updated application information has error.';1359 return false;1360 }1361 }).catch(function (error) {1362 appTrackingObjSave.message = error && error.message || 'Updated application information has error.';1363 return false;1364 });1365 }).then(function () {1366 var trackingId = angular.copy(applicationVm.model.$id);1367 memAppTimeLineService.create(trackingId, appTrackingObjSave);1368 });1369 }1370 function unLock() {1371 appUtils.showLoading();1372 applicationVm.model.isLocked = false;1373 applicationVm.model.isVerified = false;1374 applicationVm.model.status = 1;1375 applicationVm.model.submitting = null;1376 var appTrackingObjUnlock = {1377 eventType: appUtils.logEvent.unlockApp,1378 message: 'Unlock - Updated application information.'1379 };1380 update("Unlock success!", appTrackingObjUnlock).then(function () {1381 _reloadGoState();1382 });1383 }1384 function submit() {1385 if (applicationVm.submitting) {1386 toaster.warning('This application is submitting');1387 return;1388 } else if (applicationVm.model.submitting) {1389 toaster.warning('This application is submitted');1390 return;1391 }1392 applicationVm.submitting = true;1393 appUtils.showLoading();1394 return memAppService.lockSubmitApp(applicationVm.model.$id).then(function () {1395 var defered;1396 return memberShipFacilitiesService.get(applicationVm.model.facilityId).then(function (facilityData) {1397 if (applicationVm.model.state !== applicationVm.memberModel.priMember.mailingAddress.state || !facilityData || !facilityData.facility_id) {1398 appUtils.hideLoading();1399 var submitMsg = 'Member address is not in the same state as selected state. Are you sure you want to continue?';1400 if (facilityData.isActive === false) {1401 submitMsg = 'This Facility is inactive. Are you sure you want to continue?';1402 }1403 defered = $ngBootbox.confirm(submitMsg).then(function () {1404 return _doSubmit(facilityData);1405 }, function () {1406 applicationVm.submitting = false;1407 appUtils.hideLoading();1408 });1409 } else {1410 defered = _doSubmit(facilityData);1411 }1412 return defered;1413 });1414 }).then(function () {1415 applicationVm.submitting = false;1416 memAppService.unlockSubmitApp(applicationVm.model.$id);1417 appUtils.hideLoading();1418 _reloadGoState();1419 // $timeout(function () {1420 // $state.go('membership.editApplication', { id: applicationVm.model.$id, 'tab': tab, 'keyword': '', 'start': timestampStart, 'end': timestampEnd, 'page': 0, 'author': clients, 'region': regions, 'reportBy': reportBy , 'sortBy': sortBy});1421 // }, 800);1422 });1423 }1424 function refreshStatus() {1425 appUtils.showLoading();1426 var app = applicationVm.model;1427 var memberModel = applicationVm.memberModel;1428 // if (!memberModel || !memberModel.accountId || memberModel.accountId === '') {1429 // appUtils.hideLoading();1430 // return false;1431 // }1432 var priEmail = memberModel && memberModel.priMember && memberModel.priMember.email,1433 hasAccId = memberModel.accountId && _.trim(memberModel.accountId) !== '';1434 var data = {1435 "action": "getMembershipProfile",1436 "data_to_submit[Email]": !hasAccId ? priEmail : "",1437 "data_to_submit[Username]": "",1438 "data_to_submit[isprimary]": "1",1439 "data_to_submit[issecondary]": "",1440 "data_to_submit[signupAccountId]": !hasAccId ? "" : memberModel.accountId,1441 "data_to_submit[source]": appSettings.TLSAPISource,1442 "request": "TLS_API",1443 "token": (currentUser && currentUser.tlsApiToken) || 'T3MPC@rdFl1ght666'1444 };1445 //Application tracking timeline obj for refresh membership1446 var appTrackingObjRefresh = {1447 eventType: appUtils.logEvent.refreshApp1448 };1449 $http({1450 method: 'POST',1451 url: appSettings.TLSAPIUrl,1452 data: $.param(data),1453 headers: { 'Content-Type': 'application/x-www-form-urlencoded' },1454 logParams: {1455 name: 'Web_RefreshStatus',1456 user: currentUser.username1457 }1458 }).then(function (result) {1459 appUtils.hideLoading();1460 if (result && result.data) {1461 if (result.data.code === 401 || result.data.code === 500 || result.data.code === 400) {1462 toaster.error(result.data.message);1463 appTrackingObjRefresh.submitResult = 'Failed';1464 appTrackingObjRefresh.message = result.data.message;1465 $ngBootbox.confirm('Membership status from TLS API is failed. Do you want to update this status in SmartAdmin?').then(function () {1466 appUtils.showLoading();1467 applicationVm.model.status = appTrackingObjRefresh.status = 3;1468 applicationVm.memberModel.isActive = false;1469 update('', appTrackingObjRefresh).then(function () {1470 appUtils.hideLoading();1471 _reloadGoState();1472 });1473 }, function () {1474 appUtils.hideLoading();1475 });1476 } else if (result.data.success && result.data.AccountStatus !== '' && result.data.AccountStatus.toLowerCase() == 'approved') {1477 appTrackingObjRefresh.submitResult = 'Success';1478 applicationVm.model.status = appTrackingObjRefresh.status = 4;1479 applicationVm.memberModel.isActive = true;1480 update("This application has been approved!", appTrackingObjRefresh).then(function () {1481 _reloadGoState();1482 });1483 } else {1484 appTrackingObjRefresh.submitResult = 'Failed';1485 appTrackingObjRefresh.message = 'This application has not been approved!';1486 $ngBootbox.confirm('Membership status from TLS API is failed. Do you want to update this status in SmartAdmin?').then(function () {1487 appUtils.showLoading();1488 applicationVm.model.status = appTrackingObjRefresh.status = 3;1489 applicationVm.memberModel.isActive = false;1490 update('', appTrackingObjRefresh).then(function () {1491 appUtils.hideLoading();1492 _reloadGoState();1493 });1494 }, function () {1495 appUtils.hideLoading();1496 });1497 }1498 } else {1499 appTrackingObjRefresh.submitResult = 'Failed';1500 appTrackingObjRefresh.message = 'Request refresh application failed';1501 toaster.error('Request failed');1502 $ngBootbox.confirm('Membership status from TLS API is failed. Do you want to update this status in SmartAdmin?').then(function () {1503 appUtils.showLoading();1504 applicationVm.model.status = appTrackingObjRefresh.status = 3;1505 applicationVm.memberModel.isActive = false;1506 update('', appTrackingObjRefresh).then(function () {1507 appUtils.hideLoading();1508 _reloadGoState();1509 });1510 }, function () {1511 appUtils.hideLoading();1512 });1513 }1514 }).catch(function (err) {1515 var rMsg = 'Request refresh application has error.';1516 appTrackingObjRefresh.submitResult = 'Failed';1517 appTrackingObjRefresh.message = rMsg;1518 toaster.error(rMsg);1519 $ngBootbox.confirm('Membership status from TLS API is failed. Do you want to update this status in SmartAdmin?').then(function () {1520 appUtils.showLoading();1521 applicationVm.model.status = appTrackingObjRefresh.status = 3;1522 applicationVm.memberModel.isActive = false;1523 update('', appTrackingObjRefresh).then(function () {1524 appUtils.hideLoading();1525 _reloadGoState();1526 });1527 });1528 });1529 }1530 function checkIndicator() {1531 if (!applicationId || _.trim(applicationId) === '') {1532 $scope.indicatorMsgErr = '';1533 return;1534 }1535 var editingBy = '';1536 return memAppIndicatorService.get(applicationId).then(function (data) {1537 if (data && data.editingBy) {1538 //add more user in indicator1539 var uEdited = data.editingBy[currentUser.$id];1540 if (uEdited === undefined) {1541 data.editingBy[currentUser.$id] = {1542 email: currentUser.email || '',1543 userName: currentUser.userName || currentUser.username || '',1544 fullName: (currentUser.firstName || '') + ' ' + (currentUser.lastName || ''),1545 timestampEdited: moment().valueOf()1546 };1547 memAppIndicatorService.update(applicationId, data);1548 }1549 } else {1550 //add default user in indicator1551 data = {1552 editingBy: {}1553 };1554 data.editingBy[currentUser.$id] = {1555 email: currentUser.email || '',1556 userName: currentUser.userName || currentUser.username || '',1557 fullName: (currentUser.firstName || '') + ' ' + (currentUser.lastName || ''),1558 timestampEdited: moment().valueOf()1559 };1560 memAppIndicatorService.create(applicationId, data);1561 }1562 editingBy = _.map(data.editingBy, function (edit) {1563 return edit.fullName || edit.email || edit.userName;1564 }).join(', ');1565 $scope.indicatorMsgErr = 'This application is being edited by ' + editingBy;1566 $timeout(angular.noop, 200);1567 //$scope.$emit('indicatorsLoad', null);1568 });1569 }1570 function unCheckIndicator() {1571 if (!applicationId || _.trim(applicationId) === '') {1572 return;1573 }1574 memAppIndicatorService.get(applicationId).then(function (data) {1575 if (data && data.editingBy) {1576 var uEdited = data.editingBy[currentUser.$id];1577 if (uEdited !== undefined) {1578 delete data.editingBy[currentUser.$id];1579 var keys = Object.keys(data.editingBy);1580 if (keys.length === 0)1581 memAppIndicatorService.remove(applicationId);1582 else1583 memAppIndicatorService.update(applicationId, data);1584 }1585 }1586 });1587 }1588 //Modal Functions==============================================1589 function popupChangeStatus(item) {1590 var modalInstance = $uibModal.open({1591 templateUrl: 'app/membership/modal/change-status-app.tpl.html',1592 controller: 'ApplicationStatusCtrl as applicationSttVm',1593 scope: $scope,1594 size: 'md',1595 resolve: {1596 currentApp: function () {1597 return item;1598 }1599 },1600 backdrop: 'static'1601 });1602 }1603 function showPopupTrackingActivities() {1604 var modalInstance = $uibModal.open({1605 templateUrl: 'app/membership/modal/tracking-activities.tpl.html',1606 controller: 'TrackingActivitiesCtrl',1607 size: 'lg',1608 scope: $scope,1609 windowClass: 'tracking-activities-modal',1610 backdrop: 'static',1611 resolve: {1612 appId: function () {1613 return applicationVm.model.$id;1614 },1615 status: function () {1616 return applicationVm.model.status;1617 }1618 }1619 });1620 }1621 var isOriginalImageOpenning = false;1622 function showPopupOriginalImage(itemFile) {1623 console.log(itemFile);1624 var now = Date.now();1625 if (now - isOriginalImageOpenning < 1000) {1626 return;1627 }1628 isOriginalImageOpenning = now;1629 appUtils.showLoading();1630 var status = applicationVm.model.status,1631 imgUrl, promise;1632 if (itemFile && (parseInt(status) === 1 || parseInt(status) === 7)) {1633 promise = $q.when(itemFile.path);1634 } else if (itemFile && itemFile.processPath && parseInt(status) !== 1 && parseInt(status) !== 7) {1635 var gsReference = firebase.storage().refFromURL(itemFile.processPath);1636 promise = firebase.storage().ref().child(gsReference.fullPath).getDownloadURL().then(function (url) {1637 // imgUrl = url;1638 return url;1639 }).catch(function (error) {1640 switch (error.code) {1641 case 'storage/object_not_found':1642 // File doesn't exist1643 console.log('File doesnt exist');1644 break;1645 case 'storage/unauthorized':1646 // User doesn't have permission to access the object1647 console.log('User doesnt have permission to access the object');1648 break;1649 case 'storage/canceled':1650 // User canceled the upload1651 console.log('User canceled the upload');1652 break;1653 case 'storage/unknown':1654 // Unknown error occurred, inspect the server response1655 console.log('Unknown error occurred, inspect the server response');1656 break;1657 }1658 return '';1659 });1660 } else {1661 promise = $q.when(itemFile.path);1662 }1663 // downloadUrl1664 promise = promise.then(function (url) {1665 return $http.get(url, { responseType: "blob" }).then(function (res) {1666 var urlImg = window.URL.createObjectURL(res.data);1667 return urlImg;1668 }, function (error) {1669 console.log(error);1670 });1671 });1672 var templateP = $http.get('app/membership/modal/window-original-image.tpl.html');1673 $q.all([promise, templateP]).then(function (res) {1674 var imageUrl = res[0],1675 template = res[1].data;1676 template = template.replace('{{imageUrl}}', imageUrl);1677 var popup = window.open("", "", "width=1200, height=1600");1678 if (!popup) {1679 $ngBootbox.alert("Please allow popup on this site");1680 return;1681 }1682 popup.document.write(template);1683 }).finally(function () {1684 appUtils.hideLoading();1685 });1686 // var modalInstance = $uibModal.open({1687 // templateUrl: 'app/membership/modal/popup-original-image.tpl.html',1688 // controller: 'originalImageCtrl',1689 // size: 'lg',1690 // windowClass: 'original-image-modal',1691 // scope: $scope,1692 // backdrop: 'static',1693 // resolve: {1694 // data: function () {1695 // return itemFile;1696 // },1697 // status: function () {1698 // return applicationVm.model.status;1699 // }1700 // }1701 // });1702 }1703 function openPreviewModal(itemFile, idx) {1704 appUtils.showLoading();1705 var modal = $uibModal.open({1706 templateUrl: 'app/membership/modal/preview-app.tpl.html',1707 controller: 'PreviewAppCtrl as applicationVm',1708 scope: $scope,1709 size: 'lg',1710 resolve: {1711 currentVersion: function () { return idx + 1; },1712 itemFile: function () {1713 return itemFile;1714 }1715 },1716 backdrop: 'static',1717 windowClass: 'preview-web-app-modal'1718 });1719 modal.result.then(function () { }, function () {1720 window.location.reload();1721 });1722 }1723 function showPopupFacilityList(state) {1724 if (!state || state === '') {1725 applicationVm.initPopup = true;1726 return;1727 }1728 var modalInstance = $uibModal.open({1729 templateUrl: 'app/membership/modal/facility-list-popup.tpl.html',1730 controller: 'FacilityListCtrl',1731 size: 'lg',1732 scope: $scope,1733 backdrop: 'static',1734 windowClass: 'facility-list-modal',1735 resolve: {1736 state: function () {1737 return state;1738 },1739 facilities: function () {1740 return applicationVm.appFacilityItems;1741 },1742 facilityId: function () {1743 return applicationVm.model.facilityId;1744 }1745 }1746 });1747 }1748 function showPopupEventList(state, facilityId) {1749 if (!state || state === '' || !facilityId || facilityId === '') {1750 applicationVm.initSeclectEvent = true;1751 return;1752 }1753 var modalInstance = $uibModal.open({1754 templateUrl: './app/event/modal/event-list-popup.tpl.html',1755 controller: 'EventListPopupCtrl as eventVm',1756 size: 'lg',1757 scope: $scope,1758 backdrop: 'static',1759 windowClass: 'select-event-modal',1760 resolve: {1761 eventId: function () {1762 return angular.copy(applicationVm.model.eventId || null);1763 },1764 facilities: function () {1765 return applicationVm.appFacilityItems;1766 },1767 states: function () {1768 return applicationVm.appStatelist;1769 },1770 state: function () {1771 return angular.copy(state);1772 },1773 facilityId: function () {1774 return angular.copy(applicationVm.model.facilityId);1775 }1776 }1777 });1778 modalInstance.result.then(function (event) {1779 applicationVm.model.eventId = angular.copy(event && event.$id || '');1780 applicationVm.eventTxt = applicationVm.model.eventName = angular.copy(event && event.name || '');1781 });1782 }1783 function showPopupEmployeeList() {1784 var modalInstance = $uibModal.open({1785 templateUrl: './app/employee/modal/employee-list-popup.tpl.html',1786 controller: 'EmployeeListPopupCtrl as employeeModalVm',1787 size: 'lg',1788 scope: $scope,1789 backdrop: 'static',1790 windowClass: 'select-event-modal',1791 resolve: {1792 employeeId: function () {1793 return angular.copy(applicationVm.employeeId || '');1794 }1795 }1796 });1797 modalInstance.result.then(function (employee) {1798 applicationVm.employeeId = employee.$id || '';1799 applicationVm.model.representativeCode = employee.repCode || '';1800 applicationVm.model.saleRep = employee ? employee.firstName + ' ' + employee.lastName : '';1801 });1802 }1803 function _doSubmit(appFacility) {1804 appUtils.showLoading();1805 var paymentMethod = memAppService.getPaymentMethodTxt(applicationVm.model.paymentMethod),1806 regionId = "",1807 cardType = "",1808 bankAddress = "",1809 saleRep = "";1810 //handle process data sequencial1811 // return memRegionService.getIdByState(applicationVm.model.state).then(function (region_id) {1812 // regionId = region_id;1813 // return;1814 // })1815 regionId = applicationVm.model.region;1816 return $q.when().then(function () {1817 if (applicationVm.model.paymentMethod === '0') {1818 if (!applicationVm.model.creditCard.type) {1819 return appUtils.getCardType2(applicationVm.model.creditCard.creditCardNumber).then(function (cardTypeData) {1820 cardType = cardTypeData;1821 return;1822 });1823 } else {1824 cardType = applicationVm.model.creditCard.type;1825 return $q.when();1826 }1827 } else if (applicationVm.model.paymentMethod === '2' && !_.isEmpty(_.trim(applicationVm.model.check.address))) {1828 bankAddress = applicationVm.model.check.address;1829 if (!_.isEmpty(_.trim(applicationVm.model.check.city))) {1830 bankAddress += ', ' + applicationVm.model.check.city;1831 }1832 if (!_.isEmpty(_.trim(applicationVm.model.check.state))) {1833 bankAddress += ', ' + applicationVm.model.check.state;1834 }1835 if (!_.isEmpty(_.trim(applicationVm.model.check.zipCode))) {1836 bankAddress += ' ' + applicationVm.model.check.zipCode;1837 }1838 }1839 }).then(function () {1840 if (applicationVm.model.saleRep && _.trim(applicationVm.model.saleRep) !== '') {1841 saleRep = applicationVm.model.saleRep;1842 } else {1843 if (applicationVm.model.representativeCode) {1844 return employeeService.getUserByRepCode(applicationVm.model.representativeCode).then(function (user) {1845 saleRep = applicationVm.model.saleRep = user ? user.firstName + ' ' + user.lastName : '';1846 return;1847 });1848 }1849 }1850 // if (applicationVm.model.uid) {1851 // return employeeService.getUser(applicationVm.model.uid).then(function (user) {1852 // saleRep = user ? user.firstName + ' ' + user.lastName : '';1853 // return;1854 // });1855 // }1856 }).then(function () {1857 var selectedPriAddons = applicationVm.model.selectedAddOns;1858 var addonObj = {},1859 addonObjLog = {},1860 index = 0;1861 _.forEach(selectedPriAddons, function (addon, key) {1862 addonObj["data_to_submit[plan_addon_addon_id][" + index + "]"] = addon.addon_id;1863 addonObjLog["plan_addon_addon_id_" + index] = addon.addon_id;1864 index++;1865 });1866 // var addonIds = _.map(selectedPriAddons, function (addon, index ) {1867 // return addon.addon_id;1868 // });1869 // console.log('addonIds');1870 // console.log(addonIds);1871 var app = applicationVm.model,1872 memberModel = applicationVm.memberModel,1873 employeeId = currentUser && currentUser.externalId ? currentUser.externalId : '',1874 repCode = $.trim(applicationVm.model.representativeCode) ? applicationVm.model.representativeCode : currentUser.username.toUpperCase(), //currentUser && currentUser.repCode ? currentUser.repCode : '';1875 isDividual = applicationVm.model.numberOfAdults == '1',1876 // promoCode = appFacility && appFacility.facility_promo_code ? appFacility.facility_promo_code : '',1877 promoCode = app.facilityCode || '',1878 facilityGuid = appFacility && appFacility.facility_affiliate_guid ? appFacility.facility_affiliate_guid : '',1879 memberStateId = '';1880 //memberStateId = applicationVm.memberModel.priMember.mailingAddress.state || '';1881 var memberState = _.find(applicationVm.appStatelist, function (o) {1882 if (o && o.iso && o.iso == applicationVm.memberModel.priMember.mailingAddress.state) {1883 return true;1884 }1885 return false;1886 });1887 if (memberState && memberState !== null) {1888 memberStateId = memberState.id;1889 }1890 if (app.waivedSetupFee === undefined) {1891 app.waivedSetupFee = false;1892 }1893 // isDividual == isInvidual1894 var memberAddressPhone = memberModel.priMember && memberModel.priMember.phone && appUtils.formatPhoneNumber(memberModel.priMember.phone) || null,1895 secondaryMemberAddressPhone = memberModel.secMember && memberModel.secMember.phone && appUtils.formatPhoneNumber(memberModel.secMember.phone) || null;1896 var data = {1897 "request": "submitSignup",1898 //"data_to_submit[plan_addon_addon_id]": addonIds,1899 "data_to_submit[process_payments]": applicationVm.model.processPayment ? '1' : '0', //appSettings.TLSAPIProcessPayments,1900 "data_to_submit[account_region_id]": regionId,1901 "data_to_submit[number_of_adults]": app.numberOfAdults,1902 "data_to_submit[account_cycle_id]": app.cycle,1903 "data_to_submit[plan_type]": app.regionCode == 'sec' ? 'security' : app.regionCode,1904 // "data_to_submit[plan_provider_id]": app.selectedPlans.plan_id,1905 // "data_to_submit[plan_provider_id]": app.selectedPlans.plan_provider_id,1906 "data_to_submit[active_retired_leo]": app.regionCode !== 'leo' ? appSettings.activeRetiredLEO : app.activeRetiredLEO,1907 "data_to_submit[member_shadow_name_prefix]": memberModel && memberModel.priMember && memberModel.priMember.prefix || "",1908 "data_to_submit[member_shadow_name_suffix]": memberModel && memberModel.priMember && memberModel.priMember.suffix || "",1909 "data_to_submit[member_shadow_firstname]": !memberModel.priMember || !memberModel.priMember.firstName || memberModel.priMember === null ? "" : memberModel.priMember.firstName,1910 "data_to_submit[member_shadow_lastname]": !memberModel.priMember || !memberModel.priMember.lastName || memberModel.priMember === null ? "" : memberModel.priMember.lastName,1911 "data_to_submit[member_shadow_email]": !memberModel.priMember || !memberModel.priMember.email || memberModel.priMember === null ? "" : memberModel.priMember.email,1912 // "data_to_submit[member_address_phone_type]": "mobile",1913 // "data_to_submit[member_address_phone]": !memberModel.priMember || !memberModel.priMember.phone || memberModel.priMember === null ? "" : memberModel.priMember.phone,1914 // "data_to_submit[member_address_phone]": memberAddressPhone,1915 "data_to_submit[member_address_phone_mobile]": memberAddressPhone,1916 "data_to_submit[member_address_phone_home]": "",1917 "data_to_submit[member_address_phone_work]": "",1918 "data_to_submit[member_address_street_1]": !memberModel.priMember || !memberModel.priMember.mailingAddress || !memberModel.priMember.mailingAddress.address || memberModel.priMember === null ? "" : memberModel.priMember.mailingAddress.address,1919 "data_to_submit[member_address_street_2]": "",1920 "data_to_submit[member_address_country_id]": 223,1921 "data_to_submit[member_address_city_name]": !memberModel.priMember || !memberModel.priMember.mailingAddress || !memberModel.priMember.mailingAddress.city || memberModel.priMember === null ? "" : memberModel.priMember.mailingAddress.city,1922 "data_to_submit[member_address_state_id]": memberStateId || '',1923 "data_to_submit[member_address_postcode]": !memberModel.priMember || !memberModel.priMember.mailingAddress || !memberModel.priMember.mailingAddress.zipCode || memberModel.priMember === null ? "" : memberModel.priMember.mailingAddress.zipCode,1924 "data_to_submit[secondary_member_shadow_name_prefix]": !isDividual && memberModel && memberModel.secMember && memberModel.secMember.prefix || "",1925 "data_to_submit[secondary_member_shadow_name_suffix]": !isDividual && memberModel && memberModel.secMember && memberModel.secMember.suffix || "",1926 "data_to_submit[secondary_member_shadow_firstname]": isDividual || !memberModel.secMember || !memberModel.secMember.firstName || memberModel.secMember === null ? "" : memberModel.secMember.firstName,1927 "data_to_submit[secondary_member_shadow_lastname]": isDividual || !memberModel.secMember || !memberModel.secMember.lastName || memberModel.secMember === null ? "" : memberModel.secMember.lastName,1928 "data_to_submit[secondary_member_shadow_email]": isDividual || !memberModel.secMember || !memberModel.secMember.email || memberModel.secMember === null ? "" : memberModel.secMember.email,1929 "data_to_submit[secondary_member_address_phone_mobile]": secondaryMemberAddressPhone,1930 "data_to_submit[secondary_member_address_phone_home]": "",1931 "data_to_submit[secondary_member_address_phone_work]": "",1932 "data_to_submit[promo_code]": promoCode || '',1933 "data_to_submit[account_order_domain]": "https://www.texaslawshield.com",1934 "data_to_submit[facility_affiliate_guid]": facilityGuid,1935 "data_to_submit[account_affiliate_campaign]": "",1936 "data_to_submit[account_affiliate_banner_id]": "",1937 "data_to_submit[link]": "",1938 "data_to_submit[refid]": "",1939 "data_to_submit[payment_select_ccOrcheck]": paymentMethod,1940 "data_to_submit[employee_id]": employeeId,1941 "data_to_submit[primary_member_number]": !memberModel.priMember || memberModel.priMember === null || !memberModel.priMember.memberId ? "" : memberModel.priMember.memberId,1942 "data_to_submit[secondary_member_number]": isDividual || !memberModel.secMember || memberModel.secMember === null || !memberModel.secMember.memberId ? "" : memberModel.secMember.memberId,1943 "data_to_submit[source]": appSettings.TLSAPISourceForWeb,1944 "data_to_submit[test_mode]": appSettings.TLSAPITestMode ? "On" : "Off",1945 "data_to_submit[rep_code]": repCode,1946 "data_to_submit[sales_rep]": saleRep,1947 "data_to_submit[apply_setup_fee]": app.waivedSetupFee ? '0' : '1',1948 "data_to_submit[force_billing_required]": applicationVm.model.paymentOverwrite ? '1' : '0',1949 "data_to_submit[signature_date]": applicationVm.model.signatureDate,1950 "token": (currentUser && currentUser.tlsApiToken) || 'T3MPC@rdFl1ght666',1951 "data_to_submit[account_profile_department]": app.regionCode == 'leo' && app.agencyName || '',1952 "data_to_submit[account_source]": app.regionCode !== 'sec' && applicationVm.accountSource || ''1953 };1954 if (paymentMethod === 'Cash') {1955 applicationVm.model.cashAmount = applicationVm.model.cashOption === 'TakeCredit' ? applicationVm.model.cashInput || 0 : applicationVm.model.total.totalAmount || 0;1956 var cashAmount = angular.copy(applicationVm.model.cashAmount);1957 var dataCash = {1958 "data_to_submit[zuora_cc_name]": "",1959 "data_to_submit[zuora_cc_billing_address]": !memberModel.priMember || !memberModel.priMember.mailingAddress || !memberModel.priMember.mailingAddress.address || memberModel.priMember === null ? "" : memberModel.priMember.mailingAddress.address,1960 "data_to_submit[zuora_cc_billing_city]": !memberModel.priMember || !memberModel.priMember.mailingAddress || !memberModel.priMember.mailingAddress.city || memberModel.priMember === null ? "" : memberModel.priMember.mailingAddress.city,1961 "data_to_submit[zuora_cc_billing_state]": memberStateId || '',1962 "data_to_submit[zuora_cc_billing_zip]": !memberModel.priMember || !memberModel.priMember.mailingAddress || !memberModel.priMember.mailingAddress.zipCode || memberModel.priMember === null ? "" : memberModel.priMember.mailingAddress.zipCode,1963 "data_to_submit[zuora_cc_card_number]": "",1964 "data_to_submit[zuora_cc_type]": "",1965 "data_to_submit[zuora_cc_exp_month]": "",1966 "data_to_submit[zuora_cc_exp_year]": "",1967 "data_to_submit[zuora_cc_cvv]": "",1968 "data_to_submit[payment_bank_routing_num]": "",1969 "data_to_submit[payment_bank_account_num]": "",1970 "data_to_submit[payment_bank_address]": "",1971 "data_to_submit[payment_bank_name]": "",1972 "data_to_submit[payment_bank_type]": "",1973 "data_to_submit[payment_bank_full_name]": "",1974 "data_to_submit[cash_amount]": cashAmount1975 };1976 angular.extend(data, dataCash);1977 } else if (paymentMethod === "Credit") {1978 var dataCard = {1979 "data_to_submit[zuora_cc_name]": "",1980 "data_to_submit[zuora_cc_billing_address]": "",1981 "data_to_submit[zuora_cc_billing_city]": "",1982 "data_to_submit[zuora_cc_billing_state]": "",1983 "data_to_submit[zuora_cc_billing_zip]": "",1984 "data_to_submit[zuora_cc_card_number]": "",1985 "data_to_submit[zuora_cc_type]": "",1986 "data_to_submit[zuora_cc_exp_month]": "",1987 "data_to_submit[zuora_cc_exp_year]": "",1988 "data_to_submit[zuora_cc_cvv]": "",1989 "data_to_submit[payment_bank_routing_num]": "",1990 "data_to_submit[payment_bank_account_num]": "",1991 "data_to_submit[payment_bank_address]": "",1992 "data_to_submit[payment_bank_name]": "",1993 "data_to_submit[payment_bank_type]": "",1994 "data_to_submit[payment_bank_full_name]": "",1995 };1996 // var dataCard = {1997 // "data_to_submit[zuora_cc_name]": (app.creditCard.name && app.creditCard.name !== '') ? app.creditCard.name : (memberModel.priMember === null ? "" : memberModel.priMember.firstName) + " " + (memberModel.priMember === null ? "" : memberModel.priMember.lastName),1998 // "data_to_submit[zuora_cc_billing_address]": !memberModel.priMember || !memberModel.priMember.mailingAddress || !memberModel.priMember.mailingAddress.address || memberModel.priMember === null ? "" : memberModel.priMember.mailingAddress.address,1999 // "data_to_submit[zuora_cc_billing_city]": !memberModel.priMember || !memberModel.priMember.mailingAddress || !memberModel.priMember.mailingAddress.city || memberModel.priMember === null ? "" : memberModel.priMember.mailingAddress.city,2000 // "data_to_submit[zuora_cc_billing_state]": memberStateId || '',2001 // "data_to_submit[zuora_cc_billing_zip]": !memberModel.priMember || !memberModel.priMember.mailingAddress || !memberModel.priMember.mailingAddress.zipCode || memberModel.priMember === null ? "" : memberModel.priMember.mailingAddress.zipCode,2002 // "data_to_submit[zuora_cc_card_number]": !app.creditCard || !app.creditCard.creditCardNumber || app.creditCard === null ? "" : app.creditCard.creditCardNumber,2003 // "data_to_submit[zuora_cc_type]": cardType,2004 // "data_to_submit[zuora_cc_exp_month]": !app.creditCard || !app.creditCard.month || app.creditCard === null ? "" : app.creditCard.month,2005 // "data_to_submit[zuora_cc_exp_year]": !app.creditCard || !app.creditCard.year || app.creditCard === null ? "" : app.creditCard.year,2006 // "data_to_submit[zuora_cc_cvv]": !app.creditCard || !app.creditCard.cvv || app.creditCard === null ? "" : app.creditCard.cvv,2007 // "data_to_submit[payment_bank_routing_num]": "",2008 // "data_to_submit[payment_bank_account_num]": "",2009 // "data_to_submit[payment_bank_address]": "",2010 // "data_to_submit[payment_bank_name]": "",2011 // "data_to_submit[payment_bank_type]": "",2012 // "data_to_submit[payment_bank_full_name]": "",2013 // };2014 if (applicationVm.model.processPayment) {2015 angular.extend(dataCard, {2016 "data_to_submit[zuora_cc_name]": (app.creditCard.name && app.creditCard.name !== '') ? app.creditCard.name : (memberModel.priMember === null ? "" : memberModel.priMember.firstName) + " " + (memberModel.priMember === null ? "" : memberModel.priMember.lastName),2017 "data_to_submit[zuora_cc_billing_address]": !memberModel.priMember || !memberModel.priMember.mailingAddress || !memberModel.priMember.mailingAddress.address || memberModel.priMember === null ? "" : memberModel.priMember.mailingAddress.address,2018 "data_to_submit[zuora_cc_billing_city]": !memberModel.priMember || !memberModel.priMember.mailingAddress || !memberModel.priMember.mailingAddress.city || memberModel.priMember === null ? "" : memberModel.priMember.mailingAddress.city,2019 "data_to_submit[zuora_cc_billing_state]": memberStateId || '',2020 "data_to_submit[zuora_cc_billing_zip]": !memberModel.priMember || !memberModel.priMember.mailingAddress || !memberModel.priMember.mailingAddress.zipCode || memberModel.priMember === null ? "" : memberModel.priMember.mailingAddress.zipCode,2021 "data_to_submit[zuora_cc_card_number]": !app.creditCard || !app.creditCard.creditCardNumber || app.creditCard === null ? "" : app.creditCard.creditCardNumber,2022 "data_to_submit[zuora_cc_type]": cardType,2023 "data_to_submit[zuora_cc_exp_month]": !app.creditCard || !app.creditCard.month || app.creditCard === null ? "" : app.creditCard.month,2024 "data_to_submit[zuora_cc_exp_year]": !app.creditCard || !app.creditCard.year || app.creditCard === null ? "" : app.creditCard.year,2025 "data_to_submit[zuora_cc_cvv]": '' //ChangeRequest #21 !app.creditCard || !app.creditCard.cvv || app.creditCard === null ? "" : app.creditCard.cvv,2026 });2027 }2028 angular.extend(data, dataCard);2029 } else {2030 var dataCheck = {2031 "data_to_submit[zuora_cc_name]": "",2032 "data_to_submit[zuora_cc_billing_address]": "",2033 "data_to_submit[zuora_cc_billing_city]": "",2034 "data_to_submit[zuora_cc_billing_state]": "",2035 "data_to_submit[zuora_cc_billing_zip]": "",2036 "data_to_submit[zuora_cc_card_number]": "",2037 "data_to_submit[zuora_cc_type]": "",2038 "data_to_submit[zuora_cc_exp_month]": "",2039 "data_to_submit[zuora_cc_exp_year]": "",2040 "data_to_submit[zuora_cc_cvv]": "",2041 "data_to_submit[payment_bank_routing_num]": "",2042 "data_to_submit[payment_bank_account_num]": "",2043 "data_to_submit[payment_bank_address]": "",2044 "data_to_submit[payment_bank_name]": "",2045 "data_to_submit[payment_bank_type]": "",2046 "data_to_submit[payment_bank_full_name]": "",2047 };2048 // var dataCheck = {2049 // "data_to_submit[zuora_cc_name]": !memberModel.priMember || !memberModel.priMember.firstName || !memberModel.priMember.lastName || memberModel.priMember === null ? "" : memberModel.priMember.firstName + " " + memberModel.priMember.lastName,2050 // "data_to_submit[zuora_cc_billing_address]": !memberModel.priMember || !memberModel.priMember.mailingAddress || !memberModel.priMember.mailingAddress.address || memberModel.priMember === null ? "" : memberModel.priMember.mailingAddress.address,2051 // "data_to_submit[zuora_cc_billing_city]": !memberModel.priMember || !memberModel.priMember.mailingAddress || !memberModel.priMember.mailingAddress.city || memberModel.priMember === null ? "" : memberModel.priMember.mailingAddress.city,2052 // "data_to_submit[zuora_cc_billing_state]": memberStateId || '',2053 // "data_to_submit[zuora_cc_billing_zip]": !memberModel.priMember || !memberModel.priMember.mailingAddress || !memberModel.priMember.mailingAddress.zipCode || memberModel.priMember === null ? "" : memberModel.priMember.mailingAddress.zipCode,2054 // "data_to_submit[zuora_cc_card_number]": "",2055 // "data_to_submit[zuora_cc_type]": "",2056 // "data_to_submit[zuora_cc_exp_month]": "",2057 // "data_to_submit[zuora_cc_exp_year]": "",2058 // "data_to_submit[zuora_cc_cvv]": "",2059 // "data_to_submit[payment_bank_routing_num]": !app.check || !app.check.routingNumber || app.check === null ? "" : app.check.routingNumber,2060 // "data_to_submit[payment_bank_account_num]": !app.check || !app.check.accountNumber || app.check === null ? "" : app.check.accountNumber,2061 // "data_to_submit[payment_bank_address]": bankAddress,2062 // "data_to_submit[payment_bank_name]": !app.check || !app.check.name || app.check === null ? "" : app.check.name,2063 // "data_to_submit[payment_bank_type]": !app.check || !app.check.type || app.check === null ? "" : app.check.type,2064 // "data_to_submit[payment_bank_full_name]": !app.check || !app.check.fullName || app.check === null ? "" : app.check.fullName2065 // };2066 if (applicationVm.model.processPayment) {2067 angular.extend(dataCheck, {2068 "data_to_submit[zuora_cc_name]": !memberModel.priMember || !memberModel.priMember.firstName || !memberModel.priMember.lastName || memberModel.priMember === null ? "" : memberModel.priMember.firstName + " " + memberModel.priMember.lastName,2069 "data_to_submit[zuora_cc_billing_address]": !memberModel.priMember || !memberModel.priMember.mailingAddress || !memberModel.priMember.mailingAddress.address || memberModel.priMember === null ? "" : memberModel.priMember.mailingAddress.address,2070 "data_to_submit[zuora_cc_billing_city]": !memberModel.priMember || !memberModel.priMember.mailingAddress || !memberModel.priMember.mailingAddress.city || memberModel.priMember === null ? "" : memberModel.priMember.mailingAddress.city,2071 "data_to_submit[zuora_cc_billing_state]": memberStateId || '',2072 "data_to_submit[zuora_cc_billing_zip]": !memberModel.priMember || !memberModel.priMember.mailingAddress || !memberModel.priMember.mailingAddress.zipCode || memberModel.priMember === null ? "" : memberModel.priMember.mailingAddress.zipCode,2073 "data_to_submit[payment_bank_routing_num]": !app.check || !app.check.routingNumber || app.check === null ? "" : app.check.routingNumber,2074 "data_to_submit[payment_bank_account_num]": !app.check || !app.check.accountNumber || app.check === null ? "" : app.check.accountNumber,2075 "data_to_submit[payment_bank_address]": bankAddress,2076 "data_to_submit[payment_bank_name]": !app.check || !app.check.name || app.check === null ? "" : app.check.name,2077 "data_to_submit[payment_bank_type]": !app.check || !app.check.type || app.check === null ? "" : app.check.type,2078 "data_to_submit[payment_bank_full_name]": !app.check || !app.check.fullName || app.check === null ? "" : app.check.fullName2079 });2080 }2081 angular.extend(data, dataCheck);2082 }2083 var target = _.extend(addonObj, data);2084 applicationVm.model.errorMessage = '';2085 //Application tracking timeline obj for submit2086 var appTrackingObjSubmit = {2087 eventType: appUtils.logEvent.submitApp,2088 };2089 var appId = angular.copy(applicationVm.model.$id),2090 eventLogPath = '';2091 //TLS DoSubmit Call2092 var tlsCall = $http({2093 method: 'POST',2094 url: appSettings.TLSAPIUrl,2095 data: $.param(target),2096 headers: { 'Content-Type': 'application/x-www-form-urlencoded' },2097 logParams: {2098 name: 'Web_Edit_DoSubmitTLSParams',2099 user: currentUser.username,2100 appId: appId2101 }2102 }).then(function (result) {2103 var submitR = [];2104 if (result.data && result.data.signupAccountId) {2105 applicationVm.memberModel.accountId = result.data.signupAccountId;2106 }2107 if (appSettings.TLSAPITestMode || (result && result.data && result.data.success)) {2108 appTrackingObjSubmit.submitResult = 'Success';2109 applicationVm.model.status = 4; //32110 var submitMsg = "Submit success!";2111 // applicationVm.model.status = 8;2112 if (result.data.payment_success === false || applicationVm.model.processPayment === false) {2113 // if(result.data.payment_status = "Billing Required"){2114 applicationVm.model.status = 8; // billing required2115 appTrackingObjSubmit.message = submitMsg = "Submitted success, but canât do billing now.";2116 // }2117 }2118 if (applicationVm.model.creditCard) {2119 var cvv = applicationVm.model.creditCard.cvv;2120 var cardNumber = applicationVm.model.creditCard.creditCardNumber;2121 applicationVm.model.creditCard.cvv = cvv.replace(/[^A-Z]/g, '*');2122 applicationVm.model.creditCard.creditCardNumber = cardNumber.substring(0, cardNumber.length - 4).replace(/[^A-Z]/g, '*') + cardNumber.substring(cardNumber.length - 4, cardNumber.length);2123 if (cardType) {2124 applicationVm.model.creditCard.type = cardType;2125 }2126 }2127 if (applicationVm.model.check) {2128 var routingNumber = applicationVm.model.check.routingNumber;2129 var accountNumber = applicationVm.model.check.accountNumber;2130 applicationVm.model.check.routingNumber = routingNumber.substring(0, routingNumber.length - 4).replace(/[^A-Z]/g, '*') + routingNumber.substring(routingNumber.length - 4, routingNumber.length);2131 applicationVm.model.check.accountNumber = accountNumber.substring(0, accountNumber.length - 4).replace(/[^A-Z]/g, '*') + accountNumber.substring(accountNumber.length - 4, accountNumber.length);2132 }2133 submitR.push(update(submitMsg, appTrackingObjSubmit));2134 } else {2135 var msg = 'Submit failed!';2136 if (result && result.data && result.data.message !== '') {2137 msg = applicationVm.model.errorMessage = 'TLS API: ' + result.data.message;2138 // if (msg.indexOf('INVALID_VALUE') != -1) {2139 // msg = 'Submit failed! Please verify this application info.';2140 // } else2141 // if (msg.indexOf('Invalid Account Number') != -1) {2142 // msg = 'Submit failed! Invalid account number.';2143 // } else2144 // if (msg.indexOf('Account Number Does Not Match Payment') != -1) {2145 // msg = 'Submit failed! Account number does not match payment.';2146 // }2147 }2148 applicationVm.model.status = 3;2149 applicationVm.model.isLocked = true;2150 //2151 appTrackingObjSubmit.submitResult = 'Failed';2152 appTrackingObjSubmit.message = msg;2153 submitR.push(update('', appTrackingObjSubmit));2154 }2155 return $q.all(submitR);2156 }).catch(function (err) {2157 console.log('do submit err');2158 console.log(err);2159 var submitR = [];2160 appTrackingObjSubmit.submitResult = 'Failed';2161 var msg = 'Submit failed!';2162 msg = applicationVm.model.errorMessage = appTrackingObjSubmit.message = 'TLS API: ' + msg;2163 applicationVm.model.status = 3;2164 applicationVm.model.isLocked = true;2165 submitR.push(update('', appTrackingObjSubmit));2166 return $q.all(submitR);2167 });2168 return tlsCall;2169 // });2170 });2171 }2172 function _initAddonCheckboxes() {2173 //Set app plans for the members 2174 var appForm = $('#edit-web-app');2175 var priPlans = appForm.find('.pri-app-plans input[type="checkbox"]:visible');2176 _.forEach(priPlans, function (element, key) {2177 var me = $(element);2178 me.change(function () {2179 // countWatch = 5;2180 _calculateTotal();2181 });2182 });2183 }2184 function _calculateTotal() {2185 var planItem = applicationVm.model.selectedPlans;2186 if (planItem) {2187 var priPlan = appUtils.formatNumber(planItem.recurring_price),2188 setupFee = appUtils.formatNumber(planItem.setup_price),2189 discount = 0;2190 //Set app plans for the members 2191 var appForm = $('#edit-web-app');2192 var priPlans = appForm.find('.pri-app-plans input[type="checkbox"]:visible');2193 var priAddons = 0;2194 //var secAddons = 0;2195 _.forEach(priPlans, function (element, key) {2196 var me = $(element);2197 if (me.is(':checked')) {2198 var addon = _.find(applicationVm.stateAddons, function (o) {2199 return o.key == me.val();2200 });2201 if (addon) {2202 priAddons += appUtils.formatNumber(addon.recurring_price);2203 }2204 }2205 });2206 var priTotal = (priPlan + priAddons);2207 var total = priTotal;2208 if (!applicationVm.model.waivedSetupFee) {2209 total = priTotal + setupFee;2210 }2211 applicationVm.model.total.subTotalAmount = appUtils.formatCurrency(priTotal);2212 applicationVm.model.total.setupFee = appUtils.formatCurrency(setupFee);2213 countWatch++;2214 // if (countWatch == 2 || countWatch == 4) {2215 // applicationVm.model.total.totalAmount = appUtils.formatCurrency(totalAmountTmp);2216 // } else {2217 // applicationVm.model.total.totalAmount = appUtils.formatCurrency(total);2218 // }2219 applicationVm.model.total.totalAmount = appUtils.formatCurrency(total);2220 $timeout(function () {2221 $scope.$apply();2222 }, 500);2223 // console.log('countWatch------------');2224 // console.log(countWatch);2225 }2226 }2227 function _selectPriPlan(key, planItem) {2228 if (key !== undefined && key !== null) {2229 if (planItem === undefined) {2230 planItem = applicationVm.statePlans[key];2231 }2232 if (!applicationVm.model.selectedPlans) {2233 applicationVm.model.selectedPlans = {};2234 }2235 planItem.key = key;2236 applicationVm.model.selectedPlans = _.clone(planItem);2237 applicationVm.planSetupPrice = appUtils.formatNumber(planItem.setup_price);2238 _loadAppAddons(key, planItem);2239 // auto check active/retiring for leo2240 if (applicationVm.model.regionCode == 'leo') {2241 applicationVm.model.activeRetiredLEO = planItem.sku.indexOf('retired') > -1 ? 'retired' : 'active';2242 }2243 }2244 }2245 function _watchPlan() {2246 applicationVm.secPlanKey = '';2247 applicationVm.stateAddons = [];2248 if (!applicationVm.model.total) {2249 applicationVm.model.total = {};2250 }2251 applicationVm.model.total.subTotalAmount = 0;2252 applicationVm.model.total.totalAmount = 0;2253 var state = applicationVm.model.state,2254 region = applicationVm.model.region;2255 // var statePlans = _.find(applicationVm.planItems, function (o) {2256 // return o.$id.toString() == state;2257 // });2258 var statePlans = state && region && applicationVm.planItemsIndex[state] && applicationVm.planItemsIndex[state][region] || [];2259 applicationVm.statePlans = statePlans;2260 if (applicationVm.model.total) {2261 applicationVm.model.total.startUpFee = '19.95';2262 }2263 if (applicationVm.memberModel) {2264 if (applicationVm.memberModel.priMember && (!applicationVm.memberModel.priMember.memberId || applicationVm.memberModel.priMember.memberId === '')) {2265 applicationVm.memberModel.priMember.memberId = state;2266 }2267 if (applicationVm.model.numberOfAdults == '2' && applicationVm.memberModel.secMember && (!applicationVm.memberModel.secMember.memberId || applicationVm.memberModel.secMember.memberId === '')) {2268 applicationVm.memberModel.secMember.memberId = state;2269 }2270 }2271 var numberOfAdult = _.find(applicationVm.appNumAdultsList, function (o) {2272 return o.key == applicationVm.model.numberOfAdults;2273 });2274 /* jshint ignore:start */2275 // var appPlan = _.find(statePlans, function (o, key) {2276 // if (o !== null && !angular.isUndefined(o["cycle_id"]) && o["cycle_id"] == applicationVm.model.cycle && numberOfAdult && ((o["name"] !== '' && o["name"].toLowerCase().indexOf(numberOfAdult.value.toLowerCase()) != -1) || (o["sku"] !== '' && o["sku"].indexOf(numberOfAdult.value.toLowerCase()) != -1))) {2277 // o.key = key;2278 // return true;2279 // } else {2280 // return false;2281 // }2282 // });2283 /* jshint ignore:end */2284 var appPlans = {};2285 // console.log('sala--------');2286 // console.log(applicationVm.model.cycle);2287 // console.log(statePlans);2288 _.each(statePlans, function (o, key) {2289 var valid = true;2290 valid = applicationVm.model.cycle && o.cycle_id == applicationVm.model.cycle;2291 if (applicationVm.model.regionCode !== 'nfa' && applicationVm.model.regionCode !== 'sec') {2292 if (!numberOfAdult) {2293 valid = false;2294 } else {2295 var sku = o.sku && o.sku.toLowerCase() || '',2296 name = o.name && o.name.toLowerCase() || '';2297 if (numberOfAdult.value == 'Individual') {2298 valid = valid && sku.indexOf('couple') < 0;2299 }2300 if (numberOfAdult.value == 'Couple') {2301 valid = valid && sku.indexOf('couple') > -1;2302 }2303 }2304 }2305 if (valid) {2306 appPlans[key] = o;2307 }2308 });2309 applicationVm.statePlans = appPlans;2310 var appPlan = null,2311 appPlanKeys = Object.keys(appPlans);2312 if (appPlanKeys.length == 1) {2313 appPlan = appPlans[appPlanKeys[0]];2314 applicationVm.isEnableSelectPlan = false;2315 // _selectPriPlan(appPlan.key, appPlan);2316 } else {2317 applicationVm.isEnableSelectPlan = true;2318 appPlan = applicationVm.model.selectedPlans && appPlans[applicationVm.model.selectedPlans.key] || null;2319 }2320 if (appPlan) {2321 _selectPriPlan(appPlan.key, appPlan);2322 }2323 // var appPlan;2324 // 2325 // if (!angular.isUndefined(appPlan)) {2326 // _selectPriPlan(appPlan.key, appPlan);2327 // }2328 }2329 function _loadAppAddons(key, planItem) {2330 var state = applicationVm.model.state,2331 region = applicationVm.model.region,2332 regionCode = applicationVm.model.regionCode,2333 numberOfAdults = applicationVm.model.numberOfAdults,2334 planNum = applicationVm.model.cycle;2335 // console.log(applicationVm.addonItemsIndex);2336 var stateAddons = state && region && applicationVm.addonItemsIndex[state][region];2337 var addonArr = _.filter(stateAddons, function (o, key) {2338 // if(regionCode == 'sec'){2339 // return false;2340 // }2341 var valid = o.cycle_id == planNum;2342 if (!valid) {2343 return valid;2344 }2345 if (numberOfAdults == "1") {2346 var rate_name = o.rate_name && o.rate_name.toLowerCase() || '',2347 sku = o.sku && o.sku.toLowerCase() || '';2348 valid = valid && rate_name.indexOf('spouse') === -1 && rate_name.indexOf('partner') === -1 && sku.indexOf('spouse') === -1 && sku.indexOf('partner') == -1;2349 }2350 if (valid) {2351 o.key = key;2352 }2353 return valid;2354 });2355 // console.log('planNum', planNum);2356 // console.log('stateAddOns');2357 // console.log(stateAddons);2358 // console.log('addonArr');2359 // console.log(addonArr);2360 applicationVm.stateAddons = addonArr;2361 applicationVm.model.total.setupFee = appUtils.formatNumber(planItem.setup_price);2362 if (planItem.name.toLowerCase().indexOf('couple') != -1) {2363 applicationVm.secPlanKey = key;2364 } else {2365 applicationVm.secPlanKey = '';2366 }2367 $timeout(function () {2368 _calculateTotal(); //Calculate total amount2369 _initAddonCheckboxes(); //Init addon checboxes2370 }, 1000);2371 // var stateAddons = _.find(applicationVm.addonItems, function (o) {2372 // return o.$id == applicationVm.model.state;2373 // });2374 // var planNum = parseInt(applicationVm.model.cycle);2375 // var arrAddons = [];2376 // _.forEach(stateAddons, function (o, key) {2377 // if (o !== null && o.cycle_id !== null && o.cycle_id == planNum) {2378 // o.key = key;2379 // if (applicationVm.model.numberOfAdults == '1') {2380 // if ((o.rate_name && o.rate_name !== '' && (o.rate_name.toLowerCase().indexOf('spouse') != -1) || o.rate_name.toLowerCase().indexOf('partner') != -1) || (o.sku && o.sku !== '' && (o.sku.toLowerCase().indexOf('spouse') != -1) || o.sku.toLowerCase().indexOf('partner') != -1)) {2381 // } else {2382 // arrAddons.push(o);2383 // }2384 // } else {2385 // arrAddons.push(o);2386 // }2387 // }2388 // });2389 // applicationVm.stateAddons = arrAddons;2390 // applicationVm.model.total.setupFee = appUtils.formatNumber(planItem.setup_price);2391 // if (planItem.name.toLowerCase().indexOf('couple') != -1) {2392 // applicationVm.secPlanKey = key;2393 // } else {2394 // applicationVm.secPlanKey = '';2395 // }2396 // $timeout(function () {2397 // _calculateTotal(); //Calculate total amount2398 // _initAddonCheckboxes(); //Init addon checboxes2399 // }, 1000);2400 }2401 function _setAppPlans() {2402 applicationVm.model.selectedAddOns = {};2403 var priPlans = $('#edit-web-app .pri-app-plans input[type="checkbox"]:visible');2404 _.forEach(priPlans, function (element, key) {2405 var me = $(element);2406 if (me.is(':checked')) {2407 var addon = _.find(applicationVm.stateAddons, function (o) {2408 return o.key == me.val();2409 });2410 if (addon) {2411 applicationVm.model.selectedAddOns[addon.key + ''] = addon;2412 }2413 }2414 });2415 }2416 // Turn off highlight onto image document2417 function _clearSelected() {2418 for (var key in $scope.mapping) {2419 if ($scope.mapping[key]) {2420 $scope.mapping[key].selected = false;2421 }2422 }2423 }2424 function _googleMapVerification(type) {2425 var city = '';2426 var state = '';2427 var zipCode = '';2428 if (type === 1 && applicationVm.memberModel.priMember.mailingAddress) {2429 address = applicationVm.memberModel.priMember.mailingAddress.address;2430 city = applicationVm.memberModel.priMember.mailingAddress.city;2431 state = applicationVm.memberModel.priMember.mailingAddress.state;2432 zipCode = applicationVm.memberModel.priMember.mailingAddress.zipCode;2433 } else {2434 address = applicationVm.model.check.address;2435 city = applicationVm.model.check.city;2436 state = applicationVm.model.check.state;2437 zipCode = applicationVm.model.check.zipCode;2438 }2439 var address = [2440 address,2441 city,2442 state,2443 zipCode,2444 'US'2445 ].join(', ');2446 address = address.replace(/ ,/g, '');2447 memberShipService.verificationAddress(address).then(function (res) {2448 var rs = res.data.results[0];2449 var streetNum = { long_name: '', short_name: '' };2450 var route = { long_name: '', short_name: '' };2451 if (rs) {2452 var keysMap = [0, 1];2453 if (rs.address_components[0] && rs.address_components[0].types[0] === 'premise') keysMap = [1, 2]; // Skip premise2454 if (rs.address_components[keysMap[0]]) streetNum = rs.address_components[keysMap[0]];2455 if (rs.address_components[keysMap[1]]) route = rs.address_components[keysMap[1]];2456 var longAddress = (streetNum.long_name + ' ' + route.long_name).toLowerCase();2457 var shortAddress = (streetNum.short_name + ' ' + route.short_name).toLowerCase();2458 if (type === 1 && $scope.addressVerification.place) {2459 $scope.addressInvalid = !(($scope.addressVerification.place.address || '').toLowerCase() === longAddress || ($scope.addressVerification.place.address || '').toLowerCase() === shortAddress);2460 } else {2461 $scope.bankAddressInvalid = !(($scope.bankAddressVerification.place.address || '').toLowerCase() === longAddress || ($scope.bankAddressVerification.place.address || '').toLowerCase() === shortAddress);2462 }2463 }2464 });2465 }2466 function _initVerifyAddressPaymentCheck() {2467 //init bank address2468 if (applicationVm.model.paymentMethod && applicationVm.model.paymentMethod === '2') {2469 $scope.bankAddressInvalid = true;2470 $scope.bankAddressVerification = {2471 show: false,2472 cls: 'gplace',2473 content: $sce.trustAsHtml('<span class="fa fa-spinner font-grey-silver"></span>'),2474 place: {2475 address: '',2476 city: '',2477 state: '',2478 zipCode: ''2479 },2480 getPlace: function (place) { }2481 };2482 $scope.bankAddressVerification.place = applicationVm.model.check.address;2483 _googleMapVerification(2);2484 $scope.bankAddressVerification.getPlace = function (addrComp) {2485 var rs = {2486 address: '',2487 city: '',2488 state: '',2489 zipCode: ''2490 };2491 _.forEach(addrComp, function (comp) {2492 if (comp.types[0] === "street_number") rs.address = comp.short_name + " ";2493 if (comp.types[0] === "route") rs.address += comp.short_name;2494 if (comp.types[0] === "locality") rs.city = comp.short_name;2495 if (comp.types[0] === "administrative_area_level_1") rs.state = comp.short_name;2496 if (comp.types[0] === "postal_code") rs.zipCode = comp.short_name;2497 });2498 $scope.$apply(function () {2499 angular.extend(applicationVm.model.check, rs);2500 $scope.bankAddressInvalid = false;2501 });2502 };2503 }2504 }2505 function _initFileModel(imgFile, mediaId) {2506 //Create physical files2507 if (!applicationVm.model.physicalFiles) {2508 applicationVm.model.physicalFiles = [];2509 }2510 applicationVm.fileModel = {};2511 applicationVm.fileModel.id = applicationVm.fileModel.timestampCreated = appUtils.getTimestamp();2512 applicationVm.fileModel.fileName = imgFile.fileName;2513 applicationVm.fileModel.path = imgFile.downloadUrl;2514 applicationVm.fileModel.status = 0;2515 applicationVm.fileModel.isSelected = false;2516 applicationVm.fileModel.processedAt = null;2517 applicationVm.fileModel.mediaId = mediaId;2518 applicationVm.model.physicalFiles.push(applicationVm.fileModel);2519 }2520 var messFlag = false;2521 function showMessageUpdateInfo(snapshot) {2522 var data = snapshot.val() || null;2523 // console.log('is Subbmitting ------');2524 if (initModel && data !== null && data.authorModifier && data.authorModifier !== currentUser.email && applicationVm.model.timestampModified !== data.timestampModified) {2525 var staff = _.find(applicationVm.employees, { email: data.authorModifier });2526 if (staff) {2527 var name = staff.firstName !== '' && staff.lastName !== '' ? (staff.firstName + ' ' + staff.lastName) : (staff.username || staff.userName || staff.email);2528 var modifiedTime = moment(data.timestampModified).fromNow();2529 var updateMess = 'This application have been edited by';2530 if (data.submitting) {2531 updateMess = 'This application have been submitted by';2532 }2533 if (!messFlag) {2534 messFlag = true;2535 $ngBootbox.alert(updateMess + ' ' + name + ' ' + modifiedTime).then(function () {2536 messFlag = false;2537 $state.reload();2538 });2539 }2540 }2541 }2542 }2543 function onValuePhysicalFiles(snapshot) {2544 var data = snapshot.val() || null;2545 if (initModel && data) {2546 var index = null;2547 var processFile = _.find(applicationVm.model.physicalFiles, function (item, key) {2548 index = key;2549 return item.mediaId === data.mediaId;2550 });2551 if (processFile !== undefined && processFile.status !== data.status) {2552 applicationVm.model.physicalFiles[index] = data;2553 $timeout(angular.noop, 300);2554 }2555 if (data.status === 3 || processFile === undefined) {2556 physicalFilesRef[data.mediaId].off('value', onValuePhysicalFiles);2557 }2558 }2559 }2560 function waivedSetupFee(val) {2561 var total = 0;2562 if (val) {2563 total = parseFloat(applicationVm.model.total.totalAmount) - parseFloat(applicationVm.model.total.setupFee);2564 } else {2565 total = parseFloat(applicationVm.model.total.totalAmount) + parseFloat(applicationVm.model.total.setupFee);2566 }2567 applicationVm.model.total.totalAmount = appUtils.formatCurrency(total);2568 }2569 function _reloadGoState() {2570 var tab = [1, 2, 3, 4, 6].indexOf(applicationVm.model.status) !== -1 ? applicationVm.model.status : -1;2571 if ($scope.userPermission.isAdmin || $scope.userPermission.viewAllApplication) {2572 alias = null;2573 }2574 $timeout(function () {2575 $state.go('membership.editApplication', { id: applicationVm.model.$id, 'tab': tab, 'keyword': '', 'start': timestampStart, 'end': timestampEnd, 'page': 0, 'author': clients, 'alias': alias, 'state': states, 'plantype': plantypes, 'reportBy': reportBy, 'sortBy': sortBy });2576 }, 800);2577 }2578 function getCashOptionTxt(application) {2579 return appUtils.getCashOptionTxt(application);2580 }2581 function detechCardType(cardNumber) {2582 appUtils.getCardType2(applicationVm.model.creditCard.creditCardNumber).then(function (cardTypeData) {2583 applicationVm.model.creditCard.type = cardTypeData;2584 return;2585 });2586 }2587 function membershipOverwrite() {2588 $ngBootbox.confirm('Are you sure want to overwrite membership?').then(function () {2589 _membershipOverwrite();2590 });2591 }2592 function _membershipOverwrite() {2593 //console.log(applicationVm.memberModel);2594 var cardType = "";2595 applicationVm.model.status = 8; // Billing Required2596 var cartTypeR = $q.when();2597 if (applicationVm.model.paymentMethod === '0') {2598 if (!applicationVm.model.creditCard.cardType) {2599 cartTypeR = appUtils.getCardType2(applicationVm.model.creditCard.creditCardNumber).then(function (cardTypeData) {2600 cardType = cardTypeData;2601 return;2602 });2603 } else {2604 cardType = applicationVm.model.creditCard.cardType;2605 }2606 }2607 // suplement data2608 return cartTypeR.then(function () {2609 if (applicationVm.model.creditCard) {2610 var cvv = applicationVm.model.creditCard.cvv;2611 var cardNumber = applicationVm.model.creditCard.creditCardNumber;2612 applicationVm.model.creditCard.cvv = cvv.replace(/[^A-Z]/g, '*');2613 applicationVm.model.creditCard.creditCardNumber = cardNumber.substring(0, cardNumber.length - 4).replace(/[^A-Z]/g, '*') + cardNumber.substring(cardNumber.length - 4, cardNumber.length);2614 if (cardType) {2615 applicationVm.model.creditCard.cardType = cardType;2616 }2617 }2618 if (applicationVm.model.check) {2619 var routingNumber = applicationVm.model.check.routingNumber;2620 var accountNumber = applicationVm.model.check.accountNumber;2621 applicationVm.model.check.routingNumber = routingNumber.substring(0, routingNumber.length - 4).replace(/[^A-Z]/g, '*') + routingNumber.substring(routingNumber.length - 4, routingNumber.length);2622 applicationVm.model.check.accountNumber = accountNumber.substring(0, accountNumber.length - 4).replace(/[^A-Z]/g, '*') + accountNumber.substring(accountNumber.length - 4, accountNumber.length);2623 }2624 // tracking data2625 var appTrackingObjSubmit = {2626 eventType: appUtils.logEvent.membershipOverwrite,2627 status: applicationVm.model.status,2628 message: 'Membership Overwrite success'2629 };2630 applicationVm.memberModel.overwrite = true;2631 applicationVm.model.overwrite = true;2632 applicationVm.model.isLocked = true;2633 // change status;2634 // submitR.push(update("Membership Overwrite success!", appTrackingObjSubmit));2635 return update("Membership Overwrite success!", appTrackingObjSubmit).then(function () {2636 _reloadGoState();2637 });2638 });2639 } // end membershipOverwrite 2640 function cancelAccount() {2641 $ngBootbox.confirm('Are you sure you want to Cancel this account?').then(function () {2642 _cancelAccount();2643 });2644 }2645 function _cancelAccount() {2646 var request = [];2647 applicationVm.model.status = 6; // Canceled2648 applicationVm.model.authorModifier = currentUser.email;2649 var updateApplicationReq = memAppService.update(applicationVm.model);2650 var appTrackingUpdate = {2651 eventType: appUtils.logEvent.changeStatus,2652 status: applicationVm.model.status,2653 message: 'Change application status success.'2654 };2655 var addTimelineReq = memAppTimeLineService.create(applicationVm.model.$id, appTrackingUpdate);2656 return $q.all([updateApplicationReq, addTimelineReq]).then(function () {2657 _reloadGoState();2658 });2659 }2660 function getState(value) {2661 var state = _.find(applicationVm.appStatelist, function (item) {2662 return item.iso === value;2663 });2664 return state && state.name || '';2665 }2666 function _getAccountSource(model) {2667 applicationVm.accountSource = '';2668 if (model.sourceSeminar) {2669 model.sourceClass = model.sourceGunShow = model.sourceOther = false;2670 applicationVm.accountSource = 'Seminar';2671 } else if (model.sourceClass) {2672 model.sourceSeminar = model.sourceGunShow = model.sourceOther = false;2673 applicationVm.accountSource = 'Class';2674 } else if (model.sourceGunShow) {2675 model.sourceSeminar = model.sourceClass = model.sourceOther = false;2676 applicationVm.accountSource = 'Gun Show';2677 } else if (model.sourceOther) {2678 model.sourceSeminar = model.sourceClass = model.sourceGunShow = false;2679 applicationVm.accountSource = 'Other';2680 }2681 }2682 function _setAccountSource(model) {2683 if (model.regionCode === 'sec') {2684 model.sourceOther = model.sourceClass = model.sourceGunShow = model.sourceOther = false;2685 return;2686 }2687 switch (applicationVm.accountSource) {2688 case 'Seminar':2689 model.sourceClass = model.sourceGunShow = model.sourceOther = false;2690 model.sourceSeminar = true;2691 break;2692 case 'Class':2693 model.sourceSeminar = model.sourceGunShow = model.sourceOther = false;2694 model.sourceClass = true;2695 break;2696 case 'Gun Show':2697 model.sourceSeminar = model.sourceClass = model.sourceOther = false;2698 model.sourceGunShow = true;2699 break;2700 case 'Other':2701 model.sourceOther = true;2702 model.sourceSeminar = model.sourceClass = model.sourceGunShow = false;2703 break;2704 }2705 }2706 //===================================================================================================================================2707 // function create() {2708 // applicationVm.model.priority = false;2709 // var stateId = $('[name="appState"]:visible option:selected').attr('data-id');2710 // applicationVm.model.stateId = !stateId ? '0' : stateId;2711 // //always get lastest promo code.2712 // memberShipFacilitiesService.get(applicationVm.model.facilityId).then(function (data) {2713 // if (data && data.facility_promo_code) {2714 // applicationVm.model.facilityCode = data.facility_promo_code;2715 // }2716 // //2717 // _createApplication();2718 // }).catch(function () {2719 // _createApplication();2720 // });2721 // }2722 // function _createApplication() {2723 // memAppService.create(applicationVm.model).then(function (rs) {2724 // if (rs.result) {2725 // //Create application timeline2726 // var appTimeline = {2727 // authorName: currentUser.email,2728 // eventType: appUtils.logEvent.createApp,2729 // eventId: '',2730 // submitResult: '',2731 // message: '',2732 // from: 'Admin Site'2733 // };2734 // memAppTimeLineService.create(rs.id, appTimeline);2735 // applicationVm.model.$id = rs.id;2736 // //Create file process queue2737 // var processQueueModel = {};2738 // processQueueModel['0'] = 0;2739 // memProcessQueueService.create(rs.id, processQueueModel).then(function (createRs) {2740 // if (!createRs.result) {2741 // toaster.error('Cannot create process queue!');2742 // }2743 // });2744 // _createMember(rs.id);2745 // toaster.success("Save success! please wait a moment to process data.");2746 // setTimeout(function () {2747 // $state.go('membership.editApplication', { id: rs.id, tab: -1 });2748 // }, 3500);2749 // } else {2750 // toaster.error(rs.errorMsg);2751 // }2752 // });2753 // }2754 // function _createMember(appId) {2755 // applicationVm.memberModel.apps = [];2756 // applicationVm.memberModel.apps.push(appId);2757 // applicationVm.memberModel.isActive = false;2758 // memberShipService.create(applicationVm.memberModel).then(function (memRs) {2759 // if (!memRs.result) {2760 // toaster.error('Cannot save membership!');2761 // } else {2762 // applicationVm.model.membershipId = memRs.id;2763 // memAppService.updateMemberShipId(appId, memRs.id).then(function (rs) {2764 // //Create application timeline2765 // var appTimeline = {2766 // authorName: currentUser.email,2767 // eventType: appUtils.logEvent.editApp,2768 // eventId: '',2769 // submitResult: '',2770 // message: !rs.result ? rs.errorMsg : '',2771 // from: 'Admin Site'2772 // };2773 // memAppTimeLineService.create(appId, appTimeline);2774 // });2775 // }2776 // });2777 // }2778 // function _createByUploadFile() {2779 // applicationVm.memberModel = {};2780 // applicationVm.model.selectedAddOns = {};2781 // applicationVm.memberModel.secMember = {};2782 // applicationVm.memberModel.priMember = {};2783 // applicationVm.model.uid = currentUser.$id;2784 // applicationVm.model.authorName = currentUser.email;2785 // //2786 // applicationVm.memberModel.uid = currentUser.$id;2787 // applicationVm.memberModel.authorName = currentUser.email;2788 // applicationVm.memberModel.timestampCreated = appUtils.getTimestamp();2789 // //Create new an application2790 // create();2791 // }2792 // function _initModel() {2793 // applicationVm.model = {2794 // state: '',2795 // status: 0,2796 // sourceSeminar: false,2797 // sourceClass: false,2798 // sourceGunShow: false,2799 // sourceOther: false,2800 // processOnSwiper: 'false',2801 // startUp: '',2802 // creditCard: {2803 // name: '',2804 // creditCardNumber: '',2805 // month: '',2806 // year: '',2807 // cvv: '',2808 // zipCode: ''2809 // },2810 // physicalFiles: [],2811 // total: {2812 // subTotalAmount: 0,2813 // setupFee: 0,2814 // totalAmount: 02815 // },2816 // signature: false,2817 // signatureDate: '',2818 // representativeCode: '',2819 // facilityCode: '',2820 // facilityId: '',2821 // isVerified: false,2822 // selectedPlans: {},2823 // selectedAddOns: {},2824 // isLocked: false,2825 // numberOfAdults: '',2826 // cycle: '',2827 // stateId: '',2828 // paymentMethod: '0',2829 // cashAmount: 0,2830 // cashOption: '',2831 // check: {2832 // accountNumber: '',2833 // routingNumber: '',2834 // type: 'BusinessChecking',2835 // address: '',2836 // state: '',2837 // city: '',2838 // zipCode: '',2839 // name: '',2840 // fullName: ''2841 // }2842 // };2843 // //Set representativeCode for model 2844 // applicationVm.model.representativeCode = currentUser && currentUser.repCode ? currentUser.repCode : '';2845 // _initMemberModel();2846 // }2847 // function _initMemberModel() {2848 // //Member model2849 // applicationVm.memberModel = {};2850 // applicationVm.memberModel.apps = [];2851 // //Primary member2852 // applicationVm.memberModel.priMember = {2853 // memberId: '',2854 // firstName: '',2855 // lastName: '',2856 // email: '',2857 // phone: '',2858 // mailingAddress: {2859 // address: '',2860 // city: '',2861 // state: '',2862 // zipCode: ''2863 // }2864 // };2865 // //Secondary member2866 // applicationVm.memberModel.secMember = {2867 // memberId: '',2868 // firstName: '',2869 // lastName: '',2870 // email: '',2871 // phone: ''2872 // };2873 // applicationVm.memberModel.isActive = false;2874 // applicationVm.memberModel.accountId = '';2875 // }2876 //===================================================================================================================================================================2877 // function unCheckAddons() {2878 // var appForm = $('#edit-web-app');2879 // var priPlans = appForm.find('.pri-app-plans input[type="checkbox"]');2880 // _.forEach(priPlans, function(element, key) {2881 // $(element).attr('checked', false);2882 // });2883 // var secPlans = appForm.find('.sec-app-plans input[type="checkbox"]');2884 // _.forEach(secPlans, function(element, key) {2885 // $(element).attr('checked', false);2886 // });2887 // }2888 // function autoFocus() {2889 // //Implement auto focus2890 // var focusElements = $('[auto-focus]:visible');2891 // _.forEach(focusElements, function(e, key) {2892 // var me = $(e);2893 // var length = me.attr('length');2894 // var toElement = me.attr('to-element');2895 // me.keydown(function(e) {2896 // var str = me.val().replace(/_/g, '');2897 // if (e.keyCode != 35 && e.keyCode != 36 && e.keyCode != 37 && e.keyCode != 38 && e.keyCode != 39 && e.keyCode != 40 && e.keyCode != 8 && e.keyCode != 46 && str.length >= length) {2898 // $('[name=' + toElement + ']:visible').focus();2899 // }2900 // });2901 // });2902 // }2903 // function loadCanvas(dataURL,index) {2904 // var canvas = document.getElementById('canvas-img-' + index);2905 // var context = canvas.getContext('2d');2906 // // load image from data url2907 // var imageObj = new Image();2908 // imageObj.onload = function() {2909 // canvas.width=1200;2910 // canvas.height=1600;2911 // context.drawImage(imageObj,0,0,imageObj.width,imageObj.height,0,0,1200,1600);2912 // };2913 // imageObj.src = "data:image/png;base64," + dataURL;2914 // }2915 // function downloadImg(url,index){2916 // var xhr = new XMLHttpRequest();2917 // xhr.open('GET', url, true);2918 // xhr.responseType = 'arraybuffer';2919 // xhr.onload = function(e) {2920 // if (this.status == 200) {2921 // var uInt8Array = new Uint8Array(this.response);2922 // var i = uInt8Array.length;2923 // var binaryString = new Array(i);2924 // while (i--)2925 // {2926 // binaryString[i] = String.fromCharCode(uInt8Array[i]);2927 // }2928 // var data = binaryString.join('');2929 // var base64 = window.btoa(data);2930 // loadCanvas(base64,index);2931 // }2932 // };2933 // xhr.send();2934 // }2935 }...
index.js
Source:index.js
1require("@babel/polyfill");2import "./scss/index.scss";3const bookingWidget = require("./app");4bookingWidget();5const appFormEl = document.querySelector("#app-form");6if (appFormEl) {7 const appForm = require("./app-form");8 appForm();...
Using AI Code Generation
1import { appFormEl } from 'ng-mocks';2import { AppComponent } from './app.component';3describe('AppComponent', () => {4 it('should create the app', () => {5 const fixture = appFormEl(AppComponent);6 const app = fixture.componentInstance;7 expect(app).toBeTruthy();8 });9 it(`should have as title 'my-project'`, () => {10 const fixture = appFormEl(AppComponent);11 const app = fixture.componentInstance;12 expect(app.title).toEqual('my-project');13 });14 it('should render title', () => {15 const fixture = appFormEl(AppComponent);16 fixture.detectChanges();17 const compiled = fixture.nativeElement;18 expect(compiled.querySelector('.content span').textContent).toContain('my-project app is running!');19 });20});21import { appFormEl } from 'ng-mocks';22import { AppComponent } from './app.component';23describe('AppComponent', () => {24 it('should create the app', () => {25 const fixture = appFormEl(AppComponent);26 const app = fixture.componentInstance;27 expect(app).toBeTruthy();28 });29 it(`should have as title 'my-project'`, () => {30 const fixture = appFormEl(AppComponent);31 const app = fixture.componentInstance;32 expect(app.title).toEqual('my-project');33 });34 it('should render title', () => {35 const fixture = appFormEl(AppComponent);36 fixture.detectChanges();37 const compiled = fixture.nativeElement;38 expect(compiled.querySelector('.content span').textContent).toContain('my-project app is running!');39 });40});41import { appFormEl } from 'ng-mocks';42import { AppComponent } from './app.component';43describe('AppComponent', () => {44 it('should create the app', () => {45 const fixture = appFormEl(AppComponent);46 const app = fixture.componentInstance;47 expect(app).toBeTruthy();48 });49 it(`should have as title 'my-project'`, () => {50 const fixture = appFormEl(AppComponent);51 const app = fixture.componentInstance;52 expect(app.title).toEqual('my-project');53 });54 it('should render title', () => {55 const fixture = appFormEl(AppComponent);56 fixture.detectChanges();
Using AI Code Generation
1import { appFormEl } from 'ng-mocks';2import { AppComponent } from './app.component';3import { AppModule } from './app.module';4import { TestBed } from '@angular/core/testing';5describe('AppComponent', () => {6 beforeEach(async () => {7 await TestBed.configureTestingModule({8 imports: [AppModule],9 }).compileComponents();10 });11 it('should render title', () => {12 const fixture = TestBed.createComponent(AppComponent);13 fixture.detectChanges();14 const app = fixture.componentInstance;15 expect(app.title).toEqual('ng-mocks');16 expect(appFormEl(fixture)).toBeDefined();17 });18});19import { Component } from '@angular/core';20@Component({21})22export class AppComponent {23 title = 'ng-mocks';24}25 <span>{{ title }}</span>26 <form [formGroup]="form" (ngSubmit)="onSubmit()">
Using AI Code Generation
1import { appFormEl } from 'ng-mocks';2import { AppComponent } from './app.component';3describe('AppComponent', () => {4 it('should render form', () => {5 const fixture = MockRender(AppComponent);6 const form = appFormEl(fixture.debugElement);7 expect(form).toBeDefined();8 });9});10import { Component } from '@angular/core';11@Component({12})13export class AppComponent {14 title = 'ng-mocks-demo';15}
Using AI Code Generation
1import { appFormEl } from 'ng-mocks';2import { appFormEl } from 'ng-mocks';3import { appFormEl } from 'ng-mocks';4import { appFormEl } from 'ng-mocks';5import { appFormEl } from 'ng-mocks';6import { appFormEl } from 'ng-mocks';7import { appFormEl } from 'ng-mocks';8import { appFormEl } from 'ng-mocks';9import { appFormEl } from 'ng-mocks';10import { appFormEl } from 'ng-mocks';11import { appFormEl } from 'ng-mocks';12import { appFormEl } from 'ng-mocks';13import { appFormEl } from
Using AI Code Generation
1import { appFormEl } from 'ng-mocks';2const fixture = MockRender(`3`);4const form = appFormEl(fixture);5expect(form).toBeDefined();6expect(form.value).toEqual({ name: '' });7import { appFormEl } from 'ng-mocks';8const fixture = MockRender(`9`);10const form = appFormEl(fixture);11expect(form).toBeDefined();12expect(form.value).toEqual({ name: '' });13import { appFormEl } from 'ng-mocks';14const fixture = MockRender(`15`);16const form = appFormEl(fixture);17expect(form).toBeDefined();18expect(form.value).toEqual({ name: '' });19import { appFormEl } from 'ng-mocks';20const fixture = MockRender(`21`);22const form = appFormEl(fixture);23expect(form).toBeDefined();24expect(form.value).toEqual({ name: '' });25import { appFormEl } from 'ng-mocks';26const fixture = MockRender(`27`);28const form = appFormEl(fixture);29expect(form).toBeDefined();30expect(form.value).toEqual({ name: '' });31import { appFormEl } from 'ng-mocks';32const fixture = MockRender(`33`);34const form = appFormEl(fixture);35expect(form).toBeDefined();
Using AI Code Generation
1import { appFormEl } from 'ng-mocks';2const formEl = appFormEl(fixture, 'form');3expect(formEl).toBeDefined();4expect(formEl).not.toBeNull();5expect(formEl).toBeInstanceOf(HTMLFormElement);6expect(formEl).toHaveClass('form');7expect(formEl).toHaveAttribute('name', 'form');8expect(formEl).toHaveAttribute('id', 'form');9expect(formEl).toHaveAttribute('action', '/test');10expect(formEl).toHaveAttribute('method', 'post');11expect(formEl).toHaveAttribute('enctype', 'multipart/form-data');12expect(formEl).toHaveAttribute('autocomplete', 'on');13expect(formEl).toHaveAttribute('novalidate', '');14expect(formEl).toHaveAttribute('target', '_blank');15expect(formEl).toHaveAttribute('rel', 'noopener');16expect(formEl).toHaveAttribute('accept-charset', 'utf-8');17expect(formEl).toHaveAttribute('dir', 'ltr');18expect(formEl).toHaveAttribute('lang', 'en');19expect(formEl).toHaveAttribute('translate', 'no');20expect(formEl).toHaveAttribute('hidden', '');21expect(formEl).toHaveAttribute('tabindex', '0');22expect(formEl).toHaveAttribute('accesskey', 'a');23expect(formEl).toHaveAttribute('contenteditable', 'false');24expect(formEl).toHaveAttribute('contextmenu', 'context-menu');25expect(formEl).toHaveAttribute('draggable', 'true');26expect(formEl).toHaveAttribute('dropzone', 'copy');27expect(formEl).toHaveAttribute('spellcheck', 'false');28expect(formEl).toHaveAttribute('style', 'color: red;');29expect(formEl).toHaveAttribute('title', 'title');30expect(formEl).toHaveAttribute('aria-activedescendant', 'active-descendant');31expect(formEl).toHaveAttribute('aria-atomic', 'true');32expect(formEl).toHaveAttribute('aria-autocomplete', 'both');33expect(formEl).toHaveAttribute('aria-busy', 'true');34expect(formEl).toHaveAttribute('aria-checked', 'true');35expect(formEl).toHaveAttribute('aria-colcount', '1');36expect(formEl).toHaveAttribute('aria-colindex', '1');37expect(formEl).toHaveAttribute('aria-colspan', '1');38expect(formEl).toHaveAttribute('aria-controls', 'controls');39expect(formEl).toHaveAttribute('aria-current', 'true');40expect(formEl).toHaveAttribute('aria
Using AI Code Generation
1import { appFormEl } from 'ng-mocks';2describe('appFormEl', () => {3 it('should return the form element', () => {4 const fixture = MockRender(`5 <input name="name" [(ngModel)]="name" />6 `);7 const form = appFormEl(fixture.point.componentInstance);8 expect(form).toBeDefined();9 });10});11import { appFormEl } from 'ng-mocks';12describe('appFormEl', () => {13 it('should return the form element', () => {14 const fixture = MockRender(`15 <input name="name" [(ngModel)]="name" />16 `);17 const form = appFormEl(fixture.point.componentInstance);18 expect(form).toBeDefined();19 });20});21import { appFormEl } from 'ng-mocks';22describe('appFormEl', () => {23 it('should return the form element', () => {24 const fixture = MockRender(`25 <input name="name" [(ngModel)]="name" />26 `);27 const form = appFormEl(fixture.point.componentInstance);28 expect(form).toBeDefined();29 });30});31import { appFormEl } from 'ng-mocks';32describe('appFormEl', () => {33 it('should return the form element', () => {34 const fixture = MockRender(`35 <input name="name" [(ngModel)]="name" />36 `);
Using AI Code Generation
1describe('appFormEl', () => {2 it('should return form element', () => {3 const { fixture } = setup();4 const form = appFormEl(fixture);5 expect(form).toBeTruthy();6 });7});8describe('appFormEl', () => {9 it('should return form element', () => {10 const { fixture } = setup();11 const form = appFormEl(fixture);12 expect(form).toBeTruthy();13 });14});15describe('appFormEl', () => {16 it('should return form element', () => {17 const { fixture } = setup();18 const form = appFormEl(fixture);19 expect(form).toBeTruthy();20 });21});22describe('appFormEl', () => {23 it('should return form element', () => {24 const { fixture } = setup();25 const form = appFormEl(fixture);26 expect(form).toBeTruthy();27 });28});29describe('appFormEl', () => {30 it('should return form element', () => {31 const { fixture } = setup();32 const form = appFormEl(fixture);33 expect(form).toBeTruthy();34 });35});36describe('appFormEl', () => {37 it('should return form element', () => {38 const { fixture } = setup();39 const form = appFormEl(fixture);40 expect(form).toBeTruthy();41 });42});43describe('appFormEl', () => {44 it('should return form element', () => {45 const { fixture } = setup();46 const form = appFormEl(fixture);47 expect(form).toBeTruthy();48 });49});50describe('appFormEl', () => {51 it('should return form element', () => {52 const { fixture } = setup();53 const form = appFormEl(fixture);54 expect(form).toBeTruthy();
Using AI Code Generation
1import { appFormEl } from 'ng-mocks';2const form = appFormEl(fixture, 'testForm');3expect(form).toBeDefined();4expect(form.value).toEqual({});5expect(form.valid).toBeFalse();6expect(form.errors).toEqual({ required: true });7expect(form.controls.testControl.errors).toEqual({ required: true });8expect(form.controls.testControl.valid).toBeFalse();9expect(form.controls.testControl.value).toEqual('');10expect(form.controls.testControl.valueChanges).toBeInstanceOf(Observable);11expect(form.controls.testControl.statusChanges).toBeInstanceOf(Observable);12expect(form.controls.testControl.disabled).toBeFalse();13expect(form.controls.testControl.enabled).toBeTrue();14expect(form.controls.testControl.touched).toBeFalse();15expect(form.controls.testControl.untouched).toBeTrue();16expect(form.controls.testControl.pristine).toBeTrue();17expect(form.controls.testControl.dirty).toBeFalse();18expect(form.controls.testControl.pending).toBeFalse();19expect(form.controls.testControl.status).toEqual('INVALID');20expect(form.controls.testControl.errors).toEqual({ required: true });21expect(form.controls.testControl.valid).toBeFalse();22expect(form.controls.testControl.value).toEqual('');23expect(form.controls.testControl.valueChanges).toBeInstanceOf(Observable);24expect(form.controls.testControl.statusChanges).toBeInstanceOf(Observable);25expect(form.controls.testControl.disabled).toBeFalse();26expect(form.controls.testControl.enabled).toBeTrue();27expect(form.controls.testControl.touched).toBeFalse();28expect(form.controls.testControl.untouched).toBeTrue();29expect(form.controls.testControl.pristine).toBeTrue();30expect(form.controls.testControl.dirty).toBeFalse();31expect(form.controls.testControl.pending).toBeFalse();32expect(form.controls.testControl.status).toEqual('INVALID');33expect(form.controls.testControl.errors).toEqual({ required: true });34expect(form.controls.testControl.valid).toBeFalse();35expect(form.controls.testControl.value).toEqual('');36expect(form.controls.testControl.valueChanges).toBeInstanceOf(Observable);37expect(form.controls.testControl.statusChanges).toBeInstanceOf(Observable);38expect(form.controls.testControl.disabled).toBeFalse();39expect(form.controls.testControl.enabled).toBeTrue();40expect(form.controls.testControl.touched).toBeFalse();41expect(form.controls.testControl.untouched).toBeTrue();42expect(form.controls.testControl.pristine).toBeTrue();43expect(form.controls.testControl.dirty).toBeFalse();44expect(form.controls.testControl.pending).toBeFalse();45expect(form.controls.testControl.status).toEqual('INVALID');46expect(form.controls.testControl.errors).toEqual({ required: true });
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!