import { Injectable } from '@angular/core'; import { BehaviorSubject , Observable } from 'rxjs'; // import { Http, Headers, RequestOptions, Response } from '@angular/http'; import { HttpClient } from '@angular/common/http'; // for debugging import { ERROR_LIST } from './error.constants'; import * as Constants from './constants'; import { RETURN_ITEM_REASONS, ISSUE_CREDIT_REASONS } from './form.constants' import Utils from './utils'; import { IDevice, IAccessory, IInventoryStatus } from './modal/common'; import { Customer } from './modal/customer'; import { TEMPLATE_TYPES, CUSTOMER_INTENT } from '../shared/form.constants'; import { UserService } from '../services/user.service'; import { CartService } from '../services/cart.service'; import { CustomerService } from '../services/customer.service'; import { LookupService } from '../services/lookup.service'; import { CatalogService } from '../services/catalog.service'; import { TradeinService } from '../services/tradein.service'; import { CheckoutService } from '../services/checkout.service'; import { LoggingService } from '../services/logging.service'; import { Cart } from './modal/cart'; import { IDormantProperties } from './modal/common'; import { Router } from '@angular/router'; /** * This class provides the Shared service with global methods to access throught out the application. */ @Injectable({providedIn:'root'}) export class SharedService { private COMPONENT_NAME: string = 'SharedService'; public spinnerStatus: BehaviorSubject = new BehaviorSubject(false); public showSidebarStatus: BehaviorSubject = new BehaviorSubject(true); public showMincartStatus: BehaviorSubject = new BehaviorSubject(false); public storeId: BehaviorSubject = new BehaviorSubject(Constants.STORE_ID_CD); public creditChoice: BehaviorSubject = new BehaviorSubject(Constants.DEFAULT_CREDIT); public errorMessage: BehaviorSubject = new BehaviorSubject(null); public clearAllStatus: BehaviorSubject = new BehaviorSubject(false); public coverageStatus: BehaviorSubject = new BehaviorSubject(false); tradeInValidate: any = []; // to validate whether tradeinoffer is valid or not. requestParams: any; dormantProperties: any; notificationModel: any = {}; surveyEnabled: boolean; invalidAdress: boolean = false; isExchangeEipPackage:boolean = false; creditIssueItems: any; isShippingCreditable:boolean = true; /** * Creates a new UserService with the injected Http. * @param {HttpClient} http - The injected Http. * @constructor */ constructor( public router: Router, public http: HttpClient, public userService: UserService, public cartService: CartService, public customerService: CustomerService, public lookupService: LookupService, public catalogService: CatalogService, public tradeinService: TradeinService, public checkoutService: CheckoutService, public loggingService: LoggingService) { const user = this.userService.getUser(); // refresh browser case if (user && user.channels) { for (const channel of user.channels) { if (channel.active) { this.updateStoreId(channel.storeId); break; } } } } get rateplanTypes(): any[] { return TEMPLATE_TYPES.filter(tempItem => { return (tempItem.key != 'MILITARY'); }); } get estimateEmailType(): any[] { return CUSTOMER_INTENT.filter(tempItem => { return (tempItem.key != 'BASE'); }); } showSpinner(value: boolean) { if (value) { this.updateErrorMessage(null); } this.spinnerStatus.next(value); } showSidebar(value: boolean) { this.showSidebarStatus.next(value); } showMinicart(value: boolean) { this.showMincartStatus.next(value); } // Updates the store Id on change. updateStoreId(value: number) { this.storeId.next(value); } updateCreditChoice(value: string) { this.creditChoice.next(value); } updateErrorMessage(value: any) { this.errorMessage.next(value); } showErrorMessage(errors: any, errorKey: boolean): void { this.updateErrorMessage(errors ? errors : errorKey) } showClearAll(value: boolean) { this.clearAllStatus.next(value); } showCoverage(value: boolean) { this.coverageStatus.next(value); } setTradeInValidate(value: any) { this.tradeInValidate.push(value); } getTradeInValidate(): any { if (this.tradeInValidate && this.tradeInValidate.length > 0) { for (let trade of this.tradeInValidate) { return (trade && !trade.isValid) ? false : true; } } else { return true; } } updateTradeInList(val: any): void { this.tradeInValidate = val; } getAllPromoAndQuoteLists(): any { return this.tradeInValidate; } getDormantProperties(): IDormantProperties { if (this.dormantProperties) { return this.dormantProperties; } else { return Utils.getDormantProperties(); } } /**Sets the master gsm rateplans */ setDormantProperties(properties: IDormantProperties) { this.dormantProperties = properties; Utils.storeDormantProperties(properties); } setAppDefault(): void { const METHOD_NAME: string = 'setAppDefault()'; this.showSpinner(false); // this.showSidebar(true); // this.showMinicart(false); this.showMinicart(false); this.showCoverage(false); // this.updateTaxRate(0); // to set the taxrate to 0 on logout or clear session this.showCoverage(false); this.updateErrorMessage(null); this.updateCreditChoice(Constants.DEFAULT_CREDIT); } clearSessionStorage(clearUser: boolean): void { const METHOD_NAME: string = 'clearSessionStorage()'; if (clearUser) { this.lookupService.setOrder(null); this.lookupService.setOrderList(null); this.cartService.setCart(null); this.cartService.setReturnCart(null); this.customerService.setCustomer(null); this.customerService.setCustomerModel(null); this.lookupService.setOrderSearchModel(null); sessionStorage.clear(); localStorage.clear(); } else { this.lookupService.setOrder(null); this.lookupService.setOrderList(null); this.cartService.setCart(null); this.cartService.setReturnCart(null); this.customerService.setCustomer(null); this.customerService.setCustomerModel(null); this.lookupService.setOrderSearchModel(null); } } clearLocalStorage(): void { const METHOD_NAME: string = 'clearLocalStorage()'; this.catalogService.setGSMRateplans(null); this.catalogService.setGSMRateplanFilters(null); this.catalogService.setGSMDevices(null); this.catalogService.setGSMDeviceFilters(null); this.catalogService.setMIRateplans(null); this.catalogService.setMIRateplanFilters(null); this.catalogService.setMIDevices(null); this.catalogService.setMIDeviceFilters(null); this.catalogService.setFeatures(null); this.catalogService.setFeatureFilters(null); this.catalogService.setAccessories(null); this.catalogService.setAccessoryFilters(null); this.catalogService.setInventoryList(null); this.tradeinService.setTradeInDevices(null); this.customerService.setCreditDetails(null); this.checkoutService.setPaymentPublicKey(null); this.setDormantProperties(null); } initializeCatalog(): void { const METHOD_NAME: string = 'initializeCatalog()'; console.log('Initializing the catalog data'); console.log('Initializing the catalog data>>>gsm rate plans.'); let channelId: number = this.storeId.value; // Start-Switch Channel-Store id update const logonTime: Date = new Date(this.userService.getUser().logonTime); if (channelId !== Constants.STORE_ID_RT && !this.catalogService.getInventoryList()) { console.log('Getting the inventory status for products.'); // this.sharedService.showSpinner(true);//spinner this.catalogService.getInventoryStatus(channelId).subscribe(result => { // this.sharedService.showSpinner(false);//spinner this.catalogService.setInventoryList(result); this.updateInventoryStatus(); }, error => { // this.sharedService.showSpinner(false);//spinner console.error('error=>' + error); console.log('Error occurred while loading the inventory status for products.'); }); } // End-Switch Channel-Store id update if (!this.catalogService.getGSMRateplans()) { console.log('Getting the master rateplans.'); // this.sharedService.showSpinner(true);//spinner this.catalogService.getRateplanList(channelId, Constants.PRODUCT_TYPE_GSM).subscribe(result => { // this.sharedService.showSpinner(false);//spinner // setting line count for dropdown if (result && result.length > 0) { for (const product of result) { product.selectedLines = product.minimumLines; } this.catalogService.setGSMRateplans(result); } }, error => { // this.sharedService.showSpinner(false);//spinner console.error('error=>' + error); console.log('Error occurred while loading the master catalog for GSM rateplans.'); }); } console.log('Initializing the catalog data>>>mi rate plans.'); if (!this.catalogService.getMIRateplans()) { console.log('Getting the master rateplans.'); // this.sharedService.showSpinner(true);//spinner this.catalogService.getRateplanList(channelId, Constants.PRODUCT_TYPE_DATA).subscribe(result => { // this.sharedService.showSpinner(false);//spinner // setting line count for dropdown if (result && result.length > 0) { for (const product of result) { product.selectedLines = product.minimumLines; } this.catalogService.setMIRateplans(result); } }, error => { // this.sharedService.showSpinner(false);//spinner console.error('error=>' + error); console.log('Error occurred while loading the master catalog for MI rateplans.'); }); } console.log('Initializing the catalog data>>>gsm devices.'); if (!this.catalogService.getGSMDevices()) { console.log('Getting the master devices.'); // this.sharedService.showSpinner(true);//spinner this.catalogService.getDeviceList(channelId, Constants.PRODUCT_TYPE_GSM).subscribe(result => { // this.sharedService.showSpinner(false);//spinner // setting local use if (result && result.length > 0) { const products = Utils.excludeProductItems(result, logonTime); if (products) { this.catalogService.setGSMDevices(products); this.updateInventoryStatus(); } } }, error => { // this.sharedService.showSpinner(false);//spinner console.error('error=>' + error); console.log('Error occurred while loading the master catalog for GSM devices.'); }); } console.log('Initializing the catalog data>>>mi devices.'); if (!this.catalogService.getMIDevices()) { console.log('Getting the master devices.'); // this.sharedService.showSpinner(true);//spinner this.catalogService.getDeviceList(channelId, Constants.PRODUCT_TYPE_DATA).subscribe(result => { // this.sharedService.showSpinner(false);//spinner // setting local use if (result && result.length > 0) { const products = Utils.excludeProductItems(result, logonTime); if (products) { this.catalogService.setMIDevices(products); this.updateInventoryStatus(); } } }, error => { // this.sharedService.showSpinner(false);//spinner console.error('error=>' + error); console.log('Error occurred while loading the master catalog for MI devices.'); }); } console.log('Initializing the catalog data>>>features.'); if (!this.catalogService.getFeatures()) { console.log('Getting the master features.'); // this.sharedService.showSpinner(true);//spinner this.catalogService.getFeatureList(channelId).subscribe(result => { // this.sharedService.showSpinner(false);//spinner // setting local use if (result && result.length > 0) { this.catalogService.setFeatures(result); } }, error => { // this.sharedService.showSpinner(false);//spinner console.error('error=>' + error); console.log('Error occurred while loading the master catalog for features.'); }); } console.log('Initializing the catalog data>>>accessories.'); if (!this.catalogService.getAccessories()) { console.log('Getting the master accessories.'); // this.sharedService.showSpinner(true);//spinner this.catalogService.getAccessoryList(channelId).subscribe(result => { // this.sharedService.showSpinner(false);//spinner // setting local use if (result && result.length > 0) { const products = Utils.excludeProductItems(result, logonTime); if (products) { this.catalogService.setAccessories(products); this.updateInventoryStatus(); } } }, error => { // this.sharedService.showSpinner(false);//spinner console.error('error=>' + error); console.log('Error occurred while loading the master catalog for accessories.'); }); } console.log('Initializing the catalog data>>>master gsm rateplan filters.'); if (!this.catalogService.getGSMRateplanFiletrs()) { console.log('Getting the master rateplan filters.'); // this.sharedService.showSpinner(true);//spinner this.catalogService.getRateplanFilterList(channelId, Constants.PRODUCT_TYPE_GSM).subscribe(result => { // this.sharedService.showSpinner(false);//spinner // setting isChecked flag as fasle for each item if (result && result.length > 0) { for (const filter of result) { if (filter && filter.items) { for (const item of filter.items) { item.isChecked = false; } } } this.catalogService.setGSMRateplanFilters(result); } }, error => { // this.sharedService.showSpinner(false);//spinner console.error('error=>' + error); console.log('Error occurred while loading the master catalog for GSM rateplan filters.'); }); } console.log('Initializing the catalog data>>>master mi rateplan filters.'); if (!this.catalogService.getMIRateplanFiletrs()) { console.log('Getting the master rateplan filters.'); // this.sharedService.showSpinner(true);//spinner this.catalogService.getRateplanFilterList(channelId, Constants.PRODUCT_TYPE_DATA).subscribe(result => { // this.sharedService.showSpinner(false);//spinner // setting isChecked flag as fasle for each item if (result && result.length > 0) { for (const filter of result) { if (filter && filter.items) { for (const item of filter.items) { item.isChecked = false; } } } this.catalogService.setMIRateplanFilters(result); } }, error => { // this.sharedService.showSpinner(false);//spinner console.error('error=>' + error); console.log('Error occurred while loading the master catalog for MI rateplan filters.'); }); } console.log('Initializing the catalog data>>>master device filters.'); if (!this.catalogService.getGSMDeviceFiletrs()) { console.log('Getting the master device filters.'); // this.sharedService.showSpinner(true);//spinner this.catalogService.getDeviceFilterList(channelId, Constants.PRODUCT_TYPE_GSM).subscribe(result => { // this.sharedService.showSpinner(false);//spinner // setting isChecked flag as fasle for each item if (result && result.length > 0) { for (const filter of result) { if (filter && filter.items) { for (const item of filter.items) { item.isChecked = false; } } } this.catalogService.setGSMDeviceFilters(result); } }, error => { // this.sharedService.showSpinner(false);//spinner console.error('error=>' + error); console.log('Error occurred while loading the master catalog for GSM device filters.'); }); } console.log('Initializing the catalog data>>>master mi device filters.'); if (!this.catalogService.getMIDeviceFiletrs()) { console.log('Getting the master device filters.'); // this.sharedService.showSpinner(true);//spinner this.catalogService.getDeviceFilterList(channelId, Constants.PRODUCT_TYPE_DATA).subscribe(result => { // this.sharedService.showSpinner(false);//spinner // setting isChecked flag as fasle for each item if (result && result.length > 0) { for (const filter of result) { if (filter && filter.items) { for (const item of filter.items) { item.isChecked = false; } } } this.catalogService.setMIDeviceFilters(result); } }, error => { // this.sharedService.showSpinner(false);//spinner console.error('error=>' + error); console.log('Error occurred while loading the master catalog for MI device filters.'); }); } console.log('Initializing the catalog data>>>master feature filters.'); if (!this.catalogService.getFeatureFiletrs()) { console.log('Getting the master feature filters.'); // this.sharedService.showSpinner(true);//spinner this.catalogService.getFeatureFilterList(channelId).subscribe(result => { // this.sharedService.showSpinner(false);//spinner // setting isChecked flag as fasle for each item if (result && result.length > 0) { for (const filter of result) { if (filter && filter.items) { for (const item of filter.items) { item.isChecked = false; } } } this.catalogService.setFeatureFilters(result); } }, error => { // this.sharedService.showSpinner(false);//spinner console.error('error=>' + error); console.log('Error occurred while loading the master catalog for feature filters.'); }); } console.log('Initializing the catalog data>>>master feature filters.'); if (!this.catalogService.getAccessoryFiletrs()) { console.log('Getting the master accessory filters.'); // this.sharedService.showSpinner(true);//spinner this.catalogService.getAccessoryFilterList(channelId).subscribe(result => { // this.sharedService.showSpinner(false);//spinner // setting isChecked flag as fasle for each item if (result && result.length > 0) { for (const filter of result) { if (filter && filter.items) { for (const item of filter.items) { item.isChecked = false; } } } this.catalogService.setAccessoryFilters(result); } }, error => { // this.sharedService.showSpinner(false);//spinner console.error('error=>' + error); console.log('Error occurred while loading the master catalog for accessory filters.'); }); } console.log('Initializing the TradeInDevice list>>>master device data.'); if (!this.tradeinService.getTradeInDevices()) { console.log('Getting the master tradein device data.'); // this.sharedService.showSpinner(true);//spinner this.tradeinService.byProgramType(channelId, 111111, 1111111).subscribe(result => { // this.sharedService.showSpinner(false);//spinner if (result) { this.tradeinService.setTradeInDevices(result); } }, error => { // this.sharedService.showSpinner(false);//spinner console.error('error=>' + error); console.log('Error occurred while loading the Tradein Devices list .'); }); } console.log('Initializing the payment public key.'); if (channelId !== Constants.STORE_ID_RT) { console.log('Getting the payment public key.'); // this.sharedService.showSpinner(true);//spinner this.checkoutService.getPublicKey(channelId, 1234567890).subscribe(result => { // this.sharedService.showSpinner(false);//spinner if (result) { this.checkoutService.setPaymentPublicKey(result); } }, error => { // this.sharedService.showSpinner(false);//spinner console.error('error=>' + error); console.log('Error occurred while loading the payment public key.'); }); } console.log('Initializing the Dorman Flag fro different Projects >>>'); if (!this.getDormantProperties()) { console.log('Getting the Domran Flag.'); // this.sharedService.showSpinner(true);//spinner this.userService.getDormantProperties(channelId).subscribe(result => { // this.sharedService.showSpinner(false);//spinner if (result) { this.setDormantProperties(result); } }, error => { // this.sharedService.showSpinner(false);//spinner console.error('error=>' + error); console.log('Error occurred while loading the dormant flag.'); }); } } /** updates the inventory status for products */ updateInventoryStatus(): void { const METHOD_NAME: string = 'updateInventoryStatus()'; const inventoryStatus: IInventoryStatus[] = this.catalogService.getInventoryList(); if (inventoryStatus && inventoryStatus.length > 0) { // updating the GSM device inventory status const deviceGSMList: Array = this.catalogService.getGSMDevices(); if (deviceGSMList && deviceGSMList.length > 0) { for (const product of deviceGSMList) { for (const item of product.items) { const invItem: any = inventoryStatus.filter((data) => data.itemId === item.itemId); if (invItem != null && invItem.length > 0) { item.status = invItem[0].statusCode; // item.quantity = invItem[0].quantity; item.shipDateFrom = invItem[0].shipDateFrom; item.shipDateTo = invItem[0].shipDateTo; // item.inventoryFlag = invItem[0].inventoryFlag; } else { // please don't remove below console log console.log('No inventory found:' + item.itemId); item.status = Constants.OUTOFSTOCK_CODE; } if (item.isByos) { // console.log('it is byos device.'); item.status = Constants.INSTOCK_CODE; } } } // console.log('updated inventory for gsm devices.'); this.catalogService.setGSMDevices(deviceGSMList); } // updating the MI device inventory status const deviceMIList: Array = this.catalogService.getMIDevices(); if (deviceMIList && deviceMIList.length > 0) { for (const product of deviceMIList) { for (const item of product.items) { const invItem: any = inventoryStatus.filter((data) => data.itemId === item.itemId); if (invItem != null && invItem.length > 0) { item.status = invItem[0].statusCode; // item.quantity = invItem[0].quantity; item.shipDateFrom = invItem[0].shipDateFrom; item.shipDateTo = invItem[0].shipDateTo; // item.inventoryFlag = invItem[0].inventoryFlag; } else { // please don't remove below console log console.log('No inventory found:' + item.itemId); item.status = Constants.OUTOFSTOCK_CODE; } if (item.isByos) { // console.log('it is byos device.'); item.status = Constants.INSTOCK_CODE; } } } // console.log('updated inventory for mi devices.'); this.catalogService.setMIDevices(deviceMIList); } // updating the MI device inventory status const accessoryList: Array = this.catalogService.getAccessories(); if (accessoryList && accessoryList.length > 0) { for (const product of accessoryList) { for (const item of product.items) { const invItem: any = inventoryStatus.filter((data) => data.itemId === item.itemId); if (invItem != null && invItem.length > 0) { item.status = invItem[0].statusCode; // item.quantity = invItem[0].quantity; item.shipDateFrom = invItem[0].shipDateFrom; item.shipDateTo = invItem[0].shipDateTo; // item.inventoryFlag = invItem[0].inventoryFlag; } else { // please don't remove below console log console.log('No inventory found:' + item.itemId); item.status = Constants.OUTOFSTOCK_CODE; } } } // console.log('updated inventory for accessories.'); this.catalogService.setAccessories(accessoryList); } // console.log('Inventory status got updated.'); } } getAllTradeinInfo(storeId: number, orderId: number) { const METHOD_NAME: string = 'getAllTradeinInfo()'; this.tradeinService.getAllTradeinInfo(storeId, orderId).subscribe(result => { this.tradeinService.saveTradeInInfo(null, result.tradeInInfo); }, error => { console.error('error=>' + error); }); } getTradeinList(storeId: number, orderId: number) { this.getAllTradeinInfo(storeId, orderId); return (this.tradeinService.getTradeInInfo()); } addOrderNotes(storeId: number, orderId: number, requestParams: any): void { const METHOD_NAME: string = 'addOrderNotes()'; //making sure logonId is lower case if (requestParams && requestParams.agentId) { requestParams.agentId = requestParams.agentId.toLowerCase(); } this.lookupService.createOrderNotes(storeId, orderId, requestParams).subscribe(result => { console.log('created order note>>>>' + result); }, error => { this.showErrorMessage(error, true); console.error('error=>' + error); }); } addLogging(componentName: string, methodName: string, comments: string): void { const METHOD_NAME: string = 'addLogging()'; let loggingText: string = 'tmDASHLogging :UITracking|storeId :' + this.storeId.value; if (this.userService.getUser()) { loggingText += '|userId :' + this.userService.getUser().userId; } if (this.cartService.getCart()) { const cart: Cart = this.cartService.getCart(); loggingText += '|orderId :' + cart.orderId; loggingText += '|status :' + cart.status; if (cart.customer && cart.customer.creditProfile && cart.customer.creditProfile.accountNumber) { loggingText += '|accountNumber :' + cart.customer.creditProfile.accountNumber; } } else { if (this.customerService.getCustomer()) { loggingText += '|accountNumber :' + this.customerService.getCustomer().creditProfile.accountNumber; } if (this.lookupService.getOrder()) { loggingText += '|orderId :' + this.lookupService.getOrder().orderId; loggingText += '|status :' + this.lookupService.getOrder().status; } } if (comments) { loggingText += '|action :' + comments; } console.log(componentName + '.' + methodName + '>>' + loggingText); if (true) { const inputData: any = { application: 'DASH', component: componentName + '.' + methodName, action: loggingText } this.loggingService.addLogging(inputData).subscribe(result => { console.log('added log into server>>>>' + result); }, error => { // this.showErrorMessage(error, null); console.error('error=>' + error); }); } } getErrorKey(errors: any): string { let errorKey: string; if (errors && typeof (errors) === 'string') { try { if (errors.indexOf(' {') !== -1) { const error = JSON.parse(errors.substring(errors.indexOf(' {'))).errors[0]; errorKey = error.errorKey; } else { errorKey = errors; } } catch (err) { errorKey = '_ERR_GENERIC'; } } return errorKey; } getErrorMessage(errors: any): string { let errorMessage: string; if (errors && typeof (errors) === 'string') { try { errorMessage = Utils.getErrorValue(errors); if (errors.indexOf(' {') !== -1) { const error = JSON.parse(errors.substring(errors.indexOf(' {'))).errors[0]; errorMessage = Utils.getErrorValue(error.errorKey); } if (!errorMessage) { errorMessage = errors; } } catch (err) { if (!errorMessage) { errorMessage = errors; } } } return errorMessage; } // @mani ==> Function to clear all the selected checkboxes while close button on the compare modal is clicked clearAllSelected(arrayToDoClearOperation) { const METHOD_NAME: string = 'clearAllSelected()'; arrayToDoClearOperation.forEach(accessoriesArray => { accessoriesArray.forEach(accessory => { accessory.items.forEach(accessoryItem => { accessoryItem.isCompare = false; }); }) }); return arrayToDoClearOperation; } // @Suman ==> Restrict user to enter aplhabets and special characters keypresshandler(event) { const METHOD_NAME: string = 'keypresshandler()'; const charCode = event.keyCode; if (charCode > 31 && (charCode < 48 || charCode > 57)) { event.preventDefault(); } } // restricting copy paste if month > 12 pasteHandler(event: any): void { let key: any; key = event.clipboardData.getData('Text'); // restricts user to copy paste dd when dd > 12 if (event.clipboardData.getData('Text').slice(0, 2) > 12) { event.preventDefault(); } // restricts user to copy paste 2nd position in dd if dd> 12 if (event.currentTarget.value.slice(2, 3) === '/' && event.currentTarget.value.slice(3, 5).length === 2 && key > 2) { event.preventDefault(); } } validate(dateType: string, date: any): number { const METHOD_NAME: string = 'validate()'; if (date) { const dateLatest = date; if (dateLatest.indexOf('/') > -1) { date = dateLatest.replace(new RegExp('/', 'g'), ''); } if (dateType === 'mmddyyyy') { const currentDay: any = new Date(); const dayDOB: any = new Date(date.slice(0, 2) + '/' + date.slice(2, 4) + '/' + date.slice(4, 8)); const ageDiff: any = currentDay.getFullYear() - (date.slice(4, 8)); if (currentDay.getFullYear() - dayDOB.getFullYear() === 18) { // Reset year of birthday to the current year. dayDOB.setFullYear(currentDay.getFullYear()); if (currentDay < dayDOB) { return (date.length === 8 ? (ageDiff - 1) : 0); } else { return (date.length === 8 ? (ageDiff) : 0); } } else { return (date.length === 8 ? (ageDiff) : 0); } } else { if ((new Date().getFullYear()) - (date.slice(2, 7)) === 0) {// === which accept the current year if ((new Date().getMonth() + 1) - (date.slice(0, 2)) <= 0) { // <= which accept the current month if (((new Date().getMonth() + 1) - (date.slice(0, 2)) === 0)) { // check for current month return 1; } else { return ((date.slice(2, 7)) - (new Date().getFullYear())); } } else { return -1; } } else { return ((date.slice(2, 7)) - (new Date().getFullYear())); } } // else if (dateType === 'mmyy') { // let currentyear : any ; // currentyear= new Date().getFullYear().toString(); // if ((currentyear.slice(2,4)) - (date.slice(2, 4)) === 0) {//=== which accept the current year // if ((new Date().getMonth()+1) - (date.slice(0,2)) <= 0) { //<= which accept the current month // if(((new Date().getMonth()+1) - (date.slice(0,2)) === 0)) { //check for current month // return 1; // } else { // return ((date.slice(2, 4)) - (currentyear.slice(2,4))); // } // } else { // return -1; // } // } else { // return ((date.slice(2, 4)) - (currentyear.slice(2,4))); // } // } } } monthOfExpiration(exprationDate: any): number { if (exprationDate) { return exprationDate.slice(0, 2); } } checkFormat(phoneNumber: string): boolean { if (phoneNumber && (phoneNumber.indexOf('-') > -1 || phoneNumber.indexOf('/') > -1)) { return true; } else { return false; } } fieldsOfDateOfBirth(date: any, pos1: number, pos2): number { if (date) { return date.substring(pos1, pos2); } } showErrorDownPaymentAdjusted(isDownPaymentAdjusted: boolean): string { if (isDownPaymentAdjusted) { return this.getErrorMessage('_ERR_ERROR_ECALIMIT'); } } /** * call generate token service */ generateMemo(storeId: any, cartSummary: any, trackingNumber: any, memoType: string): void { const METHOD_NAME = 'generateMemo()'; let originalCart: any = this.lookupService.getOrder(); let reason: any; let accountNumber = (cartSummary.customerInfo.creditProfile.accountNumber) ? cartSummary.customerInfo.creditProfile.accountNumber : (cartSummary.customerInfo && cartSummary.customerInfo.creditProfile && cartSummary.customerInfo.creditProfile.tentativeBAN) ? cartSummary.customerInfo.creditProfile.tentativeBAN : null; if (cartSummary.packages) { for (let cartPack of cartSummary.packages) { // for (let originalPack of originalCart.packages) { if (cartPack.device && cartPack.device.itemId) { if (cartPack.device.reason) { reason = cartPack.device.reason; } else if (cartPack.device.returnReason) { reason = cartPack.device.returnReason; } else if (cartPack.device.issueCreditReason) { reason = cartPack.device.issueCreditReason; } if (reason != null || memoType === 'resend') { this.callGenerateMemo(storeId, cartPack.device.name, cartPack.device.imei, reason, cartPack.device.finalPrice, accountNumber, cartSummary, trackingNumber, memoType); } } else if (cartPack.accessories && cartPack.accessories.length > 0) { // for (let originalAcc of cartPack.accessories) { for (let acc of cartPack.accessories) { if (acc.itemId && acc.itemId) { if (acc.reason != null) { reason = acc.reason; } else if (acc.returnReason != null) { reason = acc.returnReason; } else if (acc.issueCreditReason != null) { reason = acc.issueCreditReason; } if (reason != null || memoType === 'resend') { this.callGenerateMemo(storeId, acc.name, null, reason, acc.finalPrice, accountNumber, cartSummary, trackingNumber, memoType); } } } // } } // } } } //create memo for shipping refund as well if (cartSummary['shippingReason']) { let shippingAmount = cartSummary.totalShippingDueToday + cartSummary.totalShippingTaxDueToday this.callGenerateMemo(storeId, null, null, cartSummary['shippingReason'], shippingAmount, accountNumber, cartSummary, trackingNumber, memoType); } } /** *@param storeId * @param returnCartSummary * @param deviceSku * @param serialNumber * @param reason * @param creditAmount */ callGenerateMemo(storeId: number, name: string, imei: string, reason: string, creditAmount: number, accountNumber: any, returnCartSummary: any, trackingNumber: string, memoType: string): void { // create memo in samson system let memoInputParam: any = {}; let dealercode: any; let memoText: any; let memoCode: any; let memoCodeVal: any; let email: any; if (returnCartSummary && returnCartSummary.dealerCode) { dealercode = (returnCartSummary.dealerCode.length === 8) ? (returnCartSummary.dealerCode.substr(1)) : returnCartSummary.dealerCode; } else if (returnCartSummary && returnCartSummary.agentDealerCode) { dealercode = (returnCartSummary.agentDealerCode.length === 8) ? (returnCartSummary.agentDealerCode.substr(1)) : returnCartSummary.agentDealerCode; } else { dealercode = '0000000'; } if (memoType != null && memoType === 'resend') { let reasonText = RETURN_ITEM_REASONS.filter(reasonItem => reasonItem); for (let rs of reasonText) { if (rs.key === reason) { reason = rs.value }; } memoCode = Constants.MEMO_RESEND_CODE; memoCodeVal = Constants.MEMO_RESEND_CODE_VALUE; email = returnCartSummary.customerInfo.email2 ? returnCartSummary.customerInfo.email2 : returnCartSummary.customerInfo.email1 ? returnCartSummary.customerInfo.email1 : null; memoText = 'The customer has requested that the return label for their coverage solution with Serial Number' + imei + ' be resent. This resend was sent to the following email address' + email; memoText = memoText + ' Order Number ' + returnCartSummary.fullOrderId + '. This label resend was completed by ' + returnCartSummary.createdBy + ' on' + '. Tracking Number is ' + trackingNumber } else if (returnCartSummary.refType === Constants.REF_TYPE_CREDIT) { let reasonText = ISSUE_CREDIT_REASONS.filter(reasonItem => reasonItem); for (let rs of reasonText) { if (rs.key === reason) { reason = rs.value }; } memoCode = Constants.MEMO_REFUND_CODE; memoCodeVal = Constants.MEMO_REFUND_CODE_VALUE; if (returnCartSummary.paymentInfo) { memoText = returnCartSummary.totalDueToday + ' Credit for transaction ' + returnCartSummary.originalOrderId + ' has been processed on ' + returnCartSummary.paymentInfo.paymentType + ' ending in ' + returnCartSummary.paymentInfo.ccAlias + '.Your reference # is ' + returnCartSummary.fullOrderId; } } else if (returnCartSummary.refType === Constants.REF_TYPE_RETURN) { let reasonText = RETURN_ITEM_REASONS.filter(reasonItem => reasonItem); for (let rs of reasonText) { if (rs.key === reason) { reason = rs.value; } } memoCode = Constants.MEMO_RETURN_CODE; memoCodeVal = Constants.MEMO_RETURN_CODE_VALUE; memoText = 'Return order ' + returnCartSummary.fullOrderId + ' has been processed for ' + name; if (imei != null && imei !== 'N/A' && trackingNumber != null) { memoText = memoText + ' and ' + imei + ' due to ' + reason + '. Return tracking label ' + trackingNumber + ' has been generated.' } else if (trackingNumber != null) { memoText = memoText + ' due to ' + reason + '. Return tracking label ' + trackingNumber + ' has been generated.' } } memoInputParam = { accountNumber: accountNumber, dealerCode: dealercode, refType: returnCartSummary.refType, orderId: returnCartSummary.fullOrderId, // cardType: returnCartSummary.paymentInfo.cardType, // lastFourDigit: returnCartSummary.paymentInfo.lastFour, // originalOrderId: returnCartSummary.originalOrderId, // serialNumber: imei, // makeModel: name, // reason: reason, // creditAmount: creditAmount, memoText: memoText, memoCode: memoCode, memoCodeValue: memoCodeVal, orderCreateDate: returnCartSummary.createdByDate, // returnTrackingNumber: trackingNumber } if (accountNumber) { this.showSpinner(true); this.customerService.generateMemo(storeId, returnCartSummary.orderId, memoInputParam).subscribe(result => { // this.showSpinner(false); // spinner }, error => { this.orderAddNote(storeId, returnCartSummary, name, imei, reason, trackingNumber); // this.showSpinner(false); // spinner // this.sharedService.showErrorMessage(error, true); // console.error('error=>' + error); }); } else { this.orderAddNote(storeId, returnCartSummary, name, imei, reason, trackingNumber); //this.showSpinner(false); } } orderAddNote(storeId: any, returnCartSummary: any, name: any, imei: any, reason: any, trackingNumber: any): void { const METHOD_NAME: string = 'orderAddNote()'; let desc: any; if (imei && imei !== 'N/A') { desc = ' and ' + imei + ' due to ' + reason + '. Return tracking label ' + trackingNumber + ' has been generated.' } else { desc = ' due to ' + reason + '. Return tracking label ' + trackingNumber + ' has been generated.' } this.addLogging(this.COMPONENT_NAME, METHOD_NAME, 'Adding order notes returnCartSummary'); if (returnCartSummary) { const requestParams: any = { agentId: this.userService.getUser().logonId, subject: 'Return', description: 'Return order ' + returnCartSummary.fullOrderId + ' has been processed for ' + name + desc } this.lookupService.createOrderNotes(storeId, returnCartSummary.orderId, requestParams).subscribe(result => { }, error => { this.showErrorMessage(error, true); console.error('error=>' + error); }); } } isSurveyEnabledForCurrentChannel(): boolean { const user = this.userService.getUser(); let surveyEnabled = false; if (user && user.channels) { for (const channel of user.channels) { if (channel.active) { if (channel.name === 'Retail' && user.isRetailSurveyEnabled || channel.name === 'Consumer Direct' && user.isCDSurveyEnabled || channel.name === 'Business Direct' && user.isBDSurveyEnabled || channel.name === 'Customer Service Care' && user.isCSSurveyEnabled) { surveyEnabled = true; } break; } } } return surveyEnabled; } showSurveyModal(modal: any, storeId: number, userId: number): void { const cart: Cart = this.cartService.getCart(); // this.clearSessionStorage(false); if (this.isSurveyEnabledForCurrentChannel()) { this.cartService.getSurveyStatus(storeId, userId).subscribe(result => { if ( result.isSurveyEnabled ) { modal.show(cart); } else { this.router.navigate(['home/search']); } },error => { // this.clearSessionStorage(false); this.router.navigate(['home/search']); }); this.router.navigate(['home/search']); } else { this.router.navigate(['home/search']); } } initializeDevices(){ let channelId: number = this.storeId.value; if (channelId !== Constants.STORE_ID_RT && !this.catalogService.getInventoryList()) { console.log('Getting the inventory status for products.'); // this.sharedService.showSpinner(true);//spinner this.catalogService.getInventoryStatus(channelId).subscribe(result => { // this.sharedService.showSpinner(false);//spinner this.catalogService.setInventoryList(result); this.updateInventoryStatus(); }, error => { // this.sharedService.showSpinner(false);//spinner console.error('error=>' + error); console.log('Error occurred while loading the inventory status for products.'); }); } console.log('Initializing the catalog data>>>gsm devices.'); if (!this.catalogService.getGSMDevices()) { console.log('Getting the master devices.'); // this.sharedService.showSpinner(true);//spinner this.catalogService.getDeviceList(channelId, Constants.PRODUCT_TYPE_GSM).subscribe(result => { // this.sharedService.showSpinner(false);//spinner // setting local use if (result && result.length > 0) { const products = Utils.excludeProductItems(result, null); if (products) { this.catalogService.setGSMDevices(products); this.updateInventoryStatus(); } } }, error => { // this.sharedService.showSpinner(false);//spinner console.error('error=>' + error); console.log('Error occurred while loading the master catalog for GSM devices.'); }); } console.log('Initializing the catalog data>>>mi devices.'); if (!this.catalogService.getMIDevices()) { console.log('Getting the master devices.'); // this.sharedService.showSpinner(true);//spinner this.catalogService.getDeviceList(channelId, Constants.PRODUCT_TYPE_DATA).subscribe(result => { // this.sharedService.showSpinner(false);//spinner // setting local use if (result && result.length > 0) { const products = Utils.excludeProductItems(result, null); if (products) { this.catalogService.setMIDevices(products); this.updateInventoryStatus(); } } }, error => { // this.sharedService.showSpinner(false);//spinner console.error('error=>' + error); console.log('Error occurred while loading the master catalog for MI devices.'); }); } } }