import {throwError as observableThrowError} from 'rxjs'; /** * @Name: Util * @Creation Date: Aug 3, 2017 * @Author: sbaireddy * @Version: 1.0 : */ import { Headers, RequestOptions } from '@angular/http'; import { Observable } from 'rxjs/Rx'; import * as _ from 'underscore'; import * as Constants from './constants'; import { KeyValue } from './modal/key.value'; import { ERROR_LIST } from './error.constants'; import { ACT_ERROR_LIST } from './act-error.constants'; import { IRateplan, IDevice, IDeviceItem, IFeature, IAccessory, IAccessoryItem, IFilterList, IFilter, IOrderList, IInventoryStatus, IError, IDormantProperties } from './modal/common'; import { User } from './modal/user'; import { Cart } from './modal/cart'; import { Customer, ICreditProfile } from './modal/customer'; import { apiProxy } from '../generated/endpoints'; declare var jQuery: any; /** Deafult Class representing the common utils for application. */ export default class Utils { private COMPONENT_NAME: string = 'Utils'; /** Gets the request options for any rest service call. */ static getRequestOptions(): RequestOptions { const METHOD_NAME: string = 'getRequestOptions()'; // console.log('Util.getRequestOptions()>>Start'); let headers = new Headers({ 'Content-Type': 'application/json' }); // headers.append('Accept','application/json;text/html'); headers.append('Cache-Control', 'no-cache'); headers.append('X-Frame-Options', 'sameorigin'); if (sessionStorage.getItem('userId')) { headers.append('userId', sessionStorage.getItem('userId')); } if (sessionStorage.getItem('WCToken')) { headers.append('WCToken', sessionStorage.getItem('WCToken')); } if (sessionStorage.getItem('WCTrustedToken')) { headers.append('WCTrustedToken', sessionStorage.getItem('WCTrustedToken')); } if (sessionStorage.getItem('personalizationID')) { headers.append('personalizationID', sessionStorage.getItem('personalizationID')); } const options = new RequestOptions({ withCredentials: true, headers: headers }); // console.log('Util.getRequestOptions()>>End'); return options; } /** * Replace a url string with path path params. * @param url - The url string containing rest service end point. * @param pathParams - The pathParams . */ static replacePathParams(url: string, pathParams: Array) { const METHOD_NAME: string = 'replacePathParams()'; let replaceUrl: string = url; if (pathParams) { for (let i = 0; i < pathParams.length; i++) { const key = '{' + pathParams[i].getKey() + '}'; // console.log('key:'+ key +' value:'+ pathParams[i].getValue()); if (replaceUrl.indexOf(key) !== -1) { replaceUrl = replaceUrl.replace(key, pathParams[i].getValue()); } } } // console.log('Util.replacePathParams()>>Final url:'+ replaceUrl); return apiProxy + replaceUrl; } /** * Append a url string with query params. * @param url - The url string containing rest service end point. * @param queryParams - The pathParams . */ static appendQueryParams(url: string, queryParams: Array) { const METHOD_NAME: string = 'appendQueryParams()'; let appendUrl: string = url; if (queryParams) { appendUrl += '?'; for (let i = 0; i < queryParams.length; i++) { appendUrl += queryParams[i].getKey() + '=' + queryParams[i].getValue(); if (i < queryParams.length - 1) { appendUrl += '&'; } } } // console.log('Util.appendQueryParams()>>Final url:'+ appendUrl); return appendUrl; } /** * Replace and apppend a url string with path params and query params. * @param url - The url string containing rest service end point. * @param pathParams - The pathParams . * @param queryParams - The pathParams . */ static replaceAppendParams(url: string, pathParams: Array, queryParams: Array) { const METHOD_NAME: string = 'replaceAppendParams()'; let replaceAppendUrl: string = url; if (pathParams) { replaceAppendUrl = this.replacePathParams(replaceAppendUrl, pathParams); } if (queryParams && queryParams.length > 0) { replaceAppendUrl = this.appendQueryParams(replaceAppendUrl, queryParams); } // console.log('Util.replaceAppendParams()>>Final url:'+ replaceAppendUrl); return replaceAppendUrl; } /** Clears the master catalog from local cache. */ static clearMasterList(): void { const METHOD_NAME: string = 'clearMasterList()'; // console.log('Util.clearMasterList()>>Start'); // removing rateplan/filter list if (localStorage.getItem(Constants.CACHE_RATEPLAN_LIST_GSM)) { localStorage.removeItem(Constants.CACHE_RATEPLAN_LIST_GSM); } if (localStorage.getItem(Constants.CACHE_RATEPLAN_LIST_DATA)) { localStorage.removeItem(Constants.CACHE_RATEPLAN_LIST_DATA); } if (localStorage.getItem(Constants.CACHE_RATEPLAN_FILTER_LIST_GSM)) { localStorage.removeItem(Constants.CACHE_RATEPLAN_FILTER_LIST_GSM); } if (localStorage.getItem(Constants.CACHE_RATEPLAN_FILTER_LIST_DATA)) { localStorage.removeItem(Constants.CACHE_RATEPLAN_FILTER_LIST_DATA); } // removing device/filter list if (localStorage.getItem(Constants.CACHE_DEVICE_LIST_GSM)) { localStorage.removeItem(Constants.CACHE_DEVICE_LIST_GSM); } if (localStorage.getItem(Constants.CACHE_DEVICE_LIST_DATA)) { localStorage.removeItem(Constants.CACHE_DEVICE_LIST_DATA); } if (localStorage.getItem(Constants.CACHE_DEVICE_FILTER_LIST_GSM)) { localStorage.removeItem(Constants.CACHE_DEVICE_FILTER_LIST_GSM); } if (localStorage.getItem(Constants.CACHE_DEVICE_FILTER_LIST_DATA)) { localStorage.removeItem(Constants.CACHE_DEVICE_FILTER_LIST_DATA); } // removing feature/filter list if (localStorage.getItem(Constants.CACHE_FEATURE_LIST)) { localStorage.removeItem(Constants.CACHE_FEATURE_LIST); } if (localStorage.getItem(Constants.CACHE_FEATURE_FILTER_LIST)) { localStorage.removeItem(Constants.CACHE_FEATURE_FILTER_LIST); } // removing accessory/filter list if (localStorage.getItem(Constants.CACHE_ACCESSORY_LIST)) { localStorage.removeItem(Constants.CACHE_ACCESSORY_LIST); } if (localStorage.getItem(Constants.CACHE_ACCESSORY_FILTER_LIST)) { localStorage.removeItem(Constants.CACHE_ACCESSORY_FILTER_LIST); } // removing inventory list if (localStorage.getItem(Constants.CACHE_INVENTORY_LIST)) { localStorage.removeItem(Constants.CACHE_INVENTORY_LIST); } if (localStorage.getItem(Constants.CACHE_PAYMENT_PUBLIC_KEY)) { localStorage.removeItem(Constants.CACHE_PAYMENT_PUBLIC_KEY); } // console.log('Util.clearMasterList()>>End'); } /** Stroes the master rateplan list to local cache. */ static storeRateplanList(rateplanList: IRateplan[], productType: string): void { const METHOD_NAME: string = 'storeRateplanList()'; // console.log('Util.storeRateplanList()>>Start'); if (rateplanList) { if (productType === Constants.PRODUCT_TYPE_GSM) { localStorage.setItem(Constants.CACHE_RATEPLAN_LIST_GSM, JSON.stringify(rateplanList)); } else if (productType === Constants.PRODUCT_TYPE_DATA) { localStorage.setItem(Constants.CACHE_RATEPLAN_LIST_DATA, JSON.stringify(rateplanList)); } } else { if (productType === Constants.PRODUCT_TYPE_GSM) { if (localStorage.getItem(Constants.CACHE_RATEPLAN_LIST_GSM)) { localStorage.removeItem(Constants.CACHE_RATEPLAN_LIST_GSM); } } else if (productType === Constants.PRODUCT_TYPE_DATA) { if (localStorage.getItem(Constants.CACHE_RATEPLAN_LIST_DATA)) { localStorage.removeItem(Constants.CACHE_RATEPLAN_LIST_DATA); } } } // console.log('Util.storeRateplanList()>>End'); } /** Gets the master rateplan list from local cache. */ static getRateplanList(productType: string): IRateplan[] { const METHOD_NAME: string = 'getRateplanList()'; // console.log('Util.getRateplanList()>>Start'); let rateplanList: IRateplan[]; if (productType === Constants.PRODUCT_TYPE_GSM && localStorage.getItem(Constants.CACHE_RATEPLAN_LIST_GSM)) { rateplanList = JSON.parse(localStorage.getItem(Constants.CACHE_RATEPLAN_LIST_GSM)); } else if (productType === Constants.PRODUCT_TYPE_DATA && localStorage.getItem(Constants.CACHE_RATEPLAN_LIST_DATA)) { rateplanList = JSON.parse(localStorage.getItem(Constants.CACHE_RATEPLAN_LIST_DATA)); } // console.log('Util.getRateplanList()>>End'); return rateplanList; } /** Stroes the master rateplan filter list to local cache. */ static storeRateplanFilterList(rateplanFilterList: IFilterList[], productType: string): void { const METHOD_NAME: string = 'storeRateplanFilterList()'; // console.log('Util.storeRateplanFilterList()>>Start'); if (rateplanFilterList) { if (productType === Constants.PRODUCT_TYPE_GSM) { localStorage.setItem(Constants.CACHE_RATEPLAN_FILTER_LIST_GSM, JSON.stringify(rateplanFilterList)); } else if (productType === Constants.PRODUCT_TYPE_DATA) { localStorage.setItem(Constants.CACHE_RATEPLAN_FILTER_LIST_DATA, JSON.stringify(rateplanFilterList)); } } else { if (productType === Constants.PRODUCT_TYPE_GSM) { if (localStorage.getItem(Constants.CACHE_RATEPLAN_FILTER_LIST_GSM)) { localStorage.removeItem(Constants.CACHE_RATEPLAN_FILTER_LIST_GSM); } } else if (productType === Constants.PRODUCT_TYPE_DATA) { if (localStorage.getItem(Constants.CACHE_RATEPLAN_FILTER_LIST_DATA)) { localStorage.removeItem(Constants.CACHE_RATEPLAN_FILTER_LIST_DATA); } } } // console.log('Util.storeRateplanFilterList()>>End'); } /** Gets the master rateplan filter list from local cache. */ static getRateplanFilterList(productType: string): IFilterList[] { const METHOD_NAME: string = 'getRateplanFilterList()'; // console.log('Util.getRateplanFilterList()>>Start'); let rateplanFilterList: IFilterList[]; if (productType === Constants.PRODUCT_TYPE_GSM && localStorage.getItem(Constants.CACHE_RATEPLAN_FILTER_LIST_GSM)) { rateplanFilterList = JSON.parse(localStorage.getItem(Constants.CACHE_RATEPLAN_FILTER_LIST_GSM)); } else if (productType === Constants.PRODUCT_TYPE_DATA && localStorage.getItem(Constants.CACHE_RATEPLAN_FILTER_LIST_DATA)) { rateplanFilterList = JSON.parse(localStorage.getItem(Constants.CACHE_RATEPLAN_FILTER_LIST_DATA)); } // console.log('Util.getRateplanFilterList()>>End'); return rateplanFilterList; } /** Stroes the master device list to local cache. */ static storeDeviceList(deviceList: IDevice[], productType: string): void { const METHOD_NAME: string = 'storeDeviceList()'; // console.log('Util.storeDeviceList()>>Start'); if (deviceList) { if (productType === Constants.PRODUCT_TYPE_GSM) { localStorage.setItem(Constants.CACHE_DEVICE_LIST_GSM, JSON.stringify(deviceList)); } else if (productType === Constants.PRODUCT_TYPE_DATA) { localStorage.setItem(Constants.CACHE_DEVICE_LIST_DATA, JSON.stringify(deviceList)); } } else { if (productType === Constants.PRODUCT_TYPE_GSM) { if (localStorage.getItem(Constants.CACHE_DEVICE_LIST_GSM)) { localStorage.removeItem(Constants.CACHE_DEVICE_LIST_GSM); } } else if (productType === Constants.PRODUCT_TYPE_DATA) { if (localStorage.getItem(Constants.CACHE_DEVICE_LIST_DATA)) { localStorage.removeItem(Constants.CACHE_DEVICE_LIST_DATA); } } } // console.log('Util.storeDeviceList()>>End'); } /** Gets the master device list from local cache. */ static getDeviceList(productType: string): IDevice[] { const METHOD_NAME: string = 'getDeviceList()'; // console.log('Util.getDeviceList()>>Start'); let deviceList: IDevice[]; if (productType === Constants.PRODUCT_TYPE_GSM && localStorage.getItem(Constants.CACHE_DEVICE_LIST_GSM)) { deviceList = JSON.parse(localStorage.getItem(Constants.CACHE_DEVICE_LIST_GSM)); } else if (productType === Constants.PRODUCT_TYPE_DATA && localStorage.getItem(Constants.CACHE_DEVICE_LIST_DATA)) { deviceList = JSON.parse(localStorage.getItem(Constants.CACHE_DEVICE_LIST_DATA)); } // console.log('Util.getDeviceList()>>End'); return deviceList; } /** Excluding the legacy items from list*/ static excludeProductItems(products: any[], logonTime: Date): Array { if (products && products.length > 0) { return products.filter((product) => { product.itemIndex = 0; const items: any = new Array(); if(!product.items || (product.items && product.items.length === 0)){ return false; }else{ product.items.forEach(function (item, i) { if (!(item.status && item.status === 'Legacy')) { // removing the item from master list items.push(item); } }); if (items && items.length > 0) { product.items = items; }else{ return false; } } if (product && product.description) { product.descriptions = product.description.split('
'); } if (logonTime && product.startDate) { const startDate: Date = new Date(product.startDate); if (isNaN(startDate.getTime())) { // d.valueOf() could also work return true; } else { return (startDate <= logonTime); } } else { return true; } }); } return products; } /** Gets the device item from local cache. */ static getDeviceItem(deviceSKU: string): IDeviceItem { const METHOD_NAME: string = 'getDeviceItem()'; // console.log('Util.getDevice()>>Start'); const gsmDevices: IDevice[] = this.getDeviceList(Constants.PRODUCT_TYPE_GSM); if (gsmDevices && gsmDevices.length > 0) { for (const product of gsmDevices) { const items: any = product.items.filter((item) => { return item.deviceSKU === deviceSKU; }); if (items && items.length > 0) { return items[0]; } } } const miDevices: IDevice[] = this.getDeviceList(Constants.PRODUCT_TYPE_DATA); if (miDevices && miDevices.length > 0) { for (const product of miDevices) { const items: any = product.items.filter((item) => { return item.deviceSKU === deviceSKU; }); if (items && items.length > 0) { return items[0]; } } } } /** Gets the parent device item from local cache. */ static getDeviceParent(deviceSKU: string): IDevice { const METHOD_NAME: string = 'getDeviceParent()'; // console.log('Util.getDevice()>>Start'); const gsmDevices: IDevice[] = this.getDeviceList(Constants.PRODUCT_TYPE_GSM); if (gsmDevices && gsmDevices.length > 0) { for (const product of gsmDevices) { const items: any = product.items.filter((item) => { return item.deviceSKU === deviceSKU; }); if (items && items.length > 0) { return product; } } } const miDevices: IDevice[] = this.getDeviceList(Constants.PRODUCT_TYPE_DATA); if (miDevices && miDevices.length > 0) { for (const product of miDevices) { const items: any = product.items.filter((item) => { return item.deviceSKU === deviceSKU; }); if (items && items.length > 0) { return product; } } } } /** Gets the device from local cache. */ static getDevice(productId: number): IDevice { const METHOD_NAME: string = 'getDevice()'; // console.log('Util.getDevice()>>Start'); const gsmDevices: IDevice[] = this.getDeviceList(Constants.PRODUCT_TYPE_GSM); if (gsmDevices && gsmDevices.length > 0) { const productList: any = gsmDevices.filter((product) => { return product.productId === productId; }); if (productList && productList.length > 0) { return productList[0]; } } const miDevices: IDevice[] = this.getDeviceList(Constants.PRODUCT_TYPE_DATA); if (miDevices && miDevices.length > 0) { const productList: any = miDevices.filter((product) => { return product.productId === productId; }); if (productList && productList.length > 0) { return productList[0]; } } } /** Stroes the master device filter list to local cache. */ static storeDeviceFilterList(deviceFilterList: IFilterList[], productType: string): void { const METHOD_NAME: string = 'storeDeviceFilterList()'; // console.log('Util.storeDeviceFilterList()>>Start'); if (deviceFilterList) { if (productType === Constants.PRODUCT_TYPE_GSM) { localStorage.setItem(Constants.CACHE_DEVICE_FILTER_LIST_GSM, JSON.stringify(deviceFilterList)); } else if (productType === Constants.PRODUCT_TYPE_DATA) { localStorage.setItem(Constants.CACHE_DEVICE_FILTER_LIST_DATA, JSON.stringify(deviceFilterList)); } } else { if (productType === Constants.PRODUCT_TYPE_GSM) { if (localStorage.getItem(Constants.CACHE_DEVICE_FILTER_LIST_GSM)) { localStorage.removeItem(Constants.CACHE_DEVICE_FILTER_LIST_GSM); } } else if (productType === Constants.PRODUCT_TYPE_DATA) { if (localStorage.getItem(Constants.CACHE_DEVICE_FILTER_LIST_DATA)) { localStorage.removeItem(Constants.CACHE_DEVICE_FILTER_LIST_DATA); } } } // console.log('Util.storeDeviceFilterList()>>End'); } /** Gets the master device filter list from local cache. */ static getDeviceFilterList(productType: string): IFilterList[] { const METHOD_NAME: string = 'getDeviceFilterList()'; // console.log('Util.getDeviceFilterList()>>Start'); let deviceFilterList: IFilterList[]; if (productType === Constants.PRODUCT_TYPE_GSM && localStorage.getItem(Constants.CACHE_DEVICE_FILTER_LIST_GSM)) { deviceFilterList = JSON.parse(localStorage.getItem(Constants.CACHE_DEVICE_FILTER_LIST_GSM)); } else if (productType === Constants.PRODUCT_TYPE_DATA && localStorage.getItem(Constants.CACHE_DEVICE_FILTER_LIST_DATA)) { deviceFilterList = JSON.parse(localStorage.getItem(Constants.CACHE_DEVICE_FILTER_LIST_DATA)); } // console.log('Util.getDeviceFilterList()>>End'); return deviceFilterList; } /** Gets the device brands from local cache. */ static getDeviceBrands(productType: string): IFilter[] { const METHOD_NAME: string = 'getDeviceBrands()'; // console.log('Util.getDevice()>>Start'); let gsmDeviceBrands: IFilter[]; const gsmDeviceFilters: IFilterList[] = this.getDeviceFilterList(Constants.PRODUCT_TYPE_GSM); if (gsmDeviceFilters && gsmDeviceFilters.length > 0) { for (const item of gsmDeviceFilters) { if (item.type === 'Manufacturer') { gsmDeviceBrands = item.items; break; } } } if (productType && productType === Constants.PRODUCT_TYPE_GSM) { return gsmDeviceBrands } let miDeviceBrands: IFilter[]; const miDeviceFilters: IFilterList[] = this.getDeviceFilterList(Constants.PRODUCT_TYPE_DATA); if (miDeviceFilters && miDeviceFilters.length > 0) { for (const item of miDeviceFilters) { if (item.type === 'Manufacturer') { miDeviceBrands = item.items; break; } } } if (productType && productType === Constants.PRODUCT_TYPE_DATA) { return miDeviceBrands } } /** Gets the device items from local cache. */ static getDeviceItems(productIds: number[]): any { const METHOD_NAME: string = 'getDeviceItems()'; // console.log('Util.getDeviceItems()>>Start'); const deviceItems: Array = []; for (const productId of productIds) { const product: IDevice = this.getDevice(productId); if (product) { const item: any = { deviceSKU: product.items[0].deviceSKU, name: product.items[0].name } deviceItems.push(item); } } } /** Stroes the master feature list to local cache. */ static storeFeatureList(featureList: IFeature[]): void { const METHOD_NAME: string = 'storeFeatureList()'; // console.log('Util.storeFeatureList()>>Start'); if (featureList) { localStorage.setItem(Constants.CACHE_FEATURE_LIST, JSON.stringify(featureList)); } else { if (localStorage.getItem(Constants.CACHE_FEATURE_LIST)) { localStorage.removeItem(Constants.CACHE_FEATURE_LIST); } } // console.log('Util.storeFeatureList()>>End'); } /** Gets the master feature list from local cache. */ static getFeatureList(): IFeature[] { const METHOD_NAME: string = 'getFeatureList()'; // console.log('Util.getFeatureList()>>Start'); let featureList: IFeature[]; if (localStorage.getItem(Constants.CACHE_FEATURE_LIST)) { featureList = JSON.parse(localStorage.getItem(Constants.CACHE_FEATURE_LIST)); } // console.log('Util.getFeatureList()>>End'); return featureList; } /** Stroes the master feature filter list to local cache. */ static storeFeatureFilterList(featureFilterList: IFilterList[]): void { const METHOD_NAME: string = 'storeFeatureFilterList()'; // console.log('Util.storeFeatureFilterList()>>Start'); if (featureFilterList) { localStorage.setItem(Constants.CACHE_FEATURE_FILTER_LIST, JSON.stringify(featureFilterList)); } else { if (localStorage.getItem(Constants.CACHE_FEATURE_FILTER_LIST)) { localStorage.removeItem(Constants.CACHE_FEATURE_FILTER_LIST); } } // console.log('Util.storeFeatureFilterList()>>End'); } /** Gets the master feature filter list from local cache. */ static getFeatureFilterList(): IFilterList[] { const METHOD_NAME: string = 'getFeatureFilterList()'; // console.log('Util.getFeatureFilterList()>>Start'); let featureFilterList: IFilterList[]; if (localStorage.getItem(Constants.CACHE_FEATURE_FILTER_LIST)) { featureFilterList = JSON.parse(localStorage.getItem(Constants.CACHE_FEATURE_FILTER_LIST)); } // console.log('Util.getFeatureFilterList()>>End'); return featureFilterList; } /** Stroes the master accesory list to local cache. */ static storeAccessoryList(accessoryList: IAccessory[]): void { const METHOD_NAME: string = 'storeAccessoryList()'; // console.log('Util.storeAccessoryList()>>Start'); if (accessoryList) { localStorage.setItem(Constants.CACHE_ACCESSORY_LIST, JSON.stringify(accessoryList)); } else { if (localStorage.getItem(Constants.CACHE_ACCESSORY_LIST)) { localStorage.removeItem(Constants.CACHE_ACCESSORY_LIST); } } // console.log('Util.storeAccessoryList()>>End'); } /** Gets the master accessory list from local cache. */ static getAccessoryList(): IAccessory[] { const METHOD_NAME: string = 'getAccessoryList()'; // console.log('Util.getAccessoryList()>>Start'); const accessoryList: IAccessory[] = JSON.parse(localStorage.getItem(Constants.CACHE_ACCESSORY_LIST)); // console.log('Util.getAccessoryList()>>End'); return accessoryList; } /** Gets the accessory item from local cache. */ static getAccessoryItem(accessorySKU: string): IAccessoryItem { const METHOD_NAME: string = 'getAccessoryItem()'; // console.log('Util.getAccessoryItem()>>Start'); const accessories: IAccessory[] = this.getAccessoryList(); if (accessories && accessories.length > 0) { for (const product of accessories) { const items: any = product.items.filter((item) => { return item.accessorySKU === accessorySKU; }); if (items && items.length > 0) { return items[0]; } } } } /** Gets the parent accessory item from local cache. */ static getAccessory(productId: number): IAccessory { const METHOD_NAME: string = 'getAccessory()'; // console.log('Util.getAccessoryItem()>>Start'); const accessories: IAccessory[] = this.getAccessoryList(); if (accessories && accessories.length > 0) { const products: any = accessories.filter((product) => { return product.productId === productId; }); if (products && products.length > 0) { return products[0]; } } } /** Gets the parent accessory item from local cache. */ static getAccessoryParent(accessorySKU: string): IAccessory { const METHOD_NAME: string = 'getAccessoryParent()'; // console.log('Util.getAccessoryItem()>>Start'); const accessories: IAccessory[] = this.getAccessoryList(); if (accessories && accessories.length > 0) { for (const product of accessories) { const items: any = product.items.filter((item) => { return item.accessorySKU === accessorySKU; }); if (items && items.length > 0) { return product; } } } } /** Stroes the master accessory filter list to local cache. */ static storeAccessoryFilterList(accessoryFilterList: IFilterList[]): void { const METHOD_NAME: string = 'storeAccessoryFilterList()'; // console.log('Util.storeAccessoryFilterList()>>Start'); if (accessoryFilterList) { localStorage.setItem(Constants.CACHE_ACCESSORY_FILTER_LIST, JSON.stringify(accessoryFilterList)); } else { if (localStorage.getItem(Constants.CACHE_ACCESSORY_FILTER_LIST)) { localStorage.removeItem(Constants.CACHE_ACCESSORY_FILTER_LIST); } } // console.log('Util.storeAccessoryFilterList()>>End'); } /** Gets the master accessory filter list from local cache. */ static getAccessoryFilterList(): IFilterList[] { const METHOD_NAME: string = 'getAccessoryFilterList()'; // console.log('Util.getAccessoryFilterList()>>Start'); const accessoryFilterList: IFilterList[] = JSON.parse(localStorage.getItem(Constants.CACHE_ACCESSORY_FILTER_LIST)); // console.log('Util.getAccessoryFilterList()>>End'); return accessoryFilterList; } /** Stroes the inventory list to local cache. */ static storeInventoryList(inventoryList: IInventoryStatus[]): void { const METHOD_NAME: string = 'storeInventoryList()'; // console.log('Util.storeInventoryList()>>Start'); if (inventoryList) { localStorage.setItem(Constants.CACHE_INVENTORY_LIST, JSON.stringify(inventoryList)); } else { if (localStorage.getItem(Constants.CACHE_INVENTORY_LIST)) { localStorage.removeItem(Constants.CACHE_INVENTORY_LIST); } } // console.log('Util.storeInventoryList()>>End'); } /** Gets the inventory list from local cache. */ static getInventoryList(): IInventoryStatus[] { const METHOD_NAME: string = 'getInventoryList()'; // console.log('Util.getInventoryList()>>Start'); const inventoryList: IInventoryStatus[] = JSON.parse(localStorage.getItem(Constants.CACHE_INVENTORY_LIST)); // console.log('Util.getInventoryList()>>End'); return inventoryList; } // Tradein Devices List static storeTradeInDeviceList(tradeInDeviceList: any): void { const METHOD_NAME: string = 'storeTradeInDeviceList()'; // console.log('Util.storeTradeInDeviceList()>>Start'); if (tradeInDeviceList) { localStorage.setItem(Constants.CACHE_TRADEIN_DEVICE_LIST, JSON.stringify(tradeInDeviceList)); } else { if (localStorage.getItem(Constants.CACHE_TRADEIN_DEVICE_LIST)) { localStorage.removeItem(Constants.CACHE_TRADEIN_DEVICE_LIST); } } // console.log('Util.storeTradeInDeviceList()>>End'); } static getTradeInDeviceList(): any { const METHOD_NAME: string = 'getTradeInDeviceList()'; // console.log('Util.getTradeInDeviceList()>>Start'); let tradeInDeviceList: any; if (localStorage.getItem(Constants.CACHE_TRADEIN_DEVICE_LIST)) { tradeInDeviceList = JSON.parse(localStorage.getItem(Constants.CACHE_TRADEIN_DEVICE_LIST)); } // console.log('Util.getTradeInDeviceList()>>End'); return tradeInDeviceList; } /** Stroes the payment public key to local cache. */ static storePaymentPublicKey(publiKey: any): void { const METHOD_NAME: string = 'storePaymentPublicKey()'; // console.log('Util.storePaymentPublicKey()>>Start'); if (publiKey) { localStorage.setItem(Constants.CACHE_PAYMENT_PUBLIC_KEY, JSON.stringify(publiKey)); } else { if (localStorage.getItem(Constants.CACHE_PAYMENT_PUBLIC_KEY)) { localStorage.removeItem(Constants.CACHE_PAYMENT_PUBLIC_KEY); } } // console.log('Util.storePaymentPublicKey()>>End'); } /** Gets the payment public key from local cache. */ static getPaymentPublicKey(): any { const METHOD_NAME: string = 'getPaymentPublicKey()'; // console.log('Util.getPaymentPublicKey()>>Start'); const publiKey: any = JSON.parse(localStorage.getItem(Constants.CACHE_PAYMENT_PUBLIC_KEY)); // console.log('Util.getPaymentPublicKey()>>End'); return publiKey; } /** Clears the data from session cache. */ static clearSessionData(): void { const METHOD_NAME: string = 'clearSessionData()'; // console.log('Util.clearSessionData()>>Start'); // removing rateplan/filter list if (sessionStorage.getItem(Constants.CACHE_USER_PROFILE)) { sessionStorage.removeItem(Constants.CACHE_USER_PROFILE); } if (sessionStorage.getItem(Constants.CACHE_CUSTOMER_DETAILS)) { sessionStorage.removeItem(Constants.CACHE_CUSTOMER_DETAILS); } if (sessionStorage.getItem(Constants.CACHE_ORDER_SEARCH_DETAILS)) { sessionStorage.removeItem(Constants.CACHE_ORDER_SEARCH_DETAILS); } if (sessionStorage.getItem(Constants.CACHE_ORDER_DETAILS)) { sessionStorage.removeItem(Constants.CACHE_ORDER_DETAILS); } // console.log('Util.clearSessionData()>>End'); } /** Stroes the user to local cache. */ static storeUserDetail(user: User): void { const METHOD_NAME: string = 'storeUserDetail()'; // console.log('Util.storeUserDetail()>>Start'); if (user) { sessionStorage.setItem(Constants.CACHE_USER_PROFILE, JSON.stringify(user)); } else { if (sessionStorage.getItem(Constants.CACHE_USER_PROFILE)) { sessionStorage.removeItem(Constants.CACHE_USER_PROFILE); } } // console.log('Util.storeUserDetail()>>End'); } /** Gets the user from local cache. */ static getUserDetail(): User { const METHOD_NAME: string = 'getUserDetail()'; // console.log('Util.getUserDetail()>>Start'); const user: User = JSON.parse(sessionStorage.getItem(Constants.CACHE_USER_PROFILE)); // console.log('Util.getUserDetail()>>End'); return user; } /** Stroes the cart deatils to local cache. */ static storeCartDetails(cart: Cart): void { const METHOD_NAME: string = 'storeCartDetails()'; // console.log('Util.storeCartDetails()>>Start'); if (cart) { sessionStorage.setItem(Constants.CACHE_CART_DETAILS, JSON.stringify(cart)); } else { if (sessionStorage.getItem(Constants.CACHE_CART_DETAILS)) { sessionStorage.removeItem(Constants.CACHE_CART_DETAILS); } } // console.log('Util.storeCartDetails()>>End'); } /** Gets the cart deatils from local cache. */ static getReturnCartDetails(): Cart { const METHOD_NAME: string = 'getReturnCartDetails()'; // console.log('Util.getCartDetails()>>Start'); const cart: Cart = JSON.parse(sessionStorage.getItem(Constants.CACHE_RETURN_CART_DETAILS)); // console.log('Util.getCartDetails()>>End'); return cart; } /** Stroes the cart deatils to local cache. */ static storeReturnCartDetails(cart: Cart): void { const METHOD_NAME: string = 'storeReturnCartDetails()'; // console.log('Util.storeCartDetails()>>Start'); if (cart) { sessionStorage.setItem(Constants.CACHE_RETURN_CART_DETAILS, JSON.stringify(cart)); } else { if (sessionStorage.getItem(Constants.CACHE_RETURN_CART_DETAILS)) { sessionStorage.removeItem(Constants.CACHE_RETURN_CART_DETAILS); } } // console.log('Util.storeCartDetails()>>End'); } /** Gets the cart deatils from local cache. */ static getCartDetails(): Cart { const METHOD_NAME: string = 'getCartDetails()'; // console.log('Util.getCartDetails()>>Start'); const cart: Cart = JSON.parse(sessionStorage.getItem(Constants.CACHE_CART_DETAILS)); // console.log('Util.getCartDetails()>>End'); return cart; } /** Stroes the customer profile deatils to local cache. */ static storeCustomerDetails(customer: Customer): void { const METHOD_NAME: string = 'storeCustomerDetails()'; // console.log('Util.storeCustomerDetails()>>Start'); if (customer) { sessionStorage.setItem(Constants.CACHE_CUSTOMER_DETAILS, JSON.stringify(customer)); } else { if (sessionStorage.getItem(Constants.CACHE_CUSTOMER_DETAILS)) { sessionStorage.removeItem(Constants.CACHE_CUSTOMER_DETAILS); } } // console.log('Util.storeCustomerDetails()>>End'); } /** Gets the customer deatils from local cache. */ static getCustomerDetails(): Customer { const METHOD_NAME: string = 'getCustomerDetails()'; // console.log('Util.getCustomerDetails()>>Start'); const customer: Customer = JSON.parse(sessionStorage.getItem(Constants.CACHE_CUSTOMER_DETAILS)); // console.log('Util.getCustomerDetails()>>End'); return customer; } /** Stroes the credit deatils to local cache. */ static storeCreditDetails(creditDetail: any): void { const METHOD_NAME: string = 'storeCreditDetails()'; // console.log('Util.storeCreditDetails()>>Start'); if (creditDetail) { sessionStorage.setItem(Constants.CACHE_CREDIT_OPTION_DETAILS, JSON.stringify(creditDetail)); } else { if (sessionStorage.getItem(Constants.CACHE_CREDIT_OPTION_DETAILS)) { sessionStorage.removeItem(Constants.CACHE_CREDIT_OPTION_DETAILS); } } // console.log('Util.storeCreditDetails()>>End'); } /** Gets the customer deatils from local cache. */ static getCreditDetails(): any { const METHOD_NAME: string = 'getCreditDetails()'; // console.log('Util.getCreditDetails()>>Start'); const creditDetail: any = JSON.parse(sessionStorage.getItem(Constants.CACHE_CREDIT_OPTION_DETAILS)); // console.log('Util.getCreditDetails()>>End'); return creditDetail; } /** Stroes the order serch result deatils to local cache. */ static storeOrderListDetails(orderList: IOrderList): void { const METHOD_NAME: string = 'storeOrderListDetails()'; // console.log('Util.storeOrderListDetails()>>Start'); if (orderList) { sessionStorage.setItem(Constants.CACHE_ORDER_SEARCH_DETAILS, JSON.stringify(orderList)); } else { if (sessionStorage.getItem(Constants.CACHE_ORDER_SEARCH_DETAILS)) { sessionStorage.removeItem(Constants.CACHE_ORDER_SEARCH_DETAILS); } } // console.log('Util.storeOrderListDetails()>>End'); } /** Gets the order search deatils from local cache. */ static getOrderListDetails(): IOrderList { const METHOD_NAME: string = 'getOrderListDetails()'; // console.log('Util.getOrderListDetails()>>Start'); const orderList: IOrderList = JSON.parse(sessionStorage.getItem(Constants.CACHE_ORDER_SEARCH_DETAILS)); // console.log('Util.getOrderListDetails()>>End'); return orderList; } /** Stroes the order deatils to local cache. */ static storeOrderDetails(order: Cart): void { const METHOD_NAME: string = 'storeOrderDetails()'; // console.log('Util.storeOrderDetails()>>Start'); if (order) { sessionStorage.setItem(Constants.CACHE_ORDER_DETAILS, JSON.stringify(order)); } else { if (sessionStorage.getItem(Constants.CACHE_ORDER_DETAILS)) { sessionStorage.removeItem(Constants.CACHE_ORDER_DETAILS); } } // console.log('Util.storeOrderDetails()>>End'); } /** Gets the order deatils from local cache. */ static getOrderDetails(): Cart { const METHOD_NAME: string = 'getOrderDetails()'; // console.log('Util.getOrderDetails()>>Start'); const order: Cart = JSON.parse(sessionStorage.getItem(Constants.CACHE_ORDER_DETAILS)); // console.log('Util.getOrderDetails()>>End'); return order; } /** Stroes the order deatils to local cache. */ static storeDormantProperties(properties: IDormantProperties): void { const METHOD_NAME: string = 'storeDormantProperties()'; // console.log('Util.storeOrderDetails()>>Start'); if (properties) { sessionStorage.setItem(Constants.CACHE_DORMANT_FLAG_PROPERTIES, JSON.stringify(properties)); } else { if (sessionStorage.getItem(Constants.CACHE_DORMANT_FLAG_PROPERTIES)) { sessionStorage.removeItem(Constants.CACHE_DORMANT_FLAG_PROPERTIES); } } // console.log('Util.storeOrderDetails()>>End'); } /** Gets the order deatils from local cache. */ static getDormantProperties(): IDormantProperties { const METHOD_NAME: string = 'getDormantProperties()'; // console.log('Util.getOrderDetails()>>Start'); const dormantProperties: IDormantProperties = JSON.parse(sessionStorage.getItem(Constants.CACHE_DORMANT_FLAG_PROPERTIES)); // console.log('Util.getOrderDetails()>>End'); return dormantProperties; } /** Gets the cart deatils from local cache. */ static getSAPBlindCartDetails(): Cart { const METHOD_NAME: string = 'getSAPBlindCartDetails()'; // console.log('Util.getCartDetails()>>Start'); const cart: Cart = JSON.parse(sessionStorage.getItem(Constants.CACHE_SAP_BLIND_CART_DETAILS)); // console.log('Util.getSAPBlindCartDetails()>>End'); return cart; } /** Stroes the cart deatils to local cache. */ static storeSAPBlindCartDetails(cart: Cart): void { const METHOD_NAME: string = 'storeSAPBlindCartDetails()'; // console.log('Util.storeCartDetails()>>Start'); if (cart) { sessionStorage.setItem(Constants.CACHE_SAP_BLIND_CART_DETAILS, JSON.stringify(cart)); } else { if (sessionStorage.getItem(Constants.CACHE_SAP_BLIND_CART_DETAILS)) { sessionStorage.removeItem(Constants.CACHE_SAP_BLIND_CART_DETAILS); } } // console.log('Util.storeSAPBlindCartDetails()>>End'); } static groupByProductCount(): number { let user: User = this.getUserDetail(); if (user && user.favorites && user.favorites.cardsPerRow) { return jQuery(window).width() <= 991 ? 2 : user.favorites.cardsPerRow; } else { return jQuery(window).width() <= 991 ? 2 : 3; } } static totalCardsPerPage(): number { let user: User = this.getUserDetail(); if (user && user.favorites && user.favorites.cardsPerPage) { return user.favorites.cardsPerPage; } else { return Constants.CARDS_PER_PAGE; } } static hasStoreAccess(storeId: number): boolean { let user: User = this.getUserDetail(); if (Number(storeId) === Constants.STORE_ID_CD) { return user.permissions.canAccessCD; } else if (Number(storeId) === Constants.STORE_ID_BD) { return user.permissions.canAccessBD; } else if (Number(storeId) === Constants.STORE_ID_CS) { return user.permissions.canAccessTIC; } return false; } /** Group the products with defined number */ static groupProducts(products: any[], count: number): Array> { const METHOD_NAME: string = 'groupProducts()'; let groups: Array>; if (products && products.length > 0) { // console.log('total products length for grouping:'+ products.length); groups = new Array>(); while (products.length > 0) { if (products.length > count) { groups.push(products.splice(0, count)); } else { groups.push(products.splice(0, products.length)); } } } return groups; } /** Search products with given filters */ static serachFilter(products: any[], filters: IFilterList[]): Array { const METHOD_NAME: string = 'serachFilter()'; if (products && products.length > 0) { // console.log('total products length for filters:'+ products.length); if (filters && filters.length > 0) { let checkedFilters: Array = new Array(); for (const filter of filters) { if (filter && filter.items) { for (const item of filter.items) { if (item.isChecked) {checkedFilters = checkedFilters.concat(item.productIds); } } checkedFilters = checkedFilters.filter((value, index, allFilterList) => (allFilterList.slice(0, index)).indexOf(value) === -1); } } return products.filter((product) => { if (checkedFilters && checkedFilters.length > 0) { return checkedFilters.indexOf(product.productId) > -1; } else { return true; } }); } else { return products; } } return []; } /** Search products with given sory by selection */ static serachSortBy(products: any[], sortBykey: string): Array { const METHOD_NAME: string = 'serachSortBy()'; if (products && products.length > 0) { // console.log('total products length for sort by:'+ products.length); return products.sort((a, b) => { // console.log('order by>>>'+ this.orderBy); if (sortBykey === 'price-asc' || sortBykey === 'price-desc') { const textA = (a.items && a.items.length > 0) ? a.items[0].finalPrice : a.monthlyPrice; const textB = (b.items && b.items.length > 0) ? b.items[0].finalPrice : b.monthlyPrice; if (sortBykey === 'price-asc') { return (textA < textB) ? -1 : (textA > textB) ? 1 : 0; } else { return (textA > textB) ? -1 : (textA < textB) ? 1 : 0; } } else if (sortBykey === 'name-asc' || sortBykey === 'name-desc') { const textC = ((a.items && a.items.length > 0) ? a.manufacturer + ' ' + a.items[0].name : a.name).toUpperCase(); const textD = ((b.items && b.items.length > 0) ? b.manufacturer + ' ' + b.items[0].name : b.name).toUpperCase(); if (sortBykey === 'name-asc') { return (textC < textD) ? -1 : (textC > textD) ? 1 : 0; } else { return (textC > textD) ? -1 : (textC < textD) ? 1 : 0; } } else { return -1; } }); } return []; } /** Search products with given search text */ static serachProducts(products: any[], serachText: string): Array { const METHOD_NAME: string = 'serachProducts()'; if (products && products.length > 0) { // console.log('total products length for search:'+ products.length); return products.filter((product) => { if (serachText && serachText.length > 0) { const productName = (product.items && product.items.length > 0) ? product.manufacturer + ' ' + product.items[0].name : product.name; let foundText: boolean = productName && productName.toUpperCase().indexOf(serachText.toUpperCase(), 0) > -1; if (!foundText) { if (product.items && product.items.length > 0) { for (const item of product.items) { if (item.deviceSKU) { if (item.deviceSKU.toUpperCase().indexOf(serachText.toUpperCase(), 0) > -1) { foundText = true; } } else if (item.accessorySKU) { if (item.accessorySKU.toUpperCase().indexOf(serachText.toUpperCase(), 0) > -1) { foundText = true; } } if (foundText) { return true; } } } else { if (product.rateplanSOC) { return product.rateplanSOC.toUpperCase().indexOf(serachText.toUpperCase(), 0) > -1; } else if (product.featureSOC) { return product.featureSOC.toUpperCase().indexOf(serachText.toUpperCase(), 0) > -1; } } } return foundText; } else { return true; } }); } return null; } /** Keeping only finance items */ static keepFinanceItems(products: any[], financeType: string, crp: number): Array { const METHOD_NAME: string = 'serachFilter()'; if (financeType === Constants.FINANCE_TYPE_LOAN || financeType === Constants.FINANCE_TYPE_LEASE) { if (products && products.length > 0) { // let productList = products.map(x => Object.assign({}, x)); const productList: any[] = new Array(); products.forEach((product, index) => { const items: any = new Array(); // get only finance items product.items.forEach((item, i) => { // console.log(product.productId+'.item#'+ item.deviceSKU +'>>name:'+ item.name); if (financeType === Constants.FINANCE_TYPE_LOAN) { if (item.loan) { for (const loan of item.loan) { if (loan.crp === crp) { items.push(Object.assign({}, item)); } } } } else if (financeType === Constants.FINANCE_TYPE_LEASE) { if (item.lease) { for (const lease of item.lease) { if (lease.crp === crp) { items.push(Object.assign({}, item)); } } } } }); if (items && items.length > 0) { const obj: any = Object.assign({}, product); obj.items = items; productList.push(obj); } }); return productList; } } else { return products; } return null; } /** Search products with given finance type */ static sortByFinance(products: any[], financeType: string, crp: number): Array { return products.filter((product) => { const items = product.items.filter((item) => { if (financeType === Constants.FINANCE_TYPE_LOAN) { if (item.loan) { const loans = item.loan.filter((ln) => { return ln.crp === crp; }); return (loans && loans.length > 0); } else { return false; } } else if (financeType === Constants.FINANCE_TYPE_LEASE) { if (item.lease) { const leases = item.lease.filter((ls) => { return ls.crp === crp; }); return (leases && leases.length > 0); } else { return false; } } else { return true; } }); return (items && items.length > 0); }); } static getPager(totalItems: number, currentPage: number = 1, pageSize: number = 10) { const METHOD_NAME: string = 'getPager()'; // calculate total pages const totalPages = Math.ceil(totalItems / pageSize); let startPage: number, endPage: number; if (totalPages <= 10) { // less than 10 total pages so show all startPage = 1; endPage = totalPages; } else { // more than 10 total pages so calculate start and end pages if (currentPage <= 6) { startPage = 1; endPage = 10; } else if (currentPage + 4 >= totalPages) { startPage = totalPages - 9; endPage = totalPages; } else { startPage = currentPage - 5; endPage = currentPage + 4; } } // calculate start and end item indexes const startIndex = (currentPage - 1) * pageSize; const endIndex = Math.min(startIndex + pageSize - 1, totalItems - 1); // create an array of pages to ng-repeat in the pager control const pages = _.range(startPage, endPage + 1); // return object with all pager properties required by the view return { totalItems: totalItems, currentPage: currentPage, pageSize: pageSize, totalPages: totalPages, startPage: startPage, endPage: endPage, startIndex: startIndex, endIndex: endIndex, pages: pages }; } static matchFiltersProducts(filters: IFilter[], products: any[]): Array { const METHOD_NAME: string = 'matchFiltersProducts()'; let matchFilters: any = filters; if (products && products.length > 0 && filters && filters.length > 0) { matchFilters = new Array(); for (const item of filters) { if (item.productIds && item.productIds.length > 0) { const pIds: number[] = new Array(); for (const productId of item.productIds) { for (const product of products) { if (product.productId === productId) { pIds.push(productId); break; } } } if (pIds && pIds.length > 0) { matchFilters.push({ name: item.name, productIds: pIds, isChecked: false }); } } } } return matchFilters; } static canDisableButton(item: any, financeType: string, crp: number) { let isDisabled: boolean = false; if (financeType === Constants.FINANCE_TYPE_LOAN) { if (!item.loan) { isDisabled = true; } else { let hasCrp: boolean = false; for (const loan of item.loan) { if (loan.crp === crp) { hasCrp = true; break; } } if (!hasCrp) { isDisabled = true; } } } else if (financeType === Constants.FINANCE_TYPE_LEASE) { if (!item.lease) { isDisabled = true; } else { let hasCrp: boolean = false; for (const lease of item.lease) { if (lease.crp === crp) { hasCrp = true; break; } } if (!hasCrp) { isDisabled = true; } } } return isDisabled; } static getLoanCrp(creditType: string): number { let crp: number = Constants.LOAN_CRP_DEFAULT; if (creditType && creditType === Constants.CREDIT_CHECK) { crp = Constants.LOAN_CRP_AVERAGE; } return crp; } static getLeaseCrp(creditType: string): number { let crp: number = Constants.LEASE_CRP_DEFAULT; if (creditType && creditType === Constants.CREDIT_CHECK) { crp = Constants.LEASE_CRP_AVERAGE; } return crp; } static hasOffer(item: any): boolean { // return false; // return (item && (item.instantDiscount && item.instantDiscount > 0) || // (item.openBoxDiscount && item.openBoxDiscount > 0) || // (item.mailInRebate && item.mailInRebate > 0)) ? true:false; return (item && (item.instantDiscount && item.instantDiscount > 0) || (item.openBoxDiscount && item.openBoxDiscount > 0) || (item.mailInRebate && item.mailInRebate > 0) || (item.promotions && item.promotions.length > 0)) ? true:false; } static getErrorValue(errorKey: string): string { const errors = ERROR_LIST.filter((item) => { return item.key === errorKey; }); if (errors && errors.length > 0) { return errors[0].value; } } static getErrorContains(errorKey: string): string { const errors = ERROR_LIST.filter((item) => { return item.key.indexOf(errorKey) !== -1; }); if (errors && errors.length > 0) { return errors[0].value; } } static getErrorKey(errorVal: string): string { const errors = ERROR_LIST.filter((item) => { if (item.value === errorVal) { return item.key; } }); if (errors && errors.length > 0) { return errors[0].value; } } static getConflictsMsg(errorKey: string, param: string): string { const errors = ERROR_LIST.filter((item) => { return item.key === errorKey; }); if (errors && errors.length > 0) { let value = errors[0].value; value = value.replace('{0}', param); return value; } } /** * Handle HTTP error */ static handleError(error: any) { const METHOD_NAME: string = 'handleError()'; if (error.status === 401) { return observableThrowError('NOT_AUTHORIZED_FOR_QUERY'); } let errorKey: string; if (error._body) { console.log('errors from service:' + error._body) const errors: IError[] = JSON.parse(error._body).errors; if (errors && errors[0].errorKey) { errorKey = errors[0].errorKey; } } if (errorKey && errorKey.length === 0) { // In a real world app, we might use a remote logging infrastructure // We'd also dig deeper into the error to get a better message errorKey = (error.message) ? error.message : error.status ? `${error.status} - ${error.statusText}` : 'Server error'; } console.error('error key from service:' + errorKey); // log to console instead return observableThrowError(errorKey); } static validate(dateType: string, date: any): number { const METHOD_NAME: string = 'validate()'; if (date) { if (dateType === 'mmddyyyy') { return (new Date().getFullYear() - Number(date.slice(0, 4))); } else { if ((new Date().getFullYear()) - Number(date.slice(0, 4)) === 0) { if ((new Date().getMonth() + 1) - Number(date.slice(5)) < 0) { return Number((date.slice(0, 4)) - (new Date().getFullYear())); } else { return -1; } } else { return Number((date.slice(0, 4)) - (new Date().getFullYear())); } } } } static isValidImei(imei): boolean { const METHOD_NAME: string = 'isValidImei()'; const validLuhn = this.luhn_checksum(imei) === 0; if (validLuhn) { return true; } else if (this.isHexaDecimal(imei)) { return true; } else { return false; } } static luhn_checksum(code): number { const METHOD_NAME: string = 'luhn_checksum()'; const len = code.length; const parity = len % 2; let sum = 0; for (let i = len - 1; i >= 0; i--) { let d = parseInt(code.charAt(i)); if (i % 2 === parity) { d *= 2 } if (d > 9) { d -= 9 } sum += d; } return sum % 10; } static isHexaDecimal(input): boolean { const METHOD_NAME: string = 'isHexaDecimal()'; const re = /[0-9A-F]{6}/g; const imei = input.toUpperCase(); if (re.test(imei) && (imei.indexOf('A') > -1 || imei.indexOf('B') > -1 || imei.indexOf('C') > -1 || imei.indexOf('D') > -1 || imei.indexOf('E') > -1 || imei.indexOf('F') > -1)) { return true; } else { return false; } } static keysToArray(input): string[] { const METHOD_NAME: string = 'keysToArray()'; let arr = []; for (let key in input) { arr.push(key); } return arr; } static setOrderItemsIdTradeInInfo(tradeInlist: any, orderItemsId: number, tradeInfo: any[]): any { const METHOD_NAME: string = 'setOrderItemsIdTradeInInfo()'; if (orderItemsId) { // for individual tradein we pass the orderItemsId for (const ls in tradeInfo) { if (tradeInlist && tradeInlist.length > 0) { // edit or more than one element for (const list of tradeInlist) { if (list.hasOwnProperty('orderItemsId') && list.orderItemsId === orderItemsId) { tradeInfo[ls] = tradeInfo; } else { tradeInfo[ls]['orderItemsId'] = orderItemsId; tradeInlist.push(tradeInfo[ls]); } } } else { tradeInfo[ls]['orderItemsId'] = orderItemsId; tradeInlist.push(tradeInfo[ls]); } } } else { tradeInlist = tradeInfo; } return tradeInlist; } static getTradeInInfoOrder(orderItemsId: number, tradeInfo: any): any { const METHOD_NAME: string = 'getTradeInInfoOrder()'; if (orderItemsId && tradeInfo && tradeInfo.length > 0) { for (const info in tradeInfo) { if (tradeInfo[info].orderItemsId === orderItemsId) { return tradeInfo[info]; } } } } static setFinanceTypeForReturn(exChangeCart: Cart, returnCart: Cart, type: String): string { const METHOD_NAME: string = 'setFinanceTypeForReturn()'; let financeType = ''; if (exChangeCart && exChangeCart.activeLineId >= 0 && returnCart) { for (const pack of returnCart.packages) { if (pack.lineId === exChangeCart.activeLineId) { if (type === 'Device') { financeType = pack.device.financeType; } else { // for accesories financeType = pack.device.financeType; } } } } return financeType; } static formatPhoneNumber(phoneNumber: string): string { if (phoneNumber && phoneNumber.indexOf('-') === -1 && phoneNumber.length === 10) { return phoneNumber.substring(0, 3) + '-' + phoneNumber.substring(3, 6) + '-' + phoneNumber.substring(6); } else { return phoneNumber; } } static nonFormatPhoneNumber(phoneNumber: string): string { if (phoneNumber && phoneNumber.indexOf('-') > -1) { return phoneNumber.replace(new RegExp('-', 'g'), ''); } else { return phoneNumber; } } static nonFormatSSN(SSN: string): string { if (SSN && SSN.indexOf('-') > -1) { return SSN.replace(new RegExp('-', 'g'), ''); } else { return SSN; } } static nonFormatDate(dateExp: string): string { if (dateExp && dateExp.indexOf('/') > -1) { return dateExp.replace(new RegExp('/', 'g'), ''); } else { return dateExp; } } static formatBirthDate(dateString: string): string { if (dateString && dateString.indexOf('/') === -1 && dateString.length === 8) { return dateString.substring(0, 2) + '/' + dateString.substring(2, 4) + '/' + dateString.substring(4); } else { return dateString; } } static formatDecimal(decimalString: string): string { if (decimalString && decimalString.length>0 && decimalString.indexOf('.') === -1) { return decimalString +'.00'; } else { return decimalString; } } static trimZipCode(zipCode: any): string { if (zipCode) { return (zipCode && zipCode.length > 5) ? zipCode.substring(0, 5) : zipCode; } } static checkDealerCode(dealercode: any): boolean { let isValid = true; if (dealercode) { dealercode = Number(dealercode.substring(1)); if (isNaN(dealercode)) { isValid = false; } } else { isValid = false; } return isValid; } /** * This function is used to update product Item Index based on device stock priority. * @param {IDevice} product contains device info. * @returns number */ static getItemIndex(product: IDevice): number { product.itemIndex = 0; const items: any = new Array(); let flag: boolean = false; if (!flag) { product.items.forEach(function (item, i) { if (!flag && item.status && item.status === 'INS') { product.itemIndex = i; flag = true; } }); } if (!flag) { product.items.forEach(function (item, i) { if (!flag && item.status && item.status === 'PRE') { product.itemIndex = i; flag = true; } }); } if (!flag) { product.items.forEach(function (item, i) { if (!flag && item.status && item.status === 'BOA') { product.itemIndex = i; flag = true; } }); } if (!flag) { product.items.forEach(function (item, i) { if (!flag && item.status && item.status === 'OOS') { product.itemIndex = i; flag = true; } }); } return product.itemIndex; } static hasActLineLevelError(errorParameters: any): boolean { const METHOD_NAME: string = 'hasActLineLevelError()'; let hasLineLevelError:boolean = false; if(errorParameters && errorParameters.length > 0){ let jsonObject = JSON.parse(errorParameters); for(const item of jsonObject) { if(item.errorCode && item.errorCode == '2025') { hasLineLevelError = true; break; } } } return hasLineLevelError; } static formatActErrorMessage(errorParameters: any): string { const METHOD_NAME: string = 'getActivationError()'; let activationError:string = null; if(errorParameters && errorParameters.length > 0){ let jsonObject = JSON.parse(errorParameters); activationError = ''; for(const item of jsonObject) { if(item.errorCode && item.errorMessage) { const errors = ACT_ERROR_LIST.filter((error) => { return error.key === '_ERR_ACTIVATION_'+ item.errorCode; }); if (errors && errors.length > 0) { activationError += errors[0].value + '
'; }else{ activationError += item.errorMessage + '
'; } } } } return activationError; } static getCreditProfile(creditClass: string): any { let creditOption: any; const creditDetails = this.getCreditDetails() if(creditDetails && creditDetails.length > 0){ for (const item of creditDetails){ if (item.creditClass === creditClass){ creditOption = item; let creditProfile:ICreditProfile = item.creditProfile; creditProfile.activeVoiceLines = 0; creditProfile.usedVoiceLines = 0; creditProfile.suspendedVoiceLines = 0; creditProfile.authorizedVoiceLines = creditProfile.maxVoiceLines; creditProfile.reservedVoiceLines = 0; creditProfile.allowedVoiceLines = 0; creditProfile.cancelledVoiceLines = 0; creditProfile.activeDataLines = 0; creditProfile.usedDataLines = 0; creditProfile.suspendedDataLines = 0; creditProfile.authorizedDataLines = creditProfile.maxDataLines; creditProfile.reservedDataLines = 0; creditProfile.allowedDataLines = 0; creditProfile.cancelledDataLines = 0; creditProfile.accountType = null; creditProfile.accountSubType = null; //creditProfile.accountStatus = null, creditProfile.accountTenure = '0'; creditProfile.behaviorScore = '0'; creditProfile.isDelinquent = false; //creditProfile.taxTreatment = null; //creditProfile.onyxReferenceNumber = null //creditProfile.autoPayIndicator = false; //creditProfile.accountNumber = null; creditProfile.isFinancedEip = false, creditProfile.totalBalanceDue = 0; creditProfile.isExtendedPaySchedule = false; //creditProfile.activationDate = null; //creditProfile.billCycleCode = null //creditProfile.billCurrent = null; creditProfile.pastDueAmount = 0; creditOption.creditProfile = creditProfile; break; } } } return creditOption; } }