react-js-plugins
Version:
A powerful and efficient React utility library designed to enhance application performance by streamlining and simplifying the management of complex asynchronous operations.
720 lines (719 loc) • 33 kB
JavaScript
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
import moment from "moment";
import * as X from 'xlsx';
import CryptoJS from 'crypto-js';
import Swal from "sweetalert2";
export var isWindowReady = function () {
return typeof window !== "undefined" && document.readyState === "complete";
};
export var isBrowser = typeof window !== 'undefined' && typeof window.btoa === 'function';
export var _alert = function (_a) {
var _b = _a.title, title = _b === void 0 ? "Are you sure?" : _b, _c = _a.text, text = _c === void 0 ? "This action cannot be undone." : _c, _d = _a.icon, icon = _d === void 0 ? "warning" : _d, _e = _a.confirmButtonText, confirmButtonText = _e === void 0 ? "OK" : _e, _f = _a.cancelButtonText, cancelButtonText = _f === void 0 ? "Cancel" : _f, _g = _a.showCancelButton, showCancelButton = _g === void 0 ? true : _g, _h = _a.showConfirmButton, showConfirmButton = _h === void 0 ? true : _h, _j = _a.confirmButtonColor, confirmButtonColor = _j === void 0 ? '#2e7d32' : _j, _k = _a.cancelButtonColor, cancelButtonColor = _k === void 0 ? '#da2a2a' : _k, _l = _a.input, input = _l === void 0 ? null : _l, _m = _a.inputPlaceholder, inputPlaceholder = _m === void 0 ? "" : _m, _o = _a.inputValidator, inputValidator = _o === void 0 ? null : _o, _p = _a.customClass, customClass = _p === void 0 ? {} : _p, _q = _a.timer, timer = _q === void 0 ? null : _q, _r = _a.allowOutsideClick, allowOutsideClick = _r === void 0 ? true : _r, _s = _a.html, html = _s === void 0 ? null : _s, _t = _a.toast, toast = _t === void 0 ? false : _t, _u = _a.position, position = _u === void 0 ? "center" : _u, rest = __rest(_a, ["title", "text", "icon", "confirmButtonText", "cancelButtonText", "showCancelButton", "showConfirmButton", "confirmButtonColor", "cancelButtonColor", "input", "inputPlaceholder", "inputValidator", "customClass", "timer", "allowOutsideClick", "html", "toast", "position"]);
return Swal.fire(__assign({ title: title, text: text, icon: icon, confirmButtonText: confirmButtonText, cancelButtonText: cancelButtonText, showCancelButton: showCancelButton, showConfirmButton: showConfirmButton, confirmButtonColor: confirmButtonColor, cancelButtonColor: cancelButtonColor, input: input, inputPlaceholder: inputPlaceholder, inputValidator: inputValidator, customClass: customClass, timer: timer, allowOutsideClick: allowOutsideClick, html: html, toast: toast, position: position }, rest));
};
export var _confirm = function (_a) {
var _b = _a.title, title = _b === void 0 ? "Are you sure?" : _b, _c = _a.text, text = _c === void 0 ? "You won't be able to revert this!" : _c, _d = _a.icon, icon = _d === void 0 ? "warning" : _d, _e = _a.confirmButtonText, confirmButtonText = _e === void 0 ? "Yes" : _e, _f = _a.cancelButtonText, cancelButtonText = _f === void 0 ? "No" : _f, _g = _a.showCancelButton, showCancelButton = _g === void 0 ? true : _g, _h = _a.confirmButtonColor, confirmButtonColor = _h === void 0 ? "#3085d6" : _h, _j = _a.cancelButtonColor, cancelButtonColor = _j === void 0 ? "#d33" : _j, _k = _a.reverseButtons, reverseButtons = _k === void 0 ? true : _k, _l = _a.focusCancel, focusCancel = _l === void 0 ? true : _l, _m = _a.allowOutsideClick, allowOutsideClick = _m === void 0 ? false : _m, _o = _a.customClass, customClass = _o === void 0 ? {} : _o, _p = _a.html, html = _p === void 0 ? null : _p, rest = __rest(_a, ["title", "text", "icon", "confirmButtonText", "cancelButtonText", "showCancelButton", "confirmButtonColor", "cancelButtonColor", "reverseButtons", "focusCancel", "allowOutsideClick", "customClass", "html"]);
return Swal.fire(__assign({ title: title, text: text, icon: icon, showCancelButton: showCancelButton, confirmButtonText: confirmButtonText, cancelButtonText: cancelButtonText, confirmButtonColor: confirmButtonColor, cancelButtonColor: cancelButtonColor, reverseButtons: reverseButtons, focusCancel: focusCancel, allowOutsideClick: allowOutsideClick, customClass: customClass, html: html }, rest)).then(function (result) {
return { result: result, instance: Swal };
});
};
export var _encodeURI = function (str) {
try {
if (typeof str !== 'string')
return '';
return encodeURIComponent(str);
}
catch (error) {
console.error('Error encoding URI component:', error);
return '';
}
};
export var _decodeURI = function (str) {
try {
if (typeof str !== 'string')
return '';
return decodeURIComponent(str);
}
catch (error) {
console.error('Error decoding URI component:', error);
return '';
}
};
export var _encryptJson = function (decrypted, secretKey) {
try {
if (!decrypted) {
throw new Error("Invalid input: 'decrypted' data cannot be empty.");
}
if (!secretKey || typeof secretKey !== 'string') {
throw new Error("Invalid input: 'secretKey' must be a non-empty string.");
}
var jsonData = JSON.stringify(decrypted);
var iv = CryptoJS.lib.WordArray.random(16);
var key = CryptoJS.enc.Utf8.parse(secretKey);
var encrypted = CryptoJS.AES.encrypt(jsonData, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7,
});
var encryptedData = iv.concat(encrypted.ciphertext);
return CryptoJS.enc.Base64.stringify(encryptedData);
}
catch (error) {
console.error("Encryption Error Contact to React Expert:", error.message);
return null;
}
};
export var _decryptJson = function (encrypted, secretKey) {
try {
if (!encrypted || typeof encrypted !== 'string') {
throw new Error("Invalid input: 'encrypted' must be a valid string.");
}
if (!secretKey || typeof secretKey !== 'string') {
throw new Error("Invalid input: 'secretKey' must be a non-empty string.");
}
var encryptedData = CryptoJS.enc.Base64.parse(encrypted);
var iv = CryptoJS.lib.WordArray.create(encryptedData.words.slice(0, 4), 16);
var ciphertext = CryptoJS.lib.WordArray.create(encryptedData.words.slice(4), encryptedData.sigBytes - 16);
var key = CryptoJS.enc.Utf8.parse(secretKey);
var decrypted = CryptoJS.AES.decrypt({ ciphertext: ciphertext }, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7,
});
var decryptedString = decrypted.toString(CryptoJS.enc.Utf8);
if (!decryptedString) {
throw new Error("Decryption failed: Invalid key or corrupted data.");
}
return JSON.parse(decryptedString);
}
catch (error) {
console.error("Decryption Error Contact to React Expert:", error.message);
return null;
}
};
export var _encryptString = function (text, secretKey, isRandom) {
if (isRandom === void 0) { isRandom = true; }
try {
var key = CryptoJS.enc.Utf8.parse(secretKey);
var iv = isRandom
? CryptoJS.lib.WordArray.random(16)
: CryptoJS.enc.Utf8.parse(secretKey);
var encrypted = CryptoJS.AES.encrypt(text, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7,
});
return {
ciphertext: encrypted.toString(),
iv: CryptoJS.enc.Base64.stringify(iv),
};
}
catch (error) {
console.error('Error:', error.message);
throw error;
}
};
export var _decryptString = function (ciphertext, ivBase64, secretKey) {
var key = CryptoJS.enc.Utf8.parse(secretKey);
var iv = CryptoJS.enc.Base64.parse(ivBase64);
var decryptedText = CryptoJS.AES.decrypt(ciphertext, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
return decryptedText.toString(CryptoJS.enc.Utf8);
};
export var _encryptPayload = function (jsonData, secretKey) {
try {
if (!jsonData || typeof jsonData !== "object") {
throw new Error("Invalid input: jsonData must be a valid JSON object.");
}
if (!secretKey || typeof secretKey !== "string") {
throw new Error("Invalid input: secretKey must be a non-empty string.");
}
var randomKey = CryptoJS.lib.WordArray.random(16);
var randomIv = CryptoJS.lib.WordArray.random(16);
var keyIvData = JSON.stringify({
key: CryptoJS.enc.Base64.stringify(randomKey),
iv: CryptoJS.enc.Base64.stringify(randomIv)
});
var header = _encryptString(keyIvData, secretKey);
var encryptedData = CryptoJS.AES.encrypt(JSON.stringify(jsonData), randomKey, {
iv: randomIv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
return {
data: encryptedData.toString(),
header: header.ciphertext,
iv: header.iv
};
}
catch (error) {
console.error("Payload Encryption Error:", error.message);
}
};
export var _generatePassword = function (length) {
if (length === void 0) { length = 8; }
var uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var lowercase = 'abcdefghijklmnopqrstuvwxyz';
var numbers = '0123456789';
var specialChars = '!@#$%^&*_-+=<>?';
var allChars = uppercase + lowercase + numbers + specialChars;
var password = "";
password += uppercase[Math.floor(Math.random() * uppercase.length)];
password += lowercase[Math.floor(Math.random() * lowercase.length)];
password += numbers[Math.floor(Math.random() * numbers.length)];
password += specialChars[Math.floor(Math.random() * specialChars.length)];
for (var i = 4; i < length; i++) {
password += allChars[Math.floor(Math.random() * allChars.length)];
}
return password.split('').sort(function () { return Math.random() - 0.5; }).join('');
};
export var _getStartStopTime = function (sdate, format) {
if (format === void 0) { format = 'YYYY-MM-DDTHH:mm:ss'; }
if (!(sdate instanceof Date) || isNaN(sdate.getTime())) {
return 'Invalid Date';
}
var start = new Date(sdate.getFullYear(), sdate.getMonth(), 1);
var end = new Date(sdate.getFullYear(), sdate.getMonth() + 1, 0, 23, 59, 59);
return {
startTime: moment(start).format(format),
stopTime: moment(end).format(format)
};
};
export var _getUTCTimestamp = function (_a) {
var year = _a.year, month = _a.month, _b = _a.day, day = _b === void 0 ? 1 : _b, _c = _a.hour, hour = _c === void 0 ? 0 : _c, _d = _a.minute, minute = _d === void 0 ? 0 : _d, _e = _a.second, second = _e === void 0 ? 0 : _e;
var monthToIndex = {
January: 0, February: 1, March: 2,
April: 3, May: 4, June: 5,
July: 6, August: 7, September: 8,
October: 9, November: 10, December: 11
};
var monthIndex;
if (typeof month === "string") {
monthIndex = monthToIndex[month];
if (monthIndex === undefined) {
throw new Error("Invalid month name: ".concat(month));
}
}
else if (typeof month === "number") {
if (month >= 1 && month <= 12) {
monthIndex = month - 1;
}
else if (month >= 0 && month <= 11) {
monthIndex = month;
}
else {
throw new Error("Invalid month number: ".concat(month));
}
}
else {
throw new Error("Month must be a string or number");
}
return Date.UTC(year, monthIndex, day, hour, minute, second);
};
export var _isEmptyArray = function (value) {
return Array.isArray(value) && value.length === 0;
};
export var _isEmptyObject = function (obj) {
if (obj == null || typeof obj !== 'object') {
throw new TypeError('The provided argument is not a valid object.');
}
return Object.keys(obj).length === 0;
};
export var _isValueInArray = function (array, value) {
if (!Array.isArray(array)) {
console.error("The first argument must be an array.");
return false;
}
return array.includes(value);
};
export var _importFile = function (file, resultType) { return __awaiter(void 0, void 0, void 0, function () {
var maxFileSize, allowedTypes, fileName, fileExtension, fileSize, buffer, base64, error_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 5, , 6]);
if (!file) {
throw new Error('No file selected');
}
maxFileSize = 10 * 1024 * 1024;
if (file.size > maxFileSize) {
throw new Error("File too large (".concat(Math.round(file.size / (1024 * 1024)), "MB). Max size is 10MB."));
}
allowedTypes = ['application/pdf', 'image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/svg+xml'];
if (!allowedTypes.includes(file.type)) {
throw new Error('Only PDF, JPEG, PNG, GIF, WEBP, and SVG files are allowed');
}
fileName = file.name;
fileExtension = ".".concat(file.type.split('/')[1]);
fileSize = "".concat((file.size / 1024).toFixed(2), " KB");
if (resultType === 'file') {
return [2 /*return*/, {
result: file,
fileName: fileName,
fileSize: fileSize,
fileExtension: fileExtension,
}];
}
if (!(resultType === 'buffer' || resultType === 'unitarray')) return [3 /*break*/, 2];
return [4 /*yield*/, new Promise(function (resolve, reject) {
var reader = new FileReader();
reader.onload = function (event) {
var _a;
var result = (_a = event.target) === null || _a === void 0 ? void 0 : _a.result;
if (result instanceof ArrayBuffer) {
resolve(result);
}
else {
reject(new Error('Failed to read file as buffer'));
}
};
reader.onerror = function () { return reject(new Error('File reading failed')); };
reader.readAsArrayBuffer(file);
})];
case 1:
buffer = _a.sent();
return [2 /*return*/, {
result: resultType === 'unitarray' ? new Uint8Array(buffer) : buffer,
fileName: fileName,
fileSize: fileSize,
fileExtension: fileExtension,
}];
case 2:
if (!(resultType === 'base64')) return [3 /*break*/, 4];
return [4 /*yield*/, new Promise(function (resolve, reject) {
var reader = new FileReader();
reader.onload = function (event) {
var _a;
var result = (_a = event.target) === null || _a === void 0 ? void 0 : _a.result;
if (typeof result === 'string') {
resolve(result);
}
else {
reject(new Error('Failed to read file as base64'));
}
};
reader.onerror = function () { return reject(new Error('File reading failed')); };
reader.readAsDataURL(file);
})];
case 3:
base64 = _a.sent();
return [2 /*return*/, {
result: base64,
fileName: fileName,
fileSize: fileSize,
fileExtension: fileExtension,
}];
case 4: throw new Error("Unsupported resultType: ".concat(resultType));
case 5:
error_1 = _a.sent();
return [2 /*return*/, {
error: error_1 instanceof Error ? error_1 : new Error('File processing failed'),
}];
case 6: return [2 /*return*/];
}
});
}); };
export var _exportExcel = function (_a) {
var data = _a.data, filename = _a.filename, _b = _a.extension, extension = _b === void 0 ? '.xlsx' : _b;
return new Promise(function (resolve, reject) {
var objectUrl = null;
var a = null;
if (!Array.isArray(data) ||
data.some(function (item) { return typeof item !== 'object' || item === null || Array.isArray(item); })) {
throw new Error('Invalid data: data must be an array of objects');
}
try {
if (!filename || typeof filename !== 'string') {
throw new Error('Filename must be a non-empty string');
}
if (!extension || typeof extension !== 'string') {
throw new Error('Extension must be a non-empty string');
}
var ws = X.utils.json_to_sheet(data);
var wb = {
Sheets: { Sheet1: ws },
SheetNames: ['Sheet1'],
};
var excelBuffer = X.write(wb, {
bookType: 'xlsx',
type: 'array',
});
var blob = new Blob([excelBuffer], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
});
objectUrl = window.URL.createObjectURL(blob);
a = document.createElement('a');
a.href = objectUrl;
a.download = "".concat(filename).concat(extension);
document.body.appendChild(a);
a.click();
setTimeout(function () {
if (a) {
document.body.removeChild(a);
}
if (objectUrl) {
window.URL.revokeObjectURL(objectUrl);
}
}, 100);
resolve('success');
}
catch (error) {
if (a) {
document.body.removeChild(a);
}
if (objectUrl) {
window.URL.revokeObjectURL(objectUrl);
}
if (error instanceof Error) {
reject(new Error("Excel export failed: ".concat(error.message)));
}
else {
reject(new Error('Excel export failed due to an unknown error'));
}
}
});
};
export var _importExcel = function (file) { return __awaiter(void 0, void 0, void 0, function () {
var maxFileSize, allowedTypes, data, error_2;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
if (!file) {
throw new Error('No file selected');
}
maxFileSize = 10 * 1024 * 1024;
if (file.size > maxFileSize) {
throw new Error("File too large (".concat(Math.round(file.size / (1024 * 1024)), "MB). Max size is 10MB."));
}
allowedTypes = [
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/vnd.ms-excel',
'text/csv',
];
if (!allowedTypes.includes(file.type)) {
throw new Error('Only Excel (.xlsx, .xls) and CSV files are allowed');
}
return [4 /*yield*/, new Promise(function (resolve, reject) {
var reader = new FileReader();
reader.onload = function (event) {
var _a;
try {
var buffer = (_a = event.target) === null || _a === void 0 ? void 0 : _a.result;
if (!buffer)
throw new Error('Failed to read file');
var workbook = X.read(buffer, { type: 'buffer' });
var firstSheetName = workbook.SheetNames[0];
var firstSheet = workbook.Sheets[firstSheetName];
var jsonData = X.utils.sheet_to_json(firstSheet, {
defval: null,
raw: false,
});
resolve(jsonData);
}
catch (err) {
reject(err);
}
};
reader.onerror = function () { return reject(new Error('File reading failed')); };
reader.readAsArrayBuffer(file);
})];
case 1:
data = _a.sent();
return [2 /*return*/, { data: data }];
case 2:
error_2 = _a.sent();
return [2 /*return*/, {
error: error_2 instanceof Error ? error_2 : new Error('File processing failed'),
}];
case 3: return [2 /*return*/];
}
});
}); };
export var _promise = function (time) { return new Promise(function (res) { return setTimeout(res, time); }); };
export var _sleep = function (time) { return new Promise(function (res) { return setTimeout(res, time); }); };
export var _hasItem = function (menuItems, path, key) {
var _a;
if (!menuItems)
return {};
for (var _i = 0, menuItems_1 = menuItems; _i < menuItems_1.length; _i++) {
var item = menuItems_1[_i];
if ((item === null || item === void 0 ? void 0 : item.path) === path)
return key ? item[key] : item;
var result = ((_a = item === null || item === void 0 ? void 0 : item.data) === null || _a === void 0 ? void 0 : _a.length) && _hasItem(item.data, path, key);
if (result)
return result;
}
return null;
};
export var _hasElement = function (arr, key, value) {
var _a;
if (!arr)
return {};
for (var _i = 0, arr_1 = arr; _i < arr_1.length; _i++) {
var ele = arr_1[_i];
if (ele[key] === value) {
return ele;
}
if ((_a = ele === null || ele === void 0 ? void 0 : ele.data) === null || _a === void 0 ? void 0 : _a.length) {
var result = _hasElement(ele.data, key, value);
if (result) {
return result;
}
}
}
return null;
};
export var _flattenArray = function (arr) {
var _a;
if (!arr)
return [];
var result = [];
for (var _i = 0, arr_2 = arr; _i < arr_2.length; _i++) {
var item = arr_2[_i];
if ((_a = item === null || item === void 0 ? void 0 : item.data) === null || _a === void 0 ? void 0 : _a.length) {
result.push.apply(result, _flattenArray(item.data));
}
else {
result.push(item);
}
}
return result;
};
var genericActionHandler = function (state, action) {
var _a;
var key = action.type;
if (Object.prototype.hasOwnProperty.call(state, key)) {
return __assign(__assign({}, state), (_a = {}, _a[key] = action.payload, _a));
}
return state;
};
export var _dynamicReducer = function (initialState) {
return function (state, action) {
if (state === void 0) { state = initialState; }
return genericActionHandler(state, action);
};
};
export var _genericReducer = function (initialState, actions) { return function (state, action) {
if (state === void 0) { state = initialState; }
if (actions[action.type]) {
return actions[action.type](state, action);
}
return state;
}; };
export var _thousandSeparator = function (num) {
try {
if (typeof num !== "number" || isNaN(num)) {
console.error("The value must be a valid number.");
}
var parts = num.toFixed(2).split(".");
var numberPart = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
var decimalPart = ".".concat(parts[1]);
var twoDecimalPart = ".".concat(parts[1].slice(0, 2));
return {
allDecimal: numberPart + decimalPart,
twoDecimal: numberPart + twoDecimalPart,
};
}
catch (error) {
return { allDecimal: "0.00", twoDecimal: "0.00" }; // Safe fallback value
}
};
export var _getFinancialYear = function () {
var currentDate = new Date();
var currentYear = currentDate.getFullYear();
var month = currentDate.getMonth();
var startYear = month >= 3 ? currentYear : currentYear - 1;
var endYear = startYear + 1;
return "".concat(startYear, "-").concat(endYear);
};
export var _getStorage = function (_a) {
var action = _a.action, type = _a.type, key = _a.key, value = _a.value;
if (typeof window === 'undefined') {
return null;
}
if (type !== 'local' && type !== 'session') {
throw new Error("Invalid storage type. Use 'local' or 'session'.");
}
var result = null;
var storage = type === 'local' ? localStorage : sessionStorage;
try {
if (action === 'CLEAR') {
storage.clear();
}
else if (action === 'SET' && value !== undefined && value !== null) {
var storageValue = typeof value === 'string' ? value : JSON.stringify(value);
storage.setItem(key, storageValue);
}
else if (action === 'GET' && key) {
var storedValue = storage.getItem(key);
if (storedValue !== null) {
try {
result = JSON.parse(storedValue);
}
catch (error) {
result = storedValue;
}
}
}
else if (action === 'REMOVE' && key) {
storage.removeItem(key);
}
}
catch (error) {
console.error('Storage error:', error);
return null;
}
return result;
};
export var _deepClone = function (obj) { return JSON.parse(JSON.stringify(obj)); };
export var _getCookie = function (name) {
var _a, _b;
try {
if (!name) {
console.error("Cookie name must be a non-empty string.");
return null;
}
if (typeof document === "undefined") {
console.error("document is not available (probably running in a non-browser environment).");
return null;
}
var value = "; ".concat(document.cookie);
var parts = value.split("; ".concat(name, "="));
if (parts.length === 2) {
return (_b = (_a = parts.pop()) === null || _a === void 0 ? void 0 : _a.split(";").shift()) !== null && _b !== void 0 ? _b : null;
}
return null;
}
catch (error) {
console.error(error);
return null;
}
};
export var _setCookie = function (name, value, days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "expires=".concat(date.toUTCString());
document.cookie = "".concat(name, "=").concat(value, "; ").concat(expires, "; path=/");
};
export var _mergeObjects = function (obj1, obj2) {
if (typeof obj1 !== "object" || obj1 === null) {
console.error("First argument must be a non-null object.");
return obj2;
}
if (typeof obj2 !== "object" || obj2 === null) {
console.error("Second argument must be a non-null object.");
return obj1;
}
return __assign(__assign({}, obj1), obj2);
};
export var _mapObject = function (obj, callback) {
return Object.keys(obj).map(function (key) { return callback(key, obj[key]); });
};
export var _isEqual = function (value1, value2) {
if (value1 == null || value2 == null) {
console.error("One or both values are null or undefined.");
return false;
}
return JSON.stringify(value1) === JSON.stringify(value2);
};
export var _capitalize = function (str) {
if (!str) {
console.error("Empty string.");
return "";
}
return str.charAt(0).toUpperCase() + str.slice(1);
};
export var _convertToCurrency = function (amount, currency) {
if (currency === void 0) { currency = 'USD'; }
return new Intl.NumberFormat('en-US', { style: 'currency', currency: currency }).format(amount);
};
export var _getBrowserInfo = function () {
var userAgent = navigator.userAgent;
if (userAgent.includes('Chrome'))
return 'Chrome';
if (userAgent.includes('Firefox'))
return 'Firefox';
return 'Unknown';
};
export var _isMobile = function () {
return /Mobi|Android/i.test(navigator.userAgent);
};
export var _parseJSON = function (json) {
try {
return JSON.parse(json);
}
catch (_a) {
console.error("JSON Parse Error: Invalid JSON format.");
return null;
}
};
export var _stringifyJSON = function (value) {
try {
return JSON.stringify(value);
}
catch (_a) {
console.error("JSON Stringify Error: Unable to convert value.");
return null;
}
};