UNPKG

omnipay-savings-sdk

Version:

Omnipay Savings SDK

300 lines (299 loc) 11.2 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; var _a; Object.defineProperty(exports, "__esModule", { value: true }); exports.getOrdinalSuffix = exports.formDataRequests = exports.waitFor = exports.isValidDate = exports.parseQueryString = exports.getDeductionFrequencyEnum = exports.getDeductionTypeEnum = exports.getFrequencyEnum = exports.getSaveAsYouCollectInterestRange = exports.getInterestRange = exports.groupArray = exports.isTablet = exports.formatDate = exports.calculateSavingsProgress = exports.correctFloatPoint = exports.convertToISODateString = exports.capitalizeText = exports.extractNumber = exports.isInteger = exports.secureEmail = exports.securePhoneNumber = exports.validateEmail = exports.formatAsCurrency = exports.formatAmount = exports.fontSz = exports.isIphoneX = exports.hp = exports.wp = exports.heightPercentageToDP = exports.widthPercentageToDP = exports.ms = exports.scale = exports.ASPECT_RATIO = exports.naira = exports.height = exports.width = void 0; const react_native_1 = require("react-native"); const dayjs_1 = __importDefault(require("dayjs")); _a = react_native_1.Dimensions.get('window'), exports.width = _a.width, exports.height = _a.height; exports.naira = '\u20A6'; const customWidth = 414; const customHeight = 896; exports.ASPECT_RATIO = exports.width / exports.height; const scale = (size) => (exports.width / customWidth) * size; exports.scale = scale; const ms = (size, factor = 0.5) => size + ((0, exports.scale)(size) - size) * factor; exports.ms = ms; const widthPercentageToDP = (widthPercent) => { const elemWidth = typeof widthPercent === 'number' ? widthPercent : parseFloat(widthPercent); return react_native_1.PixelRatio.roundToNearestPixel((exports.width * elemWidth) / 100); }; exports.widthPercentageToDP = widthPercentageToDP; const heightPercentageToDP = (heightPercent) => { const elemHeight = typeof heightPercent === 'number' ? heightPercent : parseFloat(heightPercent); return react_native_1.PixelRatio.roundToNearestPixel((exports.height * elemHeight) / 100); }; exports.heightPercentageToDP = heightPercentageToDP; const wp = (val) => { const percent = (val / customWidth) * 100; return (0, exports.widthPercentageToDP)(percent); }; exports.wp = wp; /** * Converts fixed value to height % then to dp based on base design */ const hp = (val) => { const percent = (val / customHeight) * 100; return (0, exports.heightPercentageToDP)(percent); }; exports.hp = hp; const isIphoneX = () => { const dimension = react_native_1.Dimensions.get('window'); return (react_native_1.Platform.OS === 'ios' && !react_native_1.Platform.isPad && !react_native_1.Platform.isTV && (dimension.height === 812 || dimension.width === 812 || dimension.height === 896 || dimension.width === 896)); }; exports.isIphoneX = isIphoneX; const fontSz = (val) => { return react_native_1.PixelRatio.roundToNearestPixel((exports.height * val) / 100 / 8.5); }; exports.fontSz = fontSz; const formatAmount = (value, toFixed = 2) => { return parseFloat(String(value) .replace(/(.*){1}/, '0$1') .replace(/[^\d]/g, '') .replace(/(\d\d?)$/, '.$1')) .toFixed(toFixed) .replace(/\B(?=(\d{3})+(?!\d))/g, ','); }; exports.formatAmount = formatAmount; const formatAsCurrency = (value) => `${exports.naira}${parseFloat(String(value)) .toFixed(2) .replace(/\B(?=(\d{3})+(?!\d))/g, ',')}`; exports.formatAsCurrency = formatAsCurrency; const validateEmail = (email) => { const isValidEmail = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email); return isValidEmail; }; exports.validateEmail = validateEmail; function securePhoneNumber(phoneNumber) { // Check if the input is a valid phone number if (!/^\d{11}$/.test(phoneNumber)) { return 'Invalid phone number'; } // Extract the first 6 digits const visibleDigits = phoneNumber.substring(0, 6); // Replace the remaining digits with asterisks const secureValue = visibleDigits + '******'; return secureValue; } exports.securePhoneNumber = securePhoneNumber; function secureEmail(email) { const atIndex = email.indexOf('@'); if (atIndex === -1) { return email; // Return the original email if '@' is not found } const [username, domain] = email.split('@'); const secureUsername = username.slice(0, Math.min(username.length, 5)) + '*'.repeat(Math.max(0, username.length - 5)); return `${secureUsername}@${domain}`; } exports.secureEmail = secureEmail; function isInteger(value, excludeDecimal) { // Check if the value is a number or a string that can be parsed as an integer if (typeof value === 'number' || (typeof value === 'string' && !isNaN(parseInt(value)))) { // Check if the parsed integer is equal to the original value if (excludeDecimal) { return ( //@ts-ignore parseInt(value) === Number(value) && !value.toString().includes('.')); } else { //@ts-ignore return parseInt(value) === Number(value); } } return false; } exports.isInteger = isInteger; function extractNumber(input) { try { const parts = input.split(','); const firstPart = parts[0].trim(); const parsedNumber = parseInt(firstPart, 10); if (isNaN(parsedNumber)) { return ''; // Return undefined if the first part is not a valid number } return parsedNumber; } catch (error) { return ''; } } exports.extractNumber = extractNumber; const capitalizeText = (text) => { return text && typeof text === 'string' ? text .toLowerCase() .split(' ') .map(word => word.charAt(0).toUpperCase() + word.slice(1)) .join(' ') : ''; }; exports.capitalizeText = capitalizeText; function convertToISODateString(dateString) { const date = (0, dayjs_1.default)(dateString); if (!date.isValid()) { return ''; } else { return date.toISOString(); } } exports.convertToISODateString = convertToISODateString; const correctFloatPoint = (number, point = 2) => { try { return Number(number.toFixed(point)); } catch (error) { return number; } }; exports.correctFloatPoint = correctFloatPoint; function calculateSavingsProgress(savingTarget, amountSaved) { // Only calculate if both values are over 100 if (savingTarget > 100 && amountSaved > 100) { const progress = (amountSaved / savingTarget) * 100; const cappedProgress = progress > 100 ? 100 : progress; return Math.ceil(cappedProgress); // Always round up to avoid showing 0% } return null; // Return null if conditions are not met } exports.calculateSavingsProgress = calculateSavingsProgress; const formatDate = (date, format = 'MMM D, YYYY. h:mm a') => { return (0, dayjs_1.default)(date).format(format); }; exports.formatDate = formatDate; exports.isTablet = (() => { // Basic heuristic: // - Tablets generally have a minimum screen width > 600 dp (density-independent pixels) // - iPads can be detected on iOS by model info but we skip that here for minimal deps const minTabletWidth = 600; // On iOS, some phones can have wide screens (like iPhone Plus models), // so you might want extra checks if desired. if (react_native_1.Platform.OS === 'web') { return false; // no tablets on web (or treat differently) } return Math.min(exports.width, exports.height) >= minTabletWidth; })(); const groupArray = (array, field) => { return array === null || array === void 0 ? void 0 : array.reduce((h, obj) => { const key = obj[field]; h[key] = (h[key] || []).concat(obj); return h; }, {}); }; exports.groupArray = groupArray; function getInterestRange(category) { const { interestRate, interestRange } = category; // If interestRange is provided from backend, parse it if (interestRange) { const rangeMatch = interestRange.match(/(\d+(?:\.\d+)?)-(\d+(?:\.\d+)?)/); if (rangeMatch) { return { min: parseFloat(rangeMatch[1]), max: parseFloat(rangeMatch[2]), }; } } // Fallback to old calculation if interestRange is not available return { min: interestRate - 2, max: interestRate + 2, }; } exports.getInterestRange = getInterestRange; function getSaveAsYouCollectInterestRange(plans) { if (!plans || plans.length === 0) { return 'N/A'; } const rates = plans.map(plan => plan.interestRate); const minRate = Math.min(...rates); const maxRate = Math.max(...rates); return minRate === maxRate ? `${minRate}` : `${minRate} - ${maxRate}`; } exports.getSaveAsYouCollectInterestRange = getSaveAsYouCollectInterestRange; const getFrequencyEnum = (name) => { switch (name) { case 'Daily': return 1; case 'Weekly': return 2; case 'Monthly': return 3; case 'Save as you collect': return 4; default: return 0; // Default or unknown frequency } }; exports.getFrequencyEnum = getFrequencyEnum; const getDeductionTypeEnum = (name) => { switch (name) { case 'Percentage': return 2; case 'Flat rate': return 1; default: return 0; // Default or unknown type } }; exports.getDeductionTypeEnum = getDeductionTypeEnum; const getDeductionFrequencyEnum = (name) => { switch (name) { case 'One-time': return 1; case 'Reoccurring': return 2; default: return 0; // Default or unknown frequency } }; exports.getDeductionFrequencyEnum = getDeductionFrequencyEnum; const parseQueryString = (queryString) => { let query = {}; let pairs = (queryString[0] === '?' ? queryString.substr(1) : queryString).split('&'); for (let i = 0; i < pairs.length; i++) { let pair = pairs[i].split('='); //@ts-ignore const value = decodeURIComponent(pair[1] || ''); query[decodeURIComponent(pair[0])] = value === 'true' ? true : value === 'false' ? false : value; } return query; }; exports.parseQueryString = parseQueryString; const isValidDate = (date) => { return (0, dayjs_1.default)(date).isValid(); }; exports.isValidDate = isValidDate; const waitFor = (duration) => { return new Promise(resolve => setTimeout(resolve, duration || 0)); }; exports.waitFor = waitFor; exports.formDataRequests = ['']; // Returns ordinal suffix for numbers (1st, 2nd, 3rd, 4th, etc.) const getOrdinalSuffix = (num) => { const j = num % 10; const k = num % 100; if (j === 1 && k !== 11) { return 'st'; } if (j === 2 && k !== 12) { return 'nd'; } if (j === 3 && k !== 13) { return 'rd'; } return 'th'; }; exports.getOrdinalSuffix = getOrdinalSuffix;