import { Injectable, Output, EventEmitter, ElementRef } from '@angular/core'; import { FormControl, FormGroup } from '@angular/forms'; declare var $; import { ToastrService } from 'ngx-toastr'; import { CoredataService } from '../core/coredata.service'; import { CommonEnum } from '../models/common-enum'; import { CommonlistRequest } from '../models/shared/commonlist'; import { DataTable } from '../models/shared/data-table/data-table' import * as CryptoJS from 'crypto-js'; import { BehaviorSubject } from 'rxjs/internal/BehaviorSubject'; import { PublicClientApplication } from '@azure/msal-browser'; import { environment } from 'src/environments/environment'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { CookieService } from 'ngx-cookie-service'; @Injectable({ providedIn: 'root' }) export class CommonService { @Output() SkinningOutemit: EventEmitter = new EventEmitter(); BrandData: any[] = []; CustomerData: any[] = []; options; internalUsers = [CommonEnum.SA, CommonEnum.VP, CommonEnum.RSM, CommonEnum.TSR, CommonEnum.CSR]; externalUserWithNoAccessOfAdmin = [CommonEnum.CU, CommonEnum.RU, CommonEnum.BU]; featureInfoAll = [CommonEnum.EP, CommonEnum.CO, CommonEnum.INFO, CommonEnum.VPS, CommonEnum.PGW, CommonEnum.SO] featureInfoPGW = [CommonEnum.HM, CommonEnum.ADM, CommonEnum.EP, CommonEnum.CO, CommonEnum.INFO, CommonEnum.SO, CommonEnum.OM, CommonEnum.VPS] featureInfoSO = [CommonEnum.HM, CommonEnum.ADM, CommonEnum.EP, CommonEnum.CO, CommonEnum.INFO, CommonEnum.PGW, CommonEnum.OM, CommonEnum.VPS] featureInfoEP = [CommonEnum.HM, CommonEnum.ADM, CommonEnum.CO, CommonEnum.INFO, CommonEnum.PGW, CommonEnum.OM, CommonEnum.VPS, CommonEnum.SO] featureInfoCO = [CommonEnum.HM, CommonEnum.ADM, CommonEnum.EP, CommonEnum.INFO, CommonEnum.PGW, CommonEnum.OM, CommonEnum.VPS, CommonEnum.SO] msalconfig = { auth: { clientId: '33c6c2da-8f7c-4770-97be-0586f28e4b2e', redirectUri: environment.logoutURL, postLogoutRedirectUri: environment.logoutURL } } public existenceEmailCheckURL = environment.adminBaseUrl + 'AdminUser/CheckEmailExistance'; public httpOptions = { headers: this.getHeader() }; constructor( private toastr: ToastrService, private coreData: CoredataService, private httpService: HttpClient, private cookieService: CookieService ) { } SkinningEmitter() { this.SkinningOutemit.emit(true); } tinyMCEOptions() { return { base_url: '/tinymce', suffix: '.min', width: 700, height: 300, statubar: true, plugins: [ "advlist autolink link image lists charmap print preview hr anchor pagebreak", "searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking", "save table contextmenu directionality emoticons template paste textcolor" ], style_formats: [ { title: "Headers", items: [ { title: "Header 1", format: "h1" }, { title: "Header 2", format: "h2" }, { title: "Header 3", format: "h3" }, { title: "Header 4", format: "h4" }, { title: "Header 5", format: "h5" }, { title: "Header 6", format: "h6" } ] }, { title: "Inline", items: [ { title: "Bold", icon: "bold", format: "bold" }, { title: "Italic", icon: "italic", format: "italic" }, { title: "Underline", icon: "underline", format: "underline" }, { title: "Strikethrough", icon: "strike-through", format: "strikethrough" }, { title: "Superscript", icon: "superscript", format: "superscript" }, { title: "Subscript", icon: "subscript", format: "subscript" }, { title: "Code", icon: "sourcecode", format: "code" } ] }, { title: "Blocks", items: [ { title: "Paragraph", format: "p" }, { title: "Blockquote", format: "blockquote" }, { title: "Div", format: "div" }, { title: "Pre", format: "pre" } ] }, { title: "Alignment", items: [ { title: "Left", icon: "align-left", format: "alignleft" }, { title: "Center", icon: "align-center", format: "aligncenter" }, { title: "Right", icon: "align-right", format: "alignright" }, { title: "Justify", icon: "align-justify", format: "alignjustify" } ] } ], toolbar: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image | print preview media fullpage | forecolor backcolor emoticons", }; } tinyMCEOptionsWithHeightWidth(getWidth: number, getHeight: number) { return { base_url: '/tinymce', suffix: '.min', width: getWidth + '%', height: getHeight, statubar: true, plugins: [ "advlist autolink link image lists charmap print preview hr anchor pagebreak", "searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking", "save table contextmenu directionality emoticons template paste textcolor" ], style_formats: [ { title: "Headers", items: [ { title: "Header 1", format: "h1" }, { title: "Header 2", format: "h2" }, { title: "Header 3", format: "h3" }, { title: "Header 4", format: "h4" }, { title: "Header 5", format: "h5" }, { title: "Header 6", format: "h6" } ] }, { title: "Inline", items: [ { title: "Bold", icon: "bold", format: "bold" }, { title: "Italic", icon: "italic", format: "italic" }, { title: "Underline", icon: "underline", format: "underline" }, { title: "Strikethrough", icon: "strike-through", format: "strikethrough" }, { title: "Superscript", icon: "superscript", format: "superscript" }, { title: "Subscript", icon: "subscript", format: "subscript" }, { title: "Code", icon: "sourcecode", format: "code" } ] }, { title: "Blocks", items: [ { title: "Paragraph", format: "p" }, { title: "Blockquote", format: "blockquote" }, { title: "Div", format: "div" }, { title: "Pre", format: "pre" } ] }, { title: "Alignment", items: [ { title: "Left", icon: "align-left", format: "alignleft" }, { title: "Center", icon: "align-center", format: "aligncenter" }, { title: "Right", icon: "align-right", format: "alignright" }, { title: "Justify", icon: "align-justify", format: "alignjustify" } ] } ], toolbar: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image | print preview media fullpage | forecolor backcolor emoticons", }; } dataTableOptions(id, ordering) { $(id).DataTable({ "paging": true, "lengthChange": false, "searching": false, "ordering": ordering, "info": true, "autoWidth": false, "responsive": true, 'aoColumnDefs': [{ 'bSortable': false, 'aTargets': [0] /*[-1]*/ /* 1st one, start by the right */ }] }); } dataTableOptionsForSN(paging, lengthChange, searching, ordering, info, autoWidth, responsive) { var dtOptions = { "paging": paging, "lengthChange": lengthChange, "searching": searching, "ordering": ordering, "info": info, "autoWidth": autoWidth, "responsive": responsive, 'aoColumnDefs': [{ 'bSortable': false, //'aTargets': [0] /* 1st one, start by the right */ }] } return dtOptions; } dataTableOptionsForSNA(paging, lengthChange, searching, ordering, info, autoWidth, responsive) { var dtOptions = { "paging": paging, "lengthChange": lengthChange, //"pageLength": 5, "destroy": true, "searching": searching, "ordering": ordering, "info": info, "autoWidth": autoWidth, "responsive": responsive, 'aoColumnDefs': [{ 'bSortable': false, //'aTargets': [0] /* 1st one, start by the right */ }] } return dtOptions; } dataTableOptionsForDA(paging, lengthChange, searching, info, autoWidth, responsive, orderBy = null, orderType = null) { var dtOptions = { "paging": paging, "lengthChange": lengthChange, "searching": searching, "info": info, "autoWidth": autoWidth, "responsive": responsive, "order": [[orderBy, orderType]], //'aoColumnDefs': [{ // 'bSortable': false, // 'aTargets': [-1] /* 1st one, start by the right */ //}] } return dtOptions; } showSuccess(message, title) { this.toastr.success(message, title, { timeOut: 5000, closeButton: true, progressBar: true, progressAnimation: "increasing", positionClass: "toast-top-right", extendedTimeOut: 2500, tapToDismiss: false }); } showError(message, title) { this.toastr.error(message, title, { timeOut: 5000, closeButton: true, progressBar: true, positionClass: "toast-top-right", extendedTimeOut: 2500, tapToDismiss: false, enableHtml: true }); } showInfo(message, title) { this.toastr.info(message, title, { timeOut: 5000, closeButton: true, progressBar: true, positionClass: "toast-top-right", extendedTimeOut: 2500, tapToDismiss: false }); } showWarning(message, title) { this.toastr.warning(message, title, { timeOut: 5000, closeButton: true, progressBar: true, positionClass: "toast-top-right", extendedTimeOut: 2500, tapToDismiss: false, enableHtml: true }); } CommonList(objCommonList: CommonlistRequest, success, error) { this.coreData.Post(CommonEnum.CompanyAPP, CommonEnum.CommonAPI, objCommonList, (result) => { if (result != null) { return success(result); } return null; }, (error) => { return error(error); }); } setSkinning(id: number = 206, success, error) { this.coreData.Get(CommonEnum.CompanyAPP, CommonEnum.SkinningAPI + '/' + id, null, (result) => { if (result != null) { return success(result); } return null; }, (error) => { return error(error); }); } GetGridList(modelDataTable: DataTable, success, error) { this.coreData.Post(CommonEnum.CommonAPP, 'Common/GridList', modelDataTable, (result) => { if (result != null) { return success(result); } return null; }, (error) => { return error(error); }); } GetFilterData(ParentShipTo, UserEmail, LoggedinUserType, success, error) { this.coreData.Get(CommonEnum.CommonAPP, 'Common/GetFilterData/' + ParentShipTo + "/" + UserEmail + "/" + LoggedinUserType, null, (result) => { if (result != null) { return success(result); } return null; }, (error) => { return error(error); }); } validateAllFormFields(formGroup: FormGroup) { Object.keys(formGroup.controls).forEach(field => { const control = formGroup.get(field); if (control instanceof FormControl) { control.markAsTouched({ onlySelf: true }); } else if (control instanceof FormGroup) { this.validateAllFormFields(control); } }); } validationfocus(formGroup: FormGroup, elementRef: ElementRef) { for (const key of Object.keys(formGroup.controls)) { if (formGroup.controls[key].invalid) { const invalidControl = elementRef.nativeElement.querySelector('[formcontrolname="' + key + '"]'); invalidControl.focus(); break; } } } deleteById(TableName: string, RecordId: number, UserId: number, IpAddress: string, success, error) { this.coreData.Delete(CommonEnum.CompanyAPP, 'Common' + '/' + TableName + '/' + RecordId + '/' + UserId + '/' + IpAddress, null, (result) => { if (result != null) { return success(result); } return null; }, (error) => { return error(error); } ); } checkUserExistence() { let email = sessionStorage.getItem('Email'); this.httpService.get(this.existenceEmailCheckURL + "/" + email, this.httpOptions).subscribe((data) => { if (data) { return true; } else { this.logout(); } }); } private getHeader(): HttpHeaders { const headers = new HttpHeaders({ 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': 'true', 'Access-Control-Allow-Headers': 'Content-Type', 'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE', 'Authorization': `Bearer ${sessionStorage.getItem("token")}`, }) return headers; } logout() { this.cookieService.deleteAll(); const myMsal = new PublicClientApplication(this.msalconfig); const logoutRequest = { account: myMsal.getAccountByHomeId(sessionStorage.getItem(CommonEnum.homeAccountId)), mainWindowRedirectUri: environment.logoutURL } sessionStorage.clear(); myMsal.logoutRedirect(logoutRequest); } Encrypt(strValue: string) { var CryptoKey = 'ABS@2021'; //replace with your key //var iv = '0000000000000000'; //replace with your IV //return CryptoJS.AES.encrypt(strValue.trim(), key.trim()).toString(); // random salt for derivation var keySize = 256; var salt = CryptoJS.lib.WordArray.random(16); // well known algorithm to generate key var key = CryptoJS.PBKDF2(CryptoKey, salt, { keySize: keySize / 32, iterations: 100 }); // random IV var iv = CryptoJS.lib.WordArray.random(128 / 8); // specify everything explicitly var encrypted = CryptoJS.AES.encrypt(strValue, key, { iv: iv, padding: CryptoJS.pad.Pkcs7, mode: CryptoJS.mode.CBC }); // combine everything together in base64 string var result = CryptoJS.enc.Base64.stringify(salt.concat(iv).concat(encrypted.ciphertext)); return result; } copy(data) { return JSON.parse(JSON.stringify(data)); } chunkArray(myArray, chunk_size) { var results = []; while (myArray.length) { results.push(myArray.splice(0, chunk_size)); } return results; } utf8_to_b64(str: string = "") { return window.btoa(unescape(encodeURIComponent(str))); } b64_to_utf8(str: string = "") { return decodeURIComponent(escape(window.atob(str))); } }