UNPKG

som-exp-sdk

Version:

Evaluate the User Expression

505 lines (504 loc) 22 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.DateExpression = void 0; const constants_1 = require("./constants"); const moment_timezone_1 = __importDefault(require("moment-timezone")); class DateExpression { constructor() { // Ex: dateExpr - dd/mm/yyyy this.day = (dateExpr) => { let output = this.const.INVALID_EXPRESSION; if (!!dateExpr) { try { const date = this.parseDateExp(dateExpr); if (date) { output = date.getDate().toString(); } } catch (e) { console.log(`Error in fetching the day. Error is ${e}`); } } return output; }; this.dayName = (dateExpr) => { let output = this.const.INVALID_EXPRESSION; if (!!dateExpr) { try { const date = this.parseDateExp(dateExpr); if (date) { const day = date.getDay(); if (this.const.WEEK_DAYS[day]) { output = this.const.WEEK_DAYS[day]; } } } catch (e) { console.log(`Error in fetching the day name. Error is ${e}`); } } return output; }; this.dayShortName = (dateExpr) => { let output = this.const.INVALID_EXPRESSION; if (!!dateExpr) { try { const date = this.parseDateExp(dateExpr); if (date) { const day = date.getDay(); if (this.const.WEEK_DAYS[day] && this.const.WEEK_DAYS[day].length >= 3) { output = this.const.WEEK_DAYS[day].slice(0, 3); } } } catch (e) { console.log(`Error in fetching the day short name. Error is ${e}`); } } return output; }; this.month = (dateExpr) => { let output = this.const.INVALID_EXPRESSION; if (!!dateExpr) { try { const date = this.parseDateExp(dateExpr); if (date) { output = (date.getMonth() + 1).toString(); } } catch (e) { console.log(`Error in fetching the month. Error is ${e}`); } } return output; }; this.monthName = (dateExpr) => { let output = this.const.INVALID_EXPRESSION; if (!!dateExpr) { try { const date = this.parseDateExp(dateExpr); if (date) { const month = date.getMonth(); if (this.const.MONTH_NAMES[month]) { output = this.const.MONTH_NAMES[month]; } } } catch (e) { console.log(`Error in fetching the month name. Error is ${e}`); } } return output; }; this.monthShortName = (dateExpr) => { let output = this.const.INVALID_EXPRESSION; if (!!dateExpr) { try { const date = this.parseDateExp(dateExpr); if (date) { const month = date.getMonth(); if (this.const.MONTH_NAMES[month] && this.const.MONTH_NAMES[month].length >= 3) { output = this.const.MONTH_NAMES[month].slice(0, 3); } } } catch (e) { console.log(`Error in fetching the month short name. Error is ${e}`); } } return output; }; this.year = (dateExpr) => { let output = this.const.INVALID_EXPRESSION; if (!!dateExpr) { try { const date = this.parseDateExp(dateExpr); if (date) { output = date.getFullYear().toString(); } } catch (e) { console.log(`Error in fetching the year. Error is ${e}`); } } return output; }; this.yearShort = (dateExpr) => { let output = this.const.INVALID_EXPRESSION; if (!!dateExpr) { try { const date = this.parseDateExp(dateExpr); if (date) { const fullYear = date.getFullYear(); if (fullYear.toString() && fullYear.toString().length == 4) { output = fullYear.toString().slice(2, 4); } } } catch (e) { console.log(`Error in fetching the year short name. Error is ${e}`); } } return output; }; this.words = (dateExpr) => { let output = this.const.INVALID_EXPRESSION; if (!!dateExpr) { try { const date = this.parseDateExp(dateExpr); if (date) { const day = this.day(dateExpr); const monthName = this.monthName(dateExpr); const year = this.year(dateExpr); output = `${day} ${monthName} ${year}`; } } catch (e) { console.log(`Error in retrieving the date in words. Error is ${e}`); } } return output; }; // Ex: dateExpr - "dd/mm/yyyy-dd/mm/yyyy" this.duration = (dateExpr) => { let output = this.const.INVALID_EXPRESSION; if (!!dateExpr) { try { const durations = this.getDuration(dateExpr); if (!!durations) { const year = durations.years(); const month = durations.months(); const day = durations.days(); const yearVal = (year > 1) ? `${year} years` : `${year} year`; const monthVal = (month > 1) ? `${month} months` : `${month} month`; const dayVal = (day > 1) ? `${day} days` : `${day} day`; output = `${yearVal}, ${monthVal}, ${dayVal}`; } } catch (e) { console.log(`Error in calculating duration. Error is ${e}`); } } return output; }; this.durationYearMonth = (dateExpr) => { let output = this.const.INVALID_EXPRESSION; if (!!dateExpr) { try { const durations = this.getDuration(dateExpr); if (!!durations) { const year = durations.years(); const month = durations.months(); const yearVal = (year > 1) ? `${year} years` : `${year} year`; const monthVal = (month > 1) ? `${month} months` : `${month} month`; output = `${yearVal}, ${monthVal}`; } } catch (e) { console.log(`Error in calculating year and month duration. Error is ${e}`); } } return output; }; this.durationOnlyYear = (dateExpr) => { let output = this.const.INVALID_EXPRESSION; if (!!dateExpr) { try { const durations = this.getDuration(dateExpr); if (!!durations) { const year = durations.years(); output = (year > 1) ? `${year} years` : `${year} year`; } } catch (e) { console.log(`Error in calculating year duration. Error is ${e}`); } } return output; }; this.durationMonths = (dateExpr) => { let output = this.const.INVALID_EXPRESSION; if (!!dateExpr) { try { const durations = this.getDuration(dateExpr); if (!!durations) { const month = durations.months(); output = (month > 1) ? `${month} months` : `${month} month`; } } catch (e) { console.log(`Error in calculating month duration. Error is ${e}`); } } return output; }; this.durationDays = (dateExpr) => { let output = this.const.INVALID_EXPRESSION; if (!!dateExpr) { try { const durations = this.getDuration(dateExpr); if (!!durations) { const day = durations.days(); output = (day > 1) ? `${day} days` : `${day} day`; } } catch (e) { console.log(`Error in calculating day duration. Error is ${e}`); } } return output; }; this.zonedDateTime = (epochTimestamp, time, timeZone) => { let zonedDT = this.const.INVALID_EXPRESSION; try { if (!!epochTimestamp && Number(epochTimestamp) > 0 && !!time && !!timeZone && this.validateTimeZone(timeZone)) { const epochTime = Number(epochTimestamp); // Convert the given epoch timeStamp to the given time zone const incomingMoment = (0, moment_timezone_1.default)(epochTime).tz(timeZone); // Add the desired time to the moment const parsedTM = (0, moment_timezone_1.default)(time, this.const.TIME_FORMAT); if (parsedTM && parsedTM.isValid()) { incomingMoment.set({ hour: parsedTM.hours(), minute: parsedTM.minutes() }); // Convert this moment back to the desired time zone incomingMoment.tz(timeZone); // Get the UTC timestamp const outboundDate = incomingMoment.toDate(); zonedDT = outboundDate.getTime().toString(); } } } catch (e) { console.log(`Error while constructing the zoned date time. Error is ${e}`); } return zonedDT; }; this.addMinutes = (epochTimestamp, minutes) => { let outboundEpochTime = this.const.INVALID_EXPRESSION; if (!!epochTimestamp && Number(epochTimestamp) > 0 && minutes && minutes > 0) { try { const epochTime = Number(epochTimestamp); const outboundDT = new Date(epochTime); // Convert minutes to milliseconds const milliseconds = minutes * this.const.MILLISECONDS; // Add the millis const outboundTimestamp = outboundDT.getTime() + milliseconds; if (outboundTimestamp != null) { outboundEpochTime = outboundTimestamp.toString(); } } catch (e) { console.log(`Error while adding minutes to the given epochTime. Error is ${e}`); } } return outboundEpochTime; }; this.getEpochMillis = (incomingDate, dateFormat, timeZone) => { let epochMillis = this.const.INVALID_EXPRESSION; const regex = this.const.DATE_FORMAT_REGEX; try { if (!!incomingDate && regex.test(incomingDate) && !!dateFormat && !!timeZone && this.validateTimeZone(timeZone)) { const parsedMoment = moment_timezone_1.default.tz(incomingDate, dateFormat, true, timeZone); if (parsedMoment && parsedMoment.isValid()) { epochMillis = parsedMoment.valueOf().toString(); } } } catch (e) { console.log(`Error occurred when converting date to epoch millis. Error is ${e}`); } return epochMillis; }; this.getDateFromEpoch = (epochMillis, dateFormat, timeZone) => { let formattedDate = this.const.INVALID_EXPRESSION; try { if (!!epochMillis && Number(epochMillis) > 0 && !!dateFormat && !!timeZone && this.validateTimeZone(timeZone)) { const epochTime = Number(epochMillis); // Convert the given epoch millis to the given time zone const incomingMoment = (0, moment_timezone_1.default)(epochTime).tz(timeZone); if (incomingMoment && incomingMoment.isValid()) { // Format the moment using the given date format formattedDate = incomingMoment.format(dateFormat); } } } catch (e) { console.log(`Error occurred while converting epoch millis to date. Error is ${e}`); } return formattedDate; }; this.addDays = (epochMillis, timeZone, days) => { let outTimestamp = this.const.INVALID_EXPRESSION; try { if (!!epochMillis && Number(epochMillis) > 0 && !!timeZone && days > 0 && this.validateTimeZone(timeZone)) { const epochTime = Number(epochMillis); // Convert the given epoch timestamp to the given time zone const incomingMoment = (0, moment_timezone_1.default)(epochTime).tz(timeZone); if (incomingMoment && incomingMoment.isValid()) { // Add the specified number of days const outboundMoment = incomingMoment.add(days, "days"); // Get the outbound timestamp in milliseconds outTimestamp = outboundMoment.valueOf().toString(); } } } catch (e) { console.log(`Error while adding days. Error is ${e}`); } return outTimestamp; }; this.addBusinessDays = (epochMillis, timeZone, days) => { let outTimestamp = this.const.INVALID_EXPRESSION; try { if (!!epochMillis && Number(epochMillis) > 0 && !!timeZone && days > 0 && this.validateTimeZone(timeZone)) { const epochTime = Number(epochMillis); // Convert the given epoch timestamp to the given time zone const incomingMoment = (0, moment_timezone_1.default)(epochTime).tz(timeZone); if (incomingMoment && incomingMoment.isValid()) { // Add the specified number of days const outboundMoment = this.addWeekDays(incomingMoment, days); // Get the outbound timestamp in milliseconds outTimestamp = outboundMoment.valueOf().toString(); } } } catch (e) { console.log(`Error while adding business days. Error is ${e}`); } return outTimestamp; }; this.getFormattedTime = (epochMillis, timeZone, hrFormat) => { let time = this.const.INVALID_EXPRESSION; try { if (!!epochMillis && Number(epochMillis) > 0 && !!timeZone) { const epochTime = parseInt(epochMillis); // Convert the given epoch timestamp to the given time zone using Moment.js const incomingMoment = (0, moment_timezone_1.default)(epochTime).tz(timeZone); if (incomingMoment && incomingMoment.isValid()) { // Get the pattern based on the 24h or 12h format const pattern = !!hrFormat ? this.getTimePattern(hrFormat.toLowerCase()) : this.const.TIME_FORMAT; time = incomingMoment.format(pattern); } } } catch (e) { console.log(`Error while retrieving the time from epochTime. Error is ${e}`); } return time; }; this.parseDateExp = (dateExpr) => { const regex = this.const.DATE_REGEX; let date = null; if (dateExpr && regex.test(dateExpr)) { try { const dateTkns = dateExpr.split(this.const.LITERAL_SLASH); if (dateTkns && Array.isArray(dateTkns) && dateTkns.length == 3) { // Extract day, month, and year from the date string const day = parseInt(dateTkns[0]); // Month is zero-based in JavaScript Date object const month = parseInt(dateTkns[1]) - 1; const year = parseInt(dateTkns[2]); // Create a Date object and validate the date const preparedDate = new Date(year, month, day); const validDate = (preparedDate.getDate() === day && preparedDate.getMonth() === month && preparedDate.getFullYear() === year); date = validDate ? preparedDate : null; } } catch (e) { console.log(`Error in parsing date input. Error is ${e}`); } } else { console.log(`Invalid date expression: ${dateExpr}`); } return date; }; this.getDuration = (inputExpr) => { let duration = null; if (!!inputExpr) { try { const dates = inputExpr.split("-"); if (dates && Array.isArray(dates) && dates.length > 0) { if (dates[0] && dates[1]) { const parsedDate1 = this.parseDateExp(dates[0]); const parsedDate2 = this.parseDateExp(dates[1]); // first date should always be greater than the second if (parsedDate1 && parsedDate2 && parsedDate1 > parsedDate2) { const date1 = (0, moment_timezone_1.default)(parsedDate1); const date2 = (0, moment_timezone_1.default)(parsedDate2); duration = moment_timezone_1.default.duration(date1.diff(date2)); } } } else { console.log("Input does not have the date range expression."); } } catch (e) { console.log(`Error while fetching the duration. Error is ${e}`); } } return duration; }; this.validateTimeZone = (timeZone) => { let isValid = true; if (!!timeZone) { try { const validZoneId = Intl.DateTimeFormat(undefined, { timeZone: timeZone }).toString(); isValid = validZoneId ? true : false; } catch (e) { console.log(`Error occurred while verifying the timezone. Error is ${e}`); } } return isValid; }; this.addWeekDays = (incomingMoment, days) => { let currentMoment = incomingMoment.clone(); let addedBusinessDays = 0; if (incomingMoment && days > 0) { while (addedBusinessDays < days) { currentMoment.add(1, "days"); // Check if it's not a Sunday (0) or Saturday (6) if (currentMoment.day() != 0 && currentMoment.day() != 6) { addedBusinessDays++; } } } return currentMoment; }; this.getTimePattern = (hrFormat) => { let pattern = this.const.TIME_FORMAT; if (!!hrFormat) { pattern = hrFormat == this.const.TIME_FORMAT_12_HOUR ? this.const.AM_PM_TIME_FORMAT : this.const.TIME_FORMAT; } return pattern; }; this.const = new constants_1.Constants(); } } exports.DateExpression = DateExpression;