/** * @Component Name: CreditCheckComponent * @Module: Home * @Module Functionality : To display the customer credit check information * @Creation Date: August 12,2017 * @Author: sbaireddy * @Version: 1.0 */ import { Component, Input, Output, EventEmitter, OnInit, OnChanges, OnDestroy, ViewChild } from '@angular/core'; import { NgForm } from '@angular/forms'; import Utils from '../../../shared/utils'; import CartUtils from '../../../shared/cart.utils'; import { STATES, ID_TYPE, ID_STATES } from '../../../shared/form.constants'; import * as Constants from '../../../shared/constants'; import { User } from '../../../shared/modal/user'; import { Cart } from '../../../shared/modal/cart'; import { Customer, ICreditCheck } from '../../../shared/modal/customer'; import { SharedService } from '../../../shared/shared.service'; import { UserService } from '../../../services/user.service'; import { CartService } from '../../../services/cart.service'; import { CustomerService } from '../../../services/customer.service'; import * as _ from 'underscore'; // To do complex array and object functions @Component({ moduleId: module.id, selector: 'credit-check-cmp', templateUrl: 'credit-check.component.html', styleUrls: ['credit-check.component.css'] }) export class CreditCheckComponent implements OnInit, OnChanges, OnDestroy { private COMPONENT_NAME: string = 'CreditCheckComponent'; karmaTestResult: any = {}; stateItems: any[]; idTypeItems: any[]; @Input() creditType: string; @Input() customerModel: any; // getting the customer address info from customer component. @Input() customerForm: any; @Output() onResetForm = new EventEmitter(); yesAuthorize: boolean = false; storeId: number; // update storeid creditCheckModel: any = { confirmPin: '', dateOfBirth: '', idExpiration: '', idIssuedState: '', idNumber: '', idType: '', isEmployee: false, isValidPIN: false, pin: '', employeeId: '', isEnglish: true}; dob: boolean; birthYear: number; expirationYear: number; expiration: number; isDateValid: boolean; minAllowedDate: any; user: User; cart: Cart; subscription: any; hasItemsInCart: boolean = false; isDealerCodeExists: boolean; maxdate: any; @ViewChild('conflictModel') conflictModel: any; disablePIN: boolean = false; today = new Date(); eligibleAge = this.today.getFullYear() - 100; type: string = 'password'; clearAllStatus: boolean = false; constructor( public sharedService: SharedService, public userService: UserService, public cartService: CartService, public customerService: CustomerService) { } /** * This function is used to initialize the directive/component after Angular * first displays the data-bound properties.It is invoked only once when the * directive is instantiated.Here it is initializing all the states, ID Types, user and cart informations * @return {void} */ ngOnInit(): void { const METHOD_NAME: string = 'ngOnInit()'; // Start-Switch Channel-Store id update this.sharedService.updateErrorMessage(null); this.creditCheckModel.idIssuedState = ''; this.creditCheckModel.idType = ''; this.sharedService.storeId.subscribe((val: number) => { this.storeId = val; this.maxdate = new Date().getFullYear() + 18 + '-12'; }); // End-Switch Channel-Store id update // US267571: changed to ID_STATES constant to include Puerto Rico ID state. this.stateItems = ID_STATES.filter(stateItem => stateItem); this.idTypeItems = ID_TYPE.filter(idTypeItem => idTypeItem); this.user = this.userService.getUser(); this.cart = this.cartService.getCart(); this.subscription = this.cartService.hasUpdate.subscribe((item) => { if (item) { this.cart = this.cartService.getCart(); } }); if (this.cart && this.cart.packages && this.cart.packages.length > 0) { this.hasItemsInCart = true; } this.sharedService.clearAllStatus.subscribe((val: boolean) => { this.clearAllStatus = val; }); // Picking only the keys that is belonged to the credit check model. if (this.customerService.getCustomerModel()) { this.creditCheckModel = Object.assign(this.creditCheckModel, _.pick(this.customerService.getCustomerModel(), ...(_.keys(this.creditCheckModel)))); } if(this.customerService.getCustomer() && this.customerService.getCustomer().creditProfile && this.customerService.getCustomer().creditProfile.accountSubType === 'S' && this.customerService.getCustomer().creditProfile.accountType === 'I'){ this.sharedService.showErrorMessage('_ERR_SOLE_PROPRIETOR', false); } } /** * This function is called whenever one or more data-bound input properties change * @return {void} */ ngOnChanges(): void { console.log('is customer form valid:' + this.customerForm.valid); this.disablePIN = false; this.creditCheckModel.isValidPIN = (this.creditCheckModel.isValidPIN) ? this.creditCheckModel.isValidPIN : false; if (this.customerModel && this.customerModel.creditProfile && this.customerModel.creditProfile.identifier) { if (this.customerModel.creditProfile.creditClass || this.customerModel.altCustomerId) { this.disablePIN = true; this.creditCheckModel.isValidPIN = true; this.creditCheckModel.pin = this.customerModel.creditProfile.identifier; this.creditCheckModel.confirmPin = this.customerModel.creditProfile.identifier; console.log('Passcode available already for customer: ' + this.customerModel.altCustomerId); } } } /** * Cleanup just before Angular destroys the directive/component. * Unsubscribe Observables and detach event handlers to avoid memory leaks. * @return void */ ngOnDestroy(): void { const METHOD_NAME: string = 'ngOnDestroy()'; if (!this.clearAllStatus) { this.customerService.setCustomerModel(this.creditCheckModel); } this.karmaTestResult = null; this.customerModel = null; this.user = null; // this.cart = null; // on page refresh the cart object is getting destroyed so getting the cart again back. this.stateItems = null; this.idTypeItems = null; this.minAllowedDate = null; this.maxdate = null; // unsubscribing the subscription this.subscription.unsubscribe(); } /** * This function is used to check the credit eligibility of a customer based on their * credit history * @return void */ checkEligibility(): void { const METHOD_NAME: string = 'checkEligibility()'; if (this.customerForm.valid) { // checking parent form is valid first console.log('[start] - CreditCheckComponent.checkEligibility()>>checking eligibility.'); this.sharedService.addLogging(this.COMPONENT_NAME, METHOD_NAME, 'Checking credit eligibility'); const orderId: number = 0; if (this.cart) { if (this.hasItemsInCart) { this.conflictModel.show(); } else { this.processCreditCheck(this.cart.orderId); } } else { console.log('Creating a cart for save the customer data.'); const cartInputData: any = CartUtils.createCartInput(this.storeId, this.user); this.sharedService.showSpinner(true); // spinner this.cartService.createCartDetails(this.storeId, cartInputData).subscribe(result => { this.karmaTestResult = result; this.sharedService.showSpinner(false); // spinner this.cart = new Cart(); this.cart = Object.assign(this.cart, result); // this.cartService.setCart(result); this.processCreditCheck(result.orderId); }, error => { this.sharedService.showSpinner(false); // spinner console.error('error=>' + error); this.sharedService.showErrorMessage(error, true); }); } console.log('[end] - CreditCheckComponent.checkEligibility()>>checking eligibility.'); } } /** * This function is used to perform the customer credit check through * creditCheck function in customer service * @param {number} orderId - order id to refer the order details * @return void */ processCreditCheck(orderId: number): void { const METHOD_NAME: string = 'processCreditCheck()'; console.log('CreditCheckComponent.processCreditCheck()>>checking eligibility.'); const creditCheck: ICreditCheck = {}; creditCheck.orderId = orderId; creditCheck.firstName = this.customerModel.firstName; creditCheck.lastName = this.customerModel.lastName; creditCheck.address1 = this.customerModel.address1; creditCheck.address2 = this.customerModel.address2; creditCheck.city = this.customerModel.city; creditCheck.state = this.customerModel.state; creditCheck.zipCode = this.customerModel.zipCode; creditCheck.middleName = this.customerModel.middleName; if (this.customerModel.hasOwnProperty(Constants.EMAIL) && (this.customerModel.email1 !== '') && (this.customerModel.email1 !== undefined)) { creditCheck.email1 = this.customerModel.email1; } if (this.customerModel.hasOwnProperty(Constants.BANNER_MI_DEVICE) && (this.customerModel.middleName !== '') && (this.customerModel.middleName !== undefined)) { creditCheck.middleName = this.customerModel.middleName; } // Have to check on CREDIT API // if (this.customerModel.hasOwnProperty(Constants.NON_TMO_MOBILENUMBER) && // (this.customerModel.nonTMOMobileNumber !== '') && (this.customerModel.nonTMOMobileNumber !== undefined)) { // creditCheck.nonTMOMobileNumber = this.customerModel.nonTMOMobileNumber; // } // if (this.customerModel.hasOwnProperty(Constants.PIN) && // (this.customerModel.pin !== '') && (this.customerModel.pin !== undefined)) { // creditCheck.pin = this.customerModel.pin; // } /* if(this.customerModel.hasOwnProperty(Constants.WEB_ORDER_ID) && (this.customerModel.webOrderId !== "") && (this.customerModel.webOrderId !== undefined)) { // creditCheck.webOrderId = this.customerModel.webOrderId; // } */ creditCheck.phone1 = Utils.nonFormatPhoneNumber(this.customerModel.phone1); creditCheck.dealerCode = this.customerModel.validDealerCode ? this.customerModel.dealerCode : null; creditCheck.pin = this.creditCheckModel.pin ? this.creditCheckModel.pin : null; creditCheck.idType = this.creditCheckModel.idType; creditCheck.idNumber = this.creditCheckModel.idNumber; creditCheck.idIssuedState = this.creditCheckModel.idIssuedState; // if(this.creditCheckModel.msisdn){ // creditCheck.nonTMOMobileNumber = this.creditCheckModel.msisdn; // } // if(this.creditCheckModel.existingPin){ // creditCheck.nonTMOMobilePin = this.creditCheckModel.existingPin; // } if (this.creditCheckModel.isEmployee) { creditCheck.employeeId = this.creditCheckModel.employeeId; } if (this.creditCheckModel.idExpiration) { const dateLatest: string = Utils.nonFormatDate(this.creditCheckModel.idExpiration); creditCheck.idExpirationMonth = dateLatest.substring(0, 2); creditCheck.idExpirationYear = dateLatest.substring(2, 6); } // commenting to make expiration as MM/YYYY // let lengthOfExpiration : any = creditCheck.idExpirationYear.toString(); // if(lengthOfExpiration.length === 2) { // let extraDigitsOfcurrentYear : any ; // extraDigitsOfcurrentYear = new Date().getFullYear().toString(); // creditCheck.idExpirationYear = extraDigitsOfcurrentYear.slice(0,2) + creditCheck.idExpirationYear; // } if (!this.creditType || this.creditType === Constants.CREDIT_CHECK) { creditCheck.creditType = Constants.CREDIT_CHECK; // creditCheck.ssn = this.creditCheckModel.ssn; const ssnNumber = this.creditCheckModel.ssn; if (this.sharedService.checkFormat(ssnNumber)) { // creditCheck.ssn  =  ssnNumber.replace(new  RegExp('-',  'g'),  ''); creditCheck.ssn = Utils.nonFormatSSN(ssnNumber); } else if (this.creditCheckModel.isEmployee) { creditCheck.ssn = this.creditCheckModel.ssn; } } else { creditCheck.creditType = Constants.NOCREDIT_CHECK; creditCheck.pin = this.creditCheckModel.pin; } //added for smart credit and passing values to creditcheck api irrrespective of credit type if(this.customerModel.eligibility === 'y') { creditCheck.accountNumber = this.customerModel.accountNumber; creditCheck.brandType = this.customerModel.brandType; creditCheck.eligibility = this.customerModel.eligibility; creditCheck.eligibilityDate = this.customerModel.eligibilityDate; creditCheck.paymentCount = this.customerModel.paymentCount; creditCheck.nonTMOMobileNumber = this.customerModel.nonTMOMobileNumber.replace(new  RegExp('-',  'g'),  ''); creditCheck.nonTMOMobilePin = this.customerModel.nonTMOMobilePin; } if (this.creditCheckModel.dateOfBirth) { const dateLatest: string = Utils.nonFormatDate(this.creditCheckModel.dateOfBirth); creditCheck.birthDate = dateLatest.substring(2, 4); creditCheck.birthMonth = dateLatest.substring(0, 2); creditCheck.birthYear = dateLatest.substring(4, 8); } this.sharedService.showSpinner(true); // spinner const inputData: any = CartUtils.validateAddressInput(creditCheck); this.customerService.validateAddress(this.storeId, inputData).subscribe(result => { this.karmaTestResult = result; this.sharedService.showSpinner(false); // spinner if (result.statusCode === Constants.ORDER_STATUS_S) { creditCheck.address1 = this.customerModel.address1 = result.addressLine1; creditCheck.address2 = this.customerModel.address2 = result.addressLine2; creditCheck.city = this.customerModel.city = result.city; creditCheck.state = this.customerModel.state = result.stateCode; creditCheck.zipCode = this.customerModel.zipCode = Utils.trimZipCode(result.zipCode); this.sharedService.showSpinner(true); // spinner this.customerService.creditCheck(this.storeId, creditCheck).subscribe(creditCheckResult => { this.karmaTestResult = creditCheckResult; this.sharedService.showSpinner(false); // spinner // clearing customer data from customer service. this.customerService.setCustomer(null); const customer: any = new Customer(); customer.firstName = this.customerModel.firstName; customer.middleName = this.customerModel.middleName; customer.lastName = this.customerModel.lastName; customer.address1 = this.customerModel.address1; customer.address2 = this.customerModel.address2; customer.city = this.customerModel.city; customer.state = this.customerModel.state; customer.zipCode = this.customerModel.zipCode; customer.phone1 = this.customerModel.phone1; customer.email1 = this.customerModel.email1; customer.nonTMOMobileNumber = this.customerModel.nonTMOMobileNumber; customer.nonTMOMobilePin = this.customerModel.nonTMOMobilePin; customer.isValidated = this.customerModel.isValidated; customer.eligibilityMsg = this.customerModel.eligibilityMsg; customer.isPromoEligibleZipCode = (this.customerModel.isPromoEligibleZipCode) ? this.customerModel.isPromoEligibleZipCode : false; customer.accountNumber = this.customerModel.accountNumber; customer.brandType = this.customerModel.brandType; customer.eligibility = this.customerModel.eligibility; customer.eligibilityDate = this.customerModel.eligibilityDate; customer.paymentCount = this.customerModel.paymentCount; customer.dateOfBirth = this.creditCheckModel.dateOfBirth; this.cart.customer = Object.assign(customer, creditCheckResult); this.cartService.setCart(this.cart); console.log('updating the credit choice'); this.sharedService.updateCreditChoice(creditCheckResult.creditType); if (this.cart && this.cart.customer && this.cart.customer.creditProfile && this.cart.customer.creditProfile.isExistingCustomer) { this.sharedService.showErrorMessage('_ERR_CUSTOMER_CREDIT_CHECK_ALREADY_DONE', false); } if (this.cart.packages && this.cart.packages.length > 0) { this.removeConflicts(); } }, error => { this.sharedService.showSpinner(false); // spinner this.sharedService.showErrorMessage(error, true); console.error('error=>' + error); }); } else { this.sharedService.showErrorMessage('_ERR_INVALID_ADDRESS', false); } }, error => { this.sharedService.showSpinner(false); // spinner this.sharedService.showErrorMessage(error, true); // console.error('validate address error=>'+ error) }); } /** * This function is used to enable/disable submit button in customer credit check * based on credit type, authorize and valid pin * @return boolean */ enableOrDisableSubmit(creditCheckForm: any): boolean { const METHOD_NAME: string = 'enableOrDisableSubmit()'; const enable: boolean = false; if (!this.customerForm.valid) { return false; } else if (this.creditCheckModel.pin && this.creditCheckModel.confirmPin && this.creditCheckModel.dateOfBirth && this.creditCheckModel.idType && this.creditCheckModel.idIssuedState && this.creditCheckModel.idExpiration && this.creditCheckModel.idNumber) { if (!this.creditCheckModel.isEmployee && this.creditCheckModel.ssn) { const ssn: string = this.creditCheckModel.ssn; if (!ssn) { return false; } else if (ssn.indexOf(' ') === 0) { return false; } else if (ssn.indexOf('-') === -1 && ssn.length !== 9) { return false; } else if (ssn.indexOf('-') !== -1 && ssn.length !== 11) { return false; } } if (this.creditCheckModel.dateOfBirth) { const dob: string = this.creditCheckModel.dateOfBirth.trim(); if (!dob) { return false; } else if (dob.length !== 10) { return false; } else if (this.sharedService.validate('mmddyyyy', this.creditCheckModel.dateOfBirth) < 18) { return false; } } if (this.creditCheckModel.idExpiration) { const exp: string = this.creditCheckModel.idExpiration.trim(); if (!exp) { return false; } else if (exp.length !== 7) { return false; } else if (this.sharedService.validate('mmyy', this.creditCheckModel.idExpiration) < 0 || this.sharedService.validate('mmyy', this.creditCheckModel.idExpiration) > 18) { return false; } } let typeValue = this.creditCheckModel.isEmployee ? this.creditCheckModel.employeeId : this.creditCheckModel.ssn; typeValue = (this.creditType === Constants.CREDIT_TYPE_NC) ? true : typeValue; this.yesAuthorize = (this.creditType === Constants.CREDIT_TYPE_NC) ? true : this.yesAuthorize; return (this.yesAuthorize && typeValue && (this.creditCheckModel.pin === this.creditCheckModel.confirmPin) && this.creditCheckModel.isValidPIN); } else { if (!this.creditCheckModel.isEmployee && this.creditCheckModel.ssn) { this.creditCheckModel.ssn = this.creditCheckModel.ssn.trim(); } if (this.creditCheckModel.dateOfBirth) { this.creditCheckModel.dateOfBirth = this.creditCheckModel.dateOfBirth.trim(); } if (this.creditCheckModel.idExpiration) { this.creditCheckModel.idExpiration = this.creditCheckModel.idExpiration.trim(); } } return false; } /** * This function is used to resolve conflicts * @returns void */ resolveConflicts(): void { const METHOD_NAME: string = 'resolveConflicts()'; this.hasItemsInCart = false; this.conflictModel.hide(); this.checkEligibility(); } /** * This function is used to resolve the conflicted data after * the process credit check * @return void */ removeConflicts(): void { const METHOD_NAME: string = 'removeConflicts()'; const inputData: any = { 'resolveType': 'NEW' }; this.sharedService.showSpinner(true); // spinner this.cartService.resolveConflicts(this.storeId, this.cart.orderId, inputData).subscribe(result => { this.karmaTestResult = result; this.cartService.getCartSummary(this.storeId, this.cart.orderId).subscribe(getCartSummaryResult => { this.sharedService.showSpinner(false); // spinner this.cartService.setCart(Object.assign(this.cart, getCartSummaryResult)); }, error => { this.sharedService.showSpinner(false); // spinner this.sharedService.showErrorMessage(error, true); console.error('error=>' + error); }); }, error => { this.sharedService.showSpinner(false); // spinner console.error('error=>' + error); this.sharedService.showErrorMessage(error, true); }); } /** * This function is used to validate the passcodes in customer credit check * @param {any} element1 - contains the passcode * @param {any} element2 - contains the confirm passcode * @return void */ validatePasscode(element1: any, element2: any): void { const METHOD_NAME: string = 'validatePasscode()'; if (element1.valid && element2.valid) { if (element1.value === element2.value) { this.creditCheckModel.isValidPIN = false; this.sharedService.showSpinner(true); // spinner this.customerService.validatePINFormat(this.storeId, element1.value).subscribe(result => { this.sharedService.showSpinner(false); // spinner console.log('result: ' + result); if (result) { if (result.is_valid) { this.creditCheckModel.isValidPIN = true; } else { this.sharedService.showErrorMessage('_ERR_ACCOUNT_PASSWORD_NOT_MEET', false); if (!this.creditCheckModel.isValidPIN) { this.creditCheckModel.pin = null; this.creditCheckModel.confirmPin = null; } } } else { this.creditCheckModel.pin = null; this.creditCheckModel.confirmPin = null; this.sharedService.showErrorMessage('_ERR_ACCOUNT_PASSWORD', false); } }, error => { this.creditCheckModel.isValidPIN = true; this.sharedService.showSpinner(false); // spinner this.sharedService.showErrorMessage(error, true); console.error('error=>' + error); }); } else { this.creditCheckModel.isValidPIN = false; this.sharedService.showErrorMessage('_ERR_ACCOUNT_PASSWORD_NOT_MATCH', false); } } } /** * This function is used to set mindate by getting current date * @returns string */ setMinDate(): string { const METHOD_NAME: string = 'setminDate()'; const yy = new Date().getFullYear() - 18; // const mm = new Date().getMonth() + 1; // const dd = new Date().getDate(); return yy + '-' + '12' + '-' + 31; } /** * This function is used for clearing the form elements * @returns void */ resetCreditCheck(frm: NgForm): void { const METHOD_NAME: string = 'resetCreditCheck()'; if (!this.disablePIN && !this.creditCheckModel.isValidPIN) { if (!this.cart) { this.customerForm.reset(); this.onResetForm.emit(); if (this.customerModel.creditType && this.customerModel.creditType === Constants.NOCREDIT_CHECK) { this.customerForm.form.controls.creditType.setValue(Constants.NOCREDIT_CHECK); } else { this.customerForm.form.controls.creditType.setValue(Constants.CREDIT_CHECK); } } frm.form.reset(); this.creditCheckModel = { isEmployee: false, idType: '', idIssuedState: '', isValidPIN: false, isEnglish: true }; frm.form.controls.idType.setValue(''); frm.form.controls.idState.setValue(''); frm.form.controls.isEnglish.setValue(true); frm.form.controls.isEmployee.setValue(false); this.customerService.setCustomerModel(null); } else if (this.disablePIN && this.creditCheckModel.isValidPIN) { if (frm.form.controls.ssn) { frm.form.controls.ssn.reset(); } if (frm.form.controls.employeeId) { frm.form.controls.employeeId.reset(); } frm.form.controls.dateOfBirth.reset(); frm.form.controls.idType.reset(); frm.form.controls.idType.setValue(''); frm.form.controls.idState.reset(); frm.form.controls.idState.setValue(''); frm.form.controls.idNumber1.reset(); frm.form.controls.isEmployee.setValue(false); frm.form.controls.isEnglish.setValue(true); } } /** * This function is used set the state as empty when selected id type US Alien ID * @param {any} idSelected - contains the selected ID * @returns void */ idTypeChanged(idSelected: any): void { if (idSelected === 'ALIE' || idSelected === 'MILI') { this.creditCheckModel.idIssuedState = ''; } } }