(function() { // global uind object window.ctp = {}; // utils object window.ctp.utils = {}; // date format window.ctp.utils.dateFormat = 'm/d/yy'; // month names const monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; // datatable default config window.ctp.dataTableDefaultConfig = { pageLength: 100, searching: true, lengthChange: false, processing: true, fixedHeader: true, dom: ` <'row'<'col-sm-5'B><'col-sm-7'f>> <'row'<'col-sm-12't>> <'row'<'col-sm-5'i><'col-sm-7'p>>`, buttons: [{ extend: 'excel', text: '', className: 'bi bi-file-earmark-spreadsheet btn-sm' }] }; // image compressor default config window.ctp.compressor = { quality: 0.8, maxWidth: 2000, maxHeight: 2000 }; // tinymce window.ctp.getTinyMceDefaultConfig = function( selector ) { return { selector: selector, skin: 'oxide', statusbar: false, plugins: [ 'advlist','autolink','lists','link','image','charmap', 'fullscreen','insertdatetime','media','table','help','wordcount', 'preview','anchor','searchreplace','visualblocks','textcolor' ], toolbar: 'undo redo | a11ycheck casechange blocks | bold italic backcolor forecolor | alignleft aligncenter alignright alignjustify | bullist numlist checklist outdent indent | removeformat | code table help' }; } // initialize datatable window.ctp.utils.initializeDataTable = function( $el, customConfig ) { customConfig = ( typeof customConfig === 'undefined' ) ? {} : customConfig; let config = Object.assign( window.ctp.dataTableDefaultConfig, customConfig ); return $el.DataTable( config ); }; // util function: populate options in a select tag window.ctp.utils.populateOptions = function( $select, optionArr, addMinusOption = false, addFirstOption = false ) { const emptyOptionStr = ''; let htmlStr = ''; if ( addFirstOption ) { htmlStr += emptyOptionStr; } for ( let i = 0; i < optionArr.length; i++ ) { htmlStr += ``; } if ( addMinusOption ) { htmlStr += ''; } $select.html( htmlStr ); }; window.ctp.utils.populateMachineOptions = function( $select, optionArr,addFirstOption = false ) { const emptyOptionStr = ''; let htmlStr = ''; if ( addFirstOption ) { htmlStr += emptyOptionStr; } for ( let i = 0; i < optionArr.length; i++ ) { htmlStr += ``; } $select.html( htmlStr ); }; // populate system users window.ctp.utils.populateUserOptions = function( $select, optionArr, addFirstOption = false ) { const emptyOptionStr = ''; let htmlStr = ''; if ( addFirstOption ) { htmlStr += emptyOptionStr; } for ( let i = 0; i < optionArr.length; i++ ) { htmlStr += ``; } $select.html( htmlStr ); }; // populate location options window.ctp.utils.populateLocationOptions = function( $select, optionArr, addFirstOption = false ) { const emptyOptionStr = ''; let htmlStr = ''; if ( addFirstOption ) { htmlStr += emptyOptionStr; } for ( let i = 0; i < optionArr.length; i++ ) { // data attributes let dataAttributes = ""; // check for unit id if ( optionArr[i].hasOwnProperty( 'unitId' ) ) { dataAttributes += `data-unit-id=${optionArr[i]['unitId']} `; } // check for floor id if ( optionArr[i].hasOwnProperty( 'floorId' ) ) { dataAttributes += `data-floor-id=${optionArr[i]['floorId']} `; } // check for store id if ( optionArr[i].hasOwnProperty( 'storeId' ) ) { dataAttributes += `data-store-id=${optionArr[i]['storeId']} `; } htmlStr += ``; } $select.html( htmlStr ); }; window.ctp.utils.populateTypeOptions = function( $select, optionArr, addMinusOption = false, addFirstOption = false ) { const emptyOptionStr = ''; let htmlStr = ''; if ( addFirstOption ) { htmlStr += emptyOptionStr; } for ( let i = 0; i < optionArr.length; i++ ) { htmlStr += ``; } if ( addMinusOption ) { htmlStr += ''; } $select.html( htmlStr ); }; // function to convert image to blob window.ctp.utils.fileToBase64 = function( file ) { return new Promise(function( resolve, reject ) { const reader= new FileReader(); reader.readAsDataURL( file ); reader.onload = function() { resolve( reader.result ); }; reader.onerror = function( err ) { reject( err ); } }); }; // debounce function window.ctp.utils.debounce = async function( func, interval ) { let lastCall = -1; return async function() { clearTimeout( lastCall ); let args = arguments; let self = this; lastCall = setTimeout(function() { func.apply( self, args ); }, interval ); }; }; // check duplicates window.ctp.utils.hasDuplicates = function( $selector, $otherSelectors, value ) { let hasDuplicate = false; $otherSelectors.not( $selector ).each(function() { if ( $( this ).val() === value ) { hasDuplicate = true; } }); return hasDuplicate; }; // number with commas window.ctp.utils.numberWithCommas = function( number ) { let floatNumber = parseFloat( number ).toFixed( 2 ); return floatNumber.toString().replace( /\B(?=(\d{3})+(?!\d))/g, "," ); }; // number with commas without fixed decimal places window.ctp.utils.numberWithCommasWithoutFixedDecimals = function( number ) { let floatNumber = parseFloat( number ); return floatNumber.toString().replace( /\B(?=(\d{3})+(?!\d))/g, "," ); }; // format currency window.ctp.utils.formatCurrency = function( number, language, location, currency ) { let locale = language + '-' + location; return new Intl.NumberFormat( locale, { style: 'currency', currency: currency }).format( number ); }; // format currency pkr window.ctp.utils.formatCurrencyPKR = function( number ) { let locale = 'en-PK'; return new Intl.NumberFormat( locale, { style: 'currency', currency: 'PKR' }).format( number ); }; window.ctp.utils.formatCurrencyPKRWithoutDecimal = function( number ) { return ( window.ctp.utils.formatCurrencyPKR( number ) ).split( '.' )[0]; }; //format decimal places of given decimal number upto given decimal places window.ctp.utils.formatDecimalPlaces = function( num, decimalPlaces ) { const strNum = num.toString(); const decimalIndex = strNum.indexOf('.'); if( decimalIndex === -1 ) { return num; } const endIndex = decimalIndex + decimalPlaces; const strFormattedNumber = strNum.slice( 0, endIndex + 1 ); return parseFloat( strFormattedNumber ); }; // number to american system window.ctp.utils.numberToAmericanSystemWords = function( number ) { number = Math.ceil( number ); const ones = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']; const tens = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']; const teens = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']; function convert_millions( num ) { if ( num >= 1000000 ) { return convert_millions( Math.floor( num / 1000000 ) ) + " million " + convert_thousands( num % 1000000 ); } else { return convert_thousands( num ); } } function convert_thousands( num ) { if ( num >= 1000 ) { return convert_hundreds( Math.floor( num / 1000 ) ) + " thousand " + convert_hundreds( num % 1000 ); } else { return convert_hundreds( num ); } } function convert_hundreds( num ) { if ( num > 99 ) { return ones[Math.floor( num / 100 )] + " hundred " + convert_tens( num % 100 ); } else { return convert_tens( num ); } } function convert_tens( num ) { if ( num < 10 ) return ones[num]; else if ( num >= 10 && num < 20 ) return teens[num - 10]; else { return tens[Math.floor( num / 10 )] + " " + ones[num % 10]; } } function convert( num ) { if ( num == 0 ) return "zero"; else return convert_millions( num ); } let result = convert( number ); if ( typeof result === 'undefined' ) { return zero; } return result.trim(); }; // number to south asian system window.ctp.utils.numberToSouthAsianSystemWords = function( number ) { const a = ['', 'one ', 'two ', 'three ', 'four ', 'five ', 'six ', 'seven ', 'eight ', 'nine ', 'ten ', 'eleven ', 'twelve ', 'thirteen ', 'fourteen ', 'fifteen ', 'sixteen ', 'seventeen ', 'eighteen ', 'nineteen ']; const b = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']; const regex = /^(\d{2})(\d{2})(\d{2})(\d{1})(\d{2})$/; const getLT20 = ( n ) => a[Number( n )]; const get20Plus = ( n ) => b[n[0]] + ' ' + a[n[1]]; function convert ( input ) { const num = Number( input ); if ( isNaN( num ) ) return ''; if ( num === 0 ) return 'zero'; const numStr = num.toString(); if ( numStr.length > 9 ) { throw new Error( 'overflow' ) // Does not support converting more than 9 digits yet } const [, n1, n2, n3, n4, n5] = ( '000000000' + numStr ).substr( -9 ).match( regex ) // left pad zeros let str = ''; str += n1 != 0 ? ( getLT20( n1 ) || get20Plus( n1 ) ) + 'crore ' : ''; str += n2 != 0 ? ( getLT20( n2 ) || get20Plus( n2 ) ) + 'lakh ' : ''; str += n3 != 0 ? ( getLT20( n3 ) || get20Plus( n3 ) ) + 'thousand ' : ''; str += n4 != 0 ? getLT20( n4 ) + 'hundred ' : ''; str += n5 != 0 && str != '' ? 'and ' : ''; str += n5 != 0 ? ( getLT20( n5 ) || get20Plus( n5 ) ) : ''; return str.trim(); } return convert( number ); }; /** * sleep method */ window.ctp.utils.sleep = async function( ms ) { return new Promise( resolve => setTimeout( resolve, ms ) ); }; // number to words window.ctp.utils.numberToWords = function( number, currencySymbol ) { let words = window.ctp.utils.numberToAmericanSystemWords( number ); return words + ' only.'; }; // format grades window.ctp.utils.formatGrades = function( grades ) { let gradesArr = []; for ( let grade of grades ) { let gradeFormatted = {}; gradeFormatted['id'] = grade.id; gradeFormatted['title'] = grade.type + '-' + grade.level + " (" + grade.description + ")"; gradesArr.push( gradeFormatted ); } return gradesArr; }; // format companies window.ctp.utils.formatCompanies = function( companies ) { let companyArr = []; for ( let company of companies ) { let companyFormatted = {}; companyFormatted['id'] = company.id; companyFormatted['title'] = company.title; companyArr.push( companyFormatted ); } return companyArr; }; // format raw expense data into pie chart data window.ctp.utils.formatExpenseDataForPieChart = function( expenses ) { let formattedData = []; for ( let expense of expenses ) { let formattedExpense = {}; formattedExpense['name'] = expense.title; formattedExpense['y'] = expense.cost; formattedData.push( formattedExpense ); } return formattedData; }; // bind cost center search window.ctp.utils.bindItemNewCostCenterSearchAutoComplete = function( $selector ) { $selector.autocomplete({ source: '/uind/rest/accounts-finance/cost-centers/search?departmentId=0', minLength: 1, select: async function (e, ui) { e.preventDefault(); //format string let splitStr = ui.item.heirarchicalString.split(">"); let hierarchyStr = `${splitStr[3]} > ${splitStr[2]} > ${splitStr[1]} > ${splitStr[0]}` let $container = $selector.closest( '[data-cost-center-search-container]' ); $container.find( '[data-cost-center-one-search-id]' ).val( ui.item.oneId ); $container.find( '[data-cost-center-two-search-id]' ).val( ui.item.twoId ); $container.find( '[data-cost-center-three-search-id]' ).val( ui.item.threeId ); $container.find( '[data-cost-center-four-search-id]' ).val( ui.item.fourId ); $selector.val( hierarchyStr ); }, focus: function ( e, ui ) { $selector.val( '' ); } }).data( 'ui-autocomplete' )._renderItem = function ( ul, ui ) { let splitStr = ui.heirarchicalString.split(">"); let hierarchyStr = `${splitStr[3]} > ${splitStr[2]} > ${splitStr[1]} > ${splitStr[0]}` return $( '